blob: c9624d0cdad4dc2a88247f2834e7be6c13c05815 [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);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800403 assert(mon != NULL); // can this happen?
404
405 if (mon->owner == self) {
406 /*
407 * We own the monitor, so nobody else can be in here.
408 */
409 if (mon->lockCount == 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800410 mon->owner = NULL;
Carl Shapiro980ffb02010-03-13 22:34:01 -0800411 dvmUnlockMutex(&mon->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800412 } else {
413 mon->lockCount--;
414 }
415 } else {
416 /*
417 * We don't own this, so we're not allowed to unlock it.
418 * The JNI spec says that we should throw IllegalMonitorStateException
419 * in this case.
420 */
Carl Shapiro91117572010-02-24 02:30:55 -0800421 dvmThrowExceptionFmt("Ljava/lang/IllegalMonitorStateException;",
422 "unlock of unowned monitor, self=%d owner=%d",
423 self->threadId,
424 mon->owner ? mon->owner->threadId : 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800425 return false;
426 }
427 return true;
428}
429
430/*
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800431 * Checks the wait set for circular structure. Returns 0 if the list
Carl Shapirob4539192010-01-04 16:50:00 -0800432 * is not circular. Otherwise, returns 1. Used only by asserts.
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800433 */
434static int waitSetCheck(Monitor *mon)
435{
436 Thread *fast, *slow;
437 size_t n;
438
439 assert(mon != NULL);
440 fast = slow = mon->waitSet;
441 n = 0;
442 for (;;) {
443 if (fast == NULL) return 0;
444 if (fast->waitNext == NULL) return 0;
Carl Shapiro5f56e672010-01-05 20:38:03 -0800445 if (fast == slow && n > 0) return 1;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800446 n += 2;
447 fast = fast->waitNext->waitNext;
448 slow = slow->waitNext;
449 }
450}
451
452/*
Carl Shapiro30aa9972010-01-13 22:07:50 -0800453 * Links a thread into a monitor's wait set. The monitor lock must be
454 * held by the caller of this routine.
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800455 */
456static void waitSetAppend(Monitor *mon, Thread *thread)
457{
458 Thread *elt;
459
460 assert(mon != NULL);
Carl Shapiro30aa9972010-01-13 22:07:50 -0800461 assert(mon->owner == dvmThreadSelf());
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800462 assert(thread != NULL);
463 assert(thread->waitNext == NULL);
464 assert(waitSetCheck(mon) == 0);
465 if (mon->waitSet == NULL) {
466 mon->waitSet = thread;
467 return;
468 }
469 elt = mon->waitSet;
470 while (elt->waitNext != NULL) {
471 elt = elt->waitNext;
472 }
473 elt->waitNext = thread;
474}
475
476/*
Carl Shapiro30aa9972010-01-13 22:07:50 -0800477 * Unlinks a thread from a monitor's wait set. The monitor lock must
478 * be held by the caller of this routine.
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800479 */
480static void waitSetRemove(Monitor *mon, Thread *thread)
481{
482 Thread *elt;
483
484 assert(mon != NULL);
Carl Shapiro30aa9972010-01-13 22:07:50 -0800485 assert(mon->owner == dvmThreadSelf());
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800486 assert(thread != NULL);
487 assert(waitSetCheck(mon) == 0);
488 if (mon->waitSet == NULL) {
489 return;
490 }
491 if (mon->waitSet == thread) {
492 mon->waitSet = thread->waitNext;
493 thread->waitNext = NULL;
494 return;
495 }
496 elt = mon->waitSet;
497 while (elt->waitNext != NULL) {
498 if (elt->waitNext == thread) {
499 elt->waitNext = thread->waitNext;
500 thread->waitNext = NULL;
501 return;
502 }
503 elt = elt->waitNext;
504 }
505}
506
Carl Shapirob4539192010-01-04 16:50:00 -0800507/*
508 * Converts the given relative waiting time into an absolute time.
509 */
Bill Buzbeefccb31d2010-02-04 16:09:55 -0800510void absoluteTime(s8 msec, s4 nsec, struct timespec *ts)
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800511{
512 s8 endSec;
513
514#ifdef HAVE_TIMEDWAIT_MONOTONIC
515 clock_gettime(CLOCK_MONOTONIC, ts);
516#else
517 {
518 struct timeval tv;
519 gettimeofday(&tv, NULL);
520 ts->tv_sec = tv.tv_sec;
521 ts->tv_nsec = tv.tv_usec * 1000;
522 }
523#endif
524 endSec = ts->tv_sec + msec / 1000;
525 if (endSec >= 0x7fffffff) {
526 LOGV("NOTE: end time exceeds epoch\n");
527 endSec = 0x7ffffffe;
528 }
529 ts->tv_sec = endSec;
530 ts->tv_nsec = (ts->tv_nsec + (msec % 1000) * 1000000) + nsec;
531
532 /* catch rollover */
533 if (ts->tv_nsec >= 1000000000L) {
534 ts->tv_sec++;
535 ts->tv_nsec -= 1000000000L;
536 }
537}
538
Bill Buzbeefccb31d2010-02-04 16:09:55 -0800539int dvmRelativeCondWait(pthread_cond_t* cond, pthread_mutex_t* mutex,
540 s8 msec, s4 nsec)
541{
542 int ret;
543 struct timespec ts;
544 absoluteTime(msec, nsec, &ts);
545#if defined(HAVE_TIMEDWAIT_MONOTONIC)
546 ret = pthread_cond_timedwait_monotonic(cond, mutex, &ts);
547#else
548 ret = pthread_cond_timedwait(cond, mutex, &ts);
549#endif
550 assert(ret == 0 || ret == ETIMEDOUT);
551 return ret;
552}
553
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800554/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800555 * Wait on a monitor until timeout, interrupt, or notification. Used for
556 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
557 *
558 * If another thread calls Thread.interrupt(), we throw InterruptedException
559 * and return immediately if one of the following are true:
560 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
561 * - blocked in join(), join(long), or join(long, int) methods of Thread
562 * - blocked in sleep(long), or sleep(long, int) methods of Thread
563 * Otherwise, we set the "interrupted" flag.
564 *
565 * Checks to make sure that "nsec" is in the range 0-999999
566 * (i.e. fractions of a millisecond) and throws the appropriate
567 * exception if it isn't.
568 *
569 * The spec allows "spurious wakeups", and recommends that all code using
570 * Object.wait() do so in a loop. This appears to derive from concerns
571 * about pthread_cond_wait() on multiprocessor systems. Some commentary
572 * on the web casts doubt on whether these can/should occur.
573 *
574 * Since we're allowed to wake up "early", we clamp extremely long durations
575 * to return at the end of the 32-bit time epoch.
576 */
577static void waitMonitor(Thread* self, Monitor* mon, s8 msec, s4 nsec,
578 bool interruptShouldThrow)
579{
580 struct timespec ts;
581 bool wasInterrupted = false;
582 bool timed;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800583 int ret;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800584
Carl Shapiro71938022009-12-22 13:49:53 -0800585 assert(self != NULL);
586 assert(mon != NULL);
587
Carl Shapiro94338aa2009-12-21 11:42:59 -0800588 /* Make sure that we hold the lock. */
Carl Shapiro71938022009-12-22 13:49:53 -0800589 if (mon->owner != self) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800590 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
591 "object not locked by thread before wait()");
592 return;
593 }
594
595 /*
596 * Enforce the timeout range.
597 */
598 if (msec < 0 || nsec < 0 || nsec > 999999) {
599 dvmThrowException("Ljava/lang/IllegalArgumentException;",
600 "timeout arguments out of range");
601 return;
602 }
603
604 /*
605 * Compute absolute wakeup time, if necessary.
606 */
607 if (msec == 0 && nsec == 0) {
608 timed = false;
609 } else {
Bill Buzbeefccb31d2010-02-04 16:09:55 -0800610 absoluteTime(msec, nsec, &ts);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800611 timed = true;
612 }
613
614 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800615 * Add ourselves to the set of threads waiting on this monitor, and
616 * release our hold. We need to let it go even if we're a few levels
617 * deep in a recursive lock, and we need to restore that later.
618 *
Carl Shapiro142ef272010-01-25 12:51:31 -0800619 * We append to the wait set ahead of clearing the count and owner
620 * fields so the subroutine can check that the calling thread owns
621 * the monitor. Aside from that, the order of member updates is
622 * not order sensitive as we hold the pthread mutex.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800623 */
Carl Shapiro142ef272010-01-25 12:51:31 -0800624 waitSetAppend(mon, self);
625 int prevLockCount = mon->lockCount;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800626 mon->lockCount = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800627 mon->owner = NULL;
628
629 /*
630 * Update thread status. If the GC wakes up, it'll ignore us, knowing
631 * that we won't touch any references in this state, and we'll check
632 * our suspend mode before we transition out.
633 */
634 if (timed)
635 dvmChangeStatus(self, THREAD_TIMED_WAIT);
636 else
637 dvmChangeStatus(self, THREAD_WAIT);
638
Carl Shapiro980ffb02010-03-13 22:34:01 -0800639 dvmLockMutex(&self->waitMutex);
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800640
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800641 /*
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800642 * Set waitMonitor to the monitor object we will be waiting on.
643 * When waitMonitor is non-NULL a notifying or interrupting thread
644 * must signal the thread's waitCond to wake it up.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800645 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800646 assert(self->waitMonitor == NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800647 self->waitMonitor = mon;
648
649 /*
650 * Handle the case where the thread was interrupted before we called
651 * wait().
652 */
653 if (self->interrupted) {
654 wasInterrupted = true;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800655 self->waitMonitor = NULL;
Carl Shapiro980ffb02010-03-13 22:34:01 -0800656 dvmUnlockMutex(&self->waitMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800657 goto done;
658 }
659
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800660 /*
661 * Release the monitor lock and wait for a notification or
662 * a timeout to occur.
663 */
Carl Shapiro980ffb02010-03-13 22:34:01 -0800664 dvmUnlockMutex(&mon->lock);
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800665
666 if (!timed) {
667 ret = pthread_cond_wait(&self->waitCond, &self->waitMutex);
668 assert(ret == 0);
669 } else {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800670#ifdef HAVE_TIMEDWAIT_MONOTONIC
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800671 ret = pthread_cond_timedwait_monotonic(&self->waitCond, &self->waitMutex, &ts);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800672#else
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800673 ret = pthread_cond_timedwait(&self->waitCond, &self->waitMutex, &ts);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800674#endif
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800675 assert(ret == 0 || ret == ETIMEDOUT);
676 }
677 if (self->interrupted) {
678 wasInterrupted = true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800679 }
680
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800681 self->interrupted = false;
682 self->waitMonitor = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800683
Carl Shapiro980ffb02010-03-13 22:34:01 -0800684 dvmUnlockMutex(&self->waitMutex);
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800685
Carl Shapiro30aa9972010-01-13 22:07:50 -0800686 /* Reacquire the monitor lock. */
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800687 lockMonitor(self, mon);
688
Carl Shapiro142ef272010-01-25 12:51:31 -0800689done:
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800690 /*
Carl Shapiro07b35922010-01-25 14:48:30 -0800691 * We remove our thread from wait set after restoring the count
692 * and owner fields so the subroutine can check that the calling
693 * thread owns the monitor. Aside from that, the order of member
694 * updates is not order sensitive as we hold the pthread mutex.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800695 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800696 mon->owner = self;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800697 mon->lockCount = prevLockCount;
Carl Shapiro07b35922010-01-25 14:48:30 -0800698 waitSetRemove(mon, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800699
700 /* set self->status back to THREAD_RUNNING, and self-suspend if needed */
701 dvmChangeStatus(self, THREAD_RUNNING);
702
703 if (wasInterrupted) {
704 /*
705 * We were interrupted while waiting, or somebody interrupted an
Carl Shapiro30aa9972010-01-13 22:07:50 -0800706 * un-interruptible thread earlier and we're bailing out immediately.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800707 *
708 * The doc sayeth: "The interrupted status of the current thread is
709 * cleared when this exception is thrown."
710 */
711 self->interrupted = false;
712 if (interruptShouldThrow)
713 dvmThrowException("Ljava/lang/InterruptedException;", NULL);
714 }
715}
716
717/*
718 * Notify one thread waiting on this monitor.
719 */
720static void notifyMonitor(Thread* self, Monitor* mon)
721{
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800722 Thread* thread;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800723
Carl Shapiro71938022009-12-22 13:49:53 -0800724 assert(self != NULL);
725 assert(mon != NULL);
726
Carl Shapiro94338aa2009-12-21 11:42:59 -0800727 /* Make sure that we hold the lock. */
Carl Shapiro71938022009-12-22 13:49:53 -0800728 if (mon->owner != self) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800729 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
730 "object not locked by thread before notify()");
731 return;
732 }
Carl Shapiro30aa9972010-01-13 22:07:50 -0800733 /* Signal the first waiting thread in the wait set. */
734 while (mon->waitSet != NULL) {
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800735 thread = mon->waitSet;
736 mon->waitSet = thread->waitNext;
737 thread->waitNext = NULL;
Carl Shapiro980ffb02010-03-13 22:34:01 -0800738 dvmLockMutex(&thread->waitMutex);
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800739 /* Check to see if the thread is still waiting. */
740 if (thread->waitMonitor != NULL) {
741 pthread_cond_signal(&thread->waitCond);
Carl Shapiro980ffb02010-03-13 22:34:01 -0800742 dvmUnlockMutex(&thread->waitMutex);
Carl Shapiro30aa9972010-01-13 22:07:50 -0800743 return;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800744 }
Carl Shapiro980ffb02010-03-13 22:34:01 -0800745 dvmUnlockMutex(&thread->waitMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800746 }
747}
748
749/*
750 * Notify all threads waiting on this monitor.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800751 */
752static void notifyAllMonitor(Thread* self, Monitor* mon)
753{
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800754 Thread* thread;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800755
Carl Shapiro71938022009-12-22 13:49:53 -0800756 assert(self != NULL);
757 assert(mon != NULL);
758
Carl Shapiro94338aa2009-12-21 11:42:59 -0800759 /* Make sure that we hold the lock. */
Carl Shapiro71938022009-12-22 13:49:53 -0800760 if (mon->owner != self) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800761 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
762 "object not locked by thread before notifyAll()");
763 return;
764 }
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800765 /* Signal all threads in the wait set. */
766 while (mon->waitSet != NULL) {
767 thread = mon->waitSet;
768 mon->waitSet = thread->waitNext;
769 thread->waitNext = NULL;
Carl Shapiro980ffb02010-03-13 22:34:01 -0800770 dvmLockMutex(&thread->waitMutex);
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800771 /* Check to see if the thread is still waiting. */
772 if (thread->waitMonitor != NULL) {
773 pthread_cond_signal(&thread->waitCond);
774 }
Carl Shapiro980ffb02010-03-13 22:34:01 -0800775 dvmUnlockMutex(&thread->waitMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800776 }
777}
778
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800779/*
Carl Shapiro66bb7df2010-03-12 15:25:37 -0800780 * Changes the shape of a monitor from thin to fat, preserving the
781 * internal lock state. The calling thread must own the lock.
782 */
783static void inflateMonitor(Thread *self, Object *obj)
784{
785 Monitor *mon;
786 u4 thin;
787
788 assert(self != NULL);
789 assert(obj != NULL);
790 assert(LW_SHAPE(obj->lock) == LW_SHAPE_THIN);
791 assert(LW_LOCK_OWNER(obj->lock) == self->threadId);
792 /* Allocate and acquire a new monitor. */
793 mon = dvmCreateMonitor(obj);
794 lockMonitor(self, mon);
795 /* Propagate the lock state. */
796 thin = obj->lock;
797 mon->lockCount = LW_LOCK_COUNT(thin);
798 thin &= LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT;
799 thin |= (u4)mon | LW_SHAPE_FAT;
800 /* Publish the updated lock word. */
801 MEM_BARRIER();
802 obj->lock = thin;
803}
804
805/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800806 * Implements monitorenter for "synchronized" stuff.
807 *
808 * This does not fail or throw an exception (unless deadlock prediction
809 * is enabled and set to "err" mode).
810 */
811void dvmLockObject(Thread* self, Object *obj)
812{
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800813 volatile u4 *thinp;
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800814 ThreadStatus oldStatus;
815 useconds_t sleepDelay;
816 const useconds_t maxSleepDelay = 1 << 20;
817 u4 thin, newThin, threadId;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800818
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800819 assert(self != NULL);
820 assert(obj != NULL);
821 threadId = self->threadId;
822 thinp = &obj->lock;
823retry:
824 thin = *thinp;
825 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
826 /*
827 * The lock is a thin lock. The owner field is used to
828 * determine the acquire method, ordered by cost.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800829 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800830 if (LW_LOCK_OWNER(thin) == threadId) {
831 /*
832 * The calling thread owns the lock. Increment the
833 * value of the recursion count field.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800834 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800835 obj->lock += 1 << LW_LOCK_COUNT_SHIFT;
836 } else if (LW_LOCK_OWNER(thin) == 0) {
837 /*
838 * The lock is unowned. Install the thread id of the
839 * calling thread into the owner field. This is the
840 * common case. In performance critical code the JIT
841 * will have tried this before calling out to the VM.
842 */
843 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
844 if (!ATOMIC_CMP_SWAP((int32_t *)thinp, thin, newThin)) {
845 /*
846 * The acquire failed. Try again.
847 */
848 goto retry;
849 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800850 } else {
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800851 LOG_THIN("(%d) spin on lock %p: %#x (%#x) %#x",
852 threadId, &obj->lock, 0, *thinp, thin);
853 /*
854 * The lock is owned by another thread. Notify the VM
855 * that we are about to wait.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800856 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800857 oldStatus = dvmChangeStatus(self, THREAD_MONITOR);
858 /*
859 * Spin until the thin lock is released or inflated.
860 */
861 sleepDelay = 0;
862 for (;;) {
863 thin = *thinp;
864 /*
865 * Check the shape of the lock word. Another thread
866 * may have inflated the lock while we were waiting.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800867 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800868 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
869 if (LW_LOCK_OWNER(thin) == 0) {
870 /*
871 * The lock has been released. Install the
872 * thread id of the calling thread into the
873 * owner field.
874 */
875 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
876 if (ATOMIC_CMP_SWAP((int32_t *)thinp,
877 thin, newThin)) {
878 /*
879 * The acquire succeed. Break out of the
880 * loop and proceed to inflate the lock.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800881 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800882 break;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800883 }
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800884 } else {
885 /*
886 * The lock has not been released. Yield so
887 * the owning thread can run.
888 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800889 if (sleepDelay == 0) {
890 sched_yield();
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800891 sleepDelay = 1000;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800892 } else {
893 usleep(sleepDelay);
894 if (sleepDelay < maxSleepDelay / 2) {
895 sleepDelay *= 2;
896 }
897 }
898 }
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800899 } else {
900 /*
901 * The thin lock was inflated by another thread.
902 * Let the VM know we are no longer waiting and
903 * try again.
904 */
905 LOG_THIN("(%d) lock %p surprise-fattened",
906 threadId, &obj->lock);
907 dvmChangeStatus(self, oldStatus);
908 goto retry;
909 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800910 }
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800911 LOG_THIN("(%d) spin on lock done %p: %#x (%#x) %#x",
912 threadId, &obj->lock, 0, *thinp, thin);
913 /*
914 * We have acquired the thin lock. Let the VM know that
915 * we are no longer waiting.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800916 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800917 dvmChangeStatus(self, oldStatus);
918 /*
919 * Fatten the lock.
920 */
Carl Shapiro66bb7df2010-03-12 15:25:37 -0800921 inflateMonitor(self, obj);
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800922 LOG_THIN("(%d) lock %p fattened", threadId, &obj->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800923 }
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800924 } else {
925 /*
926 * The lock is a fat lock.
927 */
928 assert(LW_MONITOR(obj->lock) != NULL);
929 lockMonitor(self, LW_MONITOR(obj->lock));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800930 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800931#ifdef WITH_DEADLOCK_PREDICTION
932 /*
933 * See if we were allowed to grab the lock at this time. We do it
934 * *after* acquiring the lock, rather than before, so that we can
935 * freely update the Monitor struct. This seems counter-intuitive,
936 * but our goal is deadlock *prediction* not deadlock *prevention*.
937 * (If we actually deadlock, the situation is easy to diagnose from
938 * a thread dump, so there's no point making a special effort to do
939 * the checks before the lock is held.)
940 *
941 * This needs to happen before we add the object to the thread's
942 * monitor list, so we can tell the difference between first-lock and
943 * re-lock.
944 *
945 * It's also important that we do this while in THREAD_RUNNING, so
946 * that we don't interfere with cleanup operations in the GC.
947 */
948 if (gDvm.deadlockPredictMode != kDPOff) {
949 if (self->status != THREAD_RUNNING) {
950 LOGE("Bad thread status (%d) in DP\n", self->status);
951 dvmDumpThread(self, false);
952 dvmAbort();
953 }
954 assert(!dvmCheckException(self));
955 updateDeadlockPrediction(self, obj);
956 if (dvmCheckException(self)) {
957 /*
958 * If we're throwing an exception here, we need to free the
959 * lock. We add the object to the thread's monitor list so the
960 * "unlock" code can remove it.
961 */
962 dvmAddToMonitorList(self, obj, false);
963 dvmUnlockObject(self, obj);
964 LOGV("--- unlocked, pending is '%s'\n",
965 dvmGetException(self)->clazz->descriptor);
966 }
967 }
968
969 /*
970 * Add the locked object, and the current stack trace, to the list
971 * held by the Thread object. If deadlock prediction isn't on,
972 * don't capture the stack trace.
973 */
974 dvmAddToMonitorList(self, obj, gDvm.deadlockPredictMode != kDPOff);
975#elif defined(WITH_MONITOR_TRACKING)
976 /*
977 * Add the locked object to the list held by the Thread object.
978 */
979 dvmAddToMonitorList(self, obj, false);
980#endif
981}
982
983/*
984 * Implements monitorexit for "synchronized" stuff.
985 *
986 * On failure, throws an exception and returns "false".
987 */
988bool dvmUnlockObject(Thread* self, Object *obj)
989{
Carl Shapiro94338aa2009-12-21 11:42:59 -0800990 u4 thin;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800991
Carl Shapiroef5b4d32010-01-26 13:22:04 -0800992 assert(self != NULL);
993 assert(self->status == THREAD_RUNNING);
994 assert(obj != NULL);
Carl Shapiroef5b4d32010-01-26 13:22:04 -0800995 /*
996 * Cache the lock word as its value can change while we are
997 * examining its state.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800998 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800999 thin = obj->lock;
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001000 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
1001 /*
1002 * The lock is thin. We must ensure that the lock is owned
1003 * by the given thread before unlocking it.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001004 */
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001005 if (LW_LOCK_OWNER(thin) == self->threadId) {
1006 /*
1007 * We are the lock owner. It is safe to update the lock
1008 * without CAS as lock ownership guards the lock itself.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001009 */
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001010 if (LW_LOCK_COUNT(thin) == 0) {
1011 /*
1012 * The lock was not recursively acquired, the common
1013 * case. Unlock by clearing all bits except for the
1014 * hash state.
1015 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -08001016 obj->lock &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001017 } else {
1018 /*
1019 * The object was recursively acquired. Decrement the
1020 * lock recursion count field.
1021 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -08001022 obj->lock -= 1 << LW_LOCK_COUNT_SHIFT;
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001023 }
1024 } else {
1025 /*
1026 * We do not own the lock. The JVM spec requires that we
1027 * throw an exception in this case.
1028 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001029 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001030 "unlock of unowned monitor");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001031 return false;
1032 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001033 } else {
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001034 /*
1035 * The lock is fat. We must check to see if unlockMonitor has
1036 * raised any exceptions before continuing.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001037 */
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001038 assert(LW_MONITOR(obj->lock) != NULL);
1039 if (!unlockMonitor(self, LW_MONITOR(obj->lock))) {
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001040 /*
1041 * An exception has been raised. Do not fall through.
1042 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001043 return false;
1044 }
1045 }
1046
1047#ifdef WITH_MONITOR_TRACKING
1048 /*
1049 * Remove the object from the Thread's list.
1050 */
1051 dvmRemoveFromMonitorList(self, obj);
1052#endif
1053
1054 return true;
1055}
1056
1057/*
1058 * Object.wait(). Also called for class init.
1059 */
1060void dvmObjectWait(Thread* self, Object *obj, s8 msec, s4 nsec,
1061 bool interruptShouldThrow)
1062{
Carl Shapiro66bb7df2010-03-12 15:25:37 -08001063 Monitor* mon;
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001064 u4 thin = obj->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001065
1066 /* If the lock is still thin, we need to fatten it.
1067 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001068 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001069 /* Make sure that 'self' holds the lock.
1070 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001071 if (LW_LOCK_OWNER(thin) != self->threadId) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001072 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
1073 "object not locked by thread before wait()");
1074 return;
1075 }
1076
1077 /* This thread holds the lock. We need to fatten the lock
1078 * so 'self' can block on it. Don't update the object lock
1079 * field yet, because 'self' needs to acquire the lock before
1080 * any other thread gets a chance.
1081 */
Carl Shapiro66bb7df2010-03-12 15:25:37 -08001082 inflateMonitor(self, obj);
1083 LOG_THIN("(%d) lock %p fattened by wait() to count %d",
1084 self->threadId, &obj->lock, mon->lockCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001085 }
Carl Shapiro66bb7df2010-03-12 15:25:37 -08001086 mon = LW_MONITOR(obj->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001087 waitMonitor(self, mon, msec, nsec, interruptShouldThrow);
1088}
1089
1090/*
1091 * Object.notify().
1092 */
1093void dvmObjectNotify(Thread* self, Object *obj)
1094{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001095 u4 thin = obj->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001096
1097 /* If the lock is still thin, there aren't any waiters;
1098 * waiting on an object forces lock fattening.
1099 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001100 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001101 /* Make sure that 'self' holds the lock.
1102 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001103 if (LW_LOCK_OWNER(thin) != self->threadId) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001104 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
1105 "object not locked by thread before notify()");
1106 return;
1107 }
1108
1109 /* no-op; there are no waiters to notify.
1110 */
1111 } else {
1112 /* It's a fat lock.
1113 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001114 notifyMonitor(self, LW_MONITOR(thin));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001115 }
1116}
1117
1118/*
1119 * Object.notifyAll().
1120 */
1121void dvmObjectNotifyAll(Thread* self, Object *obj)
1122{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001123 u4 thin = obj->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001124
1125 /* If the lock is still thin, there aren't any waiters;
1126 * waiting on an object forces lock fattening.
1127 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001128 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001129 /* Make sure that 'self' holds the lock.
1130 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001131 if (LW_LOCK_OWNER(thin) != self->threadId) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001132 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
1133 "object not locked by thread before notifyAll()");
1134 return;
1135 }
1136
1137 /* no-op; there are no waiters to notify.
1138 */
1139 } else {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001140 /* It's a fat lock.
1141 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001142 notifyAllMonitor(self, LW_MONITOR(thin));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001143 }
1144}
1145
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001146/*
1147 * This implements java.lang.Thread.sleep(long msec, int nsec).
1148 *
1149 * The sleep is interruptible by other threads, which means we can't just
1150 * plop into an OS sleep call. (We probably could if we wanted to send
1151 * signals around and rely on EINTR, but that's inefficient and relies
1152 * on native code respecting our signal mask.)
1153 *
1154 * We have to do all of this stuff for Object.wait() as well, so it's
1155 * easiest to just sleep on a private Monitor.
1156 *
1157 * It appears that we want sleep(0,0) to go through the motions of sleeping
1158 * for a very short duration, rather than just returning.
1159 */
1160void dvmThreadSleep(u8 msec, u4 nsec)
1161{
1162 Thread* self = dvmThreadSelf();
1163 Monitor* mon = gDvm.threadSleepMon;
1164
1165 /* sleep(0,0) wakes up immediately, wait(0,0) means wait forever; adjust */
1166 if (msec == 0 && nsec == 0)
1167 nsec++;
1168
1169 lockMonitor(self, mon);
1170 waitMonitor(self, mon, msec, nsec, true);
1171 unlockMonitor(self, mon);
1172}
1173
1174/*
1175 * Implement java.lang.Thread.interrupt().
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001176 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001177void dvmThreadInterrupt(Thread* thread)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001178{
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001179 assert(thread != NULL);
1180
Carl Shapiro980ffb02010-03-13 22:34:01 -08001181 dvmLockMutex(&thread->waitMutex);
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001182
1183 /*
1184 * If the interrupted flag is already set no additional action is
1185 * required.
1186 */
1187 if (thread->interrupted == true) {
Carl Shapiro980ffb02010-03-13 22:34:01 -08001188 dvmUnlockMutex(&thread->waitMutex);
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001189 return;
1190 }
1191
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001192 /*
1193 * Raise the "interrupted" flag. This will cause it to bail early out
1194 * of the next wait() attempt, if it's not currently waiting on
1195 * something.
1196 */
1197 thread->interrupted = true;
1198 MEM_BARRIER();
1199
1200 /*
1201 * Is the thread waiting?
1202 *
1203 * Note that fat vs. thin doesn't matter here; waitMonitor
1204 * is only set when a thread actually waits on a monitor,
1205 * which implies that the monitor has already been fattened.
1206 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001207 if (thread->waitMonitor != NULL) {
1208 pthread_cond_signal(&thread->waitCond);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001209 }
1210
Carl Shapiro980ffb02010-03-13 22:34:01 -08001211 dvmUnlockMutex(&thread->waitMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001212}
1213
Carl Shapiro30aa9972010-01-13 22:07:50 -08001214#ifndef WITH_COPYING_GC
Carl Shapiro94338aa2009-12-21 11:42:59 -08001215u4 dvmIdentityHashCode(Object *obj)
1216{
1217 return (u4)obj;
1218}
Carl Shapiro30aa9972010-01-13 22:07:50 -08001219#else
Carl Shapiro30aa9972010-01-13 22:07:50 -08001220/*
1221 * Returns the identity hash code of the given object.
1222 */
1223u4 dvmIdentityHashCode(Object *obj)
1224{
1225 Thread *self, *thread;
1226 volatile u4 *lw;
1227 size_t length;
1228 u4 lock, owner, hashState;
1229
1230 if (obj == NULL) {
1231 /*
1232 * Null is defined to have an identity hash code of 0.
1233 */
1234 return 0;
1235 }
1236 lw = &obj->lock;
1237retry:
1238 hashState = LW_HASH_STATE(*lw);
1239 if (hashState == LW_HASH_STATE_HASHED) {
1240 /*
1241 * The object has been hashed but has not had its hash code
1242 * relocated by the garbage collector. Use the raw object
1243 * address.
1244 */
1245 return (u4)obj >> 3;
1246 } else if (hashState == LW_HASH_STATE_HASHED_AND_MOVED) {
1247 /*
1248 * The object has been hashed and its hash code has been
1249 * relocated by the collector. Use the value of the naturally
1250 * aligned word following the instance data.
1251 */
1252 if (IS_CLASS_FLAG_SET(obj->clazz, CLASS_ISARRAY)) {
Carl Shapiro1e714bb2010-03-16 03:26:49 -07001253 length = dvmArrayObjectLength((ArrayObject *)obj);
Carl Shapiro30aa9972010-01-13 22:07:50 -08001254 length = (length + 3) & ~3;
1255 } else {
1256 length = obj->clazz->objectSize;
1257 }
1258 return *(u4 *)(((char *)obj) + length);
1259 } else if (hashState == LW_HASH_STATE_UNHASHED) {
1260 /*
1261 * The object has never been hashed. Change the hash state to
1262 * hashed and use the raw object address.
1263 */
1264 self = dvmThreadSelf();
1265 if (self->threadId == lockOwner(obj)) {
1266 /*
1267 * We already own the lock so we can update the hash state
1268 * directly.
1269 */
1270 *lw |= (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1271 return (u4)obj >> 3;
1272 }
1273 /*
1274 * We do not own the lock. Try acquiring the lock. Should
1275 * this fail, we must suspend the owning thread.
1276 */
1277 if (LW_SHAPE(*lw) == LW_SHAPE_THIN) {
1278 /*
1279 * If the lock is thin assume it is unowned. We simulate
1280 * an acquire, update, and release with a single CAS.
1281 */
1282 lock = DVM_LOCK_INITIAL_THIN_VALUE;
1283 lock |= (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1284 if (ATOMIC_CMP_SWAP((int32_t *)lw,
1285 (int32_t)DVM_LOCK_INITIAL_THIN_VALUE,
1286 (int32_t)lock)) {
1287 /*
1288 * A new lockword has been installed with a hash state
1289 * of hashed. Use the raw object address.
1290 */
1291 return (u4)obj >> 3;
1292 }
1293 } else {
1294 if (tryLockMonitor(self, LW_MONITOR(*lw))) {
1295 /*
1296 * The monitor lock has been acquired. Change the
1297 * hash state to hashed and use the raw object
1298 * address.
1299 */
1300 *lw |= (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1301 unlockMonitor(self, LW_MONITOR(*lw));
1302 return (u4)obj >> 3;
1303 }
1304 }
1305 /*
1306 * At this point we have failed to acquire the lock. We must
1307 * identify the owning thread and suspend it.
1308 */
1309 dvmLockThreadList(self);
1310 /*
1311 * Cache the lock word as its value can change between
1312 * determining its shape and retrieving its owner.
1313 */
1314 lock = *lw;
1315 if (LW_SHAPE(lock) == LW_SHAPE_THIN) {
1316 /*
1317 * Find the thread with the corresponding thread id.
1318 */
1319 owner = LW_LOCK_OWNER(lock);
1320 assert(owner != self->threadId);
1321 /*
1322 * If the lock has no owner do not bother scanning the
1323 * thread list and fall through to the failure handler.
1324 */
1325 thread = owner ? gDvm.threadList : NULL;
1326 while (thread != NULL) {
1327 if (thread->threadId == owner) {
1328 break;
1329 }
1330 thread = thread->next;
1331 }
1332 } else {
1333 thread = LW_MONITOR(lock)->owner;
1334 }
1335 /*
1336 * If thread is NULL the object has been released since the
1337 * thread list lock was acquired. Try again.
1338 */
1339 if (thread == NULL) {
1340 dvmUnlockThreadList();
1341 goto retry;
1342 }
1343 /*
1344 * Wait for the owning thread to suspend.
1345 */
1346 dvmSuspendThread(thread);
1347 if (dvmHoldsLock(thread, obj)) {
1348 /*
1349 * The owning thread has been suspended. We can safely
1350 * change the hash state to hashed.
1351 */
1352 *lw |= (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1353 dvmResumeThread(thread);
1354 dvmUnlockThreadList();
1355 return (u4)obj >> 3;
1356 }
1357 /*
1358 * The wrong thread has been suspended. Try again.
1359 */
1360 dvmResumeThread(thread);
1361 dvmUnlockThreadList();
1362 goto retry;
1363 }
1364 LOGE("object %p has an unknown hash state %#x", obj, hashState);
1365 dvmDumpThread(dvmThreadSelf(), false);
1366 dvmAbort();
1367 return 0; /* Quiet the compiler. */
1368}
1369#endif /* WITH_COPYING_GC */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001370
1371#ifdef WITH_DEADLOCK_PREDICTION
1372/*
1373 * ===========================================================================
1374 * Deadlock prediction
1375 * ===========================================================================
1376 */
1377/*
1378The idea is to predict the possibility of deadlock by recording the order
1379in which monitors are acquired. If we see an attempt to acquire a lock
1380out of order, we can identify the locks and offending code.
1381
1382To make this work, we need to keep track of the locks held by each thread,
1383and create history trees for each lock. When a thread tries to acquire
1384a new lock, we walk through the "history children" of the lock, looking
1385for a match with locks the thread already holds. If we find a match,
1386it means the thread has made a request that could result in a deadlock.
1387
1388To support recursive locks, we always allow re-locking a currently-held
1389lock, and maintain a recursion depth count.
1390
1391An ASCII-art example, where letters represent Objects:
1392
1393 A
1394 /|\
1395 / | \
1396 B | D
1397 \ |
1398 \|
1399 C
1400
1401The above is the tree we'd have after handling Object synchronization
1402sequences "ABC", "AC", "AD". A has three children, {B, C, D}. C is also
1403a child of B. (The lines represent pointers between parent and child.
1404Every node can have multiple parents and multiple children.)
1405
1406If we hold AC, and want to lock B, we recursively search through B's
1407children to see if A or C appears. It does, so we reject the attempt.
1408(A straightforward way to implement it: add a link from C to B, then
1409determine whether the graph starting at B contains a cycle.)
1410
1411If we hold AC and want to lock D, we would succeed, creating a new link
1412from C to D.
1413
1414The lock history and a stack trace is attached to the Object's Monitor
1415struct, which means we need to fatten every Object we lock (thin locking
1416is effectively disabled). If we don't need the stack trace we can
1417avoid fattening the leaf nodes, only fattening objects that need to hold
1418history trees.
1419
1420Updates to Monitor structs are only allowed for the thread that holds
1421the Monitor, so we actually do most of our deadlock prediction work after
1422the lock has been acquired.
1423
1424When an object with a monitor is GCed, we need to remove it from the
1425history trees. There are two basic approaches:
1426 (1) For through the entire set of known monitors, search all child
1427 lists for the object in question. This is rather slow, resulting
1428 in GC passes that take upwards of 10 seconds to complete.
1429 (2) Maintain "parent" pointers in each node. Remove the entries as
1430 required. This requires additional storage and maintenance for
1431 every operation, but is significantly faster at GC time.
1432For each GCed object, we merge all of the object's children into each of
1433the object's parents.
1434*/
1435
1436#if !defined(WITH_MONITOR_TRACKING)
1437# error "WITH_DEADLOCK_PREDICTION requires WITH_MONITOR_TRACKING"
1438#endif
1439
1440/*
1441 * Clear out the contents of an ExpandingObjectList, freeing any
1442 * dynamic allocations.
1443 */
1444static void expandObjClear(ExpandingObjectList* pList)
1445{
1446 if (pList->list != NULL) {
1447 free(pList->list);
1448 pList->list = NULL;
1449 }
1450 pList->alloc = pList->count = 0;
1451}
1452
1453/*
1454 * Get the number of objects currently stored in the list.
1455 */
1456static inline int expandBufGetCount(const ExpandingObjectList* pList)
1457{
1458 return pList->count;
1459}
1460
1461/*
1462 * Get the Nth entry from the list.
1463 */
1464static inline Object* expandBufGetEntry(const ExpandingObjectList* pList,
1465 int i)
1466{
1467 return pList->list[i];
1468}
1469
1470/*
1471 * Add a new entry to the list.
1472 *
1473 * We don't check for or try to enforce uniqueness. It's expected that
1474 * the higher-level code does this for us.
1475 */
1476static void expandObjAddEntry(ExpandingObjectList* pList, Object* obj)
1477{
1478 if (pList->count == pList->alloc) {
1479 /* time to expand */
1480 Object** newList;
1481
1482 if (pList->alloc == 0)
1483 pList->alloc = 4;
1484 else
1485 pList->alloc *= 2;
1486 LOGVV("expanding %p to %d\n", pList, pList->alloc);
1487 newList = realloc(pList->list, pList->alloc * sizeof(Object*));
1488 if (newList == NULL) {
1489 LOGE("Failed expanding DP object list (alloc=%d)\n", pList->alloc);
1490 dvmAbort();
1491 }
1492 pList->list = newList;
1493 }
1494
1495 pList->list[pList->count++] = obj;
1496}
1497
1498/*
1499 * Returns "true" if the element was successfully removed.
1500 */
1501static bool expandObjRemoveEntry(ExpandingObjectList* pList, Object* obj)
1502{
1503 int i;
1504
1505 for (i = pList->count-1; i >= 0; i--) {
1506 if (pList->list[i] == obj)
1507 break;
1508 }
1509 if (i < 0)
1510 return false;
1511
1512 if (i != pList->count-1) {
1513 /*
1514 * The order of elements is not important, so we just copy the
1515 * last entry into the new slot.
1516 */
1517 //memmove(&pList->list[i], &pList->list[i+1],
1518 // (pList->count-1 - i) * sizeof(pList->list[0]));
1519 pList->list[i] = pList->list[pList->count-1];
1520 }
1521
1522 pList->count--;
1523 pList->list[pList->count] = (Object*) 0xdecadead;
1524 return true;
1525}
1526
1527/*
1528 * Returns "true" if "obj" appears in the list.
1529 */
1530static bool expandObjHas(const ExpandingObjectList* pList, Object* obj)
1531{
1532 int i;
1533
1534 for (i = 0; i < pList->count; i++) {
1535 if (pList->list[i] == obj)
1536 return true;
1537 }
1538 return false;
1539}
1540
1541/*
1542 * Print the list contents to stdout. For debugging.
1543 */
1544static void expandObjDump(const ExpandingObjectList* pList)
1545{
1546 int i;
1547 for (i = 0; i < pList->count; i++)
1548 printf(" %p", pList->list[i]);
1549}
1550
1551/*
1552 * Check for duplicate entries. Returns the index of the first instance
1553 * of the duplicated value, or -1 if no duplicates were found.
1554 */
1555static int expandObjCheckForDuplicates(const ExpandingObjectList* pList)
1556{
1557 int i, j;
1558 for (i = 0; i < pList->count-1; i++) {
1559 for (j = i + 1; j < pList->count; j++) {
1560 if (pList->list[i] == pList->list[j]) {
1561 return i;
1562 }
1563 }
1564 }
1565
1566 return -1;
1567}
1568
1569
1570/*
1571 * Determine whether "child" appears in the list of objects associated
1572 * with the Monitor in "parent". If "parent" is a thin lock, we return
1573 * false immediately.
1574 */
1575static bool objectInChildList(const Object* parent, Object* child)
1576{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001577 u4 lock = parent->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001578 if (!IS_LOCK_FAT(&lock)) {
1579 //LOGI("on thin\n");
1580 return false;
1581 }
1582
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001583 return expandObjHas(&LW_MONITOR(lock)->historyChildren, child);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001584}
1585
1586/*
1587 * Print the child list.
1588 */
1589static void dumpKids(Object* parent)
1590{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001591 Monitor* mon = LW_MONITOR(parent->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001592
1593 printf("Children of %p:", parent);
1594 expandObjDump(&mon->historyChildren);
1595 printf("\n");
1596}
1597
1598/*
1599 * Add "child" to the list of children in "parent", and add "parent" to
1600 * the list of parents in "child".
1601 */
1602static void linkParentToChild(Object* parent, Object* child)
1603{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001604 //assert(LW_MONITOR(parent->lock)->owner == dvmThreadSelf()); // !owned for merge
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001605 assert(IS_LOCK_FAT(&parent->lock));
1606 assert(IS_LOCK_FAT(&child->lock));
1607 assert(parent != child);
1608 Monitor* mon;
1609
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001610 mon = LW_MONITOR(parent->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001611 assert(!expandObjHas(&mon->historyChildren, child));
1612 expandObjAddEntry(&mon->historyChildren, child);
1613
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001614 mon = LW_MONITOR(child->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001615 assert(!expandObjHas(&mon->historyParents, parent));
1616 expandObjAddEntry(&mon->historyParents, parent);
1617}
1618
1619
1620/*
1621 * Remove "child" from the list of children in "parent".
1622 */
1623static void unlinkParentFromChild(Object* parent, Object* child)
1624{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001625 //assert(LW_MONITOR(parent->lock)->owner == dvmThreadSelf()); // !owned for GC
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001626 assert(IS_LOCK_FAT(&parent->lock));
1627 assert(IS_LOCK_FAT(&child->lock));
1628 assert(parent != child);
1629 Monitor* mon;
1630
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001631 mon = LW_MONITOR(parent->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001632 if (!expandObjRemoveEntry(&mon->historyChildren, child)) {
1633 LOGW("WARNING: child %p not found in parent %p\n", child, parent);
1634 }
1635 assert(!expandObjHas(&mon->historyChildren, child));
1636 assert(expandObjCheckForDuplicates(&mon->historyChildren) < 0);
1637
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001638 mon = LW_MONITOR(child->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001639 if (!expandObjRemoveEntry(&mon->historyParents, parent)) {
1640 LOGW("WARNING: parent %p not found in child %p\n", parent, child);
1641 }
1642 assert(!expandObjHas(&mon->historyParents, parent));
1643 assert(expandObjCheckForDuplicates(&mon->historyParents) < 0);
1644}
1645
1646
1647/*
1648 * Log the monitors held by the current thread. This is done as part of
1649 * flagging an error.
1650 */
1651static void logHeldMonitors(Thread* self)
1652{
1653 char* name = NULL;
1654
1655 name = dvmGetThreadName(self);
1656 LOGW("Monitors currently held by thread (threadid=%d '%s')\n",
1657 self->threadId, name);
1658 LOGW("(most-recently-acquired on top):\n");
1659 free(name);
1660
1661 LockedObjectData* lod = self->pLockedObjects;
1662 while (lod != NULL) {
1663 LOGW("--- object %p[%d] (%s)\n",
1664 lod->obj, lod->recursionCount, lod->obj->clazz->descriptor);
1665 dvmLogRawStackTrace(lod->rawStackTrace, lod->stackDepth);
1666
1667 lod = lod->next;
1668 }
1669}
1670
1671/*
1672 * Recursively traverse the object hierarchy starting at "obj". We mark
1673 * ourselves on entry and clear the mark on exit. If we ever encounter
1674 * a marked object, we have a cycle.
1675 *
1676 * Returns "true" if all is well, "false" if we found a cycle.
1677 */
1678static bool traverseTree(Thread* self, const Object* obj)
1679{
1680 assert(IS_LOCK_FAT(&obj->lock));
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001681 Monitor* mon = LW_MONITOR(obj->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001682
1683 /*
1684 * Have we been here before?
1685 */
1686 if (mon->historyMark) {
1687 int* rawStackTrace;
1688 int stackDepth;
1689
1690 LOGW("%s\n", kStartBanner);
1691 LOGW("Illegal lock attempt:\n");
1692 LOGW("--- object %p (%s)\n", obj, obj->clazz->descriptor);
1693
1694 rawStackTrace = dvmFillInStackTraceRaw(self, &stackDepth);
1695 dvmLogRawStackTrace(rawStackTrace, stackDepth);
1696 free(rawStackTrace);
1697
1698 LOGW(" ");
1699 logHeldMonitors(self);
1700
1701 LOGW(" ");
1702 LOGW("Earlier, the following lock order (from last to first) was\n");
1703 LOGW("established -- stack trace is from first successful lock):\n");
1704 return false;
1705 }
1706 mon->historyMark = true;
1707
1708 /*
1709 * Examine the children. We do NOT hold these locks, so they might
1710 * very well transition from thin to fat or change ownership while
1711 * we work.
1712 *
1713 * NOTE: we rely on the fact that they cannot revert from fat to thin
1714 * while we work. This is currently a safe assumption.
1715 *
1716 * We can safely ignore thin-locked children, because by definition
1717 * they have no history and are leaf nodes. In the current
1718 * implementation we always fatten the locks to provide a place to
1719 * hang the stack trace.
1720 */
1721 ExpandingObjectList* pList = &mon->historyChildren;
1722 int i;
1723 for (i = expandBufGetCount(pList)-1; i >= 0; i--) {
1724 const Object* child = expandBufGetEntry(pList, i);
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001725 u4 lock = child->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001726 if (!IS_LOCK_FAT(&lock))
1727 continue;
1728 if (!traverseTree(self, child)) {
1729 LOGW("--- object %p (%s)\n", obj, obj->clazz->descriptor);
1730 dvmLogRawStackTrace(mon->historyRawStackTrace,
1731 mon->historyStackDepth);
1732 mon->historyMark = false;
1733 return false;
1734 }
1735 }
1736
1737 mon->historyMark = false;
1738
1739 return true;
1740}
1741
1742/*
1743 * Update the deadlock prediction tree, based on the current thread
1744 * acquiring "acqObj". This must be called before the object is added to
1745 * the thread's list of held monitors.
1746 *
1747 * If the thread already holds the lock (recursion), or this is a known
1748 * lock configuration, we return without doing anything. Otherwise, we add
1749 * a link from the most-recently-acquired lock in this thread to "acqObj"
1750 * after ensuring that the parent lock is "fat".
1751 *
1752 * This MUST NOT be called while a GC is in progress in another thread,
1753 * because we assume exclusive access to history trees in owned monitors.
1754 */
1755static void updateDeadlockPrediction(Thread* self, Object* acqObj)
1756{
1757 LockedObjectData* lod;
1758 LockedObjectData* mrl;
1759
1760 /*
1761 * Quick check for recursive access.
1762 */
1763 lod = dvmFindInMonitorList(self, acqObj);
1764 if (lod != NULL) {
1765 LOGV("+++ DP: recursive %p\n", acqObj);
1766 return;
1767 }
1768
1769 /*
1770 * Make the newly-acquired object's monitor "fat". In some ways this
1771 * isn't strictly necessary, but we need the GC to tell us when
1772 * "interesting" objects go away, and right now the only way to make
1773 * an object look interesting is to give it a monitor.
1774 *
1775 * This also gives us a place to hang a stack trace.
1776 *
1777 * Our thread holds the lock, so we're allowed to rewrite the lock
1778 * without worrying that something will change out from under us.
1779 */
1780 if (!IS_LOCK_FAT(&acqObj->lock)) {
1781 LOGVV("fattening lockee %p (recur=%d)\n",
Carl Shapiro94338aa2009-12-21 11:42:59 -08001782 acqObj, LW_LOCK_COUNT(acqObj->lock.thin));
Carl Shapiro66bb7df2010-03-12 15:25:37 -08001783 inflateMonitor(self, acqObj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001784 }
1785
1786 /* if we don't have a stack trace for this monitor, establish one */
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001787 if (LW_MONITOR(acqObj->lock)->historyRawStackTrace == NULL) {
1788 Monitor* mon = LW_MONITOR(acqObj->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001789 mon->historyRawStackTrace = dvmFillInStackTraceRaw(self,
1790 &mon->historyStackDepth);
1791 }
1792
1793 /*
1794 * We need to examine and perhaps modify the most-recently-locked
1795 * monitor. We own that, so there's no risk of another thread
1796 * stepping on us.
1797 *
1798 * Retrieve the most-recently-locked entry from our thread.
1799 */
1800 mrl = self->pLockedObjects;
1801 if (mrl == NULL)
1802 return; /* no other locks held */
1803
1804 /*
1805 * Do a quick check to see if "acqObj" is a direct descendant. We can do
1806 * this without holding the global lock because of our assertion that
1807 * a GC is not running in parallel -- nobody except the GC can
1808 * modify a history list in a Monitor they don't own, and we own "mrl".
1809 * (There might be concurrent *reads*, but no concurrent *writes.)
1810 *
1811 * If we find it, this is a known good configuration, and we're done.
1812 */
1813 if (objectInChildList(mrl->obj, acqObj))
1814 return;
1815
1816 /*
1817 * "mrl" is going to need to have a history tree. If it's currently
1818 * a thin lock, we make it fat now. The thin lock might have a
1819 * nonzero recursive lock count, which we need to carry over.
1820 *
1821 * Our thread holds the lock, so we're allowed to rewrite the lock
1822 * without worrying that something will change out from under us.
1823 */
1824 if (!IS_LOCK_FAT(&mrl->obj->lock)) {
1825 LOGVV("fattening parent %p f/b/o child %p (recur=%d)\n",
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001826 mrl->obj, acqObj, LW_LOCK_COUNT(mrl->obj->lock));
Carl Shapiro66bb7df2010-03-12 15:25:37 -08001827 inflateMonitor(self, mrl->obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001828 }
1829
1830 /*
1831 * We haven't seen this configuration before. We need to scan down
1832 * acqObj's tree to see if any of the monitors in self->pLockedObjects
1833 * appear. We grab a global lock before traversing or updating the
1834 * history list.
1835 *
1836 * If we find a match for any of our held locks, we know that the lock
1837 * has previously been acquired *after* acqObj, and we throw an error.
1838 *
1839 * The easiest way to do this is to create a link from "mrl" to "acqObj"
1840 * and do a recursive traversal, marking nodes as we cross them. If
1841 * we cross one a second time, we have a cycle and can throw an error.
1842 * (We do the flag-clearing traversal before adding the new link, so
1843 * that we're guaranteed to terminate.)
1844 *
1845 * If "acqObj" is a thin lock, it has no history, and we can create a
1846 * link to it without additional checks. [ We now guarantee that it's
1847 * always fat. ]
1848 */
1849 bool failed = false;
1850 dvmLockMutex(&gDvm.deadlockHistoryLock);
1851 linkParentToChild(mrl->obj, acqObj);
1852 if (!traverseTree(self, acqObj)) {
1853 LOGW("%s\n", kEndBanner);
1854 failed = true;
1855
1856 /* remove the entry so we're still okay when in "warning" mode */
1857 unlinkParentFromChild(mrl->obj, acqObj);
1858 }
1859 dvmUnlockMutex(&gDvm.deadlockHistoryLock);
1860
1861 if (failed) {
1862 switch (gDvm.deadlockPredictMode) {
1863 case kDPErr:
1864 dvmThrowException("Ldalvik/system/PotentialDeadlockError;", NULL);
1865 break;
1866 case kDPAbort:
1867 LOGE("Aborting due to potential deadlock\n");
1868 dvmAbort();
1869 break;
1870 default:
1871 /* warn only */
1872 break;
1873 }
1874 }
1875}
1876
1877/*
1878 * We're removing "child" from existence. We want to pull all of
1879 * child's children into "parent", filtering out duplicates. This is
1880 * called during the GC.
1881 *
1882 * This does not modify "child", which might have multiple parents.
1883 */
1884static void mergeChildren(Object* parent, const Object* child)
1885{
1886 Monitor* mon;
1887 int i;
1888
1889 assert(IS_LOCK_FAT(&child->lock));
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001890 mon = LW_MONITOR(child->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001891 ExpandingObjectList* pList = &mon->historyChildren;
1892
1893 for (i = expandBufGetCount(pList)-1; i >= 0; i--) {
1894 Object* grandChild = expandBufGetEntry(pList, i);
1895
1896 if (!objectInChildList(parent, grandChild)) {
1897 LOGVV("+++ migrating %p link to %p\n", grandChild, parent);
1898 linkParentToChild(parent, grandChild);
1899 } else {
1900 LOGVV("+++ parent %p already links to %p\n", parent, grandChild);
1901 }
1902 }
1903}
1904
1905/*
1906 * An object with a fat lock is being collected during a GC pass. We
1907 * want to remove it from any lock history trees that it is a part of.
1908 *
1909 * This may require updating the history trees in several monitors. The
1910 * monitor semantics guarantee that no other thread will be accessing
1911 * the history trees at the same time.
1912 */
1913static void removeCollectedObject(Object* obj)
1914{
1915 Monitor* mon;
1916
1917 LOGVV("+++ collecting %p\n", obj);
1918
1919#if 0
1920 /*
1921 * We're currently running through the entire set of known monitors.
1922 * This can be somewhat slow. We may want to keep lists of parents
1923 * in each child to speed up GC.
1924 */
1925 mon = gDvm.monitorList;
1926 while (mon != NULL) {
1927 Object* parent = mon->obj;
1928 if (parent != NULL) { /* value nulled for deleted entries */
1929 if (objectInChildList(parent, obj)) {
1930 LOGVV("removing child %p from parent %p\n", obj, parent);
1931 unlinkParentFromChild(parent, obj);
1932 mergeChildren(parent, obj);
1933 }
1934 }
1935 mon = mon->next;
1936 }
1937#endif
1938
1939 /*
1940 * For every parent of this object:
1941 * - merge all of our children into the parent's child list (creates
1942 * a two-way link between parent and child)
1943 * - remove ourselves from the parent's child list
1944 */
1945 ExpandingObjectList* pList;
1946 int i;
1947
1948 assert(IS_LOCK_FAT(&obj->lock));
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001949 mon = LW_MONITOR(obj->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001950 pList = &mon->historyParents;
1951 for (i = expandBufGetCount(pList)-1; i >= 0; i--) {
1952 Object* parent = expandBufGetEntry(pList, i);
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001953 Monitor* parentMon = LW_MONITOR(parent->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001954
1955 if (!expandObjRemoveEntry(&parentMon->historyChildren, obj)) {
1956 LOGW("WARNING: child %p not found in parent %p\n", obj, parent);
1957 }
1958 assert(!expandObjHas(&parentMon->historyChildren, obj));
1959
1960 mergeChildren(parent, obj);
1961 }
1962
1963 /*
1964 * For every child of this object:
1965 * - remove ourselves from the child's parent list
1966 */
1967 pList = &mon->historyChildren;
1968 for (i = expandBufGetCount(pList)-1; i >= 0; i--) {
1969 Object* child = expandBufGetEntry(pList, i);
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001970 Monitor* childMon = LW_MONITOR(child->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001971
1972 if (!expandObjRemoveEntry(&childMon->historyParents, obj)) {
1973 LOGW("WARNING: parent %p not found in child %p\n", obj, child);
1974 }
1975 assert(!expandObjHas(&childMon->historyParents, obj));
1976 }
1977}
1978
1979#endif /*WITH_DEADLOCK_PREDICTION*/