blob: 1da6c4526c93dab079e8b382d34c56b27e9c6feb [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 Shapiro980ffb02010-03-13 22:34:01 -0800313 assert(dvmTryLockMutex(&mon->lock) == 0);
314 dvmDestroyMutex(&mon->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800315#ifdef WITH_DEADLOCK_PREDICTION
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800316 expandObjClear(&mon->historyChildren);
317 expandObjClear(&mon->historyParents);
318 free(mon->historyRawStackTrace);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800319#endif
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800320 free(mon);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800321}
322
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800323/*
324 * Frees monitor objects belonging to unmarked objects.
325 */
326void dvmSweepMonitorList(Monitor** mon, int (*isUnmarkedObject)(void*))
327{
328 Monitor handle;
329 Monitor *prev, *curr;
330 Object *obj;
331
332 assert(mon != NULL);
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800333 assert(isUnmarkedObject != NULL);
334 prev = &handle;
335 prev->next = curr = *mon;
336 while (curr != NULL) {
337 obj = curr->obj;
338 if (obj != NULL && (*isUnmarkedObject)(obj) != 0) {
339 prev->next = curr = curr->next;
340 freeObjectMonitor(obj);
341 } else {
342 prev = curr;
343 curr = curr->next;
344 }
345 }
346 *mon = handle.next;
347}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800348
349/*
350 * Lock a monitor.
351 */
352static void lockMonitor(Thread* self, Monitor* mon)
353{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800354 if (mon->owner == self) {
355 mon->lockCount++;
356 } else {
357 ThreadStatus oldStatus;
358
Carl Shapiro980ffb02010-03-13 22:34:01 -0800359 if (dvmTryLockMutex(&mon->lock) != 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800360 /* mutex is locked, switch to wait status and sleep on it */
361 oldStatus = dvmChangeStatus(self, THREAD_MONITOR);
Carl Shapiro980ffb02010-03-13 22:34:01 -0800362 dvmLockMutex(&mon->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800363 dvmChangeStatus(self, oldStatus);
364 }
365
366 mon->owner = self;
367 assert(mon->lockCount == 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800368 }
369}
370
371/*
372 * Try to lock a monitor.
373 *
374 * Returns "true" on success.
375 */
376static bool tryLockMonitor(Thread* self, Monitor* mon)
377{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800378 if (mon->owner == self) {
379 mon->lockCount++;
380 return true;
381 } else {
Carl Shapiro980ffb02010-03-13 22:34:01 -0800382 if (dvmTryLockMutex(&mon->lock) == 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800383 mon->owner = self;
384 assert(mon->lockCount == 0);
385 return true;
386 } else {
387 return false;
388 }
389 }
390}
391
392
393/*
394 * Unlock a monitor.
395 *
396 * Returns true if the unlock succeeded.
397 * If the unlock failed, an exception will be pending.
398 */
399static bool unlockMonitor(Thread* self, Monitor* mon)
400{
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800401 assert(self != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800402 assert(mon != NULL); // can this happen?
403
404 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;",
421 "unlock of unowned monitor, self=%d owner=%d",
422 self->threadId,
423 mon->owner ? mon->owner->threadId : 0);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800424 return false;
425 }
426 return true;
427}
428
429/*
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800430 * Checks the wait set for circular structure. Returns 0 if the list
Carl Shapirob4539192010-01-04 16:50:00 -0800431 * is not circular. Otherwise, returns 1. Used only by asserts.
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800432 */
433static int waitSetCheck(Monitor *mon)
434{
435 Thread *fast, *slow;
436 size_t n;
437
438 assert(mon != NULL);
439 fast = slow = mon->waitSet;
440 n = 0;
441 for (;;) {
442 if (fast == NULL) return 0;
443 if (fast->waitNext == NULL) return 0;
Carl Shapiro5f56e672010-01-05 20:38:03 -0800444 if (fast == slow && n > 0) return 1;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800445 n += 2;
446 fast = fast->waitNext->waitNext;
447 slow = slow->waitNext;
448 }
449}
450
451/*
Carl Shapiro30aa9972010-01-13 22:07:50 -0800452 * Links a thread into a monitor's wait set. The monitor lock must be
453 * held by the caller of this routine.
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800454 */
455static void waitSetAppend(Monitor *mon, Thread *thread)
456{
457 Thread *elt;
458
459 assert(mon != NULL);
Carl Shapiro30aa9972010-01-13 22:07:50 -0800460 assert(mon->owner == dvmThreadSelf());
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800461 assert(thread != NULL);
462 assert(thread->waitNext == NULL);
463 assert(waitSetCheck(mon) == 0);
464 if (mon->waitSet == NULL) {
465 mon->waitSet = thread;
466 return;
467 }
468 elt = mon->waitSet;
469 while (elt->waitNext != NULL) {
470 elt = elt->waitNext;
471 }
472 elt->waitNext = thread;
473}
474
475/*
Carl Shapiro30aa9972010-01-13 22:07:50 -0800476 * Unlinks a thread from a monitor's wait set. The monitor lock must
477 * be held by the caller of this routine.
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800478 */
479static void waitSetRemove(Monitor *mon, Thread *thread)
480{
481 Thread *elt;
482
483 assert(mon != NULL);
Carl Shapiro30aa9972010-01-13 22:07:50 -0800484 assert(mon->owner == dvmThreadSelf());
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800485 assert(thread != NULL);
486 assert(waitSetCheck(mon) == 0);
487 if (mon->waitSet == NULL) {
488 return;
489 }
490 if (mon->waitSet == thread) {
491 mon->waitSet = thread->waitNext;
492 thread->waitNext = NULL;
493 return;
494 }
495 elt = mon->waitSet;
496 while (elt->waitNext != NULL) {
497 if (elt->waitNext == thread) {
498 elt->waitNext = thread->waitNext;
499 thread->waitNext = NULL;
500 return;
501 }
502 elt = elt->waitNext;
503 }
504}
505
Carl Shapirob4539192010-01-04 16:50:00 -0800506/*
507 * Converts the given relative waiting time into an absolute time.
508 */
Bill Buzbeefccb31d2010-02-04 16:09:55 -0800509void absoluteTime(s8 msec, s4 nsec, struct timespec *ts)
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800510{
511 s8 endSec;
512
513#ifdef HAVE_TIMEDWAIT_MONOTONIC
514 clock_gettime(CLOCK_MONOTONIC, ts);
515#else
516 {
517 struct timeval tv;
518 gettimeofday(&tv, NULL);
519 ts->tv_sec = tv.tv_sec;
520 ts->tv_nsec = tv.tv_usec * 1000;
521 }
522#endif
523 endSec = ts->tv_sec + msec / 1000;
524 if (endSec >= 0x7fffffff) {
525 LOGV("NOTE: end time exceeds epoch\n");
526 endSec = 0x7ffffffe;
527 }
528 ts->tv_sec = endSec;
529 ts->tv_nsec = (ts->tv_nsec + (msec % 1000) * 1000000) + nsec;
530
531 /* catch rollover */
532 if (ts->tv_nsec >= 1000000000L) {
533 ts->tv_sec++;
534 ts->tv_nsec -= 1000000000L;
535 }
536}
537
Bill Buzbeefccb31d2010-02-04 16:09:55 -0800538int dvmRelativeCondWait(pthread_cond_t* cond, pthread_mutex_t* mutex,
539 s8 msec, s4 nsec)
540{
541 int ret;
542 struct timespec ts;
543 absoluteTime(msec, nsec, &ts);
544#if defined(HAVE_TIMEDWAIT_MONOTONIC)
545 ret = pthread_cond_timedwait_monotonic(cond, mutex, &ts);
546#else
547 ret = pthread_cond_timedwait(cond, mutex, &ts);
548#endif
549 assert(ret == 0 || ret == ETIMEDOUT);
550 return ret;
551}
552
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800553/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800554 * Wait on a monitor until timeout, interrupt, or notification. Used for
555 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
556 *
557 * If another thread calls Thread.interrupt(), we throw InterruptedException
558 * and return immediately if one of the following are true:
559 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
560 * - blocked in join(), join(long), or join(long, int) methods of Thread
561 * - blocked in sleep(long), or sleep(long, int) methods of Thread
562 * Otherwise, we set the "interrupted" flag.
563 *
564 * Checks to make sure that "nsec" is in the range 0-999999
565 * (i.e. fractions of a millisecond) and throws the appropriate
566 * exception if it isn't.
567 *
568 * The spec allows "spurious wakeups", and recommends that all code using
569 * Object.wait() do so in a loop. This appears to derive from concerns
570 * about pthread_cond_wait() on multiprocessor systems. Some commentary
571 * on the web casts doubt on whether these can/should occur.
572 *
573 * Since we're allowed to wake up "early", we clamp extremely long durations
574 * to return at the end of the 32-bit time epoch.
575 */
576static void waitMonitor(Thread* self, Monitor* mon, s8 msec, s4 nsec,
577 bool interruptShouldThrow)
578{
579 struct timespec ts;
580 bool wasInterrupted = false;
581 bool timed;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800582 int ret;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800583
Carl Shapiro71938022009-12-22 13:49:53 -0800584 assert(self != NULL);
585 assert(mon != NULL);
586
Carl Shapiro94338aa2009-12-21 11:42:59 -0800587 /* Make sure that we hold the lock. */
Carl Shapiro71938022009-12-22 13:49:53 -0800588 if (mon->owner != self) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800589 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
590 "object not locked by thread before wait()");
591 return;
592 }
593
594 /*
595 * Enforce the timeout range.
596 */
597 if (msec < 0 || nsec < 0 || nsec > 999999) {
598 dvmThrowException("Ljava/lang/IllegalArgumentException;",
599 "timeout arguments out of range");
600 return;
601 }
602
603 /*
604 * Compute absolute wakeup time, if necessary.
605 */
606 if (msec == 0 && nsec == 0) {
607 timed = false;
608 } else {
Bill Buzbeefccb31d2010-02-04 16:09:55 -0800609 absoluteTime(msec, nsec, &ts);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800610 timed = true;
611 }
612
613 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800614 * Add ourselves to the set of threads waiting on this monitor, and
615 * release our hold. We need to let it go even if we're a few levels
616 * deep in a recursive lock, and we need to restore that later.
617 *
Carl Shapiro142ef272010-01-25 12:51:31 -0800618 * We append to the wait set ahead of clearing the count and owner
619 * fields so the subroutine can check that the calling thread owns
620 * the monitor. Aside from that, the order of member updates is
621 * not order sensitive as we hold the pthread mutex.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800622 */
Carl Shapiro142ef272010-01-25 12:51:31 -0800623 waitSetAppend(mon, self);
624 int prevLockCount = mon->lockCount;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800625 mon->lockCount = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800626 mon->owner = NULL;
627
628 /*
629 * Update thread status. If the GC wakes up, it'll ignore us, knowing
630 * that we won't touch any references in this state, and we'll check
631 * our suspend mode before we transition out.
632 */
633 if (timed)
634 dvmChangeStatus(self, THREAD_TIMED_WAIT);
635 else
636 dvmChangeStatus(self, THREAD_WAIT);
637
Carl Shapiro980ffb02010-03-13 22:34:01 -0800638 dvmLockMutex(&self->waitMutex);
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800639
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800640 /*
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800641 * Set waitMonitor to the monitor object we will be waiting on.
642 * When waitMonitor is non-NULL a notifying or interrupting thread
643 * must signal the thread's waitCond to wake it up.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800644 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800645 assert(self->waitMonitor == NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800646 self->waitMonitor = mon;
647
648 /*
649 * Handle the case where the thread was interrupted before we called
650 * wait().
651 */
652 if (self->interrupted) {
653 wasInterrupted = true;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800654 self->waitMonitor = NULL;
Carl Shapiro980ffb02010-03-13 22:34:01 -0800655 dvmUnlockMutex(&self->waitMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800656 goto done;
657 }
658
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800659 /*
660 * Release the monitor lock and wait for a notification or
661 * a timeout to occur.
662 */
Carl Shapiro980ffb02010-03-13 22:34:01 -0800663 dvmUnlockMutex(&mon->lock);
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800664
665 if (!timed) {
666 ret = pthread_cond_wait(&self->waitCond, &self->waitMutex);
667 assert(ret == 0);
668 } else {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800669#ifdef HAVE_TIMEDWAIT_MONOTONIC
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800670 ret = pthread_cond_timedwait_monotonic(&self->waitCond, &self->waitMutex, &ts);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800671#else
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800672 ret = pthread_cond_timedwait(&self->waitCond, &self->waitMutex, &ts);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800673#endif
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800674 assert(ret == 0 || ret == ETIMEDOUT);
675 }
676 if (self->interrupted) {
677 wasInterrupted = true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800678 }
679
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800680 self->interrupted = false;
681 self->waitMonitor = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800682
Carl Shapiro980ffb02010-03-13 22:34:01 -0800683 dvmUnlockMutex(&self->waitMutex);
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800684
Carl Shapiro30aa9972010-01-13 22:07:50 -0800685 /* Reacquire the monitor lock. */
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800686 lockMonitor(self, mon);
687
Carl Shapiro142ef272010-01-25 12:51:31 -0800688done:
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800689 /*
Carl Shapiro07b35922010-01-25 14:48:30 -0800690 * We remove our thread from wait set after restoring the count
691 * and owner fields so the subroutine can check that the calling
692 * thread owns the monitor. Aside from that, the order of member
693 * updates is not order sensitive as we hold the pthread mutex.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800694 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800695 mon->owner = self;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800696 mon->lockCount = prevLockCount;
Carl Shapiro07b35922010-01-25 14:48:30 -0800697 waitSetRemove(mon, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800698
699 /* set self->status back to THREAD_RUNNING, and self-suspend if needed */
700 dvmChangeStatus(self, THREAD_RUNNING);
701
702 if (wasInterrupted) {
703 /*
704 * We were interrupted while waiting, or somebody interrupted an
Carl Shapiro30aa9972010-01-13 22:07:50 -0800705 * un-interruptible thread earlier and we're bailing out immediately.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800706 *
707 * The doc sayeth: "The interrupted status of the current thread is
708 * cleared when this exception is thrown."
709 */
710 self->interrupted = false;
711 if (interruptShouldThrow)
712 dvmThrowException("Ljava/lang/InterruptedException;", NULL);
713 }
714}
715
716/*
717 * Notify one thread waiting on this monitor.
718 */
719static void notifyMonitor(Thread* self, Monitor* mon)
720{
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800721 Thread* thread;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800722
Carl Shapiro71938022009-12-22 13:49:53 -0800723 assert(self != NULL);
724 assert(mon != NULL);
725
Carl Shapiro94338aa2009-12-21 11:42:59 -0800726 /* Make sure that we hold the lock. */
Carl Shapiro71938022009-12-22 13:49:53 -0800727 if (mon->owner != self) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800728 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
729 "object not locked by thread before notify()");
730 return;
731 }
Carl Shapiro30aa9972010-01-13 22:07:50 -0800732 /* Signal the first waiting thread in the wait set. */
733 while (mon->waitSet != NULL) {
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800734 thread = mon->waitSet;
735 mon->waitSet = thread->waitNext;
736 thread->waitNext = NULL;
Carl Shapiro980ffb02010-03-13 22:34:01 -0800737 dvmLockMutex(&thread->waitMutex);
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800738 /* Check to see if the thread is still waiting. */
739 if (thread->waitMonitor != NULL) {
740 pthread_cond_signal(&thread->waitCond);
Carl Shapiro980ffb02010-03-13 22:34:01 -0800741 dvmUnlockMutex(&thread->waitMutex);
Carl Shapiro30aa9972010-01-13 22:07:50 -0800742 return;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800743 }
Carl Shapiro980ffb02010-03-13 22:34:01 -0800744 dvmUnlockMutex(&thread->waitMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800745 }
746}
747
748/*
749 * Notify all threads waiting on this monitor.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800750 */
751static void notifyAllMonitor(Thread* self, Monitor* mon)
752{
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800753 Thread* thread;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800754
Carl Shapiro71938022009-12-22 13:49:53 -0800755 assert(self != NULL);
756 assert(mon != NULL);
757
Carl Shapiro94338aa2009-12-21 11:42:59 -0800758 /* Make sure that we hold the lock. */
Carl Shapiro71938022009-12-22 13:49:53 -0800759 if (mon->owner != self) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800760 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
761 "object not locked by thread before notifyAll()");
762 return;
763 }
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800764 /* Signal all threads in the wait set. */
765 while (mon->waitSet != NULL) {
766 thread = mon->waitSet;
767 mon->waitSet = thread->waitNext;
768 thread->waitNext = NULL;
Carl Shapiro980ffb02010-03-13 22:34:01 -0800769 dvmLockMutex(&thread->waitMutex);
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800770 /* Check to see if the thread is still waiting. */
771 if (thread->waitMonitor != NULL) {
772 pthread_cond_signal(&thread->waitCond);
773 }
Carl Shapiro980ffb02010-03-13 22:34:01 -0800774 dvmUnlockMutex(&thread->waitMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800775 }
776}
777
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800778/*
Carl Shapiro66bb7df2010-03-12 15:25:37 -0800779 * Changes the shape of a monitor from thin to fat, preserving the
780 * internal lock state. The calling thread must own the lock.
781 */
782static void inflateMonitor(Thread *self, Object *obj)
783{
784 Monitor *mon;
785 u4 thin;
786
787 assert(self != NULL);
788 assert(obj != NULL);
789 assert(LW_SHAPE(obj->lock) == LW_SHAPE_THIN);
790 assert(LW_LOCK_OWNER(obj->lock) == self->threadId);
791 /* Allocate and acquire a new monitor. */
792 mon = dvmCreateMonitor(obj);
793 lockMonitor(self, mon);
794 /* Propagate the lock state. */
795 thin = obj->lock;
796 mon->lockCount = LW_LOCK_COUNT(thin);
797 thin &= LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT;
798 thin |= (u4)mon | LW_SHAPE_FAT;
799 /* Publish the updated lock word. */
800 MEM_BARRIER();
801 obj->lock = thin;
802}
803
804/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800805 * Implements monitorenter for "synchronized" stuff.
806 *
807 * This does not fail or throw an exception (unless deadlock prediction
808 * is enabled and set to "err" mode).
809 */
810void dvmLockObject(Thread* self, Object *obj)
811{
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800812 volatile u4 *thinp;
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800813 ThreadStatus oldStatus;
814 useconds_t sleepDelay;
815 const useconds_t maxSleepDelay = 1 << 20;
816 u4 thin, newThin, threadId;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800817
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800818 assert(self != NULL);
819 assert(obj != NULL);
820 threadId = self->threadId;
821 thinp = &obj->lock;
822retry:
823 thin = *thinp;
824 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
825 /*
826 * The lock is a thin lock. The owner field is used to
827 * determine the acquire method, ordered by cost.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800828 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800829 if (LW_LOCK_OWNER(thin) == threadId) {
830 /*
831 * The calling thread owns the lock. Increment the
832 * value of the recursion count field.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800833 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800834 obj->lock += 1 << LW_LOCK_COUNT_SHIFT;
835 } else if (LW_LOCK_OWNER(thin) == 0) {
836 /*
837 * The lock is unowned. Install the thread id of the
838 * calling thread into the owner field. This is the
839 * common case. In performance critical code the JIT
840 * will have tried this before calling out to the VM.
841 */
842 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
843 if (!ATOMIC_CMP_SWAP((int32_t *)thinp, thin, newThin)) {
844 /*
845 * The acquire failed. Try again.
846 */
847 goto retry;
848 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800849 } else {
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800850 LOG_THIN("(%d) spin on lock %p: %#x (%#x) %#x",
851 threadId, &obj->lock, 0, *thinp, thin);
852 /*
853 * The lock is owned by another thread. Notify the VM
854 * that we are about to wait.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800855 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800856 oldStatus = dvmChangeStatus(self, THREAD_MONITOR);
857 /*
858 * Spin until the thin lock is released or inflated.
859 */
860 sleepDelay = 0;
861 for (;;) {
862 thin = *thinp;
863 /*
864 * Check the shape of the lock word. Another thread
865 * may have inflated the lock while we were waiting.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800866 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800867 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
868 if (LW_LOCK_OWNER(thin) == 0) {
869 /*
870 * The lock has been released. Install the
871 * thread id of the calling thread into the
872 * owner field.
873 */
874 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
875 if (ATOMIC_CMP_SWAP((int32_t *)thinp,
876 thin, newThin)) {
877 /*
878 * The acquire succeed. Break out of the
879 * loop and proceed to inflate the lock.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800880 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800881 break;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800882 }
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800883 } else {
884 /*
885 * The lock has not been released. Yield so
886 * the owning thread can run.
887 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800888 if (sleepDelay == 0) {
889 sched_yield();
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800890 sleepDelay = 1000;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800891 } else {
892 usleep(sleepDelay);
893 if (sleepDelay < maxSleepDelay / 2) {
894 sleepDelay *= 2;
895 }
896 }
897 }
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800898 } else {
899 /*
900 * The thin lock was inflated by another thread.
901 * Let the VM know we are no longer waiting and
902 * try again.
903 */
904 LOG_THIN("(%d) lock %p surprise-fattened",
905 threadId, &obj->lock);
906 dvmChangeStatus(self, oldStatus);
907 goto retry;
908 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800909 }
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800910 LOG_THIN("(%d) spin on lock done %p: %#x (%#x) %#x",
911 threadId, &obj->lock, 0, *thinp, thin);
912 /*
913 * We have acquired the thin lock. Let the VM know that
914 * we are no longer waiting.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800915 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800916 dvmChangeStatus(self, oldStatus);
917 /*
918 * Fatten the lock.
919 */
Carl Shapiro66bb7df2010-03-12 15:25:37 -0800920 inflateMonitor(self, obj);
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800921 LOG_THIN("(%d) lock %p fattened", threadId, &obj->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800922 }
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800923 } else {
924 /*
925 * The lock is a fat lock.
926 */
927 assert(LW_MONITOR(obj->lock) != NULL);
928 lockMonitor(self, LW_MONITOR(obj->lock));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800929 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800930#ifdef WITH_DEADLOCK_PREDICTION
931 /*
932 * See if we were allowed to grab the lock at this time. We do it
933 * *after* acquiring the lock, rather than before, so that we can
934 * freely update the Monitor struct. This seems counter-intuitive,
935 * but our goal is deadlock *prediction* not deadlock *prevention*.
936 * (If we actually deadlock, the situation is easy to diagnose from
937 * a thread dump, so there's no point making a special effort to do
938 * the checks before the lock is held.)
939 *
940 * This needs to happen before we add the object to the thread's
941 * monitor list, so we can tell the difference between first-lock and
942 * re-lock.
943 *
944 * It's also important that we do this while in THREAD_RUNNING, so
945 * that we don't interfere with cleanup operations in the GC.
946 */
947 if (gDvm.deadlockPredictMode != kDPOff) {
948 if (self->status != THREAD_RUNNING) {
949 LOGE("Bad thread status (%d) in DP\n", self->status);
950 dvmDumpThread(self, false);
951 dvmAbort();
952 }
953 assert(!dvmCheckException(self));
954 updateDeadlockPrediction(self, obj);
955 if (dvmCheckException(self)) {
956 /*
957 * If we're throwing an exception here, we need to free the
958 * lock. We add the object to the thread's monitor list so the
959 * "unlock" code can remove it.
960 */
961 dvmAddToMonitorList(self, obj, false);
962 dvmUnlockObject(self, obj);
963 LOGV("--- unlocked, pending is '%s'\n",
964 dvmGetException(self)->clazz->descriptor);
965 }
966 }
967
968 /*
969 * Add the locked object, and the current stack trace, to the list
970 * held by the Thread object. If deadlock prediction isn't on,
971 * don't capture the stack trace.
972 */
973 dvmAddToMonitorList(self, obj, gDvm.deadlockPredictMode != kDPOff);
974#elif defined(WITH_MONITOR_TRACKING)
975 /*
976 * Add the locked object to the list held by the Thread object.
977 */
978 dvmAddToMonitorList(self, obj, false);
979#endif
980}
981
982/*
983 * Implements monitorexit for "synchronized" stuff.
984 *
985 * On failure, throws an exception and returns "false".
986 */
987bool dvmUnlockObject(Thread* self, Object *obj)
988{
Carl Shapiro94338aa2009-12-21 11:42:59 -0800989 u4 thin;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800990
Carl Shapiroef5b4d32010-01-26 13:22:04 -0800991 assert(self != NULL);
992 assert(self->status == THREAD_RUNNING);
993 assert(obj != NULL);
Carl Shapiroef5b4d32010-01-26 13:22:04 -0800994 /*
995 * Cache the lock word as its value can change while we are
996 * examining its state.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800997 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -0800998 thin = obj->lock;
Carl Shapiroef5b4d32010-01-26 13:22:04 -0800999 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
1000 /*
1001 * The lock is thin. We must ensure that the lock is owned
1002 * by the given thread before unlocking it.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001003 */
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001004 if (LW_LOCK_OWNER(thin) == self->threadId) {
1005 /*
1006 * We are the lock owner. It is safe to update the lock
1007 * without CAS as lock ownership guards the lock itself.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001008 */
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001009 if (LW_LOCK_COUNT(thin) == 0) {
1010 /*
1011 * The lock was not recursively acquired, the common
1012 * case. Unlock by clearing all bits except for the
1013 * hash state.
1014 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -08001015 obj->lock &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001016 } else {
1017 /*
1018 * The object was recursively acquired. Decrement the
1019 * lock recursion count field.
1020 */
Carl Shapiro147dd3f2010-03-08 14:38:42 -08001021 obj->lock -= 1 << LW_LOCK_COUNT_SHIFT;
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001022 }
1023 } else {
1024 /*
1025 * We do not own the lock. The JVM spec requires that we
1026 * throw an exception in this case.
1027 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001028 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001029 "unlock of unowned monitor");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001030 return false;
1031 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001032 } else {
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001033 /*
1034 * The lock is fat. We must check to see if unlockMonitor has
1035 * raised any exceptions before continuing.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001036 */
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001037 assert(LW_MONITOR(obj->lock) != NULL);
1038 if (!unlockMonitor(self, LW_MONITOR(obj->lock))) {
Carl Shapiroef5b4d32010-01-26 13:22:04 -08001039 /*
1040 * An exception has been raised. Do not fall through.
1041 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001042 return false;
1043 }
1044 }
1045
1046#ifdef WITH_MONITOR_TRACKING
1047 /*
1048 * Remove the object from the Thread's list.
1049 */
1050 dvmRemoveFromMonitorList(self, obj);
1051#endif
1052
1053 return true;
1054}
1055
1056/*
1057 * Object.wait(). Also called for class init.
1058 */
1059void dvmObjectWait(Thread* self, Object *obj, s8 msec, s4 nsec,
1060 bool interruptShouldThrow)
1061{
Carl Shapiro66bb7df2010-03-12 15:25:37 -08001062 Monitor* mon;
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001063 u4 thin = obj->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001064
1065 /* If the lock is still thin, we need to fatten it.
1066 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001067 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001068 /* Make sure that 'self' holds the lock.
1069 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001070 if (LW_LOCK_OWNER(thin) != self->threadId) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001071 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
1072 "object not locked by thread before wait()");
1073 return;
1074 }
1075
1076 /* This thread holds the lock. We need to fatten the lock
1077 * so 'self' can block on it. Don't update the object lock
1078 * field yet, because 'self' needs to acquire the lock before
1079 * any other thread gets a chance.
1080 */
Carl Shapiro66bb7df2010-03-12 15:25:37 -08001081 inflateMonitor(self, obj);
1082 LOG_THIN("(%d) lock %p fattened by wait() to count %d",
1083 self->threadId, &obj->lock, mon->lockCount);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001084 }
Carl Shapiro66bb7df2010-03-12 15:25:37 -08001085 mon = LW_MONITOR(obj->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001086 waitMonitor(self, mon, msec, nsec, interruptShouldThrow);
1087}
1088
1089/*
1090 * Object.notify().
1091 */
1092void dvmObjectNotify(Thread* self, Object *obj)
1093{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001094 u4 thin = obj->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001095
1096 /* If the lock is still thin, there aren't any waiters;
1097 * waiting on an object forces lock fattening.
1098 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001099 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001100 /* Make sure that 'self' holds the lock.
1101 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001102 if (LW_LOCK_OWNER(thin) != self->threadId) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001103 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
1104 "object not locked by thread before notify()");
1105 return;
1106 }
1107
1108 /* no-op; there are no waiters to notify.
1109 */
1110 } else {
1111 /* It's a fat lock.
1112 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001113 notifyMonitor(self, LW_MONITOR(thin));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001114 }
1115}
1116
1117/*
1118 * Object.notifyAll().
1119 */
1120void dvmObjectNotifyAll(Thread* self, Object *obj)
1121{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001122 u4 thin = obj->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001123
1124 /* If the lock is still thin, there aren't any waiters;
1125 * waiting on an object forces lock fattening.
1126 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001127 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001128 /* Make sure that 'self' holds the lock.
1129 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001130 if (LW_LOCK_OWNER(thin) != self->threadId) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001131 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
1132 "object not locked by thread before notifyAll()");
1133 return;
1134 }
1135
1136 /* no-op; there are no waiters to notify.
1137 */
1138 } else {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001139 /* It's a fat lock.
1140 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001141 notifyAllMonitor(self, LW_MONITOR(thin));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001142 }
1143}
1144
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001145/*
1146 * This implements java.lang.Thread.sleep(long msec, int nsec).
1147 *
1148 * The sleep is interruptible by other threads, which means we can't just
1149 * plop into an OS sleep call. (We probably could if we wanted to send
1150 * signals around and rely on EINTR, but that's inefficient and relies
1151 * on native code respecting our signal mask.)
1152 *
1153 * We have to do all of this stuff for Object.wait() as well, so it's
1154 * easiest to just sleep on a private Monitor.
1155 *
1156 * It appears that we want sleep(0,0) to go through the motions of sleeping
1157 * for a very short duration, rather than just returning.
1158 */
1159void dvmThreadSleep(u8 msec, u4 nsec)
1160{
1161 Thread* self = dvmThreadSelf();
1162 Monitor* mon = gDvm.threadSleepMon;
1163
1164 /* sleep(0,0) wakes up immediately, wait(0,0) means wait forever; adjust */
1165 if (msec == 0 && nsec == 0)
1166 nsec++;
1167
1168 lockMonitor(self, mon);
1169 waitMonitor(self, mon, msec, nsec, true);
1170 unlockMonitor(self, mon);
1171}
1172
1173/*
1174 * Implement java.lang.Thread.interrupt().
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001175 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001176void dvmThreadInterrupt(Thread* thread)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001177{
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001178 assert(thread != NULL);
1179
Carl Shapiro980ffb02010-03-13 22:34:01 -08001180 dvmLockMutex(&thread->waitMutex);
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001181
1182 /*
1183 * If the interrupted flag is already set no additional action is
1184 * required.
1185 */
1186 if (thread->interrupted == true) {
Carl Shapiro980ffb02010-03-13 22:34:01 -08001187 dvmUnlockMutex(&thread->waitMutex);
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001188 return;
1189 }
1190
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001191 /*
1192 * Raise the "interrupted" flag. This will cause it to bail early out
1193 * of the next wait() attempt, if it's not currently waiting on
1194 * something.
1195 */
1196 thread->interrupted = true;
1197 MEM_BARRIER();
1198
1199 /*
1200 * Is the thread waiting?
1201 *
1202 * Note that fat vs. thin doesn't matter here; waitMonitor
1203 * is only set when a thread actually waits on a monitor,
1204 * which implies that the monitor has already been fattened.
1205 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001206 if (thread->waitMonitor != NULL) {
1207 pthread_cond_signal(&thread->waitCond);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001208 }
1209
Carl Shapiro980ffb02010-03-13 22:34:01 -08001210 dvmUnlockMutex(&thread->waitMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001211}
1212
Carl Shapiro30aa9972010-01-13 22:07:50 -08001213#ifndef WITH_COPYING_GC
Carl Shapiro94338aa2009-12-21 11:42:59 -08001214u4 dvmIdentityHashCode(Object *obj)
1215{
1216 return (u4)obj;
1217}
Carl Shapiro30aa9972010-01-13 22:07:50 -08001218#else
1219static size_t arrayElementWidth(const ArrayObject *array)
1220{
1221 const char *descriptor;
1222
1223 if (dvmIsObjectArray(array)) {
1224 return sizeof(Object *);
1225 } else {
1226 descriptor = array->obj.clazz->descriptor;
1227 switch (descriptor[1]) {
1228 case 'B': return 1; /* byte */
1229 case 'C': return 2; /* char */
1230 case 'D': return 8; /* double */
1231 case 'F': return 4; /* float */
1232 case 'I': return 4; /* int */
1233 case 'J': return 8; /* long */
1234 case 'S': return 2; /* short */
1235 case 'Z': return 1; /* boolean */
1236 }
1237 }
1238 LOGE("object %p has an unhandled descriptor '%s'", array, descriptor);
1239 dvmDumpThread(dvmThreadSelf(), false);
1240 dvmAbort();
1241 return 0; /* Quiet the compiler. */
1242}
1243
1244static size_t arrayObjectLength(const ArrayObject *array)
1245{
1246 size_t length;
1247
1248 length = offsetof(ArrayObject, contents);
1249 length += array->length * arrayElementWidth(array);
1250 return length;
1251}
1252
1253/*
1254 * Returns the identity hash code of the given object.
1255 */
1256u4 dvmIdentityHashCode(Object *obj)
1257{
1258 Thread *self, *thread;
1259 volatile u4 *lw;
1260 size_t length;
1261 u4 lock, owner, hashState;
1262
1263 if (obj == NULL) {
1264 /*
1265 * Null is defined to have an identity hash code of 0.
1266 */
1267 return 0;
1268 }
1269 lw = &obj->lock;
1270retry:
1271 hashState = LW_HASH_STATE(*lw);
1272 if (hashState == LW_HASH_STATE_HASHED) {
1273 /*
1274 * The object has been hashed but has not had its hash code
1275 * relocated by the garbage collector. Use the raw object
1276 * address.
1277 */
1278 return (u4)obj >> 3;
1279 } else if (hashState == LW_HASH_STATE_HASHED_AND_MOVED) {
1280 /*
1281 * The object has been hashed and its hash code has been
1282 * relocated by the collector. Use the value of the naturally
1283 * aligned word following the instance data.
1284 */
1285 if (IS_CLASS_FLAG_SET(obj->clazz, CLASS_ISARRAY)) {
1286 length = arrayObjectLength((ArrayObject *)obj);
1287 length = (length + 3) & ~3;
1288 } else {
1289 length = obj->clazz->objectSize;
1290 }
1291 return *(u4 *)(((char *)obj) + length);
1292 } else if (hashState == LW_HASH_STATE_UNHASHED) {
1293 /*
1294 * The object has never been hashed. Change the hash state to
1295 * hashed and use the raw object address.
1296 */
1297 self = dvmThreadSelf();
1298 if (self->threadId == lockOwner(obj)) {
1299 /*
1300 * We already own the lock so we can update the hash state
1301 * directly.
1302 */
1303 *lw |= (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1304 return (u4)obj >> 3;
1305 }
1306 /*
1307 * We do not own the lock. Try acquiring the lock. Should
1308 * this fail, we must suspend the owning thread.
1309 */
1310 if (LW_SHAPE(*lw) == LW_SHAPE_THIN) {
1311 /*
1312 * If the lock is thin assume it is unowned. We simulate
1313 * an acquire, update, and release with a single CAS.
1314 */
1315 lock = DVM_LOCK_INITIAL_THIN_VALUE;
1316 lock |= (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1317 if (ATOMIC_CMP_SWAP((int32_t *)lw,
1318 (int32_t)DVM_LOCK_INITIAL_THIN_VALUE,
1319 (int32_t)lock)) {
1320 /*
1321 * A new lockword has been installed with a hash state
1322 * of hashed. Use the raw object address.
1323 */
1324 return (u4)obj >> 3;
1325 }
1326 } else {
1327 if (tryLockMonitor(self, LW_MONITOR(*lw))) {
1328 /*
1329 * The monitor lock has been acquired. Change the
1330 * hash state to hashed and use the raw object
1331 * address.
1332 */
1333 *lw |= (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1334 unlockMonitor(self, LW_MONITOR(*lw));
1335 return (u4)obj >> 3;
1336 }
1337 }
1338 /*
1339 * At this point we have failed to acquire the lock. We must
1340 * identify the owning thread and suspend it.
1341 */
1342 dvmLockThreadList(self);
1343 /*
1344 * Cache the lock word as its value can change between
1345 * determining its shape and retrieving its owner.
1346 */
1347 lock = *lw;
1348 if (LW_SHAPE(lock) == LW_SHAPE_THIN) {
1349 /*
1350 * Find the thread with the corresponding thread id.
1351 */
1352 owner = LW_LOCK_OWNER(lock);
1353 assert(owner != self->threadId);
1354 /*
1355 * If the lock has no owner do not bother scanning the
1356 * thread list and fall through to the failure handler.
1357 */
1358 thread = owner ? gDvm.threadList : NULL;
1359 while (thread != NULL) {
1360 if (thread->threadId == owner) {
1361 break;
1362 }
1363 thread = thread->next;
1364 }
1365 } else {
1366 thread = LW_MONITOR(lock)->owner;
1367 }
1368 /*
1369 * If thread is NULL the object has been released since the
1370 * thread list lock was acquired. Try again.
1371 */
1372 if (thread == NULL) {
1373 dvmUnlockThreadList();
1374 goto retry;
1375 }
1376 /*
1377 * Wait for the owning thread to suspend.
1378 */
1379 dvmSuspendThread(thread);
1380 if (dvmHoldsLock(thread, obj)) {
1381 /*
1382 * The owning thread has been suspended. We can safely
1383 * change the hash state to hashed.
1384 */
1385 *lw |= (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1386 dvmResumeThread(thread);
1387 dvmUnlockThreadList();
1388 return (u4)obj >> 3;
1389 }
1390 /*
1391 * The wrong thread has been suspended. Try again.
1392 */
1393 dvmResumeThread(thread);
1394 dvmUnlockThreadList();
1395 goto retry;
1396 }
1397 LOGE("object %p has an unknown hash state %#x", obj, hashState);
1398 dvmDumpThread(dvmThreadSelf(), false);
1399 dvmAbort();
1400 return 0; /* Quiet the compiler. */
1401}
1402#endif /* WITH_COPYING_GC */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001403
1404#ifdef WITH_DEADLOCK_PREDICTION
1405/*
1406 * ===========================================================================
1407 * Deadlock prediction
1408 * ===========================================================================
1409 */
1410/*
1411The idea is to predict the possibility of deadlock by recording the order
1412in which monitors are acquired. If we see an attempt to acquire a lock
1413out of order, we can identify the locks and offending code.
1414
1415To make this work, we need to keep track of the locks held by each thread,
1416and create history trees for each lock. When a thread tries to acquire
1417a new lock, we walk through the "history children" of the lock, looking
1418for a match with locks the thread already holds. If we find a match,
1419it means the thread has made a request that could result in a deadlock.
1420
1421To support recursive locks, we always allow re-locking a currently-held
1422lock, and maintain a recursion depth count.
1423
1424An ASCII-art example, where letters represent Objects:
1425
1426 A
1427 /|\
1428 / | \
1429 B | D
1430 \ |
1431 \|
1432 C
1433
1434The above is the tree we'd have after handling Object synchronization
1435sequences "ABC", "AC", "AD". A has three children, {B, C, D}. C is also
1436a child of B. (The lines represent pointers between parent and child.
1437Every node can have multiple parents and multiple children.)
1438
1439If we hold AC, and want to lock B, we recursively search through B's
1440children to see if A or C appears. It does, so we reject the attempt.
1441(A straightforward way to implement it: add a link from C to B, then
1442determine whether the graph starting at B contains a cycle.)
1443
1444If we hold AC and want to lock D, we would succeed, creating a new link
1445from C to D.
1446
1447The lock history and a stack trace is attached to the Object's Monitor
1448struct, which means we need to fatten every Object we lock (thin locking
1449is effectively disabled). If we don't need the stack trace we can
1450avoid fattening the leaf nodes, only fattening objects that need to hold
1451history trees.
1452
1453Updates to Monitor structs are only allowed for the thread that holds
1454the Monitor, so we actually do most of our deadlock prediction work after
1455the lock has been acquired.
1456
1457When an object with a monitor is GCed, we need to remove it from the
1458history trees. There are two basic approaches:
1459 (1) For through the entire set of known monitors, search all child
1460 lists for the object in question. This is rather slow, resulting
1461 in GC passes that take upwards of 10 seconds to complete.
1462 (2) Maintain "parent" pointers in each node. Remove the entries as
1463 required. This requires additional storage and maintenance for
1464 every operation, but is significantly faster at GC time.
1465For each GCed object, we merge all of the object's children into each of
1466the object's parents.
1467*/
1468
1469#if !defined(WITH_MONITOR_TRACKING)
1470# error "WITH_DEADLOCK_PREDICTION requires WITH_MONITOR_TRACKING"
1471#endif
1472
1473/*
1474 * Clear out the contents of an ExpandingObjectList, freeing any
1475 * dynamic allocations.
1476 */
1477static void expandObjClear(ExpandingObjectList* pList)
1478{
1479 if (pList->list != NULL) {
1480 free(pList->list);
1481 pList->list = NULL;
1482 }
1483 pList->alloc = pList->count = 0;
1484}
1485
1486/*
1487 * Get the number of objects currently stored in the list.
1488 */
1489static inline int expandBufGetCount(const ExpandingObjectList* pList)
1490{
1491 return pList->count;
1492}
1493
1494/*
1495 * Get the Nth entry from the list.
1496 */
1497static inline Object* expandBufGetEntry(const ExpandingObjectList* pList,
1498 int i)
1499{
1500 return pList->list[i];
1501}
1502
1503/*
1504 * Add a new entry to the list.
1505 *
1506 * We don't check for or try to enforce uniqueness. It's expected that
1507 * the higher-level code does this for us.
1508 */
1509static void expandObjAddEntry(ExpandingObjectList* pList, Object* obj)
1510{
1511 if (pList->count == pList->alloc) {
1512 /* time to expand */
1513 Object** newList;
1514
1515 if (pList->alloc == 0)
1516 pList->alloc = 4;
1517 else
1518 pList->alloc *= 2;
1519 LOGVV("expanding %p to %d\n", pList, pList->alloc);
1520 newList = realloc(pList->list, pList->alloc * sizeof(Object*));
1521 if (newList == NULL) {
1522 LOGE("Failed expanding DP object list (alloc=%d)\n", pList->alloc);
1523 dvmAbort();
1524 }
1525 pList->list = newList;
1526 }
1527
1528 pList->list[pList->count++] = obj;
1529}
1530
1531/*
1532 * Returns "true" if the element was successfully removed.
1533 */
1534static bool expandObjRemoveEntry(ExpandingObjectList* pList, Object* obj)
1535{
1536 int i;
1537
1538 for (i = pList->count-1; i >= 0; i--) {
1539 if (pList->list[i] == obj)
1540 break;
1541 }
1542 if (i < 0)
1543 return false;
1544
1545 if (i != pList->count-1) {
1546 /*
1547 * The order of elements is not important, so we just copy the
1548 * last entry into the new slot.
1549 */
1550 //memmove(&pList->list[i], &pList->list[i+1],
1551 // (pList->count-1 - i) * sizeof(pList->list[0]));
1552 pList->list[i] = pList->list[pList->count-1];
1553 }
1554
1555 pList->count--;
1556 pList->list[pList->count] = (Object*) 0xdecadead;
1557 return true;
1558}
1559
1560/*
1561 * Returns "true" if "obj" appears in the list.
1562 */
1563static bool expandObjHas(const ExpandingObjectList* pList, Object* obj)
1564{
1565 int i;
1566
1567 for (i = 0; i < pList->count; i++) {
1568 if (pList->list[i] == obj)
1569 return true;
1570 }
1571 return false;
1572}
1573
1574/*
1575 * Print the list contents to stdout. For debugging.
1576 */
1577static void expandObjDump(const ExpandingObjectList* pList)
1578{
1579 int i;
1580 for (i = 0; i < pList->count; i++)
1581 printf(" %p", pList->list[i]);
1582}
1583
1584/*
1585 * Check for duplicate entries. Returns the index of the first instance
1586 * of the duplicated value, or -1 if no duplicates were found.
1587 */
1588static int expandObjCheckForDuplicates(const ExpandingObjectList* pList)
1589{
1590 int i, j;
1591 for (i = 0; i < pList->count-1; i++) {
1592 for (j = i + 1; j < pList->count; j++) {
1593 if (pList->list[i] == pList->list[j]) {
1594 return i;
1595 }
1596 }
1597 }
1598
1599 return -1;
1600}
1601
1602
1603/*
1604 * Determine whether "child" appears in the list of objects associated
1605 * with the Monitor in "parent". If "parent" is a thin lock, we return
1606 * false immediately.
1607 */
1608static bool objectInChildList(const Object* parent, Object* child)
1609{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001610 u4 lock = parent->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001611 if (!IS_LOCK_FAT(&lock)) {
1612 //LOGI("on thin\n");
1613 return false;
1614 }
1615
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001616 return expandObjHas(&LW_MONITOR(lock)->historyChildren, child);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001617}
1618
1619/*
1620 * Print the child list.
1621 */
1622static void dumpKids(Object* parent)
1623{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001624 Monitor* mon = LW_MONITOR(parent->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001625
1626 printf("Children of %p:", parent);
1627 expandObjDump(&mon->historyChildren);
1628 printf("\n");
1629}
1630
1631/*
1632 * Add "child" to the list of children in "parent", and add "parent" to
1633 * the list of parents in "child".
1634 */
1635static void linkParentToChild(Object* parent, Object* child)
1636{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001637 //assert(LW_MONITOR(parent->lock)->owner == dvmThreadSelf()); // !owned for merge
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001638 assert(IS_LOCK_FAT(&parent->lock));
1639 assert(IS_LOCK_FAT(&child->lock));
1640 assert(parent != child);
1641 Monitor* mon;
1642
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001643 mon = LW_MONITOR(parent->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001644 assert(!expandObjHas(&mon->historyChildren, child));
1645 expandObjAddEntry(&mon->historyChildren, child);
1646
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001647 mon = LW_MONITOR(child->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001648 assert(!expandObjHas(&mon->historyParents, parent));
1649 expandObjAddEntry(&mon->historyParents, parent);
1650}
1651
1652
1653/*
1654 * Remove "child" from the list of children in "parent".
1655 */
1656static void unlinkParentFromChild(Object* parent, Object* child)
1657{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001658 //assert(LW_MONITOR(parent->lock)->owner == dvmThreadSelf()); // !owned for GC
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001659 assert(IS_LOCK_FAT(&parent->lock));
1660 assert(IS_LOCK_FAT(&child->lock));
1661 assert(parent != child);
1662 Monitor* mon;
1663
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001664 mon = LW_MONITOR(parent->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001665 if (!expandObjRemoveEntry(&mon->historyChildren, child)) {
1666 LOGW("WARNING: child %p not found in parent %p\n", child, parent);
1667 }
1668 assert(!expandObjHas(&mon->historyChildren, child));
1669 assert(expandObjCheckForDuplicates(&mon->historyChildren) < 0);
1670
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001671 mon = LW_MONITOR(child->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001672 if (!expandObjRemoveEntry(&mon->historyParents, parent)) {
1673 LOGW("WARNING: parent %p not found in child %p\n", parent, child);
1674 }
1675 assert(!expandObjHas(&mon->historyParents, parent));
1676 assert(expandObjCheckForDuplicates(&mon->historyParents) < 0);
1677}
1678
1679
1680/*
1681 * Log the monitors held by the current thread. This is done as part of
1682 * flagging an error.
1683 */
1684static void logHeldMonitors(Thread* self)
1685{
1686 char* name = NULL;
1687
1688 name = dvmGetThreadName(self);
1689 LOGW("Monitors currently held by thread (threadid=%d '%s')\n",
1690 self->threadId, name);
1691 LOGW("(most-recently-acquired on top):\n");
1692 free(name);
1693
1694 LockedObjectData* lod = self->pLockedObjects;
1695 while (lod != NULL) {
1696 LOGW("--- object %p[%d] (%s)\n",
1697 lod->obj, lod->recursionCount, lod->obj->clazz->descriptor);
1698 dvmLogRawStackTrace(lod->rawStackTrace, lod->stackDepth);
1699
1700 lod = lod->next;
1701 }
1702}
1703
1704/*
1705 * Recursively traverse the object hierarchy starting at "obj". We mark
1706 * ourselves on entry and clear the mark on exit. If we ever encounter
1707 * a marked object, we have a cycle.
1708 *
1709 * Returns "true" if all is well, "false" if we found a cycle.
1710 */
1711static bool traverseTree(Thread* self, const Object* obj)
1712{
1713 assert(IS_LOCK_FAT(&obj->lock));
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001714 Monitor* mon = LW_MONITOR(obj->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001715
1716 /*
1717 * Have we been here before?
1718 */
1719 if (mon->historyMark) {
1720 int* rawStackTrace;
1721 int stackDepth;
1722
1723 LOGW("%s\n", kStartBanner);
1724 LOGW("Illegal lock attempt:\n");
1725 LOGW("--- object %p (%s)\n", obj, obj->clazz->descriptor);
1726
1727 rawStackTrace = dvmFillInStackTraceRaw(self, &stackDepth);
1728 dvmLogRawStackTrace(rawStackTrace, stackDepth);
1729 free(rawStackTrace);
1730
1731 LOGW(" ");
1732 logHeldMonitors(self);
1733
1734 LOGW(" ");
1735 LOGW("Earlier, the following lock order (from last to first) was\n");
1736 LOGW("established -- stack trace is from first successful lock):\n");
1737 return false;
1738 }
1739 mon->historyMark = true;
1740
1741 /*
1742 * Examine the children. We do NOT hold these locks, so they might
1743 * very well transition from thin to fat or change ownership while
1744 * we work.
1745 *
1746 * NOTE: we rely on the fact that they cannot revert from fat to thin
1747 * while we work. This is currently a safe assumption.
1748 *
1749 * We can safely ignore thin-locked children, because by definition
1750 * they have no history and are leaf nodes. In the current
1751 * implementation we always fatten the locks to provide a place to
1752 * hang the stack trace.
1753 */
1754 ExpandingObjectList* pList = &mon->historyChildren;
1755 int i;
1756 for (i = expandBufGetCount(pList)-1; i >= 0; i--) {
1757 const Object* child = expandBufGetEntry(pList, i);
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001758 u4 lock = child->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001759 if (!IS_LOCK_FAT(&lock))
1760 continue;
1761 if (!traverseTree(self, child)) {
1762 LOGW("--- object %p (%s)\n", obj, obj->clazz->descriptor);
1763 dvmLogRawStackTrace(mon->historyRawStackTrace,
1764 mon->historyStackDepth);
1765 mon->historyMark = false;
1766 return false;
1767 }
1768 }
1769
1770 mon->historyMark = false;
1771
1772 return true;
1773}
1774
1775/*
1776 * Update the deadlock prediction tree, based on the current thread
1777 * acquiring "acqObj". This must be called before the object is added to
1778 * the thread's list of held monitors.
1779 *
1780 * If the thread already holds the lock (recursion), or this is a known
1781 * lock configuration, we return without doing anything. Otherwise, we add
1782 * a link from the most-recently-acquired lock in this thread to "acqObj"
1783 * after ensuring that the parent lock is "fat".
1784 *
1785 * This MUST NOT be called while a GC is in progress in another thread,
1786 * because we assume exclusive access to history trees in owned monitors.
1787 */
1788static void updateDeadlockPrediction(Thread* self, Object* acqObj)
1789{
1790 LockedObjectData* lod;
1791 LockedObjectData* mrl;
1792
1793 /*
1794 * Quick check for recursive access.
1795 */
1796 lod = dvmFindInMonitorList(self, acqObj);
1797 if (lod != NULL) {
1798 LOGV("+++ DP: recursive %p\n", acqObj);
1799 return;
1800 }
1801
1802 /*
1803 * Make the newly-acquired object's monitor "fat". In some ways this
1804 * isn't strictly necessary, but we need the GC to tell us when
1805 * "interesting" objects go away, and right now the only way to make
1806 * an object look interesting is to give it a monitor.
1807 *
1808 * This also gives us a place to hang a stack trace.
1809 *
1810 * Our thread holds the lock, so we're allowed to rewrite the lock
1811 * without worrying that something will change out from under us.
1812 */
1813 if (!IS_LOCK_FAT(&acqObj->lock)) {
1814 LOGVV("fattening lockee %p (recur=%d)\n",
Carl Shapiro94338aa2009-12-21 11:42:59 -08001815 acqObj, LW_LOCK_COUNT(acqObj->lock.thin));
Carl Shapiro66bb7df2010-03-12 15:25:37 -08001816 inflateMonitor(self, acqObj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001817 }
1818
1819 /* if we don't have a stack trace for this monitor, establish one */
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001820 if (LW_MONITOR(acqObj->lock)->historyRawStackTrace == NULL) {
1821 Monitor* mon = LW_MONITOR(acqObj->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001822 mon->historyRawStackTrace = dvmFillInStackTraceRaw(self,
1823 &mon->historyStackDepth);
1824 }
1825
1826 /*
1827 * We need to examine and perhaps modify the most-recently-locked
1828 * monitor. We own that, so there's no risk of another thread
1829 * stepping on us.
1830 *
1831 * Retrieve the most-recently-locked entry from our thread.
1832 */
1833 mrl = self->pLockedObjects;
1834 if (mrl == NULL)
1835 return; /* no other locks held */
1836
1837 /*
1838 * Do a quick check to see if "acqObj" is a direct descendant. We can do
1839 * this without holding the global lock because of our assertion that
1840 * a GC is not running in parallel -- nobody except the GC can
1841 * modify a history list in a Monitor they don't own, and we own "mrl".
1842 * (There might be concurrent *reads*, but no concurrent *writes.)
1843 *
1844 * If we find it, this is a known good configuration, and we're done.
1845 */
1846 if (objectInChildList(mrl->obj, acqObj))
1847 return;
1848
1849 /*
1850 * "mrl" is going to need to have a history tree. If it's currently
1851 * a thin lock, we make it fat now. The thin lock might have a
1852 * nonzero recursive lock count, which we need to carry over.
1853 *
1854 * Our thread holds the lock, so we're allowed to rewrite the lock
1855 * without worrying that something will change out from under us.
1856 */
1857 if (!IS_LOCK_FAT(&mrl->obj->lock)) {
1858 LOGVV("fattening parent %p f/b/o child %p (recur=%d)\n",
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001859 mrl->obj, acqObj, LW_LOCK_COUNT(mrl->obj->lock));
Carl Shapiro66bb7df2010-03-12 15:25:37 -08001860 inflateMonitor(self, mrl->obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001861 }
1862
1863 /*
1864 * We haven't seen this configuration before. We need to scan down
1865 * acqObj's tree to see if any of the monitors in self->pLockedObjects
1866 * appear. We grab a global lock before traversing or updating the
1867 * history list.
1868 *
1869 * If we find a match for any of our held locks, we know that the lock
1870 * has previously been acquired *after* acqObj, and we throw an error.
1871 *
1872 * The easiest way to do this is to create a link from "mrl" to "acqObj"
1873 * and do a recursive traversal, marking nodes as we cross them. If
1874 * we cross one a second time, we have a cycle and can throw an error.
1875 * (We do the flag-clearing traversal before adding the new link, so
1876 * that we're guaranteed to terminate.)
1877 *
1878 * If "acqObj" is a thin lock, it has no history, and we can create a
1879 * link to it without additional checks. [ We now guarantee that it's
1880 * always fat. ]
1881 */
1882 bool failed = false;
1883 dvmLockMutex(&gDvm.deadlockHistoryLock);
1884 linkParentToChild(mrl->obj, acqObj);
1885 if (!traverseTree(self, acqObj)) {
1886 LOGW("%s\n", kEndBanner);
1887 failed = true;
1888
1889 /* remove the entry so we're still okay when in "warning" mode */
1890 unlinkParentFromChild(mrl->obj, acqObj);
1891 }
1892 dvmUnlockMutex(&gDvm.deadlockHistoryLock);
1893
1894 if (failed) {
1895 switch (gDvm.deadlockPredictMode) {
1896 case kDPErr:
1897 dvmThrowException("Ldalvik/system/PotentialDeadlockError;", NULL);
1898 break;
1899 case kDPAbort:
1900 LOGE("Aborting due to potential deadlock\n");
1901 dvmAbort();
1902 break;
1903 default:
1904 /* warn only */
1905 break;
1906 }
1907 }
1908}
1909
1910/*
1911 * We're removing "child" from existence. We want to pull all of
1912 * child's children into "parent", filtering out duplicates. This is
1913 * called during the GC.
1914 *
1915 * This does not modify "child", which might have multiple parents.
1916 */
1917static void mergeChildren(Object* parent, const Object* child)
1918{
1919 Monitor* mon;
1920 int i;
1921
1922 assert(IS_LOCK_FAT(&child->lock));
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001923 mon = LW_MONITOR(child->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001924 ExpandingObjectList* pList = &mon->historyChildren;
1925
1926 for (i = expandBufGetCount(pList)-1; i >= 0; i--) {
1927 Object* grandChild = expandBufGetEntry(pList, i);
1928
1929 if (!objectInChildList(parent, grandChild)) {
1930 LOGVV("+++ migrating %p link to %p\n", grandChild, parent);
1931 linkParentToChild(parent, grandChild);
1932 } else {
1933 LOGVV("+++ parent %p already links to %p\n", parent, grandChild);
1934 }
1935 }
1936}
1937
1938/*
1939 * An object with a fat lock is being collected during a GC pass. We
1940 * want to remove it from any lock history trees that it is a part of.
1941 *
1942 * This may require updating the history trees in several monitors. The
1943 * monitor semantics guarantee that no other thread will be accessing
1944 * the history trees at the same time.
1945 */
1946static void removeCollectedObject(Object* obj)
1947{
1948 Monitor* mon;
1949
1950 LOGVV("+++ collecting %p\n", obj);
1951
1952#if 0
1953 /*
1954 * We're currently running through the entire set of known monitors.
1955 * This can be somewhat slow. We may want to keep lists of parents
1956 * in each child to speed up GC.
1957 */
1958 mon = gDvm.monitorList;
1959 while (mon != NULL) {
1960 Object* parent = mon->obj;
1961 if (parent != NULL) { /* value nulled for deleted entries */
1962 if (objectInChildList(parent, obj)) {
1963 LOGVV("removing child %p from parent %p\n", obj, parent);
1964 unlinkParentFromChild(parent, obj);
1965 mergeChildren(parent, obj);
1966 }
1967 }
1968 mon = mon->next;
1969 }
1970#endif
1971
1972 /*
1973 * For every parent of this object:
1974 * - merge all of our children into the parent's child list (creates
1975 * a two-way link between parent and child)
1976 * - remove ourselves from the parent's child list
1977 */
1978 ExpandingObjectList* pList;
1979 int i;
1980
1981 assert(IS_LOCK_FAT(&obj->lock));
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001982 mon = LW_MONITOR(obj->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001983 pList = &mon->historyParents;
1984 for (i = expandBufGetCount(pList)-1; i >= 0; i--) {
1985 Object* parent = expandBufGetEntry(pList, i);
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001986 Monitor* parentMon = LW_MONITOR(parent->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001987
1988 if (!expandObjRemoveEntry(&parentMon->historyChildren, obj)) {
1989 LOGW("WARNING: child %p not found in parent %p\n", obj, parent);
1990 }
1991 assert(!expandObjHas(&parentMon->historyChildren, obj));
1992
1993 mergeChildren(parent, obj);
1994 }
1995
1996 /*
1997 * For every child of this object:
1998 * - remove ourselves from the child's parent list
1999 */
2000 pList = &mon->historyChildren;
2001 for (i = expandBufGetCount(pList)-1; i >= 0; i--) {
2002 Object* child = expandBufGetEntry(pList, i);
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08002003 Monitor* childMon = LW_MONITOR(child->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08002004
2005 if (!expandObjRemoveEntry(&childMon->historyParents, obj)) {
2006 LOGW("WARNING: parent %p not found in child %p\n", obj, child);
2007 }
2008 assert(!expandObjHas(&childMon->historyParents, obj));
2009 }
2010}
2011
2012#endif /*WITH_DEADLOCK_PREDICTION*/