blob: 3b13159f87f6b348b89a73daca7379df42be9f4c [file] [log] [blame]
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Andy McFadden581bed72009-10-15 11:24:54 -070016
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080017/*
18 * Fundamental synchronization mechanisms.
19 *
20 * The top part of the file has operations on "monitor" structs; the
21 * next part has the native calls on objects.
22 *
23 * The current implementation uses "thin locking" to avoid allocating
24 * an Object's full Monitor struct until absolutely necessary (i.e.,
25 * during contention or a call to wait()).
26 *
27 * TODO: make improvements to thin locking
28 * We may be able to improve performance and reduce memory requirements by:
29 * - reverting to a thin lock once the Monitor is no longer necessary
30 * - using a pool of monitor objects, with some sort of recycling scheme
31 *
32 * TODO: recycle native-level monitors when objects are garbage collected.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080033 */
34#include "Dalvik.h"
35
36#include <stdlib.h>
37#include <unistd.h>
38#include <pthread.h>
39#include <time.h>
40#include <sys/time.h>
41#include <errno.h>
42
43#define LOG_THIN LOGV
44
45#ifdef WITH_DEADLOCK_PREDICTION /* fwd */
46static const char* kStartBanner =
47 "<-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#";
48static const char* kEndBanner =
49 "#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#->";
50
51/*
52 * Unsorted, expanding list of objects.
53 *
54 * This is very similar to PointerSet (which came into existence after this),
55 * but these are unsorted, uniqueness is not enforced by the "add" function,
56 * and the base object isn't allocated on the heap.
57 */
58typedef struct ExpandingObjectList {
59 u2 alloc;
60 u2 count;
61 Object** list;
62} ExpandingObjectList;
63
64/* fwd */
65static void updateDeadlockPrediction(Thread* self, Object* obj);
66static void removeCollectedObject(Object* obj);
67static void expandObjClear(ExpandingObjectList* pList);
68#endif
69
70/*
71 * Every Object has a monitor associated with it, but not every Object is
72 * actually locked. Even the ones that are locked do not need a
73 * full-fledged monitor until a) there is actual contention or b) wait()
74 * is called on the Object.
75 *
76 * For Dalvik, we have implemented a scheme similar to the one described
77 * in Bacon et al.'s "Thin locks: featherweight synchronization for Java"
78 * (ACM 1998). Things are even easier for us, though, because we have
79 * a full 32 bits to work with.
80 *
Carl Shapiro94338aa2009-12-21 11:42:59 -080081 * The two states of an Object's lock are referred to as "thin" and
82 * "fat". A lock may transition from the "thin" state to the "fat"
83 * state and this transition is referred to as inflation. Once a lock
84 * has been inflated it remains in the "fat" state indefinitely.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080085 *
Carl Shapiro77f52eb2009-12-24 19:56:53 -080086 * The lock value itself is stored in Object.lock. The LSB of the
87 * lock encodes its state. When cleared, the lock is in the "thin"
88 * state and its bits are formatted as follows:
Carl Shapiro71938022009-12-22 13:49:53 -080089 *
Carl Shapiro94338aa2009-12-21 11:42:59 -080090 * [31 ---- 19] [18 ---- 3] [2 ---- 1] [0]
91 * lock count thread id hash state 0
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080092 *
Carl Shapiro77f52eb2009-12-24 19:56:53 -080093 * When set, the lock is in the "fat" state and its bits are formatted
Carl Shapiro94338aa2009-12-21 11:42:59 -080094 * as follows:
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080095 *
Carl Shapiro94338aa2009-12-21 11:42:59 -080096 * [31 ---- 3] [2 ---- 1] [0]
97 * pointer hash state 1
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080098 *
99 * For an in-depth description of the mechanics of thin-vs-fat locking,
100 * read the paper referred to above.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800101 */
102
103/*
104 * Monitors provide:
105 * - mutually exclusive access to resources
106 * - a way for multiple threads to wait for notification
107 *
108 * In effect, they fill the role of both mutexes and condition variables.
109 *
110 * Only one thread can own the monitor at any time. There may be several
111 * threads waiting on it (the wait call unlocks it). One or more waiting
112 * threads may be getting interrupted or notified at any given time.
113 */
114struct Monitor {
115 Thread* owner; /* which thread currently owns the lock? */
116 int lockCount; /* owner's recursive lock depth */
117 Object* obj; /* what object are we part of [debug only] */
118
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800119 Thread* waitSet; /* threads currently waiting on this monitor */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800120
121 pthread_mutex_t lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800122
123 Monitor* next;
124
125#ifdef WITH_DEADLOCK_PREDICTION
126 /*
127 * Objects that have been locked immediately after this one in the
128 * past. We use an expanding flat array, allocated on first use, to
129 * minimize allocations. Deletions from the list, expected to be
130 * infrequent, are crunched down.
131 */
132 ExpandingObjectList historyChildren;
133
134 /*
135 * We also track parents. This isn't strictly necessary, but it makes
136 * the cleanup at GC time significantly faster.
137 */
138 ExpandingObjectList historyParents;
139
140 /* used during cycle detection */
141 bool historyMark;
142
143 /* stack trace, established the first time we locked the object */
144 int historyStackDepth;
145 int* historyRawStackTrace;
146#endif
147};
148
149
150/*
151 * Create and initialize a monitor.
152 */
153Monitor* dvmCreateMonitor(Object* obj)
154{
155 Monitor* mon;
156
157 mon = (Monitor*) calloc(1, sizeof(Monitor));
158 if (mon == NULL) {
159 LOGE("Unable to allocate monitor\n");
160 dvmAbort();
161 }
Carl Shapiro94338aa2009-12-21 11:42:59 -0800162 if (((u4)mon & 7) != 0) {
163 LOGE("Misaligned monitor: %p\n", mon);
164 dvmAbort();
165 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800166 mon->obj = obj;
167 dvmInitMutex(&mon->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800168
169 /* replace the head of the list with the new monitor */
170 do {
171 mon->next = gDvm.monitorList;
172 } while (!ATOMIC_CMP_SWAP((int32_t*)(void*)&gDvm.monitorList,
173 (int32_t)mon->next, (int32_t)mon));
174
175 return mon;
176}
177
178/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800179 * Free the monitor list. Only used when shutting the VM down.
180 */
181void dvmFreeMonitorList(void)
182{
183 Monitor* mon;
184 Monitor* nextMon;
185
186 mon = gDvm.monitorList;
187 while (mon != NULL) {
188 nextMon = mon->next;
189
190#ifdef WITH_DEADLOCK_PREDICTION
191 expandObjClear(&mon->historyChildren);
192 expandObjClear(&mon->historyParents);
193 free(mon->historyRawStackTrace);
194#endif
195 free(mon);
196 mon = nextMon;
197 }
198}
199
200/*
201 * Log some info about our monitors.
202 */
203void dvmDumpMonitorInfo(const char* msg)
204{
205#if QUIET_ZYGOTE_MONITOR
206 if (gDvm.zygote) {
207 return;
208 }
209#endif
210
211 int totalCount;
212 int liveCount;
213
214 totalCount = liveCount = 0;
215 Monitor* mon = gDvm.monitorList;
216 while (mon != NULL) {
217 totalCount++;
218 if (mon->obj != NULL)
219 liveCount++;
220 mon = mon->next;
221 }
222
223 LOGD("%s: monitor list has %d entries (%d live)\n",
224 msg, totalCount, liveCount);
225}
226
227/*
228 * Get the object that a monitor is part of.
229 */
230Object* dvmGetMonitorObject(Monitor* mon)
231{
232 if (mon == NULL)
233 return NULL;
234 else
235 return mon->obj;
236}
237
238/*
Carl Shapiro30aa9972010-01-13 22:07:50 -0800239 * Returns the thread id of the thread owning the given lock.
240 */
241static u4 lockOwner(Object* obj)
242{
243 Thread *owner;
244 u4 lock;
245
246 assert(obj != NULL);
247 /*
248 * Since we're reading the lock value multiple times, latch it so
249 * that it doesn't change out from under us if we get preempted.
250 */
251 lock = obj->lock;
252 if (LW_SHAPE(lock) == LW_SHAPE_THIN) {
253 return LW_LOCK_OWNER(lock);
254 } else {
255 owner = LW_MONITOR(lock)->owner;
256 return owner ? owner->threadId : 0;
257 }
258}
259
260/*
Andy McFaddenfd542662010-03-12 13:39:59 -0800261 * Get the thread that holds the lock on the specified object. The
262 * object may be unlocked, thin-locked, or fat-locked.
263 *
264 * The caller must lock the thread list before calling here.
265 */
266Thread* dvmGetObjectLockHolder(Object* obj)
267{
268 u4 threadId = lockOwner(obj);
269
270 if (threadId == 0)
271 return NULL;
272 return dvmGetThreadByThreadId(threadId);
273}
274
275/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800276 * Checks whether the given thread holds the given
277 * objects's lock.
278 */
279bool dvmHoldsLock(Thread* thread, Object* obj)
280{
281 if (thread == NULL || obj == NULL) {
282 return false;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800283 } else {
Carl Shapiro30aa9972010-01-13 22:07:50 -0800284 return thread->threadId == lockOwner(obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800285 }
286}
287
288/*
289 * Free the monitor associated with an object and make the object's lock
290 * thin again. This is called during garbage collection.
291 */
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800292static void freeObjectMonitor(Object* obj)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800293{
294 Monitor *mon;
295
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800296 assert(LW_SHAPE(obj->lock) == LW_SHAPE_FAT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800297
298#ifdef WITH_DEADLOCK_PREDICTION
299 if (gDvm.deadlockPredictMode != kDPOff)
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800300 removeCollectedObject(obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800301#endif
302
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800303 mon = LW_MONITOR(obj->lock);
304 obj->lock = DVM_LOCK_INITIAL_THIN_VALUE;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800305
306 /* This lock is associated with an object
307 * that's being swept. The only possible way
308 * anyone could be holding this lock would be
309 * if some JNI code locked but didn't unlock
310 * the object, in which case we've got some bad
311 * native code somewhere.
312 */
Carl Shapiro1ff876d2010-04-04 01:56:48 -0700313 assert(pthread_mutex_trylock(&mon->lock) == 0);
314 assert(pthread_mutex_unlock(&mon->lock) == 0);
Carl Shapiro980ffb02010-03-13 22:34:01 -0800315 dvmDestroyMutex(&mon->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800316#ifdef WITH_DEADLOCK_PREDICTION
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800317 expandObjClear(&mon->historyChildren);
318 expandObjClear(&mon->historyParents);
319 free(mon->historyRawStackTrace);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800320#endif
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800321 free(mon);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800322}
323
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800324/*
325 * Frees monitor objects belonging to unmarked objects.
326 */
327void dvmSweepMonitorList(Monitor** mon, int (*isUnmarkedObject)(void*))
328{
329 Monitor handle;
330 Monitor *prev, *curr;
331 Object *obj;
332
333 assert(mon != NULL);
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800334 assert(isUnmarkedObject != NULL);
335 prev = &handle;
336 prev->next = curr = *mon;
337 while (curr != NULL) {
338 obj = curr->obj;
339 if (obj != NULL && (*isUnmarkedObject)(obj) != 0) {
340 prev->next = curr = curr->next;
341 freeObjectMonitor(obj);
342 } else {
343 prev = curr;
344 curr = curr->next;
345 }
346 }
347 *mon = handle.next;
348}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800349
350/*
351 * Lock a monitor.
352 */
353static void lockMonitor(Thread* self, Monitor* mon)
354{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800355 if (mon->owner == self) {
356 mon->lockCount++;
357 } else {
358 ThreadStatus oldStatus;
359
Carl Shapiro980ffb02010-03-13 22:34:01 -0800360 if (dvmTryLockMutex(&mon->lock) != 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800361 /* mutex is locked, switch to wait status and sleep on it */
362 oldStatus = dvmChangeStatus(self, THREAD_MONITOR);
Carl Shapiro980ffb02010-03-13 22:34:01 -0800363 dvmLockMutex(&mon->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800364 dvmChangeStatus(self, oldStatus);
365 }
366
367 mon->owner = self;
368 assert(mon->lockCount == 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800369 }
370}
371
372/*
373 * Try to lock a monitor.
374 *
375 * Returns "true" on success.
376 */
377static bool tryLockMonitor(Thread* self, Monitor* mon)
378{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800379 if (mon->owner == self) {
380 mon->lockCount++;
381 return true;
382 } else {
Carl Shapiro980ffb02010-03-13 22:34:01 -0800383 if (dvmTryLockMutex(&mon->lock) == 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800384 mon->owner = self;
385 assert(mon->lockCount == 0);
386 return true;
387 } else {
388 return false;
389 }
390 }
391}
392
393
394/*
395 * Unlock a monitor.
396 *
397 * Returns true if the unlock succeeded.
398 * If the unlock failed, an exception will be pending.
399 */
400static bool unlockMonitor(Thread* self, Monitor* mon)
401{
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800402 assert(self != NULL);
Carl Shapiro92277082010-04-06 15:35:59 -0700403 assert(mon != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800404 if (mon->owner == self) {
405 /*
406 * We own the monitor, so nobody else can be in here.
407 */
408 if (mon->lockCount == 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800409 mon->owner = NULL;
Carl Shapiro980ffb02010-03-13 22:34:01 -0800410 dvmUnlockMutex(&mon->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800411 } else {
412 mon->lockCount--;
413 }
414 } else {
415 /*
416 * We don't own this, so we're not allowed to unlock it.
417 * The JNI spec says that we should throw IllegalMonitorStateException
418 * in this case.
419 */
Carl Shapiro91117572010-02-24 02:30:55 -0800420 dvmThrowExceptionFmt("Ljava/lang/IllegalMonitorStateException;",
Carl Shapiro92277082010-04-06 15:35:59 -0700421 "unlock of unowned monitor");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800422 return false;
423 }
424 return true;
425}
426
427/*
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800428 * Checks the wait set for circular structure. Returns 0 if the list
Carl Shapirob4539192010-01-04 16:50:00 -0800429 * is not circular. Otherwise, returns 1. Used only by asserts.
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800430 */
431static int waitSetCheck(Monitor *mon)
432{
433 Thread *fast, *slow;
434 size_t n;
435
436 assert(mon != NULL);
437 fast = slow = mon->waitSet;
438 n = 0;
439 for (;;) {
440 if (fast == NULL) return 0;
441 if (fast->waitNext == NULL) return 0;
Carl Shapiro5f56e672010-01-05 20:38:03 -0800442 if (fast == slow && n > 0) return 1;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800443 n += 2;
444 fast = fast->waitNext->waitNext;
445 slow = slow->waitNext;
446 }
447}
448
449/*
Carl Shapiro30aa9972010-01-13 22:07:50 -0800450 * Links a thread into a monitor's wait set. The monitor lock must be
451 * held by the caller of this routine.
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800452 */
453static void waitSetAppend(Monitor *mon, Thread *thread)
454{
455 Thread *elt;
456
457 assert(mon != NULL);
Carl Shapiro30aa9972010-01-13 22:07:50 -0800458 assert(mon->owner == dvmThreadSelf());
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800459 assert(thread != NULL);
460 assert(thread->waitNext == NULL);
461 assert(waitSetCheck(mon) == 0);
462 if (mon->waitSet == NULL) {
463 mon->waitSet = thread;
464 return;
465 }
466 elt = mon->waitSet;
467 while (elt->waitNext != NULL) {
468 elt = elt->waitNext;
469 }
470 elt->waitNext = thread;
471}
472
473/*
Carl Shapiro30aa9972010-01-13 22:07:50 -0800474 * Unlinks a thread from a monitor's wait set. The monitor lock must
475 * be held by the caller of this routine.
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800476 */
477static void waitSetRemove(Monitor *mon, Thread *thread)
478{
479 Thread *elt;
480
481 assert(mon != NULL);
Carl Shapiro30aa9972010-01-13 22:07:50 -0800482 assert(mon->owner == dvmThreadSelf());
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800483 assert(thread != NULL);
484 assert(waitSetCheck(mon) == 0);
485 if (mon->waitSet == NULL) {
486 return;
487 }
488 if (mon->waitSet == thread) {
489 mon->waitSet = thread->waitNext;
490 thread->waitNext = NULL;
491 return;
492 }
493 elt = mon->waitSet;
494 while (elt->waitNext != NULL) {
495 if (elt->waitNext == thread) {
496 elt->waitNext = thread->waitNext;
497 thread->waitNext = NULL;
498 return;
499 }
500 elt = elt->waitNext;
501 }
502}
503
Carl Shapirob4539192010-01-04 16:50:00 -0800504/*
505 * Converts the given relative waiting time into an absolute time.
506 */
Bill Buzbeefccb31d2010-02-04 16:09:55 -0800507void absoluteTime(s8 msec, s4 nsec, struct timespec *ts)
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800508{
509 s8 endSec;
510
511#ifdef HAVE_TIMEDWAIT_MONOTONIC
512 clock_gettime(CLOCK_MONOTONIC, ts);
513#else
514 {
515 struct timeval tv;
516 gettimeofday(&tv, NULL);
517 ts->tv_sec = tv.tv_sec;
518 ts->tv_nsec = tv.tv_usec * 1000;
519 }
520#endif
521 endSec = ts->tv_sec + msec / 1000;
522 if (endSec >= 0x7fffffff) {
523 LOGV("NOTE: end time exceeds epoch\n");
524 endSec = 0x7ffffffe;
525 }
526 ts->tv_sec = endSec;
527 ts->tv_nsec = (ts->tv_nsec + (msec % 1000) * 1000000) + nsec;
528
529 /* catch rollover */
530 if (ts->tv_nsec >= 1000000000L) {
531 ts->tv_sec++;
532 ts->tv_nsec -= 1000000000L;
533 }
534}
535
Bill Buzbeefccb31d2010-02-04 16:09:55 -0800536int dvmRelativeCondWait(pthread_cond_t* cond, pthread_mutex_t* mutex,
537 s8 msec, s4 nsec)
538{
539 int ret;
540 struct timespec ts;
541 absoluteTime(msec, nsec, &ts);
542#if defined(HAVE_TIMEDWAIT_MONOTONIC)
543 ret = pthread_cond_timedwait_monotonic(cond, mutex, &ts);
544#else
545 ret = pthread_cond_timedwait(cond, mutex, &ts);
546#endif
547 assert(ret == 0 || ret == ETIMEDOUT);
548 return ret;
549}
550
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800551/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800552 * Wait on a monitor until timeout, interrupt, or notification. Used for
553 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
554 *
555 * If another thread calls Thread.interrupt(), we throw InterruptedException
556 * and return immediately if one of the following are true:
557 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
558 * - blocked in join(), join(long), or join(long, int) methods of Thread
559 * - blocked in sleep(long), or sleep(long, int) methods of Thread
560 * Otherwise, we set the "interrupted" flag.
561 *
562 * Checks to make sure that "nsec" is in the range 0-999999
563 * (i.e. fractions of a millisecond) and throws the appropriate
564 * exception if it isn't.
565 *
566 * The spec allows "spurious wakeups", and recommends that all code using
567 * Object.wait() do so in a loop. This appears to derive from concerns
568 * about pthread_cond_wait() on multiprocessor systems. Some commentary
569 * on the web casts doubt on whether these can/should occur.
570 *
571 * Since we're allowed to wake up "early", we clamp extremely long durations
572 * to return at the end of the 32-bit time epoch.
573 */
574static void waitMonitor(Thread* self, Monitor* mon, s8 msec, s4 nsec,
575 bool interruptShouldThrow)
576{
577 struct timespec ts;
578 bool wasInterrupted = false;
579 bool timed;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800580 int ret;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800581
Carl Shapiro71938022009-12-22 13:49:53 -0800582 assert(self != NULL);
583 assert(mon != NULL);
584
Carl Shapiro94338aa2009-12-21 11:42:59 -0800585 /* Make sure that we hold the lock. */
Carl Shapiro71938022009-12-22 13:49:53 -0800586 if (mon->owner != self) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800587 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
588 "object not locked by thread before wait()");
589 return;
590 }
591
592 /*
593 * Enforce the timeout range.
594 */
595 if (msec < 0 || nsec < 0 || nsec > 999999) {
596 dvmThrowException("Ljava/lang/IllegalArgumentException;",
597 "timeout arguments out of range");
598 return;
599 }
600
601 /*
602 * Compute absolute wakeup time, if necessary.
603 */
604 if (msec == 0 && nsec == 0) {
605 timed = false;
606 } else {
Bill Buzbeefccb31d2010-02-04 16:09:55 -0800607 absoluteTime(msec, nsec, &ts);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800608 timed = true;
609 }
610
611 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800612 * Add ourselves to the set of threads waiting on this monitor, and
613 * release our hold. We need to let it go even if we're a few levels
614 * deep in a recursive lock, and we need to restore that later.
615 *
Carl Shapiro142ef272010-01-25 12:51:31 -0800616 * We append to the wait set ahead of clearing the count and owner
617 * fields so the subroutine can check that the calling thread owns
618 * the monitor. Aside from that, the order of member updates is
619 * not order sensitive as we hold the pthread mutex.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800620 */
Carl Shapiro142ef272010-01-25 12:51:31 -0800621 waitSetAppend(mon, self);
622 int prevLockCount = mon->lockCount;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800623 mon->lockCount = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800624 mon->owner = NULL;
625
626 /*
627 * Update thread status. If the GC wakes up, it'll ignore us, knowing
628 * that we won't touch any references in this state, and we'll check
629 * our suspend mode before we transition out.
630 */
631 if (timed)
632 dvmChangeStatus(self, THREAD_TIMED_WAIT);
633 else
634 dvmChangeStatus(self, THREAD_WAIT);
635
Carl Shapiro980ffb02010-03-13 22:34:01 -0800636 dvmLockMutex(&self->waitMutex);
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800637
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800638 /*
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800639 * Set waitMonitor to the monitor object we will be waiting on.
640 * When waitMonitor is non-NULL a notifying or interrupting thread
641 * must signal the thread's waitCond to wake it up.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800642 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800643 assert(self->waitMonitor == NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800644 self->waitMonitor = mon;
645
646 /*
647 * Handle the case where the thread was interrupted before we called
648 * wait().
649 */
650 if (self->interrupted) {
651 wasInterrupted = true;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800652 self->waitMonitor = NULL;
Carl Shapiro980ffb02010-03-13 22:34:01 -0800653 dvmUnlockMutex(&self->waitMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800654 goto done;
655 }
656
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800657 /*
658 * Release the monitor lock and wait for a notification or
659 * a timeout to occur.
660 */
Carl Shapiro980ffb02010-03-13 22:34:01 -0800661 dvmUnlockMutex(&mon->lock);
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800662
663 if (!timed) {
664 ret = pthread_cond_wait(&self->waitCond, &self->waitMutex);
665 assert(ret == 0);
666 } else {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800667#ifdef HAVE_TIMEDWAIT_MONOTONIC
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800668 ret = pthread_cond_timedwait_monotonic(&self->waitCond, &self->waitMutex, &ts);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800669#else
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800670 ret = pthread_cond_timedwait(&self->waitCond, &self->waitMutex, &ts);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800671#endif
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800672 assert(ret == 0 || ret == ETIMEDOUT);
673 }
674 if (self->interrupted) {
675 wasInterrupted = true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800676 }
677
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800678 self->interrupted = false;
679 self->waitMonitor = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800680
Carl Shapiro980ffb02010-03-13 22:34:01 -0800681 dvmUnlockMutex(&self->waitMutex);
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800682
Carl Shapiro30aa9972010-01-13 22:07:50 -0800683 /* Reacquire the monitor lock. */
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800684 lockMonitor(self, mon);
685
Carl Shapiro142ef272010-01-25 12:51:31 -0800686done:
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800687 /*
Carl Shapiro07b35922010-01-25 14:48:30 -0800688 * We remove our thread from wait set after restoring the count
689 * and owner fields so the subroutine can check that the calling
690 * thread owns the monitor. Aside from that, the order of member
691 * updates is not order sensitive as we hold the pthread mutex.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800692 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800693 mon->owner = self;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800694 mon->lockCount = prevLockCount;
Carl Shapiro07b35922010-01-25 14:48:30 -0800695 waitSetRemove(mon, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800696
697 /* set self->status back to THREAD_RUNNING, and self-suspend if needed */
698 dvmChangeStatus(self, THREAD_RUNNING);
699
700 if (wasInterrupted) {
701 /*
702 * We were interrupted while waiting, or somebody interrupted an
Carl Shapiro30aa9972010-01-13 22:07:50 -0800703 * un-interruptible thread earlier and we're bailing out immediately.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800704 *
705 * The doc sayeth: "The interrupted status of the current thread is
706 * cleared when this exception is thrown."
707 */
708 self->interrupted = false;
709 if (interruptShouldThrow)
710 dvmThrowException("Ljava/lang/InterruptedException;", NULL);
711 }
712}
713
714/*
715 * Notify one thread waiting on this monitor.
716 */
717static void notifyMonitor(Thread* self, Monitor* mon)
718{
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800719 Thread* thread;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800720
Carl Shapiro71938022009-12-22 13:49:53 -0800721 assert(self != NULL);
722 assert(mon != NULL);
723
Carl Shapiro94338aa2009-12-21 11:42:59 -0800724 /* Make sure that we hold the lock. */
Carl Shapiro71938022009-12-22 13:49:53 -0800725 if (mon->owner != self) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800726 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
727 "object not locked by thread before notify()");
728 return;
729 }
Carl Shapiro30aa9972010-01-13 22:07:50 -0800730 /* Signal the first waiting thread in the wait set. */
731 while (mon->waitSet != NULL) {
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800732 thread = mon->waitSet;
733 mon->waitSet = thread->waitNext;
734 thread->waitNext = NULL;
Carl Shapiro980ffb02010-03-13 22:34:01 -0800735 dvmLockMutex(&thread->waitMutex);
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800736 /* Check to see if the thread is still waiting. */
737 if (thread->waitMonitor != NULL) {
738 pthread_cond_signal(&thread->waitCond);
Carl Shapiro980ffb02010-03-13 22:34:01 -0800739 dvmUnlockMutex(&thread->waitMutex);
Carl Shapiro30aa9972010-01-13 22:07:50 -0800740 return;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800741 }
Carl Shapiro980ffb02010-03-13 22:34:01 -0800742 dvmUnlockMutex(&thread->waitMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800743 }
744}
745
746/*
747 * Notify all threads waiting on this monitor.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800748 */
749static void notifyAllMonitor(Thread* self, Monitor* mon)
750{
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800751 Thread* thread;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800752
Carl Shapiro71938022009-12-22 13:49:53 -0800753 assert(self != NULL);
754 assert(mon != NULL);
755
Carl Shapiro94338aa2009-12-21 11:42:59 -0800756 /* Make sure that we hold the lock. */
Carl Shapiro71938022009-12-22 13:49:53 -0800757 if (mon->owner != self) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800758 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
759 "object not locked by thread before notifyAll()");
760 return;
761 }
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800762 /* Signal all threads in the wait set. */
763 while (mon->waitSet != NULL) {
764 thread = mon->waitSet;
765 mon->waitSet = thread->waitNext;
766 thread->waitNext = NULL;
Carl Shapiro980ffb02010-03-13 22:34:01 -0800767 dvmLockMutex(&thread->waitMutex);
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800768 /* Check to see if the thread is still waiting. */
769 if (thread->waitMonitor != NULL) {
770 pthread_cond_signal(&thread->waitCond);
771 }
Carl Shapiro980ffb02010-03-13 22:34:01 -0800772 dvmUnlockMutex(&thread->waitMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800773 }
774}
775
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800776/*
Carl Shapiro66bb7df2010-03-12 15:25:37 -0800777 * Changes the shape of a monitor from thin to fat, preserving the
778 * internal lock state. The calling thread must own the lock.
779 */
780static void inflateMonitor(Thread *self, Object *obj)
781{
782 Monitor *mon;
783 u4 thin;
784
785 assert(self != NULL);
786 assert(obj != NULL);
787 assert(LW_SHAPE(obj->lock) == LW_SHAPE_THIN);
788 assert(LW_LOCK_OWNER(obj->lock) == self->threadId);
789 /* Allocate and acquire a new monitor. */
790 mon = dvmCreateMonitor(obj);
791 lockMonitor(self, mon);
792 /* Propagate the lock state. */
793 thin = obj->lock;
794 mon->lockCount = LW_LOCK_COUNT(thin);
795 thin &= LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT;
796 thin |= (u4)mon | LW_SHAPE_FAT;
797 /* Publish the updated lock word. */
798 MEM_BARRIER();
799 obj->lock = thin;
800}
801
802/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800803 * Implements monitorenter for "synchronized" stuff.
804 *
805 * This does not fail or throw an exception (unless deadlock prediction
806 * is enabled and set to "err" mode).
807 */
808void dvmLockObject(Thread* self, Object *obj)
809{
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800810 volatile u4 *thinp;
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800811 ThreadStatus oldStatus;
812 useconds_t sleepDelay;
813 const useconds_t maxSleepDelay = 1 << 20;
814 u4 thin, newThin, threadId;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800815
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800816 assert(self != NULL);
817 assert(obj != NULL);
818 threadId = self->threadId;
819 thinp = &obj->lock;
820retry:
821 thin = *thinp;
822 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
823 /*
824 * The lock is a thin lock. The owner field is used to
825 * determine the acquire method, ordered by cost.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800826 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800827 if (LW_LOCK_OWNER(thin) == threadId) {
828 /*
829 * The calling thread owns the lock. Increment the
830 * value of the recursion count field.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800831 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800832 obj->lock += 1 << LW_LOCK_COUNT_SHIFT;
833 } else if (LW_LOCK_OWNER(thin) == 0) {
834 /*
835 * The lock is unowned. Install the thread id of the
836 * calling thread into the owner field. This is the
837 * common case. In performance critical code the JIT
838 * will have tried this before calling out to the VM.
839 */
840 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
841 if (!ATOMIC_CMP_SWAP((int32_t *)thinp, thin, newThin)) {
842 /*
843 * The acquire failed. Try again.
844 */
845 goto retry;
846 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800847 } else {
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800848 LOG_THIN("(%d) spin on lock %p: %#x (%#x) %#x",
849 threadId, &obj->lock, 0, *thinp, thin);
850 /*
851 * The lock is owned by another thread. Notify the VM
852 * that we are about to wait.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800853 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800854 oldStatus = dvmChangeStatus(self, THREAD_MONITOR);
855 /*
856 * Spin until the thin lock is released or inflated.
857 */
858 sleepDelay = 0;
859 for (;;) {
860 thin = *thinp;
861 /*
862 * Check the shape of the lock word. Another thread
863 * may have inflated the lock while we were waiting.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800864 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800865 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
866 if (LW_LOCK_OWNER(thin) == 0) {
867 /*
868 * The lock has been released. Install the
869 * thread id of the calling thread into the
870 * owner field.
871 */
872 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
873 if (ATOMIC_CMP_SWAP((int32_t *)thinp,
874 thin, newThin)) {
875 /*
876 * The acquire succeed. Break out of the
877 * loop and proceed to inflate the lock.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800878 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800879 break;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800880 }
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800881 } else {
882 /*
883 * The lock has not been released. Yield so
884 * the owning thread can run.
885 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800886 if (sleepDelay == 0) {
887 sched_yield();
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800888 sleepDelay = 1000;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800889 } else {
890 usleep(sleepDelay);
891 if (sleepDelay < maxSleepDelay / 2) {
892 sleepDelay *= 2;
893 }
894 }
895 }
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800896 } else {
897 /*
898 * The thin lock was inflated by another thread.
899 * Let the VM know we are no longer waiting and
900 * try again.
901 */
902 LOG_THIN("(%d) lock %p surprise-fattened",
903 threadId, &obj->lock);
904 dvmChangeStatus(self, oldStatus);
905 goto retry;
906 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800907 }
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800908 LOG_THIN("(%d) spin on lock done %p: %#x (%#x) %#x",
909 threadId, &obj->lock, 0, *thinp, thin);
910 /*
911 * We have acquired the thin lock. Let the VM know that
912 * we are no longer waiting.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800913 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800914 dvmChangeStatus(self, oldStatus);
915 /*
916 * Fatten the lock.
917 */
Carl Shapiro66bb7df2010-03-12 15:25:37 -0800918 inflateMonitor(self, obj);
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800919 LOG_THIN("(%d) lock %p fattened", threadId, &obj->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800920 }
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800921 } else {
922 /*
923 * The lock is a fat lock.
924 */
925 assert(LW_MONITOR(obj->lock) != NULL);
926 lockMonitor(self, LW_MONITOR(obj->lock));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800927 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800928#ifdef WITH_DEADLOCK_PREDICTION
929 /*
930 * See if we were allowed to grab the lock at this time. We do it
931 * *after* acquiring the lock, rather than before, so that we can
932 * freely update the Monitor struct. This seems counter-intuitive,
933 * but our goal is deadlock *prediction* not deadlock *prevention*.
934 * (If we actually deadlock, the situation is easy to diagnose from
935 * a thread dump, so there's no point making a special effort to do
936 * the checks before the lock is held.)
937 *
938 * This needs to happen before we add the object to the thread's
939 * monitor list, so we can tell the difference between first-lock and
940 * re-lock.
941 *
942 * It's also important that we do this while in THREAD_RUNNING, so
943 * that we don't interfere with cleanup operations in the GC.
944 */
945 if (gDvm.deadlockPredictMode != kDPOff) {
946 if (self->status != THREAD_RUNNING) {
947 LOGE("Bad thread status (%d) in DP\n", self->status);
948 dvmDumpThread(self, false);
949 dvmAbort();
950 }
951 assert(!dvmCheckException(self));
952 updateDeadlockPrediction(self, obj);
953 if (dvmCheckException(self)) {
954 /*
955 * If we're throwing an exception here, we need to free the
956 * lock. We add the object to the thread's monitor list so the
957 * "unlock" code can remove it.
958 */
959 dvmAddToMonitorList(self, obj, false);
960 dvmUnlockObject(self, obj);
961 LOGV("--- unlocked, pending is '%s'\n",
962 dvmGetException(self)->clazz->descriptor);
963 }
964 }
965
966 /*
967 * Add the locked object, and the current stack trace, to the list
968 * held by the Thread object. If deadlock prediction isn't on,
969 * don't capture the stack trace.
970 */
971 dvmAddToMonitorList(self, obj, gDvm.deadlockPredictMode != kDPOff);
972#elif defined(WITH_MONITOR_TRACKING)
973 /*
974 * Add the locked object to the list held by the Thread object.
975 */
976 dvmAddToMonitorList(self, obj, false);
977#endif
978}
979
980/*
981 * Implements monitorexit for "synchronized" stuff.
982 *
983 * On failure, throws an exception and returns "false".
984 */
985bool dvmUnlockObject(Thread* self, Object *obj)
986{
Carl Shapiro94338aa2009-12-21 11:42:59 -0800987 u4 thin;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800988
Carl Shapiroef5b4d32010-01-26 13:22:04 -0800989 assert(self != NULL);
990 assert(self->status == THREAD_RUNNING);
991 assert(obj != NULL);
Carl Shapiroef5b4d32010-01-26 13:22:04 -0800992 /*
993 * Cache the lock word as its value can change while we are
994 * examining its state.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800995 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800996 thin = obj->lock;
Carl Shapiroef5b4d32010-01-26 13:22:04 -0800997 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
998 /*
999 * The lock is thin. We must ensure that the lock is owned
1000 * by the given thread before unlocking it.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001001 */
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001002 if (LW_LOCK_OWNER(thin) == self->threadId) {
1003 /*
1004 * We are the lock owner. It is safe to update the lock
1005 * without CAS as lock ownership guards the lock itself.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001006 */
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001007 if (LW_LOCK_COUNT(thin) == 0) {
1008 /*
1009 * The lock was not recursively acquired, the common
1010 * case. Unlock by clearing all bits except for the
1011 * hash state.
1012 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -08001013 obj->lock &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001014 } else {
1015 /*
1016 * The object was recursively acquired. Decrement the
1017 * lock recursion count field.
1018 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -08001019 obj->lock -= 1 << LW_LOCK_COUNT_SHIFT;
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001020 }
1021 } else {
1022 /*
1023 * We do not own the lock. The JVM spec requires that we
1024 * throw an exception in this case.
1025 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001026 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001027 "unlock of unowned monitor");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001028 return false;
1029 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001030 } else {
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001031 /*
1032 * The lock is fat. We must check to see if unlockMonitor has
1033 * raised any exceptions before continuing.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001034 */
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001035 assert(LW_MONITOR(obj->lock) != NULL);
1036 if (!unlockMonitor(self, LW_MONITOR(obj->lock))) {
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001037 /*
1038 * An exception has been raised. Do not fall through.
1039 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001040 return false;
1041 }
1042 }
1043
1044#ifdef WITH_MONITOR_TRACKING
1045 /*
1046 * Remove the object from the Thread's list.
1047 */
1048 dvmRemoveFromMonitorList(self, obj);
1049#endif
1050
1051 return true;
1052}
1053
1054/*
1055 * Object.wait(). Also called for class init.
1056 */
1057void dvmObjectWait(Thread* self, Object *obj, s8 msec, s4 nsec,
1058 bool interruptShouldThrow)
1059{
Carl Shapiro66bb7df2010-03-12 15:25:37 -08001060 Monitor* mon;
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001061 u4 thin = obj->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001062
1063 /* If the lock is still thin, we need to fatten it.
1064 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001065 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001066 /* Make sure that 'self' holds the lock.
1067 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001068 if (LW_LOCK_OWNER(thin) != self->threadId) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001069 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
1070 "object not locked by thread before wait()");
1071 return;
1072 }
1073
1074 /* This thread holds the lock. We need to fatten the lock
1075 * so 'self' can block on it. Don't update the object lock
1076 * field yet, because 'self' needs to acquire the lock before
1077 * any other thread gets a chance.
1078 */
Carl Shapiro66bb7df2010-03-12 15:25:37 -08001079 inflateMonitor(self, obj);
1080 LOG_THIN("(%d) lock %p fattened by wait() to count %d",
1081 self->threadId, &obj->lock, mon->lockCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001082 }
Carl Shapiro66bb7df2010-03-12 15:25:37 -08001083 mon = LW_MONITOR(obj->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001084 waitMonitor(self, mon, msec, nsec, interruptShouldThrow);
1085}
1086
1087/*
1088 * Object.notify().
1089 */
1090void dvmObjectNotify(Thread* self, Object *obj)
1091{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001092 u4 thin = obj->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001093
1094 /* If the lock is still thin, there aren't any waiters;
1095 * waiting on an object forces lock fattening.
1096 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001097 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001098 /* Make sure that 'self' holds the lock.
1099 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001100 if (LW_LOCK_OWNER(thin) != self->threadId) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001101 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
1102 "object not locked by thread before notify()");
1103 return;
1104 }
1105
1106 /* no-op; there are no waiters to notify.
1107 */
1108 } else {
1109 /* It's a fat lock.
1110 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001111 notifyMonitor(self, LW_MONITOR(thin));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001112 }
1113}
1114
1115/*
1116 * Object.notifyAll().
1117 */
1118void dvmObjectNotifyAll(Thread* self, Object *obj)
1119{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001120 u4 thin = obj->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001121
1122 /* If the lock is still thin, there aren't any waiters;
1123 * waiting on an object forces lock fattening.
1124 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001125 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001126 /* Make sure that 'self' holds the lock.
1127 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001128 if (LW_LOCK_OWNER(thin) != self->threadId) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001129 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
1130 "object not locked by thread before notifyAll()");
1131 return;
1132 }
1133
1134 /* no-op; there are no waiters to notify.
1135 */
1136 } else {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001137 /* It's a fat lock.
1138 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001139 notifyAllMonitor(self, LW_MONITOR(thin));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001140 }
1141}
1142
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001143/*
1144 * This implements java.lang.Thread.sleep(long msec, int nsec).
1145 *
1146 * The sleep is interruptible by other threads, which means we can't just
1147 * plop into an OS sleep call. (We probably could if we wanted to send
1148 * signals around and rely on EINTR, but that's inefficient and relies
1149 * on native code respecting our signal mask.)
1150 *
1151 * We have to do all of this stuff for Object.wait() as well, so it's
1152 * easiest to just sleep on a private Monitor.
1153 *
1154 * It appears that we want sleep(0,0) to go through the motions of sleeping
1155 * for a very short duration, rather than just returning.
1156 */
1157void dvmThreadSleep(u8 msec, u4 nsec)
1158{
1159 Thread* self = dvmThreadSelf();
1160 Monitor* mon = gDvm.threadSleepMon;
1161
1162 /* sleep(0,0) wakes up immediately, wait(0,0) means wait forever; adjust */
1163 if (msec == 0 && nsec == 0)
1164 nsec++;
1165
1166 lockMonitor(self, mon);
1167 waitMonitor(self, mon, msec, nsec, true);
1168 unlockMonitor(self, mon);
1169}
1170
1171/*
1172 * Implement java.lang.Thread.interrupt().
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001173 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001174void dvmThreadInterrupt(Thread* thread)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001175{
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001176 assert(thread != NULL);
1177
Carl Shapiro980ffb02010-03-13 22:34:01 -08001178 dvmLockMutex(&thread->waitMutex);
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001179
1180 /*
1181 * If the interrupted flag is already set no additional action is
1182 * required.
1183 */
1184 if (thread->interrupted == true) {
Carl Shapiro980ffb02010-03-13 22:34:01 -08001185 dvmUnlockMutex(&thread->waitMutex);
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001186 return;
1187 }
1188
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001189 /*
1190 * Raise the "interrupted" flag. This will cause it to bail early out
1191 * of the next wait() attempt, if it's not currently waiting on
1192 * something.
1193 */
1194 thread->interrupted = true;
1195 MEM_BARRIER();
1196
1197 /*
1198 * Is the thread waiting?
1199 *
1200 * Note that fat vs. thin doesn't matter here; waitMonitor
1201 * is only set when a thread actually waits on a monitor,
1202 * which implies that the monitor has already been fattened.
1203 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001204 if (thread->waitMonitor != NULL) {
1205 pthread_cond_signal(&thread->waitCond);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001206 }
1207
Carl Shapiro980ffb02010-03-13 22:34:01 -08001208 dvmUnlockMutex(&thread->waitMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001209}
1210
Carl Shapiro30aa9972010-01-13 22:07:50 -08001211#ifndef WITH_COPYING_GC
Carl Shapiro94338aa2009-12-21 11:42:59 -08001212u4 dvmIdentityHashCode(Object *obj)
1213{
1214 return (u4)obj;
1215}
Carl Shapiro30aa9972010-01-13 22:07:50 -08001216#else
Carl Shapiro30aa9972010-01-13 22:07:50 -08001217/*
1218 * Returns the identity hash code of the given object.
1219 */
1220u4 dvmIdentityHashCode(Object *obj)
1221{
1222 Thread *self, *thread;
1223 volatile u4 *lw;
1224 size_t length;
1225 u4 lock, owner, hashState;
1226
1227 if (obj == NULL) {
1228 /*
1229 * Null is defined to have an identity hash code of 0.
1230 */
1231 return 0;
1232 }
1233 lw = &obj->lock;
1234retry:
1235 hashState = LW_HASH_STATE(*lw);
1236 if (hashState == LW_HASH_STATE_HASHED) {
1237 /*
1238 * The object has been hashed but has not had its hash code
1239 * relocated by the garbage collector. Use the raw object
1240 * address.
1241 */
1242 return (u4)obj >> 3;
1243 } else if (hashState == LW_HASH_STATE_HASHED_AND_MOVED) {
1244 /*
1245 * The object has been hashed and its hash code has been
1246 * relocated by the collector. Use the value of the naturally
1247 * aligned word following the instance data.
1248 */
1249 if (IS_CLASS_FLAG_SET(obj->clazz, CLASS_ISARRAY)) {
Carl Shapiro1e714bb2010-03-16 03:26:49 -07001250 length = dvmArrayObjectLength((ArrayObject *)obj);
Carl Shapiro30aa9972010-01-13 22:07:50 -08001251 length = (length + 3) & ~3;
1252 } else {
1253 length = obj->clazz->objectSize;
1254 }
1255 return *(u4 *)(((char *)obj) + length);
1256 } else if (hashState == LW_HASH_STATE_UNHASHED) {
1257 /*
1258 * The object has never been hashed. Change the hash state to
1259 * hashed and use the raw object address.
1260 */
1261 self = dvmThreadSelf();
1262 if (self->threadId == lockOwner(obj)) {
1263 /*
1264 * We already own the lock so we can update the hash state
1265 * directly.
1266 */
1267 *lw |= (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1268 return (u4)obj >> 3;
1269 }
1270 /*
1271 * We do not own the lock. Try acquiring the lock. Should
1272 * this fail, we must suspend the owning thread.
1273 */
1274 if (LW_SHAPE(*lw) == LW_SHAPE_THIN) {
1275 /*
1276 * If the lock is thin assume it is unowned. We simulate
1277 * an acquire, update, and release with a single CAS.
1278 */
1279 lock = DVM_LOCK_INITIAL_THIN_VALUE;
1280 lock |= (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1281 if (ATOMIC_CMP_SWAP((int32_t *)lw,
1282 (int32_t)DVM_LOCK_INITIAL_THIN_VALUE,
1283 (int32_t)lock)) {
1284 /*
1285 * A new lockword has been installed with a hash state
1286 * of hashed. Use the raw object address.
1287 */
1288 return (u4)obj >> 3;
1289 }
1290 } else {
1291 if (tryLockMonitor(self, LW_MONITOR(*lw))) {
1292 /*
1293 * The monitor lock has been acquired. Change the
1294 * hash state to hashed and use the raw object
1295 * address.
1296 */
1297 *lw |= (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1298 unlockMonitor(self, LW_MONITOR(*lw));
1299 return (u4)obj >> 3;
1300 }
1301 }
1302 /*
1303 * At this point we have failed to acquire the lock. We must
1304 * identify the owning thread and suspend it.
1305 */
1306 dvmLockThreadList(self);
1307 /*
1308 * Cache the lock word as its value can change between
1309 * determining its shape and retrieving its owner.
1310 */
1311 lock = *lw;
1312 if (LW_SHAPE(lock) == LW_SHAPE_THIN) {
1313 /*
1314 * Find the thread with the corresponding thread id.
1315 */
1316 owner = LW_LOCK_OWNER(lock);
1317 assert(owner != self->threadId);
1318 /*
1319 * If the lock has no owner do not bother scanning the
1320 * thread list and fall through to the failure handler.
1321 */
1322 thread = owner ? gDvm.threadList : NULL;
1323 while (thread != NULL) {
1324 if (thread->threadId == owner) {
1325 break;
1326 }
1327 thread = thread->next;
1328 }
1329 } else {
1330 thread = LW_MONITOR(lock)->owner;
1331 }
1332 /*
1333 * If thread is NULL the object has been released since the
1334 * thread list lock was acquired. Try again.
1335 */
1336 if (thread == NULL) {
1337 dvmUnlockThreadList();
1338 goto retry;
1339 }
1340 /*
1341 * Wait for the owning thread to suspend.
1342 */
1343 dvmSuspendThread(thread);
1344 if (dvmHoldsLock(thread, obj)) {
1345 /*
1346 * The owning thread has been suspended. We can safely
1347 * change the hash state to hashed.
1348 */
1349 *lw |= (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1350 dvmResumeThread(thread);
1351 dvmUnlockThreadList();
1352 return (u4)obj >> 3;
1353 }
1354 /*
1355 * The wrong thread has been suspended. Try again.
1356 */
1357 dvmResumeThread(thread);
1358 dvmUnlockThreadList();
1359 goto retry;
1360 }
1361 LOGE("object %p has an unknown hash state %#x", obj, hashState);
1362 dvmDumpThread(dvmThreadSelf(), false);
1363 dvmAbort();
1364 return 0; /* Quiet the compiler. */
1365}
1366#endif /* WITH_COPYING_GC */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001367
1368#ifdef WITH_DEADLOCK_PREDICTION
1369/*
1370 * ===========================================================================
1371 * Deadlock prediction
1372 * ===========================================================================
1373 */
1374/*
1375The idea is to predict the possibility of deadlock by recording the order
1376in which monitors are acquired. If we see an attempt to acquire a lock
1377out of order, we can identify the locks and offending code.
1378
1379To make this work, we need to keep track of the locks held by each thread,
1380and create history trees for each lock. When a thread tries to acquire
1381a new lock, we walk through the "history children" of the lock, looking
1382for a match with locks the thread already holds. If we find a match,
1383it means the thread has made a request that could result in a deadlock.
1384
1385To support recursive locks, we always allow re-locking a currently-held
1386lock, and maintain a recursion depth count.
1387
1388An ASCII-art example, where letters represent Objects:
1389
1390 A
1391 /|\
1392 / | \
1393 B | D
1394 \ |
1395 \|
1396 C
1397
1398The above is the tree we'd have after handling Object synchronization
1399sequences "ABC", "AC", "AD". A has three children, {B, C, D}. C is also
1400a child of B. (The lines represent pointers between parent and child.
1401Every node can have multiple parents and multiple children.)
1402
1403If we hold AC, and want to lock B, we recursively search through B's
1404children to see if A or C appears. It does, so we reject the attempt.
1405(A straightforward way to implement it: add a link from C to B, then
1406determine whether the graph starting at B contains a cycle.)
1407
1408If we hold AC and want to lock D, we would succeed, creating a new link
1409from C to D.
1410
1411The lock history and a stack trace is attached to the Object's Monitor
1412struct, which means we need to fatten every Object we lock (thin locking
1413is effectively disabled). If we don't need the stack trace we can
1414avoid fattening the leaf nodes, only fattening objects that need to hold
1415history trees.
1416
1417Updates to Monitor structs are only allowed for the thread that holds
1418the Monitor, so we actually do most of our deadlock prediction work after
1419the lock has been acquired.
1420
1421When an object with a monitor is GCed, we need to remove it from the
1422history trees. There are two basic approaches:
1423 (1) For through the entire set of known monitors, search all child
1424 lists for the object in question. This is rather slow, resulting
1425 in GC passes that take upwards of 10 seconds to complete.
1426 (2) Maintain "parent" pointers in each node. Remove the entries as
1427 required. This requires additional storage and maintenance for
1428 every operation, but is significantly faster at GC time.
1429For each GCed object, we merge all of the object's children into each of
1430the object's parents.
1431*/
1432
1433#if !defined(WITH_MONITOR_TRACKING)
1434# error "WITH_DEADLOCK_PREDICTION requires WITH_MONITOR_TRACKING"
1435#endif
1436
1437/*
1438 * Clear out the contents of an ExpandingObjectList, freeing any
1439 * dynamic allocations.
1440 */
1441static void expandObjClear(ExpandingObjectList* pList)
1442{
1443 if (pList->list != NULL) {
1444 free(pList->list);
1445 pList->list = NULL;
1446 }
1447 pList->alloc = pList->count = 0;
1448}
1449
1450/*
1451 * Get the number of objects currently stored in the list.
1452 */
1453static inline int expandBufGetCount(const ExpandingObjectList* pList)
1454{
1455 return pList->count;
1456}
1457
1458/*
1459 * Get the Nth entry from the list.
1460 */
1461static inline Object* expandBufGetEntry(const ExpandingObjectList* pList,
1462 int i)
1463{
1464 return pList->list[i];
1465}
1466
1467/*
1468 * Add a new entry to the list.
1469 *
1470 * We don't check for or try to enforce uniqueness. It's expected that
1471 * the higher-level code does this for us.
1472 */
1473static void expandObjAddEntry(ExpandingObjectList* pList, Object* obj)
1474{
1475 if (pList->count == pList->alloc) {
1476 /* time to expand */
1477 Object** newList;
1478
1479 if (pList->alloc == 0)
1480 pList->alloc = 4;
1481 else
1482 pList->alloc *= 2;
1483 LOGVV("expanding %p to %d\n", pList, pList->alloc);
1484 newList = realloc(pList->list, pList->alloc * sizeof(Object*));
1485 if (newList == NULL) {
1486 LOGE("Failed expanding DP object list (alloc=%d)\n", pList->alloc);
1487 dvmAbort();
1488 }
1489 pList->list = newList;
1490 }
1491
1492 pList->list[pList->count++] = obj;
1493}
1494
1495/*
1496 * Returns "true" if the element was successfully removed.
1497 */
1498static bool expandObjRemoveEntry(ExpandingObjectList* pList, Object* obj)
1499{
1500 int i;
1501
1502 for (i = pList->count-1; i >= 0; i--) {
1503 if (pList->list[i] == obj)
1504 break;
1505 }
1506 if (i < 0)
1507 return false;
1508
1509 if (i != pList->count-1) {
1510 /*
1511 * The order of elements is not important, so we just copy the
1512 * last entry into the new slot.
1513 */
1514 //memmove(&pList->list[i], &pList->list[i+1],
1515 // (pList->count-1 - i) * sizeof(pList->list[0]));
1516 pList->list[i] = pList->list[pList->count-1];
1517 }
1518
1519 pList->count--;
1520 pList->list[pList->count] = (Object*) 0xdecadead;
1521 return true;
1522}
1523
1524/*
1525 * Returns "true" if "obj" appears in the list.
1526 */
1527static bool expandObjHas(const ExpandingObjectList* pList, Object* obj)
1528{
1529 int i;
1530
1531 for (i = 0; i < pList->count; i++) {
1532 if (pList->list[i] == obj)
1533 return true;
1534 }
1535 return false;
1536}
1537
1538/*
1539 * Print the list contents to stdout. For debugging.
1540 */
1541static void expandObjDump(const ExpandingObjectList* pList)
1542{
1543 int i;
1544 for (i = 0; i < pList->count; i++)
1545 printf(" %p", pList->list[i]);
1546}
1547
1548/*
1549 * Check for duplicate entries. Returns the index of the first instance
1550 * of the duplicated value, or -1 if no duplicates were found.
1551 */
1552static int expandObjCheckForDuplicates(const ExpandingObjectList* pList)
1553{
1554 int i, j;
1555 for (i = 0; i < pList->count-1; i++) {
1556 for (j = i + 1; j < pList->count; j++) {
1557 if (pList->list[i] == pList->list[j]) {
1558 return i;
1559 }
1560 }
1561 }
1562
1563 return -1;
1564}
1565
1566
1567/*
1568 * Determine whether "child" appears in the list of objects associated
1569 * with the Monitor in "parent". If "parent" is a thin lock, we return
1570 * false immediately.
1571 */
1572static bool objectInChildList(const Object* parent, Object* child)
1573{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001574 u4 lock = parent->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001575 if (!IS_LOCK_FAT(&lock)) {
1576 //LOGI("on thin\n");
1577 return false;
1578 }
1579
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001580 return expandObjHas(&LW_MONITOR(lock)->historyChildren, child);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001581}
1582
1583/*
1584 * Print the child list.
1585 */
1586static void dumpKids(Object* parent)
1587{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001588 Monitor* mon = LW_MONITOR(parent->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001589
1590 printf("Children of %p:", parent);
1591 expandObjDump(&mon->historyChildren);
1592 printf("\n");
1593}
1594
1595/*
1596 * Add "child" to the list of children in "parent", and add "parent" to
1597 * the list of parents in "child".
1598 */
1599static void linkParentToChild(Object* parent, Object* child)
1600{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001601 //assert(LW_MONITOR(parent->lock)->owner == dvmThreadSelf()); // !owned for merge
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001602 assert(IS_LOCK_FAT(&parent->lock));
1603 assert(IS_LOCK_FAT(&child->lock));
1604 assert(parent != child);
1605 Monitor* mon;
1606
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001607 mon = LW_MONITOR(parent->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001608 assert(!expandObjHas(&mon->historyChildren, child));
1609 expandObjAddEntry(&mon->historyChildren, child);
1610
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001611 mon = LW_MONITOR(child->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001612 assert(!expandObjHas(&mon->historyParents, parent));
1613 expandObjAddEntry(&mon->historyParents, parent);
1614}
1615
1616
1617/*
1618 * Remove "child" from the list of children in "parent".
1619 */
1620static void unlinkParentFromChild(Object* parent, Object* child)
1621{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001622 //assert(LW_MONITOR(parent->lock)->owner == dvmThreadSelf()); // !owned for GC
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001623 assert(IS_LOCK_FAT(&parent->lock));
1624 assert(IS_LOCK_FAT(&child->lock));
1625 assert(parent != child);
1626 Monitor* mon;
1627
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001628 mon = LW_MONITOR(parent->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001629 if (!expandObjRemoveEntry(&mon->historyChildren, child)) {
1630 LOGW("WARNING: child %p not found in parent %p\n", child, parent);
1631 }
1632 assert(!expandObjHas(&mon->historyChildren, child));
1633 assert(expandObjCheckForDuplicates(&mon->historyChildren) < 0);
1634
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001635 mon = LW_MONITOR(child->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001636 if (!expandObjRemoveEntry(&mon->historyParents, parent)) {
1637 LOGW("WARNING: parent %p not found in child %p\n", parent, child);
1638 }
1639 assert(!expandObjHas(&mon->historyParents, parent));
1640 assert(expandObjCheckForDuplicates(&mon->historyParents) < 0);
1641}
1642
1643
1644/*
1645 * Log the monitors held by the current thread. This is done as part of
1646 * flagging an error.
1647 */
1648static void logHeldMonitors(Thread* self)
1649{
1650 char* name = NULL;
1651
1652 name = dvmGetThreadName(self);
1653 LOGW("Monitors currently held by thread (threadid=%d '%s')\n",
1654 self->threadId, name);
1655 LOGW("(most-recently-acquired on top):\n");
1656 free(name);
1657
1658 LockedObjectData* lod = self->pLockedObjects;
1659 while (lod != NULL) {
1660 LOGW("--- object %p[%d] (%s)\n",
1661 lod->obj, lod->recursionCount, lod->obj->clazz->descriptor);
1662 dvmLogRawStackTrace(lod->rawStackTrace, lod->stackDepth);
1663
1664 lod = lod->next;
1665 }
1666}
1667
1668/*
1669 * Recursively traverse the object hierarchy starting at "obj". We mark
1670 * ourselves on entry and clear the mark on exit. If we ever encounter
1671 * a marked object, we have a cycle.
1672 *
1673 * Returns "true" if all is well, "false" if we found a cycle.
1674 */
1675static bool traverseTree(Thread* self, const Object* obj)
1676{
1677 assert(IS_LOCK_FAT(&obj->lock));
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001678 Monitor* mon = LW_MONITOR(obj->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001679
1680 /*
1681 * Have we been here before?
1682 */
1683 if (mon->historyMark) {
1684 int* rawStackTrace;
1685 int stackDepth;
1686
1687 LOGW("%s\n", kStartBanner);
1688 LOGW("Illegal lock attempt:\n");
1689 LOGW("--- object %p (%s)\n", obj, obj->clazz->descriptor);
1690
1691 rawStackTrace = dvmFillInStackTraceRaw(self, &stackDepth);
1692 dvmLogRawStackTrace(rawStackTrace, stackDepth);
1693 free(rawStackTrace);
1694
1695 LOGW(" ");
1696 logHeldMonitors(self);
1697
1698 LOGW(" ");
1699 LOGW("Earlier, the following lock order (from last to first) was\n");
1700 LOGW("established -- stack trace is from first successful lock):\n");
1701 return false;
1702 }
1703 mon->historyMark = true;
1704
1705 /*
1706 * Examine the children. We do NOT hold these locks, so they might
1707 * very well transition from thin to fat or change ownership while
1708 * we work.
1709 *
1710 * NOTE: we rely on the fact that they cannot revert from fat to thin
1711 * while we work. This is currently a safe assumption.
1712 *
1713 * We can safely ignore thin-locked children, because by definition
1714 * they have no history and are leaf nodes. In the current
1715 * implementation we always fatten the locks to provide a place to
1716 * hang the stack trace.
1717 */
1718 ExpandingObjectList* pList = &mon->historyChildren;
1719 int i;
1720 for (i = expandBufGetCount(pList)-1; i >= 0; i--) {
1721 const Object* child = expandBufGetEntry(pList, i);
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001722 u4 lock = child->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001723 if (!IS_LOCK_FAT(&lock))
1724 continue;
1725 if (!traverseTree(self, child)) {
1726 LOGW("--- object %p (%s)\n", obj, obj->clazz->descriptor);
1727 dvmLogRawStackTrace(mon->historyRawStackTrace,
1728 mon->historyStackDepth);
1729 mon->historyMark = false;
1730 return false;
1731 }
1732 }
1733
1734 mon->historyMark = false;
1735
1736 return true;
1737}
1738
1739/*
1740 * Update the deadlock prediction tree, based on the current thread
1741 * acquiring "acqObj". This must be called before the object is added to
1742 * the thread's list of held monitors.
1743 *
1744 * If the thread already holds the lock (recursion), or this is a known
1745 * lock configuration, we return without doing anything. Otherwise, we add
1746 * a link from the most-recently-acquired lock in this thread to "acqObj"
1747 * after ensuring that the parent lock is "fat".
1748 *
1749 * This MUST NOT be called while a GC is in progress in another thread,
1750 * because we assume exclusive access to history trees in owned monitors.
1751 */
1752static void updateDeadlockPrediction(Thread* self, Object* acqObj)
1753{
1754 LockedObjectData* lod;
1755 LockedObjectData* mrl;
1756
1757 /*
1758 * Quick check for recursive access.
1759 */
1760 lod = dvmFindInMonitorList(self, acqObj);
1761 if (lod != NULL) {
1762 LOGV("+++ DP: recursive %p\n", acqObj);
1763 return;
1764 }
1765
1766 /*
1767 * Make the newly-acquired object's monitor "fat". In some ways this
1768 * isn't strictly necessary, but we need the GC to tell us when
1769 * "interesting" objects go away, and right now the only way to make
1770 * an object look interesting is to give it a monitor.
1771 *
1772 * This also gives us a place to hang a stack trace.
1773 *
1774 * Our thread holds the lock, so we're allowed to rewrite the lock
1775 * without worrying that something will change out from under us.
1776 */
1777 if (!IS_LOCK_FAT(&acqObj->lock)) {
1778 LOGVV("fattening lockee %p (recur=%d)\n",
Carl Shapiro94338aa2009-12-21 11:42:59 -08001779 acqObj, LW_LOCK_COUNT(acqObj->lock.thin));
Carl Shapiro66bb7df2010-03-12 15:25:37 -08001780 inflateMonitor(self, acqObj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001781 }
1782
1783 /* if we don't have a stack trace for this monitor, establish one */
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001784 if (LW_MONITOR(acqObj->lock)->historyRawStackTrace == NULL) {
1785 Monitor* mon = LW_MONITOR(acqObj->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001786 mon->historyRawStackTrace = dvmFillInStackTraceRaw(self,
1787 &mon->historyStackDepth);
1788 }
1789
1790 /*
1791 * We need to examine and perhaps modify the most-recently-locked
1792 * monitor. We own that, so there's no risk of another thread
1793 * stepping on us.
1794 *
1795 * Retrieve the most-recently-locked entry from our thread.
1796 */
1797 mrl = self->pLockedObjects;
1798 if (mrl == NULL)
1799 return; /* no other locks held */
1800
1801 /*
1802 * Do a quick check to see if "acqObj" is a direct descendant. We can do
1803 * this without holding the global lock because of our assertion that
1804 * a GC is not running in parallel -- nobody except the GC can
1805 * modify a history list in a Monitor they don't own, and we own "mrl".
1806 * (There might be concurrent *reads*, but no concurrent *writes.)
1807 *
1808 * If we find it, this is a known good configuration, and we're done.
1809 */
1810 if (objectInChildList(mrl->obj, acqObj))
1811 return;
1812
1813 /*
1814 * "mrl" is going to need to have a history tree. If it's currently
1815 * a thin lock, we make it fat now. The thin lock might have a
1816 * nonzero recursive lock count, which we need to carry over.
1817 *
1818 * Our thread holds the lock, so we're allowed to rewrite the lock
1819 * without worrying that something will change out from under us.
1820 */
1821 if (!IS_LOCK_FAT(&mrl->obj->lock)) {
1822 LOGVV("fattening parent %p f/b/o child %p (recur=%d)\n",
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001823 mrl->obj, acqObj, LW_LOCK_COUNT(mrl->obj->lock));
Carl Shapiro66bb7df2010-03-12 15:25:37 -08001824 inflateMonitor(self, mrl->obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001825 }
1826
1827 /*
1828 * We haven't seen this configuration before. We need to scan down
1829 * acqObj's tree to see if any of the monitors in self->pLockedObjects
1830 * appear. We grab a global lock before traversing or updating the
1831 * history list.
1832 *
1833 * If we find a match for any of our held locks, we know that the lock
1834 * has previously been acquired *after* acqObj, and we throw an error.
1835 *
1836 * The easiest way to do this is to create a link from "mrl" to "acqObj"
1837 * and do a recursive traversal, marking nodes as we cross them. If
1838 * we cross one a second time, we have a cycle and can throw an error.
1839 * (We do the flag-clearing traversal before adding the new link, so
1840 * that we're guaranteed to terminate.)
1841 *
1842 * If "acqObj" is a thin lock, it has no history, and we can create a
1843 * link to it without additional checks. [ We now guarantee that it's
1844 * always fat. ]
1845 */
1846 bool failed = false;
1847 dvmLockMutex(&gDvm.deadlockHistoryLock);
1848 linkParentToChild(mrl->obj, acqObj);
1849 if (!traverseTree(self, acqObj)) {
1850 LOGW("%s\n", kEndBanner);
1851 failed = true;
1852
1853 /* remove the entry so we're still okay when in "warning" mode */
1854 unlinkParentFromChild(mrl->obj, acqObj);
1855 }
1856 dvmUnlockMutex(&gDvm.deadlockHistoryLock);
1857
1858 if (failed) {
1859 switch (gDvm.deadlockPredictMode) {
1860 case kDPErr:
1861 dvmThrowException("Ldalvik/system/PotentialDeadlockError;", NULL);
1862 break;
1863 case kDPAbort:
1864 LOGE("Aborting due to potential deadlock\n");
1865 dvmAbort();
1866 break;
1867 default:
1868 /* warn only */
1869 break;
1870 }
1871 }
1872}
1873
1874/*
1875 * We're removing "child" from existence. We want to pull all of
1876 * child's children into "parent", filtering out duplicates. This is
1877 * called during the GC.
1878 *
1879 * This does not modify "child", which might have multiple parents.
1880 */
1881static void mergeChildren(Object* parent, const Object* child)
1882{
1883 Monitor* mon;
1884 int i;
1885
1886 assert(IS_LOCK_FAT(&child->lock));
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001887 mon = LW_MONITOR(child->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001888 ExpandingObjectList* pList = &mon->historyChildren;
1889
1890 for (i = expandBufGetCount(pList)-1; i >= 0; i--) {
1891 Object* grandChild = expandBufGetEntry(pList, i);
1892
1893 if (!objectInChildList(parent, grandChild)) {
1894 LOGVV("+++ migrating %p link to %p\n", grandChild, parent);
1895 linkParentToChild(parent, grandChild);
1896 } else {
1897 LOGVV("+++ parent %p already links to %p\n", parent, grandChild);
1898 }
1899 }
1900}
1901
1902/*
1903 * An object with a fat lock is being collected during a GC pass. We
1904 * want to remove it from any lock history trees that it is a part of.
1905 *
1906 * This may require updating the history trees in several monitors. The
1907 * monitor semantics guarantee that no other thread will be accessing
1908 * the history trees at the same time.
1909 */
1910static void removeCollectedObject(Object* obj)
1911{
1912 Monitor* mon;
1913
1914 LOGVV("+++ collecting %p\n", obj);
1915
1916#if 0
1917 /*
1918 * We're currently running through the entire set of known monitors.
1919 * This can be somewhat slow. We may want to keep lists of parents
1920 * in each child to speed up GC.
1921 */
1922 mon = gDvm.monitorList;
1923 while (mon != NULL) {
1924 Object* parent = mon->obj;
1925 if (parent != NULL) { /* value nulled for deleted entries */
1926 if (objectInChildList(parent, obj)) {
1927 LOGVV("removing child %p from parent %p\n", obj, parent);
1928 unlinkParentFromChild(parent, obj);
1929 mergeChildren(parent, obj);
1930 }
1931 }
1932 mon = mon->next;
1933 }
1934#endif
1935
1936 /*
1937 * For every parent of this object:
1938 * - merge all of our children into the parent's child list (creates
1939 * a two-way link between parent and child)
1940 * - remove ourselves from the parent's child list
1941 */
1942 ExpandingObjectList* pList;
1943 int i;
1944
1945 assert(IS_LOCK_FAT(&obj->lock));
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001946 mon = LW_MONITOR(obj->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001947 pList = &mon->historyParents;
1948 for (i = expandBufGetCount(pList)-1; i >= 0; i--) {
1949 Object* parent = expandBufGetEntry(pList, i);
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001950 Monitor* parentMon = LW_MONITOR(parent->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001951
1952 if (!expandObjRemoveEntry(&parentMon->historyChildren, obj)) {
1953 LOGW("WARNING: child %p not found in parent %p\n", obj, parent);
1954 }
1955 assert(!expandObjHas(&parentMon->historyChildren, obj));
1956
1957 mergeChildren(parent, obj);
1958 }
1959
1960 /*
1961 * For every child of this object:
1962 * - remove ourselves from the child's parent list
1963 */
1964 pList = &mon->historyChildren;
1965 for (i = expandBufGetCount(pList)-1; i >= 0; i--) {
1966 Object* child = expandBufGetEntry(pList, i);
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001967 Monitor* childMon = LW_MONITOR(child->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001968
1969 if (!expandObjRemoveEntry(&childMon->historyParents, obj)) {
1970 LOGW("WARNING: parent %p not found in child %p\n", obj, child);
1971 }
1972 assert(!expandObjHas(&childMon->historyParents, obj));
1973 }
1974}
1975
1976#endif /*WITH_DEADLOCK_PREDICTION*/