Mercurial > hg > truffle
annotate src/share/vm/runtime/objectMonitor.cpp @ 17747:f99e331f6ef6
8029162: G1: Shared SATB queue never enabled
Reviewed-by: brutisso, mgerdin, tschatzl
author | pliden |
---|---|
date | Fri, 10 Jan 2014 09:54:25 +0100 |
parents | d35df3079834 |
children | 8c6165f9ea8e bbfbe9b06038 |
rev | line source |
---|---|
1878 | 1 /* |
17693
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
2 * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. |
1878 | 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 | |
1972 | 25 #include "precompiled.hpp" |
26 #include "classfile/vmSymbols.hpp" | |
27 #include "memory/resourceArea.hpp" | |
28 #include "oops/markOop.hpp" | |
29 #include "oops/oop.inline.hpp" | |
30 #include "runtime/handles.inline.hpp" | |
31 #include "runtime/interfaceSupport.hpp" | |
32 #include "runtime/mutexLocker.hpp" | |
33 #include "runtime/objectMonitor.hpp" | |
34 #include "runtime/objectMonitor.inline.hpp" | |
35 #include "runtime/osThread.hpp" | |
36 #include "runtime/stubRoutines.hpp" | |
7180
f34d701e952e
8003935: Simplify the needed includes for using Thread::current()
stefank
parents:
6725
diff
changeset
|
37 #include "runtime/thread.inline.hpp" |
1972 | 38 #include "services/threadService.hpp" |
10405 | 39 #include "trace/tracing.hpp" |
40 #include "trace/traceMacros.hpp" | |
1972 | 41 #include "utilities/dtrace.hpp" |
10405 | 42 #include "utilities/macros.hpp" |
1972 | 43 #include "utilities/preserveException.hpp" |
44 #ifdef TARGET_OS_FAMILY_linux | |
45 # include "os_linux.inline.hpp" | |
46 #endif | |
47 #ifdef TARGET_OS_FAMILY_solaris | |
48 # include "os_solaris.inline.hpp" | |
49 #endif | |
50 #ifdef TARGET_OS_FAMILY_windows | |
51 # include "os_windows.inline.hpp" | |
52 #endif | |
3960 | 53 #ifdef TARGET_OS_FAMILY_bsd |
54 # include "os_bsd.inline.hpp" | |
55 #endif | |
1878 | 56 |
57 #if defined(__GNUC__) && !defined(IA64) | |
58 // Need to inhibit inlining for older versions of GCC to avoid build-time failures | |
59 #define ATTR __attribute__((noinline)) | |
60 #else | |
61 #define ATTR | |
62 #endif | |
63 | |
64 | |
65 #ifdef DTRACE_ENABLED | |
66 | |
67 // Only bother with this argument setup if dtrace is available | |
68 // TODO-FIXME: probes should not fire when caller is _blocked. assert() accordingly. | |
69 | |
4006 | 70 |
6725
da91efe96a93
6964458: Reimplement class meta-data storage to use native memory
coleenp
parents:
4006
diff
changeset
|
71 #define DTRACE_MONITOR_PROBE_COMMON(obj, thread) \ |
4006 | 72 char* bytes = NULL; \ |
73 int len = 0; \ | |
74 jlong jtid = SharedRuntime::get_java_tid(thread); \ | |
6725
da91efe96a93
6964458: Reimplement class meta-data storage to use native memory
coleenp
parents:
4006
diff
changeset
|
75 Symbol* klassname = ((oop)obj)->klass()->name(); \ |
4006 | 76 if (klassname != NULL) { \ |
77 bytes = (char*)klassname->bytes(); \ | |
78 len = klassname->utf8_length(); \ | |
79 } | |
80 | |
81 #ifndef USDT2 | |
82 | |
1878 | 83 HS_DTRACE_PROBE_DECL4(hotspot, monitor__notify, |
84 jlong, uintptr_t, char*, int); | |
85 HS_DTRACE_PROBE_DECL4(hotspot, monitor__notifyAll, | |
86 jlong, uintptr_t, char*, int); | |
87 HS_DTRACE_PROBE_DECL4(hotspot, monitor__contended__enter, | |
88 jlong, uintptr_t, char*, int); | |
89 HS_DTRACE_PROBE_DECL4(hotspot, monitor__contended__entered, | |
90 jlong, uintptr_t, char*, int); | |
91 HS_DTRACE_PROBE_DECL4(hotspot, monitor__contended__exit, | |
92 jlong, uintptr_t, char*, int); | |
93 | |
6725
da91efe96a93
6964458: Reimplement class meta-data storage to use native memory
coleenp
parents:
4006
diff
changeset
|
94 #define DTRACE_MONITOR_WAIT_PROBE(monitor, obj, thread, millis) \ |
1878 | 95 { \ |
96 if (DTraceMonitorProbes) { \ | |
6725
da91efe96a93
6964458: Reimplement class meta-data storage to use native memory
coleenp
parents:
4006
diff
changeset
|
97 DTRACE_MONITOR_PROBE_COMMON(obj, thread); \ |
1878 | 98 HS_DTRACE_PROBE5(hotspot, monitor__wait, jtid, \ |
99 (monitor), bytes, len, (millis)); \ | |
100 } \ | |
101 } | |
102 | |
6725
da91efe96a93
6964458: Reimplement class meta-data storage to use native memory
coleenp
parents:
4006
diff
changeset
|
103 #define DTRACE_MONITOR_PROBE(probe, monitor, obj, thread) \ |
1878 | 104 { \ |
105 if (DTraceMonitorProbes) { \ | |
6725
da91efe96a93
6964458: Reimplement class meta-data storage to use native memory
coleenp
parents:
4006
diff
changeset
|
106 DTRACE_MONITOR_PROBE_COMMON(obj, thread); \ |
1878 | 107 HS_DTRACE_PROBE4(hotspot, monitor__##probe, jtid, \ |
108 (uintptr_t)(monitor), bytes, len); \ | |
109 } \ | |
110 } | |
111 | |
4006 | 112 #else /* USDT2 */ |
113 | |
6725
da91efe96a93
6964458: Reimplement class meta-data storage to use native memory
coleenp
parents:
4006
diff
changeset
|
114 #define DTRACE_MONITOR_WAIT_PROBE(monitor, obj, thread, millis) \ |
4006 | 115 { \ |
116 if (DTraceMonitorProbes) { \ | |
6725
da91efe96a93
6964458: Reimplement class meta-data storage to use native memory
coleenp
parents:
4006
diff
changeset
|
117 DTRACE_MONITOR_PROBE_COMMON(obj, thread); \ |
4006 | 118 HOTSPOT_MONITOR_WAIT(jtid, \ |
119 (monitor), bytes, len, (millis)); \ | |
120 } \ | |
121 } | |
122 | |
123 #define HOTSPOT_MONITOR_contended__enter HOTSPOT_MONITOR_CONTENDED_ENTER | |
124 #define HOTSPOT_MONITOR_contended__entered HOTSPOT_MONITOR_CONTENDED_ENTERED | |
125 #define HOTSPOT_MONITOR_contended__exit HOTSPOT_MONITOR_CONTENDED_EXIT | |
126 #define HOTSPOT_MONITOR_notify HOTSPOT_MONITOR_NOTIFY | |
127 #define HOTSPOT_MONITOR_notifyAll HOTSPOT_MONITOR_NOTIFYALL | |
128 | |
6725
da91efe96a93
6964458: Reimplement class meta-data storage to use native memory
coleenp
parents:
4006
diff
changeset
|
129 #define DTRACE_MONITOR_PROBE(probe, monitor, obj, thread) \ |
4006 | 130 { \ |
131 if (DTraceMonitorProbes) { \ | |
6725
da91efe96a93
6964458: Reimplement class meta-data storage to use native memory
coleenp
parents:
4006
diff
changeset
|
132 DTRACE_MONITOR_PROBE_COMMON(obj, thread); \ |
4006 | 133 HOTSPOT_MONITOR_##probe(jtid, \ |
134 (uintptr_t)(monitor), bytes, len); \ | |
135 } \ | |
136 } | |
137 | |
138 #endif /* USDT2 */ | |
1878 | 139 #else // ndef DTRACE_ENABLED |
140 | |
6725
da91efe96a93
6964458: Reimplement class meta-data storage to use native memory
coleenp
parents:
4006
diff
changeset
|
141 #define DTRACE_MONITOR_WAIT_PROBE(obj, thread, millis, mon) {;} |
da91efe96a93
6964458: Reimplement class meta-data storage to use native memory
coleenp
parents:
4006
diff
changeset
|
142 #define DTRACE_MONITOR_PROBE(probe, obj, thread, mon) {;} |
1878 | 143 |
144 #endif // ndef DTRACE_ENABLED | |
145 | |
146 // Tunables ... | |
147 // The knob* variables are effectively final. Once set they should | |
148 // never be modified hence. Consider using __read_mostly with GCC. | |
149 | |
150 int ObjectMonitor::Knob_Verbose = 0 ; | |
151 int ObjectMonitor::Knob_SpinLimit = 5000 ; // derived by an external tool - | |
152 static int Knob_LogSpins = 0 ; // enable jvmstat tally for spins | |
153 static int Knob_HandOff = 0 ; | |
154 static int Knob_ReportSettings = 0 ; | |
155 | |
156 static int Knob_SpinBase = 0 ; // Floor AKA SpinMin | |
157 static int Knob_SpinBackOff = 0 ; // spin-loop backoff | |
158 static int Knob_CASPenalty = -1 ; // Penalty for failed CAS | |
159 static int Knob_OXPenalty = -1 ; // Penalty for observed _owner change | |
160 static int Knob_SpinSetSucc = 1 ; // spinners set the _succ field | |
161 static int Knob_SpinEarly = 1 ; | |
162 static int Knob_SuccEnabled = 1 ; // futile wake throttling | |
163 static int Knob_SuccRestrict = 0 ; // Limit successors + spinners to at-most-one | |
164 static int Knob_MaxSpinners = -1 ; // Should be a function of # CPUs | |
165 static int Knob_Bonus = 100 ; // spin success bonus | |
166 static int Knob_BonusB = 100 ; // spin success bonus | |
167 static int Knob_Penalty = 200 ; // spin failure penalty | |
168 static int Knob_Poverty = 1000 ; | |
169 static int Knob_SpinAfterFutile = 1 ; // Spin after returning from park() | |
170 static int Knob_FixedSpin = 0 ; | |
171 static int Knob_OState = 3 ; // Spinner checks thread state of _owner | |
172 static int Knob_UsePause = 1 ; | |
173 static int Knob_ExitPolicy = 0 ; | |
174 static int Knob_PreSpin = 10 ; // 20-100 likely better | |
175 static int Knob_ResetEvent = 0 ; | |
176 static int BackOffMask = 0 ; | |
177 | |
178 static int Knob_FastHSSEC = 0 ; | |
179 static int Knob_MoveNotifyee = 2 ; // notify() - disposition of notifyee | |
180 static int Knob_QMode = 0 ; // EntryList-cxq policy - queue discipline | |
181 static volatile int InitDone = 0 ; | |
182 | |
183 #define TrySpin TrySpin_VaryDuration | |
184 | |
185 // ----------------------------------------------------------------------------- | |
186 // Theory of operations -- Monitors lists, thread residency, etc: | |
187 // | |
188 // * A thread acquires ownership of a monitor by successfully | |
189 // CAS()ing the _owner field from null to non-null. | |
190 // | |
191 // * Invariant: A thread appears on at most one monitor list -- | |
192 // cxq, EntryList or WaitSet -- at any one time. | |
193 // | |
194 // * Contending threads "push" themselves onto the cxq with CAS | |
195 // and then spin/park. | |
196 // | |
197 // * After a contending thread eventually acquires the lock it must | |
198 // dequeue itself from either the EntryList or the cxq. | |
199 // | |
200 // * The exiting thread identifies and unparks an "heir presumptive" | |
201 // tentative successor thread on the EntryList. Critically, the | |
202 // exiting thread doesn't unlink the successor thread from the EntryList. | |
203 // After having been unparked, the wakee will recontend for ownership of | |
204 // the monitor. The successor (wakee) will either acquire the lock or | |
205 // re-park itself. | |
206 // | |
207 // Succession is provided for by a policy of competitive handoff. | |
208 // The exiting thread does _not_ grant or pass ownership to the | |
209 // successor thread. (This is also referred to as "handoff" succession"). | |
210 // Instead the exiting thread releases ownership and possibly wakes | |
211 // a successor, so the successor can (re)compete for ownership of the lock. | |
212 // If the EntryList is empty but the cxq is populated the exiting | |
213 // thread will drain the cxq into the EntryList. It does so by | |
214 // by detaching the cxq (installing null with CAS) and folding | |
215 // the threads from the cxq into the EntryList. The EntryList is | |
216 // doubly linked, while the cxq is singly linked because of the | |
217 // CAS-based "push" used to enqueue recently arrived threads (RATs). | |
218 // | |
219 // * Concurrency invariants: | |
220 // | |
221 // -- only the monitor owner may access or mutate the EntryList. | |
222 // The mutex property of the monitor itself protects the EntryList | |
223 // from concurrent interference. | |
224 // -- Only the monitor owner may detach the cxq. | |
225 // | |
226 // * The monitor entry list operations avoid locks, but strictly speaking | |
227 // they're not lock-free. Enter is lock-free, exit is not. | |
228 // See http://j2se.east/~dice/PERSIST/040825-LockFreeQueues.html | |
229 // | |
230 // * The cxq can have multiple concurrent "pushers" but only one concurrent | |
231 // detaching thread. This mechanism is immune from the ABA corruption. | |
232 // More precisely, the CAS-based "push" onto cxq is ABA-oblivious. | |
233 // | |
234 // * Taken together, the cxq and the EntryList constitute or form a | |
235 // single logical queue of threads stalled trying to acquire the lock. | |
236 // We use two distinct lists to improve the odds of a constant-time | |
237 // dequeue operation after acquisition (in the ::enter() epilog) and | |
238 // to reduce heat on the list ends. (c.f. Michael Scott's "2Q" algorithm). | |
239 // A key desideratum is to minimize queue & monitor metadata manipulation | |
240 // that occurs while holding the monitor lock -- that is, we want to | |
241 // minimize monitor lock holds times. Note that even a small amount of | |
242 // fixed spinning will greatly reduce the # of enqueue-dequeue operations | |
243 // on EntryList|cxq. That is, spinning relieves contention on the "inner" | |
244 // locks and monitor metadata. | |
245 // | |
246 // Cxq points to the the set of Recently Arrived Threads attempting entry. | |
247 // Because we push threads onto _cxq with CAS, the RATs must take the form of | |
248 // a singly-linked LIFO. We drain _cxq into EntryList at unlock-time when | |
249 // the unlocking thread notices that EntryList is null but _cxq is != null. | |
250 // | |
251 // The EntryList is ordered by the prevailing queue discipline and | |
252 // can be organized in any convenient fashion, such as a doubly-linked list or | |
253 // a circular doubly-linked list. Critically, we want insert and delete operations | |
254 // to operate in constant-time. If we need a priority queue then something akin | |
255 // to Solaris' sleepq would work nicely. Viz., | |
256 // http://agg.eng/ws/on10_nightly/source/usr/src/uts/common/os/sleepq.c. | |
257 // Queue discipline is enforced at ::exit() time, when the unlocking thread | |
258 // drains the cxq into the EntryList, and orders or reorders the threads on the | |
259 // EntryList accordingly. | |
260 // | |
261 // Barring "lock barging", this mechanism provides fair cyclic ordering, | |
262 // somewhat similar to an elevator-scan. | |
263 // | |
264 // * The monitor synchronization subsystem avoids the use of native | |
265 // synchronization primitives except for the narrow platform-specific | |
266 // park-unpark abstraction. See the comments in os_solaris.cpp regarding | |
267 // the semantics of park-unpark. Put another way, this monitor implementation | |
268 // depends only on atomic operations and park-unpark. The monitor subsystem | |
269 // manages all RUNNING->BLOCKED and BLOCKED->READY transitions while the | |
270 // underlying OS manages the READY<->RUN transitions. | |
271 // | |
272 // * Waiting threads reside on the WaitSet list -- wait() puts | |
273 // the caller onto the WaitSet. | |
274 // | |
275 // * notify() or notifyAll() simply transfers threads from the WaitSet to | |
276 // either the EntryList or cxq. Subsequent exit() operations will | |
277 // unpark the notifyee. Unparking a notifee in notify() is inefficient - | |
278 // it's likely the notifyee would simply impale itself on the lock held | |
279 // by the notifier. | |
280 // | |
281 // * An interesting alternative is to encode cxq as (List,LockByte) where | |
282 // the LockByte is 0 iff the monitor is owned. _owner is simply an auxiliary | |
283 // variable, like _recursions, in the scheme. The threads or Events that form | |
284 // the list would have to be aligned in 256-byte addresses. A thread would | |
285 // try to acquire the lock or enqueue itself with CAS, but exiting threads | |
286 // could use a 1-0 protocol and simply STB to set the LockByte to 0. | |
287 // Note that is is *not* word-tearing, but it does presume that full-word | |
288 // CAS operations are coherent with intermix with STB operations. That's true | |
289 // on most common processors. | |
290 // | |
291 // * See also http://blogs.sun.com/dave | |
292 | |
293 | |
294 // ----------------------------------------------------------------------------- | |
295 // Enter support | |
296 | |
297 bool ObjectMonitor::try_enter(Thread* THREAD) { | |
298 if (THREAD != _owner) { | |
299 if (THREAD->is_lock_owned ((address)_owner)) { | |
300 assert(_recursions == 0, "internal state error"); | |
301 _owner = THREAD ; | |
302 _recursions = 1 ; | |
303 OwnerIsThread = 1 ; | |
304 return true; | |
305 } | |
306 if (Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) != NULL) { | |
307 return false; | |
308 } | |
309 return true; | |
310 } else { | |
311 _recursions++; | |
312 return true; | |
313 } | |
314 } | |
315 | |
316 void ATTR ObjectMonitor::enter(TRAPS) { | |
317 // The following code is ordered to check the most common cases first | |
318 // and to reduce RTS->RTO cache line upgrades on SPARC and IA32 processors. | |
319 Thread * const Self = THREAD ; | |
320 void * cur ; | |
321 | |
322 cur = Atomic::cmpxchg_ptr (Self, &_owner, NULL) ; | |
323 if (cur == NULL) { | |
324 // Either ASSERT _recursions == 0 or explicitly set _recursions = 0. | |
325 assert (_recursions == 0 , "invariant") ; | |
326 assert (_owner == Self, "invariant") ; | |
327 // CONSIDER: set or assert OwnerIsThread == 1 | |
328 return ; | |
329 } | |
330 | |
331 if (cur == Self) { | |
332 // TODO-FIXME: check for integer overflow! BUGID 6557169. | |
333 _recursions ++ ; | |
334 return ; | |
335 } | |
336 | |
337 if (Self->is_lock_owned ((address)cur)) { | |
338 assert (_recursions == 0, "internal state error"); | |
339 _recursions = 1 ; | |
340 // Commute owner from a thread-specific on-stack BasicLockObject address to | |
341 // a full-fledged "Thread *". | |
342 _owner = Self ; | |
343 OwnerIsThread = 1 ; | |
344 return ; | |
345 } | |
346 | |
347 // We've encountered genuine contention. | |
348 assert (Self->_Stalled == 0, "invariant") ; | |
349 Self->_Stalled = intptr_t(this) ; | |
350 | |
351 // Try one round of spinning *before* enqueueing Self | |
352 // and before going through the awkward and expensive state | |
353 // transitions. The following spin is strictly optional ... | |
354 // Note that if we acquire the monitor from an initial spin | |
355 // we forgo posting JVMTI events and firing DTRACE probes. | |
356 if (Knob_SpinEarly && TrySpin (Self) > 0) { | |
357 assert (_owner == Self , "invariant") ; | |
358 assert (_recursions == 0 , "invariant") ; | |
359 assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ; | |
360 Self->_Stalled = 0 ; | |
361 return ; | |
362 } | |
363 | |
364 assert (_owner != Self , "invariant") ; | |
365 assert (_succ != Self , "invariant") ; | |
366 assert (Self->is_Java_thread() , "invariant") ; | |
367 JavaThread * jt = (JavaThread *) Self ; | |
368 assert (!SafepointSynchronize::is_at_safepoint(), "invariant") ; | |
369 assert (jt->thread_state() != _thread_blocked , "invariant") ; | |
370 assert (this->object() != NULL , "invariant") ; | |
371 assert (_count >= 0, "invariant") ; | |
372 | |
373 // Prevent deflation at STW-time. See deflate_idle_monitors() and is_busy(). | |
374 // Ensure the object-monitor relationship remains stable while there's contention. | |
375 Atomic::inc_ptr(&_count); | |
376 | |
10405 | 377 EventJavaMonitorEnter event; |
378 | |
1878 | 379 { // Change java thread status to indicate blocked on monitor enter. |
380 JavaThreadBlockedOnMonitorEnterState jtbmes(jt, this); | |
381 | |
382 DTRACE_MONITOR_PROBE(contended__enter, this, object(), jt); | |
383 if (JvmtiExport::should_post_monitor_contended_enter()) { | |
384 JvmtiExport::post_monitor_contended_enter(jt, this); | |
17693
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
385 |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
386 // The current thread does not yet own the monitor and does not |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
387 // yet appear on any queues that would get it made the successor. |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
388 // This means that the JVMTI_EVENT_MONITOR_CONTENDED_ENTER event |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
389 // handler cannot accidentally consume an unpark() meant for the |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
390 // ParkEvent associated with this ObjectMonitor. |
1878 | 391 } |
392 | |
393 OSThreadContendState osts(Self->osthread()); | |
394 ThreadBlockInVM tbivm(jt); | |
395 | |
396 Self->set_current_pending_monitor(this); | |
397 | |
398 // TODO-FIXME: change the following for(;;) loop to straight-line code. | |
399 for (;;) { | |
400 jt->set_suspend_equivalent(); | |
401 // cleared by handle_special_suspend_equivalent_condition() | |
402 // or java_suspend_self() | |
403 | |
404 EnterI (THREAD) ; | |
405 | |
406 if (!ExitSuspendEquivalent(jt)) break ; | |
407 | |
408 // | |
409 // We have acquired the contended monitor, but while we were | |
410 // waiting another thread suspended us. We don't want to enter | |
411 // the monitor while suspended because that would surprise the | |
412 // thread that suspended us. | |
413 // | |
414 _recursions = 0 ; | |
415 _succ = NULL ; | |
10405 | 416 exit (false, Self) ; |
1878 | 417 |
418 jt->java_suspend_self(); | |
419 } | |
420 Self->set_current_pending_monitor(NULL); | |
421 } | |
422 | |
423 Atomic::dec_ptr(&_count); | |
424 assert (_count >= 0, "invariant") ; | |
425 Self->_Stalled = 0 ; | |
426 | |
427 // Must either set _recursions = 0 or ASSERT _recursions == 0. | |
428 assert (_recursions == 0 , "invariant") ; | |
429 assert (_owner == Self , "invariant") ; | |
430 assert (_succ != Self , "invariant") ; | |
431 assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ; | |
432 | |
433 // The thread -- now the owner -- is back in vm mode. | |
434 // Report the glorious news via TI,DTrace and jvmstat. | |
435 // The probe effect is non-trivial. All the reportage occurs | |
436 // while we hold the monitor, increasing the length of the critical | |
437 // section. Amdahl's parallel speedup law comes vividly into play. | |
438 // | |
439 // Another option might be to aggregate the events (thread local or | |
440 // per-monitor aggregation) and defer reporting until a more opportune | |
441 // time -- such as next time some thread encounters contention but has | |
442 // yet to acquire the lock. While spinning that thread could | |
443 // spinning we could increment JVMStat counters, etc. | |
444 | |
445 DTRACE_MONITOR_PROBE(contended__entered, this, object(), jt); | |
446 if (JvmtiExport::should_post_monitor_contended_entered()) { | |
447 JvmtiExport::post_monitor_contended_entered(jt, this); | |
17693
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
448 |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
449 // The current thread already owns the monitor and is not going to |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
450 // call park() for the remainder of the monitor enter protocol. So |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
451 // it doesn't matter if the JVMTI_EVENT_MONITOR_CONTENDED_ENTERED |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
452 // event handler consumed an unpark() issued by the thread that |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
453 // just exited the monitor. |
1878 | 454 } |
10405 | 455 |
456 if (event.should_commit()) { | |
457 event.set_klass(((oop)this->object())->klass()); | |
458 event.set_previousOwner((TYPE_JAVALANGTHREAD)_previous_owner_tid); | |
459 event.set_address((TYPE_ADDRESS)(uintptr_t)(this->object_addr())); | |
460 event.commit(); | |
461 } | |
462 | |
1878 | 463 if (ObjectMonitor::_sync_ContendedLockAttempts != NULL) { |
464 ObjectMonitor::_sync_ContendedLockAttempts->inc() ; | |
465 } | |
466 } | |
467 | |
468 | |
469 // Caveat: TryLock() is not necessarily serializing if it returns failure. | |
470 // Callers must compensate as needed. | |
471 | |
472 int ObjectMonitor::TryLock (Thread * Self) { | |
473 for (;;) { | |
474 void * own = _owner ; | |
475 if (own != NULL) return 0 ; | |
476 if (Atomic::cmpxchg_ptr (Self, &_owner, NULL) == NULL) { | |
477 // Either guarantee _recursions == 0 or set _recursions = 0. | |
478 assert (_recursions == 0, "invariant") ; | |
479 assert (_owner == Self, "invariant") ; | |
480 // CONSIDER: set or assert that OwnerIsThread == 1 | |
481 return 1 ; | |
482 } | |
483 // The lock had been free momentarily, but we lost the race to the lock. | |
484 // Interference -- the CAS failed. | |
485 // We can either return -1 or retry. | |
486 // Retry doesn't make as much sense because the lock was just acquired. | |
487 if (true) return -1 ; | |
488 } | |
489 } | |
490 | |
491 void ATTR ObjectMonitor::EnterI (TRAPS) { | |
492 Thread * Self = THREAD ; | |
493 assert (Self->is_Java_thread(), "invariant") ; | |
494 assert (((JavaThread *) Self)->thread_state() == _thread_blocked , "invariant") ; | |
495 | |
496 // Try the lock - TATAS | |
497 if (TryLock (Self) > 0) { | |
498 assert (_succ != Self , "invariant") ; | |
499 assert (_owner == Self , "invariant") ; | |
500 assert (_Responsible != Self , "invariant") ; | |
501 return ; | |
502 } | |
503 | |
504 DeferredInitialize () ; | |
505 | |
506 // We try one round of spinning *before* enqueueing Self. | |
507 // | |
508 // If the _owner is ready but OFFPROC we could use a YieldTo() | |
509 // operation to donate the remainder of this thread's quantum | |
510 // to the owner. This has subtle but beneficial affinity | |
511 // effects. | |
512 | |
513 if (TrySpin (Self) > 0) { | |
514 assert (_owner == Self , "invariant") ; | |
515 assert (_succ != Self , "invariant") ; | |
516 assert (_Responsible != Self , "invariant") ; | |
517 return ; | |
518 } | |
519 | |
520 // The Spin failed -- Enqueue and park the thread ... | |
521 assert (_succ != Self , "invariant") ; | |
522 assert (_owner != Self , "invariant") ; | |
523 assert (_Responsible != Self , "invariant") ; | |
524 | |
525 // Enqueue "Self" on ObjectMonitor's _cxq. | |
526 // | |
527 // Node acts as a proxy for Self. | |
528 // As an aside, if were to ever rewrite the synchronization code mostly | |
529 // in Java, WaitNodes, ObjectMonitors, and Events would become 1st-class | |
530 // Java objects. This would avoid awkward lifecycle and liveness issues, | |
531 // as well as eliminate a subset of ABA issues. | |
532 // TODO: eliminate ObjectWaiter and enqueue either Threads or Events. | |
533 // | |
534 | |
535 ObjectWaiter node(Self) ; | |
536 Self->_ParkEvent->reset() ; | |
537 node._prev = (ObjectWaiter *) 0xBAD ; | |
538 node.TState = ObjectWaiter::TS_CXQ ; | |
539 | |
540 // Push "Self" onto the front of the _cxq. | |
541 // Once on cxq/EntryList, Self stays on-queue until it acquires the lock. | |
542 // Note that spinning tends to reduce the rate at which threads | |
543 // enqueue and dequeue on EntryList|cxq. | |
544 ObjectWaiter * nxt ; | |
545 for (;;) { | |
546 node._next = nxt = _cxq ; | |
547 if (Atomic::cmpxchg_ptr (&node, &_cxq, nxt) == nxt) break ; | |
548 | |
549 // Interference - the CAS failed because _cxq changed. Just retry. | |
550 // As an optional optimization we retry the lock. | |
551 if (TryLock (Self) > 0) { | |
552 assert (_succ != Self , "invariant") ; | |
553 assert (_owner == Self , "invariant") ; | |
554 assert (_Responsible != Self , "invariant") ; | |
555 return ; | |
556 } | |
557 } | |
558 | |
559 // Check for cxq|EntryList edge transition to non-null. This indicates | |
560 // the onset of contention. While contention persists exiting threads | |
561 // will use a ST:MEMBAR:LD 1-1 exit protocol. When contention abates exit | |
562 // operations revert to the faster 1-0 mode. This enter operation may interleave | |
563 // (race) a concurrent 1-0 exit operation, resulting in stranding, so we | |
564 // arrange for one of the contending thread to use a timed park() operations | |
565 // to detect and recover from the race. (Stranding is form of progress failure | |
566 // where the monitor is unlocked but all the contending threads remain parked). | |
567 // That is, at least one of the contended threads will periodically poll _owner. | |
568 // One of the contending threads will become the designated "Responsible" thread. | |
569 // The Responsible thread uses a timed park instead of a normal indefinite park | |
570 // operation -- it periodically wakes and checks for and recovers from potential | |
571 // strandings admitted by 1-0 exit operations. We need at most one Responsible | |
572 // thread per-monitor at any given moment. Only threads on cxq|EntryList may | |
573 // be responsible for a monitor. | |
574 // | |
575 // Currently, one of the contended threads takes on the added role of "Responsible". | |
576 // A viable alternative would be to use a dedicated "stranding checker" thread | |
577 // that periodically iterated over all the threads (or active monitors) and unparked | |
578 // successors where there was risk of stranding. This would help eliminate the | |
579 // timer scalability issues we see on some platforms as we'd only have one thread | |
580 // -- the checker -- parked on a timer. | |
581 | |
582 if ((SyncFlags & 16) == 0 && nxt == NULL && _EntryList == NULL) { | |
583 // Try to assume the role of responsible thread for the monitor. | |
584 // CONSIDER: ST vs CAS vs { if (Responsible==null) Responsible=Self } | |
585 Atomic::cmpxchg_ptr (Self, &_Responsible, NULL) ; | |
586 } | |
587 | |
588 // The lock have been released while this thread was occupied queueing | |
589 // itself onto _cxq. To close the race and avoid "stranding" and | |
590 // progress-liveness failure we must resample-retry _owner before parking. | |
591 // Note the Dekker/Lamport duality: ST cxq; MEMBAR; LD Owner. | |
592 // In this case the ST-MEMBAR is accomplished with CAS(). | |
593 // | |
594 // TODO: Defer all thread state transitions until park-time. | |
595 // Since state transitions are heavy and inefficient we'd like | |
596 // to defer the state transitions until absolutely necessary, | |
597 // and in doing so avoid some transitions ... | |
598 | |
599 TEVENT (Inflated enter - Contention) ; | |
600 int nWakeups = 0 ; | |
601 int RecheckInterval = 1 ; | |
602 | |
603 for (;;) { | |
604 | |
605 if (TryLock (Self) > 0) break ; | |
606 assert (_owner != Self, "invariant") ; | |
607 | |
608 if ((SyncFlags & 2) && _Responsible == NULL) { | |
609 Atomic::cmpxchg_ptr (Self, &_Responsible, NULL) ; | |
610 } | |
611 | |
612 // park self | |
613 if (_Responsible == Self || (SyncFlags & 1)) { | |
614 TEVENT (Inflated enter - park TIMED) ; | |
615 Self->_ParkEvent->park ((jlong) RecheckInterval) ; | |
616 // Increase the RecheckInterval, but clamp the value. | |
617 RecheckInterval *= 8 ; | |
618 if (RecheckInterval > 1000) RecheckInterval = 1000 ; | |
619 } else { | |
620 TEVENT (Inflated enter - park UNTIMED) ; | |
621 Self->_ParkEvent->park() ; | |
622 } | |
623 | |
624 if (TryLock(Self) > 0) break ; | |
625 | |
626 // The lock is still contested. | |
627 // Keep a tally of the # of futile wakeups. | |
628 // Note that the counter is not protected by a lock or updated by atomics. | |
629 // That is by design - we trade "lossy" counters which are exposed to | |
630 // races during updates for a lower probe effect. | |
631 TEVENT (Inflated enter - Futile wakeup) ; | |
632 if (ObjectMonitor::_sync_FutileWakeups != NULL) { | |
633 ObjectMonitor::_sync_FutileWakeups->inc() ; | |
634 } | |
635 ++ nWakeups ; | |
636 | |
637 // Assuming this is not a spurious wakeup we'll normally find _succ == Self. | |
638 // We can defer clearing _succ until after the spin completes | |
639 // TrySpin() must tolerate being called with _succ == Self. | |
640 // Try yet another round of adaptive spinning. | |
641 if ((Knob_SpinAfterFutile & 1) && TrySpin (Self) > 0) break ; | |
642 | |
643 // We can find that we were unpark()ed and redesignated _succ while | |
644 // we were spinning. That's harmless. If we iterate and call park(), | |
645 // park() will consume the event and return immediately and we'll | |
646 // just spin again. This pattern can repeat, leaving _succ to simply | |
647 // spin on a CPU. Enable Knob_ResetEvent to clear pending unparks(). | |
648 // Alternately, we can sample fired() here, and if set, forgo spinning | |
649 // in the next iteration. | |
650 | |
651 if ((Knob_ResetEvent & 1) && Self->_ParkEvent->fired()) { | |
652 Self->_ParkEvent->reset() ; | |
653 OrderAccess::fence() ; | |
654 } | |
655 if (_succ == Self) _succ = NULL ; | |
656 | |
657 // Invariant: after clearing _succ a thread *must* retry _owner before parking. | |
658 OrderAccess::fence() ; | |
659 } | |
660 | |
661 // Egress : | |
662 // Self has acquired the lock -- Unlink Self from the cxq or EntryList. | |
663 // Normally we'll find Self on the EntryList . | |
664 // From the perspective of the lock owner (this thread), the | |
665 // EntryList is stable and cxq is prepend-only. | |
666 // The head of cxq is volatile but the interior is stable. | |
667 // In addition, Self.TState is stable. | |
668 | |
669 assert (_owner == Self , "invariant") ; | |
670 assert (object() != NULL , "invariant") ; | |
671 // I'd like to write: | |
672 // guarantee (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ; | |
673 // but as we're at a safepoint that's not safe. | |
674 | |
675 UnlinkAfterAcquire (Self, &node) ; | |
676 if (_succ == Self) _succ = NULL ; | |
677 | |
678 assert (_succ != Self, "invariant") ; | |
679 if (_Responsible == Self) { | |
680 _Responsible = NULL ; | |
7629
22ba8c8ce6a6
8004902: correctness fixes motivated by contended locking work (6607129)
dcubed
parents:
7180
diff
changeset
|
681 OrderAccess::fence(); // Dekker pivot-point |
1878 | 682 |
683 // We may leave threads on cxq|EntryList without a designated | |
684 // "Responsible" thread. This is benign. When this thread subsequently | |
685 // exits the monitor it can "see" such preexisting "old" threads -- | |
686 // threads that arrived on the cxq|EntryList before the fence, above -- | |
687 // by LDing cxq|EntryList. Newly arrived threads -- that is, threads | |
688 // that arrive on cxq after the ST:MEMBAR, above -- will set Responsible | |
689 // non-null and elect a new "Responsible" timer thread. | |
690 // | |
691 // This thread executes: | |
692 // ST Responsible=null; MEMBAR (in enter epilog - here) | |
693 // LD cxq|EntryList (in subsequent exit) | |
694 // | |
695 // Entering threads in the slow/contended path execute: | |
696 // ST cxq=nonnull; MEMBAR; LD Responsible (in enter prolog) | |
697 // The (ST cxq; MEMBAR) is accomplished with CAS(). | |
698 // | |
699 // The MEMBAR, above, prevents the LD of cxq|EntryList in the subsequent | |
700 // exit operation from floating above the ST Responsible=null. | |
701 } | |
702 | |
703 // We've acquired ownership with CAS(). | |
704 // CAS is serializing -- it has MEMBAR/FENCE-equivalent semantics. | |
705 // But since the CAS() this thread may have also stored into _succ, | |
706 // EntryList, cxq or Responsible. These meta-data updates must be | |
707 // visible __before this thread subsequently drops the lock. | |
708 // Consider what could occur if we didn't enforce this constraint -- | |
709 // STs to monitor meta-data and user-data could reorder with (become | |
710 // visible after) the ST in exit that drops ownership of the lock. | |
711 // Some other thread could then acquire the lock, but observe inconsistent | |
712 // or old monitor meta-data and heap data. That violates the JMM. | |
713 // To that end, the 1-0 exit() operation must have at least STST|LDST | |
714 // "release" barrier semantics. Specifically, there must be at least a | |
715 // STST|LDST barrier in exit() before the ST of null into _owner that drops | |
716 // the lock. The barrier ensures that changes to monitor meta-data and data | |
717 // protected by the lock will be visible before we release the lock, and | |
718 // therefore before some other thread (CPU) has a chance to acquire the lock. | |
719 // See also: http://gee.cs.oswego.edu/dl/jmm/cookbook.html. | |
720 // | |
721 // Critically, any prior STs to _succ or EntryList must be visible before | |
722 // the ST of null into _owner in the *subsequent* (following) corresponding | |
723 // monitorexit. Recall too, that in 1-0 mode monitorexit does not necessarily | |
724 // execute a serializing instruction. | |
725 | |
726 if (SyncFlags & 8) { | |
727 OrderAccess::fence() ; | |
728 } | |
729 return ; | |
730 } | |
731 | |
732 // ReenterI() is a specialized inline form of the latter half of the | |
733 // contended slow-path from EnterI(). We use ReenterI() only for | |
734 // monitor reentry in wait(). | |
735 // | |
736 // In the future we should reconcile EnterI() and ReenterI(), adding | |
737 // Knob_Reset and Knob_SpinAfterFutile support and restructuring the | |
738 // loop accordingly. | |
739 | |
740 void ATTR ObjectMonitor::ReenterI (Thread * Self, ObjectWaiter * SelfNode) { | |
741 assert (Self != NULL , "invariant") ; | |
742 assert (SelfNode != NULL , "invariant") ; | |
743 assert (SelfNode->_thread == Self , "invariant") ; | |
744 assert (_waiters > 0 , "invariant") ; | |
745 assert (((oop)(object()))->mark() == markOopDesc::encode(this) , "invariant") ; | |
746 assert (((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant") ; | |
747 JavaThread * jt = (JavaThread *) Self ; | |
748 | |
749 int nWakeups = 0 ; | |
750 for (;;) { | |
751 ObjectWaiter::TStates v = SelfNode->TState ; | |
752 guarantee (v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant") ; | |
753 assert (_owner != Self, "invariant") ; | |
754 | |
755 if (TryLock (Self) > 0) break ; | |
756 if (TrySpin (Self) > 0) break ; | |
757 | |
758 TEVENT (Wait Reentry - parking) ; | |
759 | |
760 // State transition wrappers around park() ... | |
761 // ReenterI() wisely defers state transitions until | |
762 // it's clear we must park the thread. | |
763 { | |
764 OSThreadContendState osts(Self->osthread()); | |
765 ThreadBlockInVM tbivm(jt); | |
766 | |
767 // cleared by handle_special_suspend_equivalent_condition() | |
768 // or java_suspend_self() | |
769 jt->set_suspend_equivalent(); | |
770 if (SyncFlags & 1) { | |
771 Self->_ParkEvent->park ((jlong)1000) ; | |
772 } else { | |
773 Self->_ParkEvent->park () ; | |
774 } | |
775 | |
776 // were we externally suspended while we were waiting? | |
777 for (;;) { | |
778 if (!ExitSuspendEquivalent (jt)) break ; | |
779 if (_succ == Self) { _succ = NULL; OrderAccess::fence(); } | |
780 jt->java_suspend_self(); | |
781 jt->set_suspend_equivalent(); | |
782 } | |
783 } | |
784 | |
785 // Try again, but just so we distinguish between futile wakeups and | |
786 // successful wakeups. The following test isn't algorithmically | |
787 // necessary, but it helps us maintain sensible statistics. | |
788 if (TryLock(Self) > 0) break ; | |
789 | |
790 // The lock is still contested. | |
791 // Keep a tally of the # of futile wakeups. | |
792 // Note that the counter is not protected by a lock or updated by atomics. | |
793 // That is by design - we trade "lossy" counters which are exposed to | |
794 // races during updates for a lower probe effect. | |
795 TEVENT (Wait Reentry - futile wakeup) ; | |
796 ++ nWakeups ; | |
797 | |
798 // Assuming this is not a spurious wakeup we'll normally | |
799 // find that _succ == Self. | |
800 if (_succ == Self) _succ = NULL ; | |
801 | |
802 // Invariant: after clearing _succ a contending thread | |
803 // *must* retry _owner before parking. | |
804 OrderAccess::fence() ; | |
805 | |
806 if (ObjectMonitor::_sync_FutileWakeups != NULL) { | |
807 ObjectMonitor::_sync_FutileWakeups->inc() ; | |
808 } | |
809 } | |
810 | |
811 // Self has acquired the lock -- Unlink Self from the cxq or EntryList . | |
812 // Normally we'll find Self on the EntryList. | |
813 // Unlinking from the EntryList is constant-time and atomic-free. | |
814 // From the perspective of the lock owner (this thread), the | |
815 // EntryList is stable and cxq is prepend-only. | |
816 // The head of cxq is volatile but the interior is stable. | |
817 // In addition, Self.TState is stable. | |
818 | |
819 assert (_owner == Self, "invariant") ; | |
820 assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ; | |
821 UnlinkAfterAcquire (Self, SelfNode) ; | |
822 if (_succ == Self) _succ = NULL ; | |
823 assert (_succ != Self, "invariant") ; | |
824 SelfNode->TState = ObjectWaiter::TS_RUN ; | |
825 OrderAccess::fence() ; // see comments at the end of EnterI() | |
826 } | |
827 | |
828 // after the thread acquires the lock in ::enter(). Equally, we could defer | |
829 // unlinking the thread until ::exit()-time. | |
830 | |
831 void ObjectMonitor::UnlinkAfterAcquire (Thread * Self, ObjectWaiter * SelfNode) | |
832 { | |
833 assert (_owner == Self, "invariant") ; | |
834 assert (SelfNode->_thread == Self, "invariant") ; | |
835 | |
836 if (SelfNode->TState == ObjectWaiter::TS_ENTER) { | |
837 // Normal case: remove Self from the DLL EntryList . | |
838 // This is a constant-time operation. | |
839 ObjectWaiter * nxt = SelfNode->_next ; | |
840 ObjectWaiter * prv = SelfNode->_prev ; | |
841 if (nxt != NULL) nxt->_prev = prv ; | |
842 if (prv != NULL) prv->_next = nxt ; | |
843 if (SelfNode == _EntryList ) _EntryList = nxt ; | |
844 assert (nxt == NULL || nxt->TState == ObjectWaiter::TS_ENTER, "invariant") ; | |
845 assert (prv == NULL || prv->TState == ObjectWaiter::TS_ENTER, "invariant") ; | |
846 TEVENT (Unlink from EntryList) ; | |
847 } else { | |
848 guarantee (SelfNode->TState == ObjectWaiter::TS_CXQ, "invariant") ; | |
849 // Inopportune interleaving -- Self is still on the cxq. | |
850 // This usually means the enqueue of self raced an exiting thread. | |
851 // Normally we'll find Self near the front of the cxq, so | |
852 // dequeueing is typically fast. If needbe we can accelerate | |
853 // this with some MCS/CHL-like bidirectional list hints and advisory | |
854 // back-links so dequeueing from the interior will normally operate | |
855 // in constant-time. | |
856 // Dequeue Self from either the head (with CAS) or from the interior | |
857 // with a linear-time scan and normal non-atomic memory operations. | |
858 // CONSIDER: if Self is on the cxq then simply drain cxq into EntryList | |
859 // and then unlink Self from EntryList. We have to drain eventually, | |
860 // so it might as well be now. | |
861 | |
862 ObjectWaiter * v = _cxq ; | |
863 assert (v != NULL, "invariant") ; | |
864 if (v != SelfNode || Atomic::cmpxchg_ptr (SelfNode->_next, &_cxq, v) != v) { | |
865 // The CAS above can fail from interference IFF a "RAT" arrived. | |
866 // In that case Self must be in the interior and can no longer be | |
867 // at the head of cxq. | |
868 if (v == SelfNode) { | |
869 assert (_cxq != v, "invariant") ; | |
870 v = _cxq ; // CAS above failed - start scan at head of list | |
871 } | |
872 ObjectWaiter * p ; | |
873 ObjectWaiter * q = NULL ; | |
874 for (p = v ; p != NULL && p != SelfNode; p = p->_next) { | |
875 q = p ; | |
876 assert (p->TState == ObjectWaiter::TS_CXQ, "invariant") ; | |
877 } | |
878 assert (v != SelfNode, "invariant") ; | |
879 assert (p == SelfNode, "Node not found on cxq") ; | |
880 assert (p != _cxq, "invariant") ; | |
881 assert (q != NULL, "invariant") ; | |
882 assert (q->_next == p, "invariant") ; | |
883 q->_next = p->_next ; | |
884 } | |
885 TEVENT (Unlink from cxq) ; | |
886 } | |
887 | |
888 // Diagnostic hygiene ... | |
889 SelfNode->_prev = (ObjectWaiter *) 0xBAD ; | |
890 SelfNode->_next = (ObjectWaiter *) 0xBAD ; | |
891 SelfNode->TState = ObjectWaiter::TS_RUN ; | |
892 } | |
893 | |
894 // ----------------------------------------------------------------------------- | |
895 // Exit support | |
896 // | |
897 // exit() | |
898 // ~~~~~~ | |
899 // Note that the collector can't reclaim the objectMonitor or deflate | |
900 // the object out from underneath the thread calling ::exit() as the | |
901 // thread calling ::exit() never transitions to a stable state. | |
902 // This inhibits GC, which in turn inhibits asynchronous (and | |
903 // inopportune) reclamation of "this". | |
904 // | |
905 // We'd like to assert that: (THREAD->thread_state() != _thread_blocked) ; | |
906 // There's one exception to the claim above, however. EnterI() can call | |
907 // exit() to drop a lock if the acquirer has been externally suspended. | |
908 // In that case exit() is called with _thread_state as _thread_blocked, | |
909 // but the monitor's _count field is > 0, which inhibits reclamation. | |
910 // | |
911 // 1-0 exit | |
912 // ~~~~~~~~ | |
913 // ::exit() uses a canonical 1-1 idiom with a MEMBAR although some of | |
914 // the fast-path operators have been optimized so the common ::exit() | |
915 // operation is 1-0. See i486.ad fast_unlock(), for instance. | |
916 // The code emitted by fast_unlock() elides the usual MEMBAR. This | |
917 // greatly improves latency -- MEMBAR and CAS having considerable local | |
918 // latency on modern processors -- but at the cost of "stranding". Absent the | |
919 // MEMBAR, a thread in fast_unlock() can race a thread in the slow | |
920 // ::enter() path, resulting in the entering thread being stranding | |
921 // and a progress-liveness failure. Stranding is extremely rare. | |
922 // We use timers (timed park operations) & periodic polling to detect | |
923 // and recover from stranding. Potentially stranded threads periodically | |
924 // wake up and poll the lock. See the usage of the _Responsible variable. | |
925 // | |
926 // The CAS() in enter provides for safety and exclusion, while the CAS or | |
927 // MEMBAR in exit provides for progress and avoids stranding. 1-0 locking | |
928 // eliminates the CAS/MEMBAR from the exist path, but it admits stranding. | |
929 // We detect and recover from stranding with timers. | |
930 // | |
931 // If a thread transiently strands it'll park until (a) another | |
932 // thread acquires the lock and then drops the lock, at which time the | |
933 // exiting thread will notice and unpark the stranded thread, or, (b) | |
934 // the timer expires. If the lock is high traffic then the stranding latency | |
935 // will be low due to (a). If the lock is low traffic then the odds of | |
936 // stranding are lower, although the worst-case stranding latency | |
937 // is longer. Critically, we don't want to put excessive load in the | |
938 // platform's timer subsystem. We want to minimize both the timer injection | |
939 // rate (timers created/sec) as well as the number of timers active at | |
940 // any one time. (more precisely, we want to minimize timer-seconds, which is | |
941 // the integral of the # of active timers at any instant over time). | |
942 // Both impinge on OS scalability. Given that, at most one thread parked on | |
943 // a monitor will use a timer. | |
944 | |
10405 | 945 void ATTR ObjectMonitor::exit(bool not_suspended, TRAPS) { |
1878 | 946 Thread * Self = THREAD ; |
947 if (THREAD != _owner) { | |
948 if (THREAD->is_lock_owned((address) _owner)) { | |
949 // Transmute _owner from a BasicLock pointer to a Thread address. | |
950 // We don't need to hold _mutex for this transition. | |
951 // Non-null to Non-null is safe as long as all readers can | |
952 // tolerate either flavor. | |
953 assert (_recursions == 0, "invariant") ; | |
954 _owner = THREAD ; | |
955 _recursions = 0 ; | |
956 OwnerIsThread = 1 ; | |
957 } else { | |
958 // NOTE: we need to handle unbalanced monitor enter/exit | |
959 // in native code by throwing an exception. | |
960 // TODO: Throw an IllegalMonitorStateException ? | |
961 TEVENT (Exit - Throw IMSX) ; | |
962 assert(false, "Non-balanced monitor enter/exit!"); | |
963 if (false) { | |
964 THROW(vmSymbols::java_lang_IllegalMonitorStateException()); | |
965 } | |
966 return; | |
967 } | |
968 } | |
969 | |
970 if (_recursions != 0) { | |
971 _recursions--; // this is simple recursive enter | |
972 TEVENT (Inflated exit - recursive) ; | |
973 return ; | |
974 } | |
975 | |
976 // Invariant: after setting Responsible=null an thread must execute | |
977 // a MEMBAR or other serializing instruction before fetching EntryList|cxq. | |
978 if ((SyncFlags & 4) == 0) { | |
979 _Responsible = NULL ; | |
980 } | |
981 | |
10405 | 982 #if INCLUDE_TRACE |
983 // get the owner's thread id for the MonitorEnter event | |
984 // if it is enabled and the thread isn't suspended | |
985 if (not_suspended && Tracing::is_event_enabled(TraceJavaMonitorEnterEvent)) { | |
986 _previous_owner_tid = SharedRuntime::get_java_tid(Self); | |
987 } | |
988 #endif | |
989 | |
1878 | 990 for (;;) { |
991 assert (THREAD == _owner, "invariant") ; | |
992 | |
993 | |
994 if (Knob_ExitPolicy == 0) { | |
995 // release semantics: prior loads and stores from within the critical section | |
996 // must not float (reorder) past the following store that drops the lock. | |
997 // On SPARC that requires MEMBAR #loadstore|#storestore. | |
998 // But of course in TSO #loadstore|#storestore is not required. | |
999 // I'd like to write one of the following: | |
1000 // A. OrderAccess::release() ; _owner = NULL | |
1001 // B. OrderAccess::loadstore(); OrderAccess::storestore(); _owner = NULL; | |
1002 // Unfortunately OrderAccess::release() and OrderAccess::loadstore() both | |
1003 // store into a _dummy variable. That store is not needed, but can result | |
1004 // in massive wasteful coherency traffic on classic SMP systems. | |
1005 // Instead, I use release_store(), which is implemented as just a simple | |
1006 // ST on x64, x86 and SPARC. | |
1007 OrderAccess::release_store_ptr (&_owner, NULL) ; // drop the lock | |
1008 OrderAccess::storeload() ; // See if we need to wake a successor | |
1009 if ((intptr_t(_EntryList)|intptr_t(_cxq)) == 0 || _succ != NULL) { | |
1010 TEVENT (Inflated exit - simple egress) ; | |
1011 return ; | |
1012 } | |
1013 TEVENT (Inflated exit - complex egress) ; | |
1014 | |
1015 // Normally the exiting thread is responsible for ensuring succession, | |
1016 // but if other successors are ready or other entering threads are spinning | |
1017 // then this thread can simply store NULL into _owner and exit without | |
1018 // waking a successor. The existence of spinners or ready successors | |
1019 // guarantees proper succession (liveness). Responsibility passes to the | |
1020 // ready or running successors. The exiting thread delegates the duty. | |
1021 // More precisely, if a successor already exists this thread is absolved | |
1022 // of the responsibility of waking (unparking) one. | |
1023 // | |
1024 // The _succ variable is critical to reducing futile wakeup frequency. | |
1025 // _succ identifies the "heir presumptive" thread that has been made | |
1026 // ready (unparked) but that has not yet run. We need only one such | |
1027 // successor thread to guarantee progress. | |
1028 // See http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf | |
1029 // section 3.3 "Futile Wakeup Throttling" for details. | |
1030 // | |
1031 // Note that spinners in Enter() also set _succ non-null. | |
1032 // In the current implementation spinners opportunistically set | |
1033 // _succ so that exiting threads might avoid waking a successor. | |
1034 // Another less appealing alternative would be for the exiting thread | |
1035 // to drop the lock and then spin briefly to see if a spinner managed | |
1036 // to acquire the lock. If so, the exiting thread could exit | |
1037 // immediately without waking a successor, otherwise the exiting | |
1038 // thread would need to dequeue and wake a successor. | |
1039 // (Note that we'd need to make the post-drop spin short, but no | |
1040 // shorter than the worst-case round-trip cache-line migration time. | |
1041 // The dropped lock needs to become visible to the spinner, and then | |
1042 // the acquisition of the lock by the spinner must become visible to | |
1043 // the exiting thread). | |
1044 // | |
1045 | |
1046 // It appears that an heir-presumptive (successor) must be made ready. | |
1047 // Only the current lock owner can manipulate the EntryList or | |
1048 // drain _cxq, so we need to reacquire the lock. If we fail | |
1049 // to reacquire the lock the responsibility for ensuring succession | |
1050 // falls to the new owner. | |
1051 // | |
1052 if (Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) != NULL) { | |
1053 return ; | |
1054 } | |
1055 TEVENT (Exit - Reacquired) ; | |
1056 } else { | |
1057 if ((intptr_t(_EntryList)|intptr_t(_cxq)) == 0 || _succ != NULL) { | |
1058 OrderAccess::release_store_ptr (&_owner, NULL) ; // drop the lock | |
1059 OrderAccess::storeload() ; | |
1060 // Ratify the previously observed values. | |
1061 if (_cxq == NULL || _succ != NULL) { | |
1062 TEVENT (Inflated exit - simple egress) ; | |
1063 return ; | |
1064 } | |
1065 | |
1066 // inopportune interleaving -- the exiting thread (this thread) | |
1067 // in the fast-exit path raced an entering thread in the slow-enter | |
1068 // path. | |
1069 // We have two choices: | |
1070 // A. Try to reacquire the lock. | |
1071 // If the CAS() fails return immediately, otherwise | |
1072 // we either restart/rerun the exit operation, or simply | |
1073 // fall-through into the code below which wakes a successor. | |
1074 // B. If the elements forming the EntryList|cxq are TSM | |
1075 // we could simply unpark() the lead thread and return | |
1076 // without having set _succ. | |
1077 if (Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) != NULL) { | |
1078 TEVENT (Inflated exit - reacquired succeeded) ; | |
1079 return ; | |
1080 } | |
1081 TEVENT (Inflated exit - reacquired failed) ; | |
1082 } else { | |
1083 TEVENT (Inflated exit - complex egress) ; | |
1084 } | |
1085 } | |
1086 | |
1087 guarantee (_owner == THREAD, "invariant") ; | |
1088 | |
1089 ObjectWaiter * w = NULL ; | |
1090 int QMode = Knob_QMode ; | |
1091 | |
1092 if (QMode == 2 && _cxq != NULL) { | |
1093 // QMode == 2 : cxq has precedence over EntryList. | |
1094 // Try to directly wake a successor from the cxq. | |
1095 // If successful, the successor will need to unlink itself from cxq. | |
1096 w = _cxq ; | |
1097 assert (w != NULL, "invariant") ; | |
1098 assert (w->TState == ObjectWaiter::TS_CXQ, "Invariant") ; | |
1099 ExitEpilog (Self, w) ; | |
1100 return ; | |
1101 } | |
1102 | |
1103 if (QMode == 3 && _cxq != NULL) { | |
1104 // Aggressively drain cxq into EntryList at the first opportunity. | |
1105 // This policy ensure that recently-run threads live at the head of EntryList. | |
1106 // Drain _cxq into EntryList - bulk transfer. | |
1107 // First, detach _cxq. | |
1108 // The following loop is tantamount to: w = swap (&cxq, NULL) | |
1109 w = _cxq ; | |
1110 for (;;) { | |
1111 assert (w != NULL, "Invariant") ; | |
1112 ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr (NULL, &_cxq, w) ; | |
1113 if (u == w) break ; | |
1114 w = u ; | |
1115 } | |
1116 assert (w != NULL , "invariant") ; | |
1117 | |
1118 ObjectWaiter * q = NULL ; | |
1119 ObjectWaiter * p ; | |
1120 for (p = w ; p != NULL ; p = p->_next) { | |
1121 guarantee (p->TState == ObjectWaiter::TS_CXQ, "Invariant") ; | |
1122 p->TState = ObjectWaiter::TS_ENTER ; | |
1123 p->_prev = q ; | |
1124 q = p ; | |
1125 } | |
1126 | |
1127 // Append the RATs to the EntryList | |
1128 // TODO: organize EntryList as a CDLL so we can locate the tail in constant-time. | |
1129 ObjectWaiter * Tail ; | |
1130 for (Tail = _EntryList ; Tail != NULL && Tail->_next != NULL ; Tail = Tail->_next) ; | |
1131 if (Tail == NULL) { | |
1132 _EntryList = w ; | |
1133 } else { | |
1134 Tail->_next = w ; | |
1135 w->_prev = Tail ; | |
1136 } | |
1137 | |
1138 // Fall thru into code that tries to wake a successor from EntryList | |
1139 } | |
1140 | |
1141 if (QMode == 4 && _cxq != NULL) { | |
1142 // Aggressively drain cxq into EntryList at the first opportunity. | |
1143 // This policy ensure that recently-run threads live at the head of EntryList. | |
1144 | |
1145 // Drain _cxq into EntryList - bulk transfer. | |
1146 // First, detach _cxq. | |
1147 // The following loop is tantamount to: w = swap (&cxq, NULL) | |
1148 w = _cxq ; | |
1149 for (;;) { | |
1150 assert (w != NULL, "Invariant") ; | |
1151 ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr (NULL, &_cxq, w) ; | |
1152 if (u == w) break ; | |
1153 w = u ; | |
1154 } | |
1155 assert (w != NULL , "invariant") ; | |
1156 | |
1157 ObjectWaiter * q = NULL ; | |
1158 ObjectWaiter * p ; | |
1159 for (p = w ; p != NULL ; p = p->_next) { | |
1160 guarantee (p->TState == ObjectWaiter::TS_CXQ, "Invariant") ; | |
1161 p->TState = ObjectWaiter::TS_ENTER ; | |
1162 p->_prev = q ; | |
1163 q = p ; | |
1164 } | |
1165 | |
1166 // Prepend the RATs to the EntryList | |
1167 if (_EntryList != NULL) { | |
1168 q->_next = _EntryList ; | |
1169 _EntryList->_prev = q ; | |
1170 } | |
1171 _EntryList = w ; | |
1172 | |
1173 // Fall thru into code that tries to wake a successor from EntryList | |
1174 } | |
1175 | |
1176 w = _EntryList ; | |
1177 if (w != NULL) { | |
1178 // I'd like to write: guarantee (w->_thread != Self). | |
1179 // But in practice an exiting thread may find itself on the EntryList. | |
1180 // Lets say thread T1 calls O.wait(). Wait() enqueues T1 on O's waitset and | |
1181 // then calls exit(). Exit release the lock by setting O._owner to NULL. | |
1182 // Lets say T1 then stalls. T2 acquires O and calls O.notify(). The | |
1183 // notify() operation moves T1 from O's waitset to O's EntryList. T2 then | |
1184 // release the lock "O". T2 resumes immediately after the ST of null into | |
1185 // _owner, above. T2 notices that the EntryList is populated, so it | |
1186 // reacquires the lock and then finds itself on the EntryList. | |
1187 // Given all that, we have to tolerate the circumstance where "w" is | |
1188 // associated with Self. | |
1189 assert (w->TState == ObjectWaiter::TS_ENTER, "invariant") ; | |
1190 ExitEpilog (Self, w) ; | |
1191 return ; | |
1192 } | |
1193 | |
1194 // If we find that both _cxq and EntryList are null then just | |
1195 // re-run the exit protocol from the top. | |
1196 w = _cxq ; | |
1197 if (w == NULL) continue ; | |
1198 | |
1199 // Drain _cxq into EntryList - bulk transfer. | |
1200 // First, detach _cxq. | |
1201 // The following loop is tantamount to: w = swap (&cxq, NULL) | |
1202 for (;;) { | |
1203 assert (w != NULL, "Invariant") ; | |
1204 ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr (NULL, &_cxq, w) ; | |
1205 if (u == w) break ; | |
1206 w = u ; | |
1207 } | |
1208 TEVENT (Inflated exit - drain cxq into EntryList) ; | |
1209 | |
1210 assert (w != NULL , "invariant") ; | |
1211 assert (_EntryList == NULL , "invariant") ; | |
1212 | |
1213 // Convert the LIFO SLL anchored by _cxq into a DLL. | |
1214 // The list reorganization step operates in O(LENGTH(w)) time. | |
1215 // It's critical that this step operate quickly as | |
1216 // "Self" still holds the outer-lock, restricting parallelism | |
1217 // and effectively lengthening the critical section. | |
1218 // Invariant: s chases t chases u. | |
1219 // TODO-FIXME: consider changing EntryList from a DLL to a CDLL so | |
1220 // we have faster access to the tail. | |
1221 | |
1222 if (QMode == 1) { | |
1223 // QMode == 1 : drain cxq to EntryList, reversing order | |
1224 // We also reverse the order of the list. | |
1225 ObjectWaiter * s = NULL ; | |
1226 ObjectWaiter * t = w ; | |
1227 ObjectWaiter * u = NULL ; | |
1228 while (t != NULL) { | |
1229 guarantee (t->TState == ObjectWaiter::TS_CXQ, "invariant") ; | |
1230 t->TState = ObjectWaiter::TS_ENTER ; | |
1231 u = t->_next ; | |
1232 t->_prev = u ; | |
1233 t->_next = s ; | |
1234 s = t; | |
1235 t = u ; | |
1236 } | |
1237 _EntryList = s ; | |
1238 assert (s != NULL, "invariant") ; | |
1239 } else { | |
1240 // QMode == 0 or QMode == 2 | |
1241 _EntryList = w ; | |
1242 ObjectWaiter * q = NULL ; | |
1243 ObjectWaiter * p ; | |
1244 for (p = w ; p != NULL ; p = p->_next) { | |
1245 guarantee (p->TState == ObjectWaiter::TS_CXQ, "Invariant") ; | |
1246 p->TState = ObjectWaiter::TS_ENTER ; | |
1247 p->_prev = q ; | |
1248 q = p ; | |
1249 } | |
1250 } | |
1251 | |
1252 // In 1-0 mode we need: ST EntryList; MEMBAR #storestore; ST _owner = NULL | |
1253 // The MEMBAR is satisfied by the release_store() operation in ExitEpilog(). | |
1254 | |
1255 // See if we can abdicate to a spinner instead of waking a thread. | |
1256 // A primary goal of the implementation is to reduce the | |
1257 // context-switch rate. | |
1258 if (_succ != NULL) continue; | |
1259 | |
1260 w = _EntryList ; | |
1261 if (w != NULL) { | |
1262 guarantee (w->TState == ObjectWaiter::TS_ENTER, "invariant") ; | |
1263 ExitEpilog (Self, w) ; | |
1264 return ; | |
1265 } | |
1266 } | |
1267 } | |
1268 | |
1269 // ExitSuspendEquivalent: | |
1270 // A faster alternate to handle_special_suspend_equivalent_condition() | |
1271 // | |
1272 // handle_special_suspend_equivalent_condition() unconditionally | |
1273 // acquires the SR_lock. On some platforms uncontended MutexLocker() | |
1274 // operations have high latency. Note that in ::enter() we call HSSEC | |
1275 // while holding the monitor, so we effectively lengthen the critical sections. | |
1276 // | |
1277 // There are a number of possible solutions: | |
1278 // | |
1279 // A. To ameliorate the problem we might also defer state transitions | |
1280 // to as late as possible -- just prior to parking. | |
1281 // Given that, we'd call HSSEC after having returned from park(), | |
1282 // but before attempting to acquire the monitor. This is only a | |
1283 // partial solution. It avoids calling HSSEC while holding the | |
1284 // monitor (good), but it still increases successor reacquisition latency -- | |
1285 // the interval between unparking a successor and the time the successor | |
1286 // resumes and retries the lock. See ReenterI(), which defers state transitions. | |
1287 // If we use this technique we can also avoid EnterI()-exit() loop | |
1288 // in ::enter() where we iteratively drop the lock and then attempt | |
1289 // to reacquire it after suspending. | |
1290 // | |
1291 // B. In the future we might fold all the suspend bits into a | |
1292 // composite per-thread suspend flag and then update it with CAS(). | |
1293 // Alternately, a Dekker-like mechanism with multiple variables | |
1294 // would suffice: | |
1295 // ST Self->_suspend_equivalent = false | |
1296 // MEMBAR | |
1297 // LD Self_>_suspend_flags | |
1298 // | |
1299 | |
1300 | |
1301 bool ObjectMonitor::ExitSuspendEquivalent (JavaThread * jSelf) { | |
1302 int Mode = Knob_FastHSSEC ; | |
1303 if (Mode && !jSelf->is_external_suspend()) { | |
1304 assert (jSelf->is_suspend_equivalent(), "invariant") ; | |
1305 jSelf->clear_suspend_equivalent() ; | |
1306 if (2 == Mode) OrderAccess::storeload() ; | |
1307 if (!jSelf->is_external_suspend()) return false ; | |
1308 // We raced a suspension -- fall thru into the slow path | |
1309 TEVENT (ExitSuspendEquivalent - raced) ; | |
1310 jSelf->set_suspend_equivalent() ; | |
1311 } | |
1312 return jSelf->handle_special_suspend_equivalent_condition() ; | |
1313 } | |
1314 | |
1315 | |
1316 void ObjectMonitor::ExitEpilog (Thread * Self, ObjectWaiter * Wakee) { | |
1317 assert (_owner == Self, "invariant") ; | |
1318 | |
1319 // Exit protocol: | |
1320 // 1. ST _succ = wakee | |
1321 // 2. membar #loadstore|#storestore; | |
1322 // 2. ST _owner = NULL | |
1323 // 3. unpark(wakee) | |
1324 | |
1325 _succ = Knob_SuccEnabled ? Wakee->_thread : NULL ; | |
1326 ParkEvent * Trigger = Wakee->_event ; | |
1327 | |
1328 // Hygiene -- once we've set _owner = NULL we can't safely dereference Wakee again. | |
1329 // The thread associated with Wakee may have grabbed the lock and "Wakee" may be | |
1330 // out-of-scope (non-extant). | |
1331 Wakee = NULL ; | |
1332 | |
1333 // Drop the lock | |
1334 OrderAccess::release_store_ptr (&_owner, NULL) ; | |
1335 OrderAccess::fence() ; // ST _owner vs LD in unpark() | |
1336 | |
1337 if (SafepointSynchronize::do_call_back()) { | |
1338 TEVENT (unpark before SAFEPOINT) ; | |
1339 } | |
1340 | |
1341 DTRACE_MONITOR_PROBE(contended__exit, this, object(), Self); | |
1342 Trigger->unpark() ; | |
1343 | |
1344 // Maintain stats and report events to JVMTI | |
1345 if (ObjectMonitor::_sync_Parks != NULL) { | |
1346 ObjectMonitor::_sync_Parks->inc() ; | |
1347 } | |
1348 } | |
1349 | |
1350 | |
1351 // ----------------------------------------------------------------------------- | |
1352 // Class Loader deadlock handling. | |
1353 // | |
1354 // complete_exit exits a lock returning recursion count | |
1355 // complete_exit/reenter operate as a wait without waiting | |
1356 // complete_exit requires an inflated monitor | |
1357 // The _owner field is not always the Thread addr even with an | |
1358 // inflated monitor, e.g. the monitor can be inflated by a non-owning | |
1359 // thread due to contention. | |
1360 intptr_t ObjectMonitor::complete_exit(TRAPS) { | |
1361 Thread * const Self = THREAD; | |
1362 assert(Self->is_Java_thread(), "Must be Java thread!"); | |
1363 JavaThread *jt = (JavaThread *)THREAD; | |
1364 | |
1365 DeferredInitialize(); | |
1366 | |
1367 if (THREAD != _owner) { | |
1368 if (THREAD->is_lock_owned ((address)_owner)) { | |
1369 assert(_recursions == 0, "internal state error"); | |
1370 _owner = THREAD ; /* Convert from basiclock addr to Thread addr */ | |
1371 _recursions = 0 ; | |
1372 OwnerIsThread = 1 ; | |
1373 } | |
1374 } | |
1375 | |
1376 guarantee(Self == _owner, "complete_exit not owner"); | |
1377 intptr_t save = _recursions; // record the old recursion count | |
1378 _recursions = 0; // set the recursion level to be 0 | |
10405 | 1379 exit (true, Self) ; // exit the monitor |
1878 | 1380 guarantee (_owner != Self, "invariant"); |
1381 return save; | |
1382 } | |
1383 | |
1384 // reenter() enters a lock and sets recursion count | |
1385 // complete_exit/reenter operate as a wait without waiting | |
1386 void ObjectMonitor::reenter(intptr_t recursions, TRAPS) { | |
1387 Thread * const Self = THREAD; | |
1388 assert(Self->is_Java_thread(), "Must be Java thread!"); | |
1389 JavaThread *jt = (JavaThread *)THREAD; | |
1390 | |
1391 guarantee(_owner != Self, "reenter already owner"); | |
1392 enter (THREAD); // enter the monitor | |
1393 guarantee (_recursions == 0, "reenter recursion"); | |
1394 _recursions = recursions; | |
1395 return; | |
1396 } | |
1397 | |
1398 | |
1399 // ----------------------------------------------------------------------------- | |
1400 // A macro is used below because there may already be a pending | |
1401 // exception which should not abort the execution of the routines | |
1402 // which use this (which is why we don't put this into check_slow and | |
1403 // call it with a CHECK argument). | |
1404 | |
1405 #define CHECK_OWNER() \ | |
1406 do { \ | |
1407 if (THREAD != _owner) { \ | |
1408 if (THREAD->is_lock_owned((address) _owner)) { \ | |
1409 _owner = THREAD ; /* Convert from basiclock addr to Thread addr */ \ | |
1410 _recursions = 0; \ | |
1411 OwnerIsThread = 1 ; \ | |
1412 } else { \ | |
1413 TEVENT (Throw IMSX) ; \ | |
1414 THROW(vmSymbols::java_lang_IllegalMonitorStateException()); \ | |
1415 } \ | |
1416 } \ | |
1417 } while (false) | |
1418 | |
1419 // check_slow() is a misnomer. It's called to simply to throw an IMSX exception. | |
1420 // TODO-FIXME: remove check_slow() -- it's likely dead. | |
1421 | |
1422 void ObjectMonitor::check_slow(TRAPS) { | |
1423 TEVENT (check_slow - throw IMSX) ; | |
1424 assert(THREAD != _owner && !THREAD->is_lock_owned((address) _owner), "must not be owner"); | |
1425 THROW_MSG(vmSymbols::java_lang_IllegalMonitorStateException(), "current thread not owner"); | |
1426 } | |
1427 | |
1428 static int Adjust (volatile int * adr, int dx) { | |
1429 int v ; | |
1430 for (v = *adr ; Atomic::cmpxchg (v + dx, adr, v) != v; v = *adr) ; | |
1431 return v ; | |
1432 } | |
10405 | 1433 |
1434 // helper method for posting a monitor wait event | |
1435 void ObjectMonitor::post_monitor_wait_event(EventJavaMonitorWait* event, | |
1436 jlong notifier_tid, | |
1437 jlong timeout, | |
1438 bool timedout) { | |
1439 event->set_klass(((oop)this->object())->klass()); | |
1440 event->set_timeout((TYPE_ULONG)timeout); | |
1441 event->set_address((TYPE_ADDRESS)(uintptr_t)(this->object_addr())); | |
1442 event->set_notifier((TYPE_OSTHREAD)notifier_tid); | |
1443 event->set_timedOut((TYPE_BOOLEAN)timedout); | |
1444 event->commit(); | |
1445 } | |
1446 | |
1878 | 1447 // ----------------------------------------------------------------------------- |
1448 // Wait/Notify/NotifyAll | |
1449 // | |
1450 // Note: a subset of changes to ObjectMonitor::wait() | |
1451 // will need to be replicated in complete_exit above | |
1452 void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) { | |
1453 Thread * const Self = THREAD ; | |
1454 assert(Self->is_Java_thread(), "Must be Java thread!"); | |
1455 JavaThread *jt = (JavaThread *)THREAD; | |
1456 | |
1457 DeferredInitialize () ; | |
1458 | |
1459 // Throw IMSX or IEX. | |
1460 CHECK_OWNER(); | |
1461 | |
10405 | 1462 EventJavaMonitorWait event; |
1463 | |
1878 | 1464 // check for a pending interrupt |
1465 if (interruptible && Thread::is_interrupted(Self, true) && !HAS_PENDING_EXCEPTION) { | |
1466 // post monitor waited event. Note that this is past-tense, we are done waiting. | |
1467 if (JvmtiExport::should_post_monitor_waited()) { | |
1468 // Note: 'false' parameter is passed here because the | |
1469 // wait was not timed out due to thread interrupt. | |
1470 JvmtiExport::post_monitor_waited(jt, this, false); | |
17693
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1471 |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1472 // In this short circuit of the monitor wait protocol, the |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1473 // current thread never drops ownership of the monitor and |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1474 // never gets added to the wait queue so the current thread |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1475 // cannot be made the successor. This means that the |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1476 // JVMTI_EVENT_MONITOR_WAITED event handler cannot accidentally |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1477 // consume an unpark() meant for the ParkEvent associated with |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1478 // this ObjectMonitor. |
1878 | 1479 } |
10405 | 1480 if (event.should_commit()) { |
1481 post_monitor_wait_event(&event, 0, millis, false); | |
1482 } | |
1878 | 1483 TEVENT (Wait - Throw IEX) ; |
1484 THROW(vmSymbols::java_lang_InterruptedException()); | |
1485 return ; | |
1486 } | |
10405 | 1487 |
1878 | 1488 TEVENT (Wait) ; |
1489 | |
1490 assert (Self->_Stalled == 0, "invariant") ; | |
1491 Self->_Stalled = intptr_t(this) ; | |
1492 jt->set_current_waiting_monitor(this); | |
1493 | |
1494 // create a node to be put into the queue | |
1495 // Critically, after we reset() the event but prior to park(), we must check | |
1496 // for a pending interrupt. | |
1497 ObjectWaiter node(Self); | |
1498 node.TState = ObjectWaiter::TS_WAIT ; | |
1499 Self->_ParkEvent->reset() ; | |
1500 OrderAccess::fence(); // ST into Event; membar ; LD interrupted-flag | |
1501 | |
1502 // Enter the waiting queue, which is a circular doubly linked list in this case | |
1503 // but it could be a priority queue or any data structure. | |
1504 // _WaitSetLock protects the wait queue. Normally the wait queue is accessed only | |
1505 // by the the owner of the monitor *except* in the case where park() | |
1506 // returns because of a timeout of interrupt. Contention is exceptionally rare | |
1507 // so we use a simple spin-lock instead of a heavier-weight blocking lock. | |
1508 | |
1509 Thread::SpinAcquire (&_WaitSetLock, "WaitSet - add") ; | |
1510 AddWaiter (&node) ; | |
1511 Thread::SpinRelease (&_WaitSetLock) ; | |
1512 | |
1513 if ((SyncFlags & 4) == 0) { | |
1514 _Responsible = NULL ; | |
1515 } | |
1516 intptr_t save = _recursions; // record the old recursion count | |
1517 _waiters++; // increment the number of waiters | |
1518 _recursions = 0; // set the recursion level to be 1 | |
10405 | 1519 exit (true, Self) ; // exit the monitor |
1878 | 1520 guarantee (_owner != Self, "invariant") ; |
1521 | |
1522 // The thread is on the WaitSet list - now park() it. | |
1523 // On MP systems it's conceivable that a brief spin before we park | |
1524 // could be profitable. | |
1525 // | |
1526 // TODO-FIXME: change the following logic to a loop of the form | |
1527 // while (!timeout && !interrupted && _notified == 0) park() | |
1528 | |
1529 int ret = OS_OK ; | |
1530 int WasNotified = 0 ; | |
1531 { // State transition wrappers | |
1532 OSThread* osthread = Self->osthread(); | |
1533 OSThreadWaitState osts(osthread, true); | |
1534 { | |
1535 ThreadBlockInVM tbivm(jt); | |
1536 // Thread is in thread_blocked state and oop access is unsafe. | |
1537 jt->set_suspend_equivalent(); | |
1538 | |
1539 if (interruptible && (Thread::is_interrupted(THREAD, false) || HAS_PENDING_EXCEPTION)) { | |
1540 // Intentionally empty | |
1541 } else | |
1542 if (node._notified == 0) { | |
1543 if (millis <= 0) { | |
1544 Self->_ParkEvent->park () ; | |
1545 } else { | |
1546 ret = Self->_ParkEvent->park (millis) ; | |
1547 } | |
1548 } | |
1549 | |
1550 // were we externally suspended while we were waiting? | |
1551 if (ExitSuspendEquivalent (jt)) { | |
1552 // TODO-FIXME: add -- if succ == Self then succ = null. | |
1553 jt->java_suspend_self(); | |
1554 } | |
1555 | |
1556 } // Exit thread safepoint: transition _thread_blocked -> _thread_in_vm | |
1557 | |
1558 | |
1559 // Node may be on the WaitSet, the EntryList (or cxq), or in transition | |
1560 // from the WaitSet to the EntryList. | |
1561 // See if we need to remove Node from the WaitSet. | |
1562 // We use double-checked locking to avoid grabbing _WaitSetLock | |
1563 // if the thread is not on the wait queue. | |
1564 // | |
1565 // Note that we don't need a fence before the fetch of TState. | |
1566 // In the worst case we'll fetch a old-stale value of TS_WAIT previously | |
1567 // written by the is thread. (perhaps the fetch might even be satisfied | |
1568 // by a look-aside into the processor's own store buffer, although given | |
1569 // the length of the code path between the prior ST and this load that's | |
1570 // highly unlikely). If the following LD fetches a stale TS_WAIT value | |
1571 // then we'll acquire the lock and then re-fetch a fresh TState value. | |
1572 // That is, we fail toward safety. | |
1573 | |
1574 if (node.TState == ObjectWaiter::TS_WAIT) { | |
1575 Thread::SpinAcquire (&_WaitSetLock, "WaitSet - unlink") ; | |
1576 if (node.TState == ObjectWaiter::TS_WAIT) { | |
1577 DequeueSpecificWaiter (&node) ; // unlink from WaitSet | |
1578 assert(node._notified == 0, "invariant"); | |
1579 node.TState = ObjectWaiter::TS_RUN ; | |
1580 } | |
1581 Thread::SpinRelease (&_WaitSetLock) ; | |
1582 } | |
1583 | |
1584 // The thread is now either on off-list (TS_RUN), | |
1585 // on the EntryList (TS_ENTER), or on the cxq (TS_CXQ). | |
1586 // The Node's TState variable is stable from the perspective of this thread. | |
1587 // No other threads will asynchronously modify TState. | |
1588 guarantee (node.TState != ObjectWaiter::TS_WAIT, "invariant") ; | |
1589 OrderAccess::loadload() ; | |
1590 if (_succ == Self) _succ = NULL ; | |
1591 WasNotified = node._notified ; | |
1592 | |
1593 // Reentry phase -- reacquire the monitor. | |
1594 // re-enter contended monitor after object.wait(). | |
1595 // retain OBJECT_WAIT state until re-enter successfully completes | |
1596 // Thread state is thread_in_vm and oop access is again safe, | |
1597 // although the raw address of the object may have changed. | |
1598 // (Don't cache naked oops over safepoints, of course). | |
1599 | |
1600 // post monitor waited event. Note that this is past-tense, we are done waiting. | |
1601 if (JvmtiExport::should_post_monitor_waited()) { | |
1602 JvmtiExport::post_monitor_waited(jt, this, ret == OS_TIMEOUT); | |
1603 } | |
10405 | 1604 |
17693
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1605 // Without the fix for 8028280, it is possible for the above call: |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1606 // |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1607 // Thread::SpinAcquire (&_WaitSetLock, "WaitSet - unlink") ; |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1608 // |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1609 // to consume the unpark() that was done when the successor was set. |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1610 // The solution for this very rare possibility is to redo the unpark() |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1611 // outside of the JvmtiExport::should_post_monitor_waited() check. |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1612 // |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1613 if (node._notified != 0 && _succ == Self) { |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1614 // In this part of the monitor wait-notify-reenter protocol it |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1615 // is possible (and normal) for another thread to do a fastpath |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1616 // monitor enter-exit while this thread is still trying to get |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1617 // to the reenter portion of the protocol. |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1618 // |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1619 // The ObjectMonitor was notified and the current thread is |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1620 // the successor which also means that an unpark() has already |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1621 // been done. The JVMTI_EVENT_MONITOR_WAITED event handler can |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1622 // consume the unpark() that was done when the successor was |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1623 // set because the same ParkEvent is shared between Java |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1624 // monitors and JVM/TI RawMonitors (for now). |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1625 // |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1626 // We redo the unpark() to ensure forward progress, i.e., we |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1627 // don't want all pending threads hanging (parked) with none |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1628 // entering the unlocked monitor. |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1629 node._event->unpark(); |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1630 } |
d35df3079834
8028073: race condition in ObjectMonitor implementation causing deadlocks
dcubed
parents:
10405
diff
changeset
|
1631 |
10405 | 1632 if (event.should_commit()) { |
1633 post_monitor_wait_event(&event, node._notifier_tid, millis, ret == OS_TIMEOUT); | |
1634 } | |
1635 | |
1878 | 1636 OrderAccess::fence() ; |
1637 | |
1638 assert (Self->_Stalled != 0, "invariant") ; | |
1639 Self->_Stalled = 0 ; | |
1640 | |
1641 assert (_owner != Self, "invariant") ; | |
1642 ObjectWaiter::TStates v = node.TState ; | |
1643 if (v == ObjectWaiter::TS_RUN) { | |
1644 enter (Self) ; | |
1645 } else { | |
1646 guarantee (v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant") ; | |
1647 ReenterI (Self, &node) ; | |
1648 node.wait_reenter_end(this); | |
1649 } | |
1650 | |
1651 // Self has reacquired the lock. | |
1652 // Lifecycle - the node representing Self must not appear on any queues. | |
1653 // Node is about to go out-of-scope, but even if it were immortal we wouldn't | |
1654 // want residual elements associated with this thread left on any lists. | |
1655 guarantee (node.TState == ObjectWaiter::TS_RUN, "invariant") ; | |
1656 assert (_owner == Self, "invariant") ; | |
1657 assert (_succ != Self , "invariant") ; | |
1658 } // OSThreadWaitState() | |
1659 | |
1660 jt->set_current_waiting_monitor(NULL); | |
1661 | |
1662 guarantee (_recursions == 0, "invariant") ; | |
1663 _recursions = save; // restore the old recursion count | |
1664 _waiters--; // decrement the number of waiters | |
1665 | |
1666 // Verify a few postconditions | |
1667 assert (_owner == Self , "invariant") ; | |
1668 assert (_succ != Self , "invariant") ; | |
1669 assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ; | |
1670 | |
1671 if (SyncFlags & 32) { | |
1672 OrderAccess::fence() ; | |
1673 } | |
1674 | |
1675 // check if the notification happened | |
1676 if (!WasNotified) { | |
1677 // no, it could be timeout or Thread.interrupt() or both | |
1678 // check for interrupt event, otherwise it is timeout | |
1679 if (interruptible && Thread::is_interrupted(Self, true) && !HAS_PENDING_EXCEPTION) { | |
1680 TEVENT (Wait - throw IEX from epilog) ; | |
1681 THROW(vmSymbols::java_lang_InterruptedException()); | |
1682 } | |
1683 } | |
1684 | |
1685 // NOTE: Spurious wake up will be consider as timeout. | |
1686 // Monitor notify has precedence over thread interrupt. | |
1687 } | |
1688 | |
1689 | |
1690 // Consider: | |
1691 // If the lock is cool (cxq == null && succ == null) and we're on an MP system | |
1692 // then instead of transferring a thread from the WaitSet to the EntryList | |
1693 // we might just dequeue a thread from the WaitSet and directly unpark() it. | |
1694 | |
1695 void ObjectMonitor::notify(TRAPS) { | |
1696 CHECK_OWNER(); | |
1697 if (_WaitSet == NULL) { | |
1698 TEVENT (Empty-Notify) ; | |
1699 return ; | |
1700 } | |
1701 DTRACE_MONITOR_PROBE(notify, this, object(), THREAD); | |
1702 | |
1703 int Policy = Knob_MoveNotifyee ; | |
1704 | |
1705 Thread::SpinAcquire (&_WaitSetLock, "WaitSet - notify") ; | |
1706 ObjectWaiter * iterator = DequeueWaiter() ; | |
1707 if (iterator != NULL) { | |
1708 TEVENT (Notify1 - Transfer) ; | |
1709 guarantee (iterator->TState == ObjectWaiter::TS_WAIT, "invariant") ; | |
1710 guarantee (iterator->_notified == 0, "invariant") ; | |
1711 if (Policy != 4) { | |
1712 iterator->TState = ObjectWaiter::TS_ENTER ; | |
1713 } | |
1714 iterator->_notified = 1 ; | |
10405 | 1715 Thread * Self = THREAD; |
1716 iterator->_notifier_tid = Self->osthread()->thread_id(); | |
1878 | 1717 |
1718 ObjectWaiter * List = _EntryList ; | |
1719 if (List != NULL) { | |
1720 assert (List->_prev == NULL, "invariant") ; | |
1721 assert (List->TState == ObjectWaiter::TS_ENTER, "invariant") ; | |
1722 assert (List != iterator, "invariant") ; | |
1723 } | |
1724 | |
1725 if (Policy == 0) { // prepend to EntryList | |
1726 if (List == NULL) { | |
1727 iterator->_next = iterator->_prev = NULL ; | |
1728 _EntryList = iterator ; | |
1729 } else { | |
1730 List->_prev = iterator ; | |
1731 iterator->_next = List ; | |
1732 iterator->_prev = NULL ; | |
1733 _EntryList = iterator ; | |
1734 } | |
1735 } else | |
1736 if (Policy == 1) { // append to EntryList | |
1737 if (List == NULL) { | |
1738 iterator->_next = iterator->_prev = NULL ; | |
1739 _EntryList = iterator ; | |
1740 } else { | |
1741 // CONSIDER: finding the tail currently requires a linear-time walk of | |
1742 // the EntryList. We can make tail access constant-time by converting to | |
1743 // a CDLL instead of using our current DLL. | |
1744 ObjectWaiter * Tail ; | |
1745 for (Tail = List ; Tail->_next != NULL ; Tail = Tail->_next) ; | |
1746 assert (Tail != NULL && Tail->_next == NULL, "invariant") ; | |
1747 Tail->_next = iterator ; | |
1748 iterator->_prev = Tail ; | |
1749 iterator->_next = NULL ; | |
1750 } | |
1751 } else | |
1752 if (Policy == 2) { // prepend to cxq | |
1753 // prepend to cxq | |
1754 if (List == NULL) { | |
1755 iterator->_next = iterator->_prev = NULL ; | |
1756 _EntryList = iterator ; | |
1757 } else { | |
1758 iterator->TState = ObjectWaiter::TS_CXQ ; | |
1759 for (;;) { | |
1760 ObjectWaiter * Front = _cxq ; | |
1761 iterator->_next = Front ; | |
1762 if (Atomic::cmpxchg_ptr (iterator, &_cxq, Front) == Front) { | |
1763 break ; | |
1764 } | |
1765 } | |
1766 } | |
1767 } else | |
1768 if (Policy == 3) { // append to cxq | |
1769 iterator->TState = ObjectWaiter::TS_CXQ ; | |
1770 for (;;) { | |
1771 ObjectWaiter * Tail ; | |
1772 Tail = _cxq ; | |
1773 if (Tail == NULL) { | |
1774 iterator->_next = NULL ; | |
1775 if (Atomic::cmpxchg_ptr (iterator, &_cxq, NULL) == NULL) { | |
1776 break ; | |
1777 } | |
1778 } else { | |
1779 while (Tail->_next != NULL) Tail = Tail->_next ; | |
1780 Tail->_next = iterator ; | |
1781 iterator->_prev = Tail ; | |
1782 iterator->_next = NULL ; | |
1783 break ; | |
1784 } | |
1785 } | |
1786 } else { | |
1787 ParkEvent * ev = iterator->_event ; | |
1788 iterator->TState = ObjectWaiter::TS_RUN ; | |
1789 OrderAccess::fence() ; | |
1790 ev->unpark() ; | |
1791 } | |
1792 | |
1793 if (Policy < 4) { | |
1794 iterator->wait_reenter_begin(this); | |
1795 } | |
1796 | |
1797 // _WaitSetLock protects the wait queue, not the EntryList. We could | |
1798 // move the add-to-EntryList operation, above, outside the critical section | |
1799 // protected by _WaitSetLock. In practice that's not useful. With the | |
1800 // exception of wait() timeouts and interrupts the monitor owner | |
1801 // is the only thread that grabs _WaitSetLock. There's almost no contention | |
1802 // on _WaitSetLock so it's not profitable to reduce the length of the | |
1803 // critical section. | |
1804 } | |
1805 | |
1806 Thread::SpinRelease (&_WaitSetLock) ; | |
1807 | |
1808 if (iterator != NULL && ObjectMonitor::_sync_Notifications != NULL) { | |
1809 ObjectMonitor::_sync_Notifications->inc() ; | |
1810 } | |
1811 } | |
1812 | |
1813 | |
1814 void ObjectMonitor::notifyAll(TRAPS) { | |
1815 CHECK_OWNER(); | |
1816 ObjectWaiter* iterator; | |
1817 if (_WaitSet == NULL) { | |
1818 TEVENT (Empty-NotifyAll) ; | |
1819 return ; | |
1820 } | |
1821 DTRACE_MONITOR_PROBE(notifyAll, this, object(), THREAD); | |
1822 | |
1823 int Policy = Knob_MoveNotifyee ; | |
1824 int Tally = 0 ; | |
1825 Thread::SpinAcquire (&_WaitSetLock, "WaitSet - notifyall") ; | |
1826 | |
1827 for (;;) { | |
1828 iterator = DequeueWaiter () ; | |
1829 if (iterator == NULL) break ; | |
1830 TEVENT (NotifyAll - Transfer1) ; | |
1831 ++Tally ; | |
1832 | |
1833 // Disposition - what might we do with iterator ? | |
1834 // a. add it directly to the EntryList - either tail or head. | |
1835 // b. push it onto the front of the _cxq. | |
1836 // For now we use (a). | |
1837 | |
1838 guarantee (iterator->TState == ObjectWaiter::TS_WAIT, "invariant") ; | |
1839 guarantee (iterator->_notified == 0, "invariant") ; | |
1840 iterator->_notified = 1 ; | |
10405 | 1841 Thread * Self = THREAD; |
1842 iterator->_notifier_tid = Self->osthread()->thread_id(); | |
1878 | 1843 if (Policy != 4) { |
1844 iterator->TState = ObjectWaiter::TS_ENTER ; | |
1845 } | |
1846 | |
1847 ObjectWaiter * List = _EntryList ; | |
1848 if (List != NULL) { | |
1849 assert (List->_prev == NULL, "invariant") ; | |
1850 assert (List->TState == ObjectWaiter::TS_ENTER, "invariant") ; | |
1851 assert (List != iterator, "invariant") ; | |
1852 } | |
1853 | |
1854 if (Policy == 0) { // prepend to EntryList | |
1855 if (List == NULL) { | |
1856 iterator->_next = iterator->_prev = NULL ; | |
1857 _EntryList = iterator ; | |
1858 } else { | |
1859 List->_prev = iterator ; | |
1860 iterator->_next = List ; | |
1861 iterator->_prev = NULL ; | |
1862 _EntryList = iterator ; | |
1863 } | |
1864 } else | |
1865 if (Policy == 1) { // append to EntryList | |
1866 if (List == NULL) { | |
1867 iterator->_next = iterator->_prev = NULL ; | |
1868 _EntryList = iterator ; | |
1869 } else { | |
1870 // CONSIDER: finding the tail currently requires a linear-time walk of | |
1871 // the EntryList. We can make tail access constant-time by converting to | |
1872 // a CDLL instead of using our current DLL. | |
1873 ObjectWaiter * Tail ; | |
1874 for (Tail = List ; Tail->_next != NULL ; Tail = Tail->_next) ; | |
1875 assert (Tail != NULL && Tail->_next == NULL, "invariant") ; | |
1876 Tail->_next = iterator ; | |
1877 iterator->_prev = Tail ; | |
1878 iterator->_next = NULL ; | |
1879 } | |
1880 } else | |
1881 if (Policy == 2) { // prepend to cxq | |
1882 // prepend to cxq | |
1883 iterator->TState = ObjectWaiter::TS_CXQ ; | |
1884 for (;;) { | |
1885 ObjectWaiter * Front = _cxq ; | |
1886 iterator->_next = Front ; | |
1887 if (Atomic::cmpxchg_ptr (iterator, &_cxq, Front) == Front) { | |
1888 break ; | |
1889 } | |
1890 } | |
1891 } else | |
1892 if (Policy == 3) { // append to cxq | |
1893 iterator->TState = ObjectWaiter::TS_CXQ ; | |
1894 for (;;) { | |
1895 ObjectWaiter * Tail ; | |
1896 Tail = _cxq ; | |
1897 if (Tail == NULL) { | |
1898 iterator->_next = NULL ; | |
1899 if (Atomic::cmpxchg_ptr (iterator, &_cxq, NULL) == NULL) { | |
1900 break ; | |
1901 } | |
1902 } else { | |
1903 while (Tail->_next != NULL) Tail = Tail->_next ; | |
1904 Tail->_next = iterator ; | |
1905 iterator->_prev = Tail ; | |
1906 iterator->_next = NULL ; | |
1907 break ; | |
1908 } | |
1909 } | |
1910 } else { | |
1911 ParkEvent * ev = iterator->_event ; | |
1912 iterator->TState = ObjectWaiter::TS_RUN ; | |
1913 OrderAccess::fence() ; | |
1914 ev->unpark() ; | |
1915 } | |
1916 | |
1917 if (Policy < 4) { | |
1918 iterator->wait_reenter_begin(this); | |
1919 } | |
1920 | |
1921 // _WaitSetLock protects the wait queue, not the EntryList. We could | |
1922 // move the add-to-EntryList operation, above, outside the critical section | |
1923 // protected by _WaitSetLock. In practice that's not useful. With the | |
1924 // exception of wait() timeouts and interrupts the monitor owner | |
1925 // is the only thread that grabs _WaitSetLock. There's almost no contention | |
1926 // on _WaitSetLock so it's not profitable to reduce the length of the | |
1927 // critical section. | |
1928 } | |
1929 | |
1930 Thread::SpinRelease (&_WaitSetLock) ; | |
1931 | |
1932 if (Tally != 0 && ObjectMonitor::_sync_Notifications != NULL) { | |
1933 ObjectMonitor::_sync_Notifications->inc(Tally) ; | |
1934 } | |
1935 } | |
1936 | |
1937 // ----------------------------------------------------------------------------- | |
1938 // Adaptive Spinning Support | |
1939 // | |
1940 // Adaptive spin-then-block - rational spinning | |
1941 // | |
1942 // Note that we spin "globally" on _owner with a classic SMP-polite TATAS | |
1943 // algorithm. On high order SMP systems it would be better to start with | |
1944 // a brief global spin and then revert to spinning locally. In the spirit of MCS/CLH, | |
1945 // a contending thread could enqueue itself on the cxq and then spin locally | |
1946 // on a thread-specific variable such as its ParkEvent._Event flag. | |
1947 // That's left as an exercise for the reader. Note that global spinning is | |
1948 // not problematic on Niagara, as the L2$ serves the interconnect and has both | |
1949 // low latency and massive bandwidth. | |
1950 // | |
1951 // Broadly, we can fix the spin frequency -- that is, the % of contended lock | |
1952 // acquisition attempts where we opt to spin -- at 100% and vary the spin count | |
1953 // (duration) or we can fix the count at approximately the duration of | |
1954 // a context switch and vary the frequency. Of course we could also | |
1955 // vary both satisfying K == Frequency * Duration, where K is adaptive by monitor. | |
1956 // See http://j2se.east/~dice/PERSIST/040824-AdaptiveSpinning.html. | |
1957 // | |
1958 // This implementation varies the duration "D", where D varies with | |
1959 // the success rate of recent spin attempts. (D is capped at approximately | |
1960 // length of a round-trip context switch). The success rate for recent | |
1961 // spin attempts is a good predictor of the success rate of future spin | |
1962 // attempts. The mechanism adapts automatically to varying critical | |
1963 // section length (lock modality), system load and degree of parallelism. | |
1964 // D is maintained per-monitor in _SpinDuration and is initialized | |
1965 // optimistically. Spin frequency is fixed at 100%. | |
1966 // | |
1967 // Note that _SpinDuration is volatile, but we update it without locks | |
1968 // or atomics. The code is designed so that _SpinDuration stays within | |
1969 // a reasonable range even in the presence of races. The arithmetic | |
1970 // operations on _SpinDuration are closed over the domain of legal values, | |
1971 // so at worst a race will install and older but still legal value. | |
1972 // At the very worst this introduces some apparent non-determinism. | |
1973 // We might spin when we shouldn't or vice-versa, but since the spin | |
1974 // count are relatively short, even in the worst case, the effect is harmless. | |
1975 // | |
1976 // Care must be taken that a low "D" value does not become an | |
1977 // an absorbing state. Transient spinning failures -- when spinning | |
1978 // is overall profitable -- should not cause the system to converge | |
1979 // on low "D" values. We want spinning to be stable and predictable | |
1980 // and fairly responsive to change and at the same time we don't want | |
1981 // it to oscillate, become metastable, be "too" non-deterministic, | |
1982 // or converge on or enter undesirable stable absorbing states. | |
1983 // | |
1984 // We implement a feedback-based control system -- using past behavior | |
1985 // to predict future behavior. We face two issues: (a) if the | |
1986 // input signal is random then the spin predictor won't provide optimal | |
1987 // results, and (b) if the signal frequency is too high then the control | |
1988 // system, which has some natural response lag, will "chase" the signal. | |
1989 // (b) can arise from multimodal lock hold times. Transient preemption | |
1990 // can also result in apparent bimodal lock hold times. | |
1991 // Although sub-optimal, neither condition is particularly harmful, as | |
1992 // in the worst-case we'll spin when we shouldn't or vice-versa. | |
1993 // The maximum spin duration is rather short so the failure modes aren't bad. | |
1994 // To be conservative, I've tuned the gain in system to bias toward | |
1995 // _not spinning. Relatedly, the system can sometimes enter a mode where it | |
1996 // "rings" or oscillates between spinning and not spinning. This happens | |
1997 // when spinning is just on the cusp of profitability, however, so the | |
1998 // situation is not dire. The state is benign -- there's no need to add | |
1999 // hysteresis control to damp the transition rate between spinning and | |
2000 // not spinning. | |
2001 // | |
2002 | |
2003 intptr_t ObjectMonitor::SpinCallbackArgument = 0 ; | |
2004 int (*ObjectMonitor::SpinCallbackFunction)(intptr_t, int) = NULL ; | |
2005 | |
2006 // Spinning: Fixed frequency (100%), vary duration | |
2007 | |
2008 | |
2009 int ObjectMonitor::TrySpin_VaryDuration (Thread * Self) { | |
2010 | |
2011 // Dumb, brutal spin. Good for comparative measurements against adaptive spinning. | |
2012 int ctr = Knob_FixedSpin ; | |
2013 if (ctr != 0) { | |
2014 while (--ctr >= 0) { | |
2015 if (TryLock (Self) > 0) return 1 ; | |
2016 SpinPause () ; | |
2017 } | |
2018 return 0 ; | |
2019 } | |
2020 | |
2021 for (ctr = Knob_PreSpin + 1; --ctr >= 0 ; ) { | |
2022 if (TryLock(Self) > 0) { | |
2023 // Increase _SpinDuration ... | |
2024 // Note that we don't clamp SpinDuration precisely at SpinLimit. | |
2025 // Raising _SpurDuration to the poverty line is key. | |
2026 int x = _SpinDuration ; | |
2027 if (x < Knob_SpinLimit) { | |
2028 if (x < Knob_Poverty) x = Knob_Poverty ; | |
2029 _SpinDuration = x + Knob_BonusB ; | |
2030 } | |
2031 return 1 ; | |
2032 } | |
2033 SpinPause () ; | |
2034 } | |
2035 | |
2036 // Admission control - verify preconditions for spinning | |
2037 // | |
2038 // We always spin a little bit, just to prevent _SpinDuration == 0 from | |
2039 // becoming an absorbing state. Put another way, we spin briefly to | |
2040 // sample, just in case the system load, parallelism, contention, or lock | |
2041 // modality changed. | |
2042 // | |
2043 // Consider the following alternative: | |
2044 // Periodically set _SpinDuration = _SpinLimit and try a long/full | |
2045 // spin attempt. "Periodically" might mean after a tally of | |
2046 // the # of failed spin attempts (or iterations) reaches some threshold. | |
2047 // This takes us into the realm of 1-out-of-N spinning, where we | |
2048 // hold the duration constant but vary the frequency. | |
2049 | |
2050 ctr = _SpinDuration ; | |
2051 if (ctr < Knob_SpinBase) ctr = Knob_SpinBase ; | |
2052 if (ctr <= 0) return 0 ; | |
2053 | |
2054 if (Knob_SuccRestrict && _succ != NULL) return 0 ; | |
2055 if (Knob_OState && NotRunnable (Self, (Thread *) _owner)) { | |
2056 TEVENT (Spin abort - notrunnable [TOP]); | |
2057 return 0 ; | |
2058 } | |
2059 | |
2060 int MaxSpin = Knob_MaxSpinners ; | |
2061 if (MaxSpin >= 0) { | |
2062 if (_Spinner > MaxSpin) { | |
2063 TEVENT (Spin abort -- too many spinners) ; | |
2064 return 0 ; | |
2065 } | |
2066 // Slighty racy, but benign ... | |
2067 Adjust (&_Spinner, 1) ; | |
2068 } | |
2069 | |
2070 // We're good to spin ... spin ingress. | |
2071 // CONSIDER: use Prefetch::write() to avoid RTS->RTO upgrades | |
2072 // when preparing to LD...CAS _owner, etc and the CAS is likely | |
2073 // to succeed. | |
2074 int hits = 0 ; | |
2075 int msk = 0 ; | |
2076 int caspty = Knob_CASPenalty ; | |
2077 int oxpty = Knob_OXPenalty ; | |
2078 int sss = Knob_SpinSetSucc ; | |
2079 if (sss && _succ == NULL ) _succ = Self ; | |
2080 Thread * prv = NULL ; | |
2081 | |
2082 // There are three ways to exit the following loop: | |
2083 // 1. A successful spin where this thread has acquired the lock. | |
2084 // 2. Spin failure with prejudice | |
2085 // 3. Spin failure without prejudice | |
2086 | |
2087 while (--ctr >= 0) { | |
2088 | |
2089 // Periodic polling -- Check for pending GC | |
2090 // Threads may spin while they're unsafe. | |
2091 // We don't want spinning threads to delay the JVM from reaching | |
2092 // a stop-the-world safepoint or to steal cycles from GC. | |
2093 // If we detect a pending safepoint we abort in order that | |
2094 // (a) this thread, if unsafe, doesn't delay the safepoint, and (b) | |
2095 // this thread, if safe, doesn't steal cycles from GC. | |
2096 // This is in keeping with the "no loitering in runtime" rule. | |
2097 // We periodically check to see if there's a safepoint pending. | |
2098 if ((ctr & 0xFF) == 0) { | |
2099 if (SafepointSynchronize::do_call_back()) { | |
2100 TEVENT (Spin: safepoint) ; | |
2101 goto Abort ; // abrupt spin egress | |
2102 } | |
2103 if (Knob_UsePause & 1) SpinPause () ; | |
2104 | |
2105 int (*scb)(intptr_t,int) = SpinCallbackFunction ; | |
2106 if (hits > 50 && scb != NULL) { | |
2107 int abend = (*scb)(SpinCallbackArgument, 0) ; | |
2108 } | |
2109 } | |
2110 | |
2111 if (Knob_UsePause & 2) SpinPause() ; | |
2112 | |
2113 // Exponential back-off ... Stay off the bus to reduce coherency traffic. | |
2114 // This is useful on classic SMP systems, but is of less utility on | |
2115 // N1-style CMT platforms. | |
2116 // | |
2117 // Trade-off: lock acquisition latency vs coherency bandwidth. | |
2118 // Lock hold times are typically short. A histogram | |
2119 // of successful spin attempts shows that we usually acquire | |
2120 // the lock early in the spin. That suggests we want to | |
2121 // sample _owner frequently in the early phase of the spin, | |
2122 // but then back-off and sample less frequently as the spin | |
2123 // progresses. The back-off makes a good citizen on SMP big | |
2124 // SMP systems. Oversampling _owner can consume excessive | |
2125 // coherency bandwidth. Relatedly, if we _oversample _owner we | |
2126 // can inadvertently interfere with the the ST m->owner=null. | |
2127 // executed by the lock owner. | |
2128 if (ctr & msk) continue ; | |
2129 ++hits ; | |
2130 if ((hits & 0xF) == 0) { | |
2131 // The 0xF, above, corresponds to the exponent. | |
2132 // Consider: (msk+1)|msk | |
2133 msk = ((msk << 2)|3) & BackOffMask ; | |
2134 } | |
2135 | |
2136 // Probe _owner with TATAS | |
2137 // If this thread observes the monitor transition or flicker | |
2138 // from locked to unlocked to locked, then the odds that this | |
2139 // thread will acquire the lock in this spin attempt go down | |
2140 // considerably. The same argument applies if the CAS fails | |
2141 // or if we observe _owner change from one non-null value to | |
2142 // another non-null value. In such cases we might abort | |
2143 // the spin without prejudice or apply a "penalty" to the | |
2144 // spin count-down variable "ctr", reducing it by 100, say. | |
2145 | |
2146 Thread * ox = (Thread *) _owner ; | |
2147 if (ox == NULL) { | |
2148 ox = (Thread *) Atomic::cmpxchg_ptr (Self, &_owner, NULL) ; | |
2149 if (ox == NULL) { | |
2150 // The CAS succeeded -- this thread acquired ownership | |
2151 // Take care of some bookkeeping to exit spin state. | |
2152 if (sss && _succ == Self) { | |
2153 _succ = NULL ; | |
2154 } | |
2155 if (MaxSpin > 0) Adjust (&_Spinner, -1) ; | |
2156 | |
2157 // Increase _SpinDuration : | |
2158 // The spin was successful (profitable) so we tend toward | |
2159 // longer spin attempts in the future. | |
2160 // CONSIDER: factor "ctr" into the _SpinDuration adjustment. | |
2161 // If we acquired the lock early in the spin cycle it | |
2162 // makes sense to increase _SpinDuration proportionally. | |
2163 // Note that we don't clamp SpinDuration precisely at SpinLimit. | |
2164 int x = _SpinDuration ; | |
2165 if (x < Knob_SpinLimit) { | |
2166 if (x < Knob_Poverty) x = Knob_Poverty ; | |
2167 _SpinDuration = x + Knob_Bonus ; | |
2168 } | |
2169 return 1 ; | |
2170 } | |
2171 | |
2172 // The CAS failed ... we can take any of the following actions: | |
2173 // * penalize: ctr -= Knob_CASPenalty | |
2174 // * exit spin with prejudice -- goto Abort; | |
2175 // * exit spin without prejudice. | |
2176 // * Since CAS is high-latency, retry again immediately. | |
2177 prv = ox ; | |
2178 TEVENT (Spin: cas failed) ; | |
2179 if (caspty == -2) break ; | |
2180 if (caspty == -1) goto Abort ; | |
2181 ctr -= caspty ; | |
2182 continue ; | |
2183 } | |
2184 | |
2185 // Did lock ownership change hands ? | |
2186 if (ox != prv && prv != NULL ) { | |
2187 TEVENT (spin: Owner changed) | |
2188 if (oxpty == -2) break ; | |
2189 if (oxpty == -1) goto Abort ; | |
2190 ctr -= oxpty ; | |
2191 } | |
2192 prv = ox ; | |
2193 | |
2194 // Abort the spin if the owner is not executing. | |
2195 // The owner must be executing in order to drop the lock. | |
2196 // Spinning while the owner is OFFPROC is idiocy. | |
2197 // Consider: ctr -= RunnablePenalty ; | |
2198 if (Knob_OState && NotRunnable (Self, ox)) { | |
2199 TEVENT (Spin abort - notrunnable); | |
2200 goto Abort ; | |
2201 } | |
2202 if (sss && _succ == NULL ) _succ = Self ; | |
2203 } | |
2204 | |
2205 // Spin failed with prejudice -- reduce _SpinDuration. | |
2206 // TODO: Use an AIMD-like policy to adjust _SpinDuration. | |
2207 // AIMD is globally stable. | |
2208 TEVENT (Spin failure) ; | |
2209 { | |
2210 int x = _SpinDuration ; | |
2211 if (x > 0) { | |
2212 // Consider an AIMD scheme like: x -= (x >> 3) + 100 | |
2213 // This is globally sample and tends to damp the response. | |
2214 x -= Knob_Penalty ; | |
2215 if (x < 0) x = 0 ; | |
2216 _SpinDuration = x ; | |
2217 } | |
2218 } | |
2219 | |
2220 Abort: | |
2221 if (MaxSpin >= 0) Adjust (&_Spinner, -1) ; | |
2222 if (sss && _succ == Self) { | |
2223 _succ = NULL ; | |
2224 // Invariant: after setting succ=null a contending thread | |
2225 // must recheck-retry _owner before parking. This usually happens | |
2226 // in the normal usage of TrySpin(), but it's safest | |
2227 // to make TrySpin() as foolproof as possible. | |
2228 OrderAccess::fence() ; | |
2229 if (TryLock(Self) > 0) return 1 ; | |
2230 } | |
2231 return 0 ; | |
2232 } | |
2233 | |
2234 // NotRunnable() -- informed spinning | |
2235 // | |
2236 // Don't bother spinning if the owner is not eligible to drop the lock. | |
2237 // Peek at the owner's schedctl.sc_state and Thread._thread_values and | |
2238 // spin only if the owner thread is _thread_in_Java or _thread_in_vm. | |
2239 // The thread must be runnable in order to drop the lock in timely fashion. | |
2240 // If the _owner is not runnable then spinning will not likely be | |
2241 // successful (profitable). | |
2242 // | |
2243 // Beware -- the thread referenced by _owner could have died | |
2244 // so a simply fetch from _owner->_thread_state might trap. | |
2245 // Instead, we use SafeFetchXX() to safely LD _owner->_thread_state. | |
2246 // Because of the lifecycle issues the schedctl and _thread_state values | |
2247 // observed by NotRunnable() might be garbage. NotRunnable must | |
2248 // tolerate this and consider the observed _thread_state value | |
2249 // as advisory. | |
2250 // | |
2251 // Beware too, that _owner is sometimes a BasicLock address and sometimes | |
2252 // a thread pointer. We differentiate the two cases with OwnerIsThread. | |
2253 // Alternately, we might tag the type (thread pointer vs basiclock pointer) | |
2254 // with the LSB of _owner. Another option would be to probablistically probe | |
2255 // the putative _owner->TypeTag value. | |
2256 // | |
2257 // Checking _thread_state isn't perfect. Even if the thread is | |
2258 // in_java it might be blocked on a page-fault or have been preempted | |
2259 // and sitting on a ready/dispatch queue. _thread state in conjunction | |
2260 // with schedctl.sc_state gives us a good picture of what the | |
2261 // thread is doing, however. | |
2262 // | |
2263 // TODO: check schedctl.sc_state. | |
2264 // We'll need to use SafeFetch32() to read from the schedctl block. | |
2265 // See RFE #5004247 and http://sac.sfbay.sun.com/Archives/CaseLog/arc/PSARC/2005/351/ | |
2266 // | |
2267 // The return value from NotRunnable() is *advisory* -- the | |
2268 // result is based on sampling and is not necessarily coherent. | |
2269 // The caller must tolerate false-negative and false-positive errors. | |
2270 // Spinning, in general, is probabilistic anyway. | |
2271 | |
2272 | |
2273 int ObjectMonitor::NotRunnable (Thread * Self, Thread * ox) { | |
2274 // Check either OwnerIsThread or ox->TypeTag == 2BAD. | |
2275 if (!OwnerIsThread) return 0 ; | |
2276 | |
2277 if (ox == NULL) return 0 ; | |
2278 | |
2279 // Avoid transitive spinning ... | |
2280 // Say T1 spins or blocks trying to acquire L. T1._Stalled is set to L. | |
2281 // Immediately after T1 acquires L it's possible that T2, also | |
2282 // spinning on L, will see L.Owner=T1 and T1._Stalled=L. | |
2283 // This occurs transiently after T1 acquired L but before | |
2284 // T1 managed to clear T1.Stalled. T2 does not need to abort | |
2285 // its spin in this circumstance. | |
2286 intptr_t BlockedOn = SafeFetchN ((intptr_t *) &ox->_Stalled, intptr_t(1)) ; | |
2287 | |
2288 if (BlockedOn == 1) return 1 ; | |
2289 if (BlockedOn != 0) { | |
2290 return BlockedOn != intptr_t(this) && _owner == ox ; | |
2291 } | |
2292 | |
2293 assert (sizeof(((JavaThread *)ox)->_thread_state == sizeof(int)), "invariant") ; | |
2294 int jst = SafeFetch32 ((int *) &((JavaThread *) ox)->_thread_state, -1) ; ; | |
2295 // consider also: jst != _thread_in_Java -- but that's overspecific. | |
2296 return jst == _thread_blocked || jst == _thread_in_native ; | |
2297 } | |
2298 | |
2299 | |
2300 // ----------------------------------------------------------------------------- | |
2301 // WaitSet management ... | |
2302 | |
2303 ObjectWaiter::ObjectWaiter(Thread* thread) { | |
2304 _next = NULL; | |
2305 _prev = NULL; | |
2306 _notified = 0; | |
2307 TState = TS_RUN ; | |
2308 _thread = thread; | |
2309 _event = thread->_ParkEvent ; | |
2310 _active = false; | |
2311 assert (_event != NULL, "invariant") ; | |
2312 } | |
2313 | |
2314 void ObjectWaiter::wait_reenter_begin(ObjectMonitor *mon) { | |
2315 JavaThread *jt = (JavaThread *)this->_thread; | |
2316 _active = JavaThreadBlockedOnMonitorEnterState::wait_reenter_begin(jt, mon); | |
2317 } | |
2318 | |
2319 void ObjectWaiter::wait_reenter_end(ObjectMonitor *mon) { | |
2320 JavaThread *jt = (JavaThread *)this->_thread; | |
2321 JavaThreadBlockedOnMonitorEnterState::wait_reenter_end(jt, _active); | |
2322 } | |
2323 | |
2324 inline void ObjectMonitor::AddWaiter(ObjectWaiter* node) { | |
2325 assert(node != NULL, "should not dequeue NULL node"); | |
2326 assert(node->_prev == NULL, "node already in list"); | |
2327 assert(node->_next == NULL, "node already in list"); | |
2328 // put node at end of queue (circular doubly linked list) | |
2329 if (_WaitSet == NULL) { | |
2330 _WaitSet = node; | |
2331 node->_prev = node; | |
2332 node->_next = node; | |
2333 } else { | |
2334 ObjectWaiter* head = _WaitSet ; | |
2335 ObjectWaiter* tail = head->_prev; | |
2336 assert(tail->_next == head, "invariant check"); | |
2337 tail->_next = node; | |
2338 head->_prev = node; | |
2339 node->_next = head; | |
2340 node->_prev = tail; | |
2341 } | |
2342 } | |
2343 | |
2344 inline ObjectWaiter* ObjectMonitor::DequeueWaiter() { | |
2345 // dequeue the very first waiter | |
2346 ObjectWaiter* waiter = _WaitSet; | |
2347 if (waiter) { | |
2348 DequeueSpecificWaiter(waiter); | |
2349 } | |
2350 return waiter; | |
2351 } | |
2352 | |
2353 inline void ObjectMonitor::DequeueSpecificWaiter(ObjectWaiter* node) { | |
2354 assert(node != NULL, "should not dequeue NULL node"); | |
2355 assert(node->_prev != NULL, "node already removed from list"); | |
2356 assert(node->_next != NULL, "node already removed from list"); | |
2357 // when the waiter has woken up because of interrupt, | |
2358 // timeout or other spurious wake-up, dequeue the | |
2359 // waiter from waiting list | |
2360 ObjectWaiter* next = node->_next; | |
2361 if (next == node) { | |
2362 assert(node->_prev == node, "invariant check"); | |
2363 _WaitSet = NULL; | |
2364 } else { | |
2365 ObjectWaiter* prev = node->_prev; | |
2366 assert(prev->_next == node, "invariant check"); | |
2367 assert(next->_prev == node, "invariant check"); | |
2368 next->_prev = prev; | |
2369 prev->_next = next; | |
2370 if (_WaitSet == node) { | |
2371 _WaitSet = next; | |
2372 } | |
2373 } | |
2374 node->_next = NULL; | |
2375 node->_prev = NULL; | |
2376 } | |
2377 | |
2378 // ----------------------------------------------------------------------------- | |
2379 // PerfData support | |
2380 PerfCounter * ObjectMonitor::_sync_ContendedLockAttempts = NULL ; | |
2381 PerfCounter * ObjectMonitor::_sync_FutileWakeups = NULL ; | |
2382 PerfCounter * ObjectMonitor::_sync_Parks = NULL ; | |
2383 PerfCounter * ObjectMonitor::_sync_EmptyNotifications = NULL ; | |
2384 PerfCounter * ObjectMonitor::_sync_Notifications = NULL ; | |
2385 PerfCounter * ObjectMonitor::_sync_PrivateA = NULL ; | |
2386 PerfCounter * ObjectMonitor::_sync_PrivateB = NULL ; | |
2387 PerfCounter * ObjectMonitor::_sync_SlowExit = NULL ; | |
2388 PerfCounter * ObjectMonitor::_sync_SlowEnter = NULL ; | |
2389 PerfCounter * ObjectMonitor::_sync_SlowNotify = NULL ; | |
2390 PerfCounter * ObjectMonitor::_sync_SlowNotifyAll = NULL ; | |
2391 PerfCounter * ObjectMonitor::_sync_FailedSpins = NULL ; | |
2392 PerfCounter * ObjectMonitor::_sync_SuccessfulSpins = NULL ; | |
2393 PerfCounter * ObjectMonitor::_sync_MonInCirculation = NULL ; | |
2394 PerfCounter * ObjectMonitor::_sync_MonScavenged = NULL ; | |
2395 PerfCounter * ObjectMonitor::_sync_Inflations = NULL ; | |
2396 PerfCounter * ObjectMonitor::_sync_Deflations = NULL ; | |
2397 PerfLongVariable * ObjectMonitor::_sync_MonExtant = NULL ; | |
2398 | |
2399 // One-shot global initialization for the sync subsystem. | |
2400 // We could also defer initialization and initialize on-demand | |
2401 // the first time we call inflate(). Initialization would | |
2402 // be protected - like so many things - by the MonitorCache_lock. | |
2403 | |
2404 void ObjectMonitor::Initialize () { | |
2405 static int InitializationCompleted = 0 ; | |
2406 assert (InitializationCompleted == 0, "invariant") ; | |
2407 InitializationCompleted = 1 ; | |
2408 if (UsePerfData) { | |
2409 EXCEPTION_MARK ; | |
2410 #define NEWPERFCOUNTER(n) {n = PerfDataManager::create_counter(SUN_RT, #n, PerfData::U_Events,CHECK); } | |
2411 #define NEWPERFVARIABLE(n) {n = PerfDataManager::create_variable(SUN_RT, #n, PerfData::U_Events,CHECK); } | |
2412 NEWPERFCOUNTER(_sync_Inflations) ; | |
2413 NEWPERFCOUNTER(_sync_Deflations) ; | |
2414 NEWPERFCOUNTER(_sync_ContendedLockAttempts) ; | |
2415 NEWPERFCOUNTER(_sync_FutileWakeups) ; | |
2416 NEWPERFCOUNTER(_sync_Parks) ; | |
2417 NEWPERFCOUNTER(_sync_EmptyNotifications) ; | |
2418 NEWPERFCOUNTER(_sync_Notifications) ; | |
2419 NEWPERFCOUNTER(_sync_SlowEnter) ; | |
2420 NEWPERFCOUNTER(_sync_SlowExit) ; | |
2421 NEWPERFCOUNTER(_sync_SlowNotify) ; | |
2422 NEWPERFCOUNTER(_sync_SlowNotifyAll) ; | |
2423 NEWPERFCOUNTER(_sync_FailedSpins) ; | |
2424 NEWPERFCOUNTER(_sync_SuccessfulSpins) ; | |
2425 NEWPERFCOUNTER(_sync_PrivateA) ; | |
2426 NEWPERFCOUNTER(_sync_PrivateB) ; | |
2427 NEWPERFCOUNTER(_sync_MonInCirculation) ; | |
2428 NEWPERFCOUNTER(_sync_MonScavenged) ; | |
2429 NEWPERFVARIABLE(_sync_MonExtant) ; | |
2430 #undef NEWPERFCOUNTER | |
2431 } | |
2432 } | |
2433 | |
2434 | |
2435 // Compile-time asserts | |
2436 // When possible, it's better to catch errors deterministically at | |
2437 // compile-time than at runtime. The down-side to using compile-time | |
2438 // asserts is that error message -- often something about negative array | |
2439 // indices -- is opaque. | |
2440 | |
2441 #define CTASSERT(x) { int tag[1-(2*!(x))]; printf ("Tag @" INTPTR_FORMAT "\n", (intptr_t)tag); } | |
2442 | |
2443 void ObjectMonitor::ctAsserts() { | |
2444 CTASSERT(offset_of (ObjectMonitor, _header) == 0); | |
2445 } | |
2446 | |
2447 | |
2448 static char * kvGet (char * kvList, const char * Key) { | |
2449 if (kvList == NULL) return NULL ; | |
2450 size_t n = strlen (Key) ; | |
2451 char * Search ; | |
2452 for (Search = kvList ; *Search ; Search += strlen(Search) + 1) { | |
2453 if (strncmp (Search, Key, n) == 0) { | |
2454 if (Search[n] == '=') return Search + n + 1 ; | |
2455 if (Search[n] == 0) return (char *) "1" ; | |
2456 } | |
2457 } | |
2458 return NULL ; | |
2459 } | |
2460 | |
2461 static int kvGetInt (char * kvList, const char * Key, int Default) { | |
2462 char * v = kvGet (kvList, Key) ; | |
2463 int rslt = v ? ::strtol (v, NULL, 0) : Default ; | |
2464 if (Knob_ReportSettings && v != NULL) { | |
2465 ::printf (" SyncKnob: %s %d(%d)\n", Key, rslt, Default) ; | |
2466 ::fflush (stdout) ; | |
2467 } | |
2468 return rslt ; | |
2469 } | |
2470 | |
2471 void ObjectMonitor::DeferredInitialize () { | |
2472 if (InitDone > 0) return ; | |
2473 if (Atomic::cmpxchg (-1, &InitDone, 0) != 0) { | |
2474 while (InitDone != 1) ; | |
2475 return ; | |
2476 } | |
2477 | |
2478 // One-shot global initialization ... | |
2479 // The initialization is idempotent, so we don't need locks. | |
2480 // In the future consider doing this via os::init_2(). | |
2481 // SyncKnobs consist of <Key>=<Value> pairs in the style | |
2482 // of environment variables. Start by converting ':' to NUL. | |
2483 | |
2484 if (SyncKnobs == NULL) SyncKnobs = "" ; | |
2485 | |
2486 size_t sz = strlen (SyncKnobs) ; | |
2487 char * knobs = (char *) malloc (sz + 2) ; | |
2488 if (knobs == NULL) { | |
10161
746b070f5022
8011661: Insufficient memory message says "malloc" when sometimes it should say "mmap"
ccheung
parents:
7629
diff
changeset
|
2489 vm_exit_out_of_memory (sz + 2, OOM_MALLOC_ERROR, "Parse SyncKnobs") ; |
1878 | 2490 guarantee (0, "invariant") ; |
2491 } | |
2492 strcpy (knobs, SyncKnobs) ; | |
2493 knobs[sz+1] = 0 ; | |
2494 for (char * p = knobs ; *p ; p++) { | |
2495 if (*p == ':') *p = 0 ; | |
2496 } | |
2497 | |
2498 #define SETKNOB(x) { Knob_##x = kvGetInt (knobs, #x, Knob_##x); } | |
2499 SETKNOB(ReportSettings) ; | |
2500 SETKNOB(Verbose) ; | |
2501 SETKNOB(FixedSpin) ; | |
2502 SETKNOB(SpinLimit) ; | |
2503 SETKNOB(SpinBase) ; | |
2504 SETKNOB(SpinBackOff); | |
2505 SETKNOB(CASPenalty) ; | |
2506 SETKNOB(OXPenalty) ; | |
2507 SETKNOB(LogSpins) ; | |
2508 SETKNOB(SpinSetSucc) ; | |
2509 SETKNOB(SuccEnabled) ; | |
2510 SETKNOB(SuccRestrict) ; | |
2511 SETKNOB(Penalty) ; | |
2512 SETKNOB(Bonus) ; | |
2513 SETKNOB(BonusB) ; | |
2514 SETKNOB(Poverty) ; | |
2515 SETKNOB(SpinAfterFutile) ; | |
2516 SETKNOB(UsePause) ; | |
2517 SETKNOB(SpinEarly) ; | |
2518 SETKNOB(OState) ; | |
2519 SETKNOB(MaxSpinners) ; | |
2520 SETKNOB(PreSpin) ; | |
2521 SETKNOB(ExitPolicy) ; | |
2522 SETKNOB(QMode); | |
2523 SETKNOB(ResetEvent) ; | |
2524 SETKNOB(MoveNotifyee) ; | |
2525 SETKNOB(FastHSSEC) ; | |
2526 #undef SETKNOB | |
2527 | |
2528 if (os::is_MP()) { | |
2529 BackOffMask = (1 << Knob_SpinBackOff) - 1 ; | |
2530 if (Knob_ReportSettings) ::printf ("BackOffMask=%X\n", BackOffMask) ; | |
2531 // CONSIDER: BackOffMask = ROUNDUP_NEXT_POWER2 (ncpus-1) | |
2532 } else { | |
2533 Knob_SpinLimit = 0 ; | |
2534 Knob_SpinBase = 0 ; | |
2535 Knob_PreSpin = 0 ; | |
2536 Knob_FixedSpin = -1 ; | |
2537 } | |
2538 | |
2539 if (Knob_LogSpins == 0) { | |
2540 ObjectMonitor::_sync_FailedSpins = NULL ; | |
2541 } | |
2542 | |
2543 free (knobs) ; | |
2544 OrderAccess::fence() ; | |
2545 InitDone = 1 ; | |
2546 } | |
2547 | |
2548 #ifndef PRODUCT | |
2549 void ObjectMonitor::verify() { | |
2550 } | |
2551 | |
2552 void ObjectMonitor::print() { | |
2553 } | |
2554 #endif |