blob: c9c039e09b3eb25bde342b140377db662a51a9c3 [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/*
239 * Checks whether the given thread holds the given
240 * objects's lock.
241 */
242bool dvmHoldsLock(Thread* thread, Object* obj)
243{
Carl Shapiro94338aa2009-12-21 11:42:59 -0800244 u4 thin;
245
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800246 if (thread == NULL || obj == NULL) {
247 return false;
248 }
249
250 /* Since we're reading the lock value multiple times,
251 * latch it so that it doesn't change out from under
252 * us if we get preempted.
253 */
Carl Shapiro8d7f9b22009-12-21 20:23:45 -0800254 thin = obj->lock;
Carl Shapiro94338aa2009-12-21 11:42:59 -0800255 if (LW_SHAPE(thin) == LW_SHAPE_FAT) {
256 return thread == LW_MONITOR(thin)->owner;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800257 } else {
Carl Shapiro94338aa2009-12-21 11:42:59 -0800258 return thread->threadId == LW_LOCK_OWNER(thin);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800259 }
260}
261
262/*
263 * Free the monitor associated with an object and make the object's lock
264 * thin again. This is called during garbage collection.
265 */
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800266static void freeObjectMonitor(Object* obj)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800267{
268 Monitor *mon;
269
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800270 assert(LW_SHAPE(obj->lock) == LW_SHAPE_FAT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800271
272#ifdef WITH_DEADLOCK_PREDICTION
273 if (gDvm.deadlockPredictMode != kDPOff)
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800274 removeCollectedObject(obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800275#endif
276
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800277 mon = LW_MONITOR(obj->lock);
278 obj->lock = DVM_LOCK_INITIAL_THIN_VALUE;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800279
280 /* This lock is associated with an object
281 * that's being swept. The only possible way
282 * anyone could be holding this lock would be
283 * if some JNI code locked but didn't unlock
284 * the object, in which case we've got some bad
285 * native code somewhere.
286 */
287 assert(pthread_mutex_trylock(&mon->lock) == 0);
288 pthread_mutex_destroy(&mon->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800289#ifdef WITH_DEADLOCK_PREDICTION
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800290 expandObjClear(&mon->historyChildren);
291 expandObjClear(&mon->historyParents);
292 free(mon->historyRawStackTrace);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800293#endif
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800294 free(mon);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800295}
296
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800297/*
298 * Frees monitor objects belonging to unmarked objects.
299 */
300void dvmSweepMonitorList(Monitor** mon, int (*isUnmarkedObject)(void*))
301{
302 Monitor handle;
303 Monitor *prev, *curr;
304 Object *obj;
305
306 assert(mon != NULL);
307 assert(*mon != NULL);
308 assert(isUnmarkedObject != NULL);
309 prev = &handle;
310 prev->next = curr = *mon;
311 while (curr != NULL) {
312 obj = curr->obj;
313 if (obj != NULL && (*isUnmarkedObject)(obj) != 0) {
314 prev->next = curr = curr->next;
315 freeObjectMonitor(obj);
316 } else {
317 prev = curr;
318 curr = curr->next;
319 }
320 }
321 *mon = handle.next;
322}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800323
324/*
325 * Lock a monitor.
326 */
327static void lockMonitor(Thread* self, Monitor* mon)
328{
329 int cc;
330
331 if (mon->owner == self) {
332 mon->lockCount++;
333 } else {
334 ThreadStatus oldStatus;
335
336 if (pthread_mutex_trylock(&mon->lock) != 0) {
337 /* mutex is locked, switch to wait status and sleep on it */
338 oldStatus = dvmChangeStatus(self, THREAD_MONITOR);
339 cc = pthread_mutex_lock(&mon->lock);
340 assert(cc == 0);
341 dvmChangeStatus(self, oldStatus);
342 }
343
344 mon->owner = self;
345 assert(mon->lockCount == 0);
346
347 /*
348 * "waiting", "notifying", and "interrupting" could all be nonzero
349 * if we're locking an object on which other threads are waiting.
350 * Nothing worth assert()ing about here.
351 */
352 }
353}
354
355/*
356 * Try to lock a monitor.
357 *
358 * Returns "true" on success.
359 */
360static bool tryLockMonitor(Thread* self, Monitor* mon)
361{
362 int cc;
363
364 if (mon->owner == self) {
365 mon->lockCount++;
366 return true;
367 } else {
368 cc = pthread_mutex_trylock(&mon->lock);
369 if (cc == 0) {
370 mon->owner = self;
371 assert(mon->lockCount == 0);
372 return true;
373 } else {
374 return false;
375 }
376 }
377}
378
379
380/*
381 * Unlock a monitor.
382 *
383 * Returns true if the unlock succeeded.
384 * If the unlock failed, an exception will be pending.
385 */
386static bool unlockMonitor(Thread* self, Monitor* mon)
387{
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800388 assert(self != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800389 assert(mon != NULL); // can this happen?
390
391 if (mon->owner == self) {
392 /*
393 * We own the monitor, so nobody else can be in here.
394 */
395 if (mon->lockCount == 0) {
396 int cc;
397 mon->owner = NULL;
398 cc = pthread_mutex_unlock(&mon->lock);
399 assert(cc == 0);
400 } else {
401 mon->lockCount--;
402 }
403 } else {
404 /*
405 * We don't own this, so we're not allowed to unlock it.
406 * The JNI spec says that we should throw IllegalMonitorStateException
407 * in this case.
408 */
409 if (mon->owner == NULL) {
410 //LOGW("Unlock fat %p: not owned\n", mon->obj);
411 } else {
412 //LOGW("Unlock fat %p: id %d vs %d\n",
413 // mon->obj, mon->owner->threadId, self->threadId);
414 }
415 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
416 "unlock of unowned monitor");
417 return false;
418 }
419 return true;
420}
421
422/*
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800423 * Checks the wait set for circular structure. Returns 0 if the list
Carl Shapirob4539192010-01-04 16:50:00 -0800424 * is not circular. Otherwise, returns 1. Used only by asserts.
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800425 */
426static int waitSetCheck(Monitor *mon)
427{
428 Thread *fast, *slow;
429 size_t n;
430
431 assert(mon != NULL);
432 fast = slow = mon->waitSet;
433 n = 0;
434 for (;;) {
435 if (fast == NULL) return 0;
436 if (fast->waitNext == NULL) return 0;
Carl Shapiro5f56e672010-01-05 20:38:03 -0800437 if (fast == slow && n > 0) return 1;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800438 n += 2;
439 fast = fast->waitNext->waitNext;
440 slow = slow->waitNext;
441 }
442}
443
444/*
445 * Links a thread into a monitor's wait set.
446 */
447static void waitSetAppend(Monitor *mon, Thread *thread)
448{
449 Thread *elt;
450
451 assert(mon != NULL);
452 assert(thread != NULL);
453 assert(thread->waitNext == NULL);
454 assert(waitSetCheck(mon) == 0);
455 if (mon->waitSet == NULL) {
456 mon->waitSet = thread;
457 return;
458 }
459 elt = mon->waitSet;
460 while (elt->waitNext != NULL) {
461 elt = elt->waitNext;
462 }
463 elt->waitNext = thread;
464}
465
466/*
467 * Unlinks a thread from a monitor's wait set.
468 */
469static void waitSetRemove(Monitor *mon, Thread *thread)
470{
471 Thread *elt;
472
473 assert(mon != NULL);
474 assert(thread != NULL);
475 assert(waitSetCheck(mon) == 0);
476 if (mon->waitSet == NULL) {
477 return;
478 }
479 if (mon->waitSet == thread) {
480 mon->waitSet = thread->waitNext;
481 thread->waitNext = NULL;
482 return;
483 }
484 elt = mon->waitSet;
485 while (elt->waitNext != NULL) {
486 if (elt->waitNext == thread) {
487 elt->waitNext = thread->waitNext;
488 thread->waitNext = NULL;
489 return;
490 }
491 elt = elt->waitNext;
492 }
493}
494
Carl Shapirob4539192010-01-04 16:50:00 -0800495/*
496 * Converts the given relative waiting time into an absolute time.
497 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800498static void absoluteTime(s8 msec, s4 nsec, struct timespec *ts)
499{
500 s8 endSec;
501
502#ifdef HAVE_TIMEDWAIT_MONOTONIC
503 clock_gettime(CLOCK_MONOTONIC, ts);
504#else
505 {
506 struct timeval tv;
507 gettimeofday(&tv, NULL);
508 ts->tv_sec = tv.tv_sec;
509 ts->tv_nsec = tv.tv_usec * 1000;
510 }
511#endif
512 endSec = ts->tv_sec + msec / 1000;
513 if (endSec >= 0x7fffffff) {
514 LOGV("NOTE: end time exceeds epoch\n");
515 endSec = 0x7ffffffe;
516 }
517 ts->tv_sec = endSec;
518 ts->tv_nsec = (ts->tv_nsec + (msec % 1000) * 1000000) + nsec;
519
520 /* catch rollover */
521 if (ts->tv_nsec >= 1000000000L) {
522 ts->tv_sec++;
523 ts->tv_nsec -= 1000000000L;
524 }
525}
526
527/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800528 * Wait on a monitor until timeout, interrupt, or notification. Used for
529 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
530 *
531 * If another thread calls Thread.interrupt(), we throw InterruptedException
532 * and return immediately if one of the following are true:
533 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
534 * - blocked in join(), join(long), or join(long, int) methods of Thread
535 * - blocked in sleep(long), or sleep(long, int) methods of Thread
536 * Otherwise, we set the "interrupted" flag.
537 *
538 * Checks to make sure that "nsec" is in the range 0-999999
539 * (i.e. fractions of a millisecond) and throws the appropriate
540 * exception if it isn't.
541 *
542 * The spec allows "spurious wakeups", and recommends that all code using
543 * Object.wait() do so in a loop. This appears to derive from concerns
544 * about pthread_cond_wait() on multiprocessor systems. Some commentary
545 * on the web casts doubt on whether these can/should occur.
546 *
547 * Since we're allowed to wake up "early", we clamp extremely long durations
548 * to return at the end of the 32-bit time epoch.
549 */
550static void waitMonitor(Thread* self, Monitor* mon, s8 msec, s4 nsec,
551 bool interruptShouldThrow)
552{
553 struct timespec ts;
554 bool wasInterrupted = false;
555 bool timed;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800556 int ret;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800557
Carl Shapiro71938022009-12-22 13:49:53 -0800558 assert(self != NULL);
559 assert(mon != NULL);
560
Carl Shapiro94338aa2009-12-21 11:42:59 -0800561 /* Make sure that we hold the lock. */
Carl Shapiro71938022009-12-22 13:49:53 -0800562 if (mon->owner != self) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800563 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
564 "object not locked by thread before wait()");
565 return;
566 }
567
568 /*
569 * Enforce the timeout range.
570 */
571 if (msec < 0 || nsec < 0 || nsec > 999999) {
572 dvmThrowException("Ljava/lang/IllegalArgumentException;",
573 "timeout arguments out of range");
574 return;
575 }
576
577 /*
578 * Compute absolute wakeup time, if necessary.
579 */
580 if (msec == 0 && nsec == 0) {
581 timed = false;
582 } else {
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800583 absoluteTime(msec, nsec, &ts);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800584 timed = true;
585 }
586
587 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800588 * Add ourselves to the set of threads waiting on this monitor, and
589 * release our hold. We need to let it go even if we're a few levels
590 * deep in a recursive lock, and we need to restore that later.
591 *
592 * The order of operations here isn't significant, because we still
593 * hold the pthread mutex.
594 */
595 int prevLockCount;
596
597 prevLockCount = mon->lockCount;
598 mon->lockCount = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800599 mon->owner = NULL;
600
601 /*
602 * Update thread status. If the GC wakes up, it'll ignore us, knowing
603 * that we won't touch any references in this state, and we'll check
604 * our suspend mode before we transition out.
605 */
606 if (timed)
607 dvmChangeStatus(self, THREAD_TIMED_WAIT);
608 else
609 dvmChangeStatus(self, THREAD_WAIT);
610
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800611 ret = pthread_mutex_lock(&self->waitMutex);
612 assert(ret == 0);
613
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800614 /*
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800615 * Set waitMonitor to the monitor object we will be waiting on.
616 * When waitMonitor is non-NULL a notifying or interrupting thread
617 * must signal the thread's waitCond to wake it up.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800618 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800619 assert(self->waitMonitor == NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800620 self->waitMonitor = mon;
621
622 /*
623 * Handle the case where the thread was interrupted before we called
624 * wait().
625 */
626 if (self->interrupted) {
627 wasInterrupted = true;
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800628 self->waitMonitor = NULL;
629 pthread_mutex_unlock(&self->waitMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800630 goto done;
631 }
632
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800633 waitSetAppend(mon, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800634
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800635 /*
636 * Release the monitor lock and wait for a notification or
637 * a timeout to occur.
638 */
639 pthread_mutex_unlock(&mon->lock);
640
641 if (!timed) {
642 ret = pthread_cond_wait(&self->waitCond, &self->waitMutex);
643 assert(ret == 0);
644 } else {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800645#ifdef HAVE_TIMEDWAIT_MONOTONIC
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800646 ret = pthread_cond_timedwait_monotonic(&self->waitCond, &self->waitMutex, &ts);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800647#else
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800648 ret = pthread_cond_timedwait(&self->waitCond, &self->waitMutex, &ts);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800649#endif
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800650 assert(ret == 0 || ret == ETIMEDOUT);
651 }
652 if (self->interrupted) {
653 wasInterrupted = true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800654 }
655
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800656 self->interrupted = false;
657 self->waitMonitor = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800658
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800659 pthread_mutex_unlock(&self->waitMutex);
660
661 /* Reaquire the monitor lock. */
662 lockMonitor(self, mon);
663
664 waitSetRemove(mon, self);
665
666done:
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800667 /*
668 * Put everything back. Again, we hold the pthread mutex, so the order
669 * here isn't significant.
670 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800671 mon->owner = self;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800672 mon->lockCount = prevLockCount;
673
674 /* set self->status back to THREAD_RUNNING, and self-suspend if needed */
675 dvmChangeStatus(self, THREAD_RUNNING);
676
677 if (wasInterrupted) {
678 /*
679 * We were interrupted while waiting, or somebody interrupted an
680 * un-interruptable thread earlier and we're bailing out immediately.
681 *
682 * The doc sayeth: "The interrupted status of the current thread is
683 * cleared when this exception is thrown."
684 */
685 self->interrupted = false;
686 if (interruptShouldThrow)
687 dvmThrowException("Ljava/lang/InterruptedException;", NULL);
688 }
689}
690
691/*
692 * Notify one thread waiting on this monitor.
693 */
694static void notifyMonitor(Thread* self, Monitor* mon)
695{
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800696 Thread* thread;
697 int ret;
698
Carl Shapiro71938022009-12-22 13:49:53 -0800699 assert(self != NULL);
700 assert(mon != NULL);
701
Carl Shapiro94338aa2009-12-21 11:42:59 -0800702 /* Make sure that we hold the lock. */
Carl Shapiro71938022009-12-22 13:49:53 -0800703 if (mon->owner != self) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800704 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
705 "object not locked by thread before notify()");
706 return;
707 }
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800708 /* Signal the first thread in the wait set. */
709 if (mon->waitSet != NULL) {
710 thread = mon->waitSet;
711 mon->waitSet = thread->waitNext;
712 thread->waitNext = NULL;
713 pthread_mutex_lock(&thread->waitMutex);
714 /* Check to see if the thread is still waiting. */
715 if (thread->waitMonitor != NULL) {
716 pthread_cond_signal(&thread->waitCond);
717 }
718 pthread_mutex_unlock(&thread->waitMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800719 }
720}
721
722/*
723 * Notify all threads waiting on this monitor.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800724 */
725static void notifyAllMonitor(Thread* self, Monitor* mon)
726{
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800727 Thread* thread;
728 int ret;
729
Carl Shapiro71938022009-12-22 13:49:53 -0800730 assert(self != NULL);
731 assert(mon != NULL);
732
Carl Shapiro94338aa2009-12-21 11:42:59 -0800733 /* Make sure that we hold the lock. */
Carl Shapiro71938022009-12-22 13:49:53 -0800734 if (mon->owner != self) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800735 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
736 "object not locked by thread before notifyAll()");
737 return;
738 }
Carl Shapiro77f52eb2009-12-24 19:56:53 -0800739 /* Signal all threads in the wait set. */
740 while (mon->waitSet != NULL) {
741 thread = mon->waitSet;
742 mon->waitSet = thread->waitNext;
743 thread->waitNext = NULL;
744 pthread_mutex_lock(&thread->waitMutex);
745 /* Check to see if the thread is still waiting. */
746 if (thread->waitMonitor != NULL) {
747 pthread_cond_signal(&thread->waitCond);
748 }
749 pthread_mutex_unlock(&thread->waitMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800750 }
751}
752
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800753/*
754 * Implements monitorenter for "synchronized" stuff.
755 *
756 * This does not fail or throw an exception (unless deadlock prediction
757 * is enabled and set to "err" mode).
758 */
759void dvmLockObject(Thread* self, Object *obj)
760{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -0800761 volatile u4 *thinp = &obj->lock;
762 u4 hashState;
Carl Shapiro94338aa2009-12-21 11:42:59 -0800763 u4 thin;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800764 u4 threadId = self->threadId;
Carl Shapiro94338aa2009-12-21 11:42:59 -0800765 Monitor *mon;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800766
767 /* First, try to grab the lock as if it's thin;
768 * this is the common case and will usually succeed.
769 */
Carl Shapiro94338aa2009-12-21 11:42:59 -0800770 thin = threadId << LW_LOCK_OWNER_SHIFT;
Carl Shapiro8d7f9b22009-12-21 20:23:45 -0800771 thin |= LW_HASH_STATE(*thinp) << LW_HASH_STATE_SHIFT;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800772 if (!ATOMIC_CMP_SWAP((int32_t *)thinp,
773 (int32_t)DVM_LOCK_INITIAL_THIN_VALUE,
Carl Shapiro94338aa2009-12-21 11:42:59 -0800774 (int32_t)thin)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800775 /* The lock is either a thin lock held by someone (possibly 'self'),
776 * or a fat lock.
777 */
Carl Shapiro94338aa2009-12-21 11:42:59 -0800778 if (LW_LOCK_OWNER(*thinp) == threadId) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800779 /* 'self' is already holding the thin lock; we can just
780 * bump the count. Atomic operations are not necessary
781 * because only the thread holding the lock is allowed
782 * to modify the Lock field.
783 */
Carl Shapiro94338aa2009-12-21 11:42:59 -0800784 *thinp += 1 << LW_LOCK_COUNT_SHIFT;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800785 } else {
786 /* If this is a thin lock we need to spin on it, if it's fat
787 * we need to acquire the monitor.
788 */
Carl Shapiro94338aa2009-12-21 11:42:59 -0800789 if (LW_SHAPE(*thinp) == LW_SHAPE_THIN) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800790 ThreadStatus oldStatus;
791 static const unsigned long maxSleepDelay = 1 * 1024 * 1024;
792 unsigned long sleepDelay;
793
794 LOG_THIN("(%d) spin on lock 0x%08x: 0x%08x (0x%08x) 0x%08x\n",
795 threadId, (uint)&obj->lock,
Carl Shapiro94338aa2009-12-21 11:42:59 -0800796 DVM_LOCK_INITIAL_THIN_VALUE, *thinp, thin);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800797
798 /* The lock is still thin, but some other thread is
799 * holding it. Let the VM know that we're about
800 * to wait on another thread.
801 */
802 oldStatus = dvmChangeStatus(self, THREAD_MONITOR);
803
804 /* Spin until the other thread lets go.
805 */
806 sleepDelay = 0;
807 do {
808 /* In addition to looking for an unlock,
809 * we need to watch out for some other thread
810 * fattening the lock behind our back.
811 */
Carl Shapiro94338aa2009-12-21 11:42:59 -0800812 while (LW_LOCK_OWNER(*thinp) != 0) {
813 if (LW_SHAPE(*thinp) == LW_SHAPE_FAT) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800814 /* The lock has been fattened already.
815 */
816 LOG_THIN("(%d) lock 0x%08x surprise-fattened\n",
817 threadId, (uint)&obj->lock);
818 dvmChangeStatus(self, oldStatus);
819 goto fat_lock;
820 }
821
822 if (sleepDelay == 0) {
823 sched_yield();
824 sleepDelay = 1 * 1000;
825 } else {
826 usleep(sleepDelay);
827 if (sleepDelay < maxSleepDelay / 2) {
828 sleepDelay *= 2;
829 }
830 }
831 }
Carl Shapiro94338aa2009-12-21 11:42:59 -0800832 thin = threadId << LW_LOCK_OWNER_SHIFT;
Carl Shapiro8d7f9b22009-12-21 20:23:45 -0800833 thin |= LW_HASH_STATE(*thinp) << LW_HASH_STATE_SHIFT;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800834 } while (!ATOMIC_CMP_SWAP((int32_t *)thinp,
835 (int32_t)DVM_LOCK_INITIAL_THIN_VALUE,
Carl Shapiro94338aa2009-12-21 11:42:59 -0800836 (int32_t)thin));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800837 LOG_THIN("(%d) spin on lock done 0x%08x: "
838 "0x%08x (0x%08x) 0x%08x\n",
839 threadId, (uint)&obj->lock,
Carl Shapiro94338aa2009-12-21 11:42:59 -0800840 DVM_LOCK_INITIAL_THIN_VALUE, *thinp, thin);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800841
842 /* We've got the thin lock; let the VM know that we're
843 * done waiting.
844 */
845 dvmChangeStatus(self, oldStatus);
846
847 /* Fatten the lock. Note this relinquishes ownership.
848 * We could also create the monitor in an "owned" state
849 * to avoid "re-locking" it in fat_lock.
850 */
Carl Shapiro94338aa2009-12-21 11:42:59 -0800851 mon = dvmCreateMonitor(obj);
Carl Shapiro8d7f9b22009-12-21 20:23:45 -0800852 hashState = LW_HASH_STATE(*thinp) << LW_HASH_STATE_SHIFT;
853 obj->lock = (u4)mon | hashState | LW_SHAPE_FAT;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800854 LOG_THIN("(%d) lock 0x%08x fattened\n",
855 threadId, (uint)&obj->lock);
856
857 /* Fall through to acquire the newly fat lock.
858 */
859 }
860
861 /* The lock is already fat, which means
Carl Shapiro8d7f9b22009-12-21 20:23:45 -0800862 * that obj->lock is a regular (Monitor *).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800863 */
864 fat_lock:
Carl Shapiro8d7f9b22009-12-21 20:23:45 -0800865 assert(LW_MONITOR(obj->lock) != NULL);
866 lockMonitor(self, LW_MONITOR(obj->lock));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800867 }
868 }
869 // else, the lock was acquired with the ATOMIC_CMP_SWAP().
870
871#ifdef WITH_DEADLOCK_PREDICTION
872 /*
873 * See if we were allowed to grab the lock at this time. We do it
874 * *after* acquiring the lock, rather than before, so that we can
875 * freely update the Monitor struct. This seems counter-intuitive,
876 * but our goal is deadlock *prediction* not deadlock *prevention*.
877 * (If we actually deadlock, the situation is easy to diagnose from
878 * a thread dump, so there's no point making a special effort to do
879 * the checks before the lock is held.)
880 *
881 * This needs to happen before we add the object to the thread's
882 * monitor list, so we can tell the difference between first-lock and
883 * re-lock.
884 *
885 * It's also important that we do this while in THREAD_RUNNING, so
886 * that we don't interfere with cleanup operations in the GC.
887 */
888 if (gDvm.deadlockPredictMode != kDPOff) {
889 if (self->status != THREAD_RUNNING) {
890 LOGE("Bad thread status (%d) in DP\n", self->status);
891 dvmDumpThread(self, false);
892 dvmAbort();
893 }
894 assert(!dvmCheckException(self));
895 updateDeadlockPrediction(self, obj);
896 if (dvmCheckException(self)) {
897 /*
898 * If we're throwing an exception here, we need to free the
899 * lock. We add the object to the thread's monitor list so the
900 * "unlock" code can remove it.
901 */
902 dvmAddToMonitorList(self, obj, false);
903 dvmUnlockObject(self, obj);
904 LOGV("--- unlocked, pending is '%s'\n",
905 dvmGetException(self)->clazz->descriptor);
906 }
907 }
908
909 /*
910 * Add the locked object, and the current stack trace, to the list
911 * held by the Thread object. If deadlock prediction isn't on,
912 * don't capture the stack trace.
913 */
914 dvmAddToMonitorList(self, obj, gDvm.deadlockPredictMode != kDPOff);
915#elif defined(WITH_MONITOR_TRACKING)
916 /*
917 * Add the locked object to the list held by the Thread object.
918 */
919 dvmAddToMonitorList(self, obj, false);
920#endif
921}
922
923/*
924 * Implements monitorexit for "synchronized" stuff.
925 *
926 * On failure, throws an exception and returns "false".
927 */
928bool dvmUnlockObject(Thread* self, Object *obj)
929{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -0800930 volatile u4 *thinp = &obj->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800931 u4 threadId = self->threadId;
Carl Shapiro94338aa2009-12-21 11:42:59 -0800932 u4 thin;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800933
934 /* Check the common case, where 'self' has locked 'obj' once, first.
935 */
Carl Shapiro94338aa2009-12-21 11:42:59 -0800936 thin = *thinp;
937 if (LW_LOCK_OWNER(thin) == threadId && LW_LOCK_COUNT(thin) == 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800938 /* Unlock 'obj' by clearing our threadId from 'thin'.
939 * The lock protects the lock field itself, so it's
940 * safe to update non-atomically.
941 */
Carl Shapiro94338aa2009-12-21 11:42:59 -0800942 *thinp &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
943 } else if (LW_SHAPE(*thinp) == LW_SHAPE_THIN) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800944 /* If the object is locked, it had better be locked by us.
945 */
Carl Shapiro94338aa2009-12-21 11:42:59 -0800946 if (LW_LOCK_OWNER(*thinp) != threadId) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800947 /* The JNI spec says that we should throw an exception
948 * in this case.
949 */
950 //LOGW("Unlock thin %p: id %d vs %d\n",
951 // obj, (*thinp & 0xfff), threadId);
952 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
953 "unlock of unowned monitor");
954 return false;
955 }
956
957 /* It's a thin lock, but 'self' has locked 'obj'
958 * more than once. Decrement the count.
959 */
Carl Shapiro94338aa2009-12-21 11:42:59 -0800960 *thinp -= 1 << LW_LOCK_COUNT_SHIFT;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800961 } else {
962 /* It's a fat lock.
963 */
Carl Shapiro8d7f9b22009-12-21 20:23:45 -0800964 assert(LW_MONITOR(obj->lock) != NULL);
965 if (!unlockMonitor(self, LW_MONITOR(obj->lock))) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800966 /* exception has been raised */
967 return false;
968 }
969 }
970
971#ifdef WITH_MONITOR_TRACKING
972 /*
973 * Remove the object from the Thread's list.
974 */
975 dvmRemoveFromMonitorList(self, obj);
976#endif
977
978 return true;
979}
980
981/*
982 * Object.wait(). Also called for class init.
983 */
984void dvmObjectWait(Thread* self, Object *obj, s8 msec, s4 nsec,
985 bool interruptShouldThrow)
986{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -0800987 Monitor* mon = LW_MONITOR(obj->lock);
988 u4 hashState;
989 u4 thin = obj->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800990
991 /* If the lock is still thin, we need to fatten it.
992 */
Carl Shapiro94338aa2009-12-21 11:42:59 -0800993 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800994 /* Make sure that 'self' holds the lock.
995 */
Carl Shapiro94338aa2009-12-21 11:42:59 -0800996 if (LW_LOCK_OWNER(thin) != self->threadId) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800997 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
998 "object not locked by thread before wait()");
999 return;
1000 }
1001
1002 /* This thread holds the lock. We need to fatten the lock
1003 * so 'self' can block on it. Don't update the object lock
1004 * field yet, because 'self' needs to acquire the lock before
1005 * any other thread gets a chance.
1006 */
1007 mon = dvmCreateMonitor(obj);
1008
1009 /* 'self' has actually locked the object one or more times;
1010 * make sure that the monitor reflects this.
1011 */
1012 lockMonitor(self, mon);
Carl Shapiro94338aa2009-12-21 11:42:59 -08001013 mon->lockCount = LW_LOCK_COUNT(thin);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001014 LOG_THIN("(%d) lock 0x%08x fattened by wait() to count %d\n",
1015 self->threadId, (uint)&obj->lock, mon->lockCount);
1016
Andy McFadden581bed72009-10-15 11:24:54 -07001017
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001018 /* Make the monitor public now that it's in the right state.
1019 */
Andy McFadden581bed72009-10-15 11:24:54 -07001020 MEM_BARRIER();
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001021 hashState = LW_HASH_STATE(thin) << LW_HASH_STATE_SHIFT;
1022 obj->lock = (u4)mon | hashState | LW_SHAPE_FAT;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001023 }
1024
1025 waitMonitor(self, mon, msec, nsec, interruptShouldThrow);
1026}
1027
1028/*
1029 * Object.notify().
1030 */
1031void dvmObjectNotify(Thread* self, Object *obj)
1032{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001033 u4 thin = obj->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001034
1035 /* If the lock is still thin, there aren't any waiters;
1036 * waiting on an object forces lock fattening.
1037 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001038 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001039 /* Make sure that 'self' holds the lock.
1040 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001041 if (LW_LOCK_OWNER(thin) != self->threadId) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001042 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
1043 "object not locked by thread before notify()");
1044 return;
1045 }
1046
1047 /* no-op; there are no waiters to notify.
1048 */
1049 } else {
1050 /* It's a fat lock.
1051 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001052 notifyMonitor(self, LW_MONITOR(thin));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001053 }
1054}
1055
1056/*
1057 * Object.notifyAll().
1058 */
1059void dvmObjectNotifyAll(Thread* self, Object *obj)
1060{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001061 u4 thin = obj->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001062
1063 /* If the lock is still thin, there aren't any waiters;
1064 * waiting on an object forces lock fattening.
1065 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001066 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001067 /* Make sure that 'self' holds the lock.
1068 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001069 if (LW_LOCK_OWNER(thin) != self->threadId) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001070 dvmThrowException("Ljava/lang/IllegalMonitorStateException;",
1071 "object not locked by thread before notifyAll()");
1072 return;
1073 }
1074
1075 /* no-op; there are no waiters to notify.
1076 */
1077 } else {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001078 /* It's a fat lock.
1079 */
Carl Shapiro94338aa2009-12-21 11:42:59 -08001080 notifyAllMonitor(self, LW_MONITOR(thin));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001081 }
1082}
1083
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001084/*
1085 * This implements java.lang.Thread.sleep(long msec, int nsec).
1086 *
1087 * The sleep is interruptible by other threads, which means we can't just
1088 * plop into an OS sleep call. (We probably could if we wanted to send
1089 * signals around and rely on EINTR, but that's inefficient and relies
1090 * on native code respecting our signal mask.)
1091 *
1092 * We have to do all of this stuff for Object.wait() as well, so it's
1093 * easiest to just sleep on a private Monitor.
1094 *
1095 * It appears that we want sleep(0,0) to go through the motions of sleeping
1096 * for a very short duration, rather than just returning.
1097 */
1098void dvmThreadSleep(u8 msec, u4 nsec)
1099{
1100 Thread* self = dvmThreadSelf();
1101 Monitor* mon = gDvm.threadSleepMon;
1102
1103 /* sleep(0,0) wakes up immediately, wait(0,0) means wait forever; adjust */
1104 if (msec == 0 && nsec == 0)
1105 nsec++;
1106
1107 lockMonitor(self, mon);
1108 waitMonitor(self, mon, msec, nsec, true);
1109 unlockMonitor(self, mon);
1110}
1111
1112/*
1113 * Implement java.lang.Thread.interrupt().
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001114 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001115void dvmThreadInterrupt(Thread* thread)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001116{
1117 Monitor* mon;
1118
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001119 assert(thread != NULL);
1120
1121 pthread_mutex_lock(&thread->waitMutex);
1122
1123 /*
1124 * If the interrupted flag is already set no additional action is
1125 * required.
1126 */
1127 if (thread->interrupted == true) {
1128 pthread_mutex_unlock(&thread->waitMutex);
1129 return;
1130 }
1131
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001132 /*
1133 * Raise the "interrupted" flag. This will cause it to bail early out
1134 * of the next wait() attempt, if it's not currently waiting on
1135 * something.
1136 */
1137 thread->interrupted = true;
1138 MEM_BARRIER();
1139
1140 /*
1141 * Is the thread waiting?
1142 *
1143 * Note that fat vs. thin doesn't matter here; waitMonitor
1144 * is only set when a thread actually waits on a monitor,
1145 * which implies that the monitor has already been fattened.
1146 */
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001147 if (thread->waitMonitor != NULL) {
1148 pthread_cond_signal(&thread->waitCond);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001149 }
1150
Carl Shapiro77f52eb2009-12-24 19:56:53 -08001151 pthread_mutex_unlock(&thread->waitMutex);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001152}
1153
Carl Shapiro94338aa2009-12-21 11:42:59 -08001154u4 dvmIdentityHashCode(Object *obj)
1155{
1156 return (u4)obj;
1157}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001158
1159#ifdef WITH_DEADLOCK_PREDICTION
1160/*
1161 * ===========================================================================
1162 * Deadlock prediction
1163 * ===========================================================================
1164 */
1165/*
1166The idea is to predict the possibility of deadlock by recording the order
1167in which monitors are acquired. If we see an attempt to acquire a lock
1168out of order, we can identify the locks and offending code.
1169
1170To make this work, we need to keep track of the locks held by each thread,
1171and create history trees for each lock. When a thread tries to acquire
1172a new lock, we walk through the "history children" of the lock, looking
1173for a match with locks the thread already holds. If we find a match,
1174it means the thread has made a request that could result in a deadlock.
1175
1176To support recursive locks, we always allow re-locking a currently-held
1177lock, and maintain a recursion depth count.
1178
1179An ASCII-art example, where letters represent Objects:
1180
1181 A
1182 /|\
1183 / | \
1184 B | D
1185 \ |
1186 \|
1187 C
1188
1189The above is the tree we'd have after handling Object synchronization
1190sequences "ABC", "AC", "AD". A has three children, {B, C, D}. C is also
1191a child of B. (The lines represent pointers between parent and child.
1192Every node can have multiple parents and multiple children.)
1193
1194If we hold AC, and want to lock B, we recursively search through B's
1195children to see if A or C appears. It does, so we reject the attempt.
1196(A straightforward way to implement it: add a link from C to B, then
1197determine whether the graph starting at B contains a cycle.)
1198
1199If we hold AC and want to lock D, we would succeed, creating a new link
1200from C to D.
1201
1202The lock history and a stack trace is attached to the Object's Monitor
1203struct, which means we need to fatten every Object we lock (thin locking
1204is effectively disabled). If we don't need the stack trace we can
1205avoid fattening the leaf nodes, only fattening objects that need to hold
1206history trees.
1207
1208Updates to Monitor structs are only allowed for the thread that holds
1209the Monitor, so we actually do most of our deadlock prediction work after
1210the lock has been acquired.
1211
1212When an object with a monitor is GCed, we need to remove it from the
1213history trees. There are two basic approaches:
1214 (1) For through the entire set of known monitors, search all child
1215 lists for the object in question. This is rather slow, resulting
1216 in GC passes that take upwards of 10 seconds to complete.
1217 (2) Maintain "parent" pointers in each node. Remove the entries as
1218 required. This requires additional storage and maintenance for
1219 every operation, but is significantly faster at GC time.
1220For each GCed object, we merge all of the object's children into each of
1221the object's parents.
1222*/
1223
1224#if !defined(WITH_MONITOR_TRACKING)
1225# error "WITH_DEADLOCK_PREDICTION requires WITH_MONITOR_TRACKING"
1226#endif
1227
1228/*
1229 * Clear out the contents of an ExpandingObjectList, freeing any
1230 * dynamic allocations.
1231 */
1232static void expandObjClear(ExpandingObjectList* pList)
1233{
1234 if (pList->list != NULL) {
1235 free(pList->list);
1236 pList->list = NULL;
1237 }
1238 pList->alloc = pList->count = 0;
1239}
1240
1241/*
1242 * Get the number of objects currently stored in the list.
1243 */
1244static inline int expandBufGetCount(const ExpandingObjectList* pList)
1245{
1246 return pList->count;
1247}
1248
1249/*
1250 * Get the Nth entry from the list.
1251 */
1252static inline Object* expandBufGetEntry(const ExpandingObjectList* pList,
1253 int i)
1254{
1255 return pList->list[i];
1256}
1257
1258/*
1259 * Add a new entry to the list.
1260 *
1261 * We don't check for or try to enforce uniqueness. It's expected that
1262 * the higher-level code does this for us.
1263 */
1264static void expandObjAddEntry(ExpandingObjectList* pList, Object* obj)
1265{
1266 if (pList->count == pList->alloc) {
1267 /* time to expand */
1268 Object** newList;
1269
1270 if (pList->alloc == 0)
1271 pList->alloc = 4;
1272 else
1273 pList->alloc *= 2;
1274 LOGVV("expanding %p to %d\n", pList, pList->alloc);
1275 newList = realloc(pList->list, pList->alloc * sizeof(Object*));
1276 if (newList == NULL) {
1277 LOGE("Failed expanding DP object list (alloc=%d)\n", pList->alloc);
1278 dvmAbort();
1279 }
1280 pList->list = newList;
1281 }
1282
1283 pList->list[pList->count++] = obj;
1284}
1285
1286/*
1287 * Returns "true" if the element was successfully removed.
1288 */
1289static bool expandObjRemoveEntry(ExpandingObjectList* pList, Object* obj)
1290{
1291 int i;
1292
1293 for (i = pList->count-1; i >= 0; i--) {
1294 if (pList->list[i] == obj)
1295 break;
1296 }
1297 if (i < 0)
1298 return false;
1299
1300 if (i != pList->count-1) {
1301 /*
1302 * The order of elements is not important, so we just copy the
1303 * last entry into the new slot.
1304 */
1305 //memmove(&pList->list[i], &pList->list[i+1],
1306 // (pList->count-1 - i) * sizeof(pList->list[0]));
1307 pList->list[i] = pList->list[pList->count-1];
1308 }
1309
1310 pList->count--;
1311 pList->list[pList->count] = (Object*) 0xdecadead;
1312 return true;
1313}
1314
1315/*
1316 * Returns "true" if "obj" appears in the list.
1317 */
1318static bool expandObjHas(const ExpandingObjectList* pList, Object* obj)
1319{
1320 int i;
1321
1322 for (i = 0; i < pList->count; i++) {
1323 if (pList->list[i] == obj)
1324 return true;
1325 }
1326 return false;
1327}
1328
1329/*
1330 * Print the list contents to stdout. For debugging.
1331 */
1332static void expandObjDump(const ExpandingObjectList* pList)
1333{
1334 int i;
1335 for (i = 0; i < pList->count; i++)
1336 printf(" %p", pList->list[i]);
1337}
1338
1339/*
1340 * Check for duplicate entries. Returns the index of the first instance
1341 * of the duplicated value, or -1 if no duplicates were found.
1342 */
1343static int expandObjCheckForDuplicates(const ExpandingObjectList* pList)
1344{
1345 int i, j;
1346 for (i = 0; i < pList->count-1; i++) {
1347 for (j = i + 1; j < pList->count; j++) {
1348 if (pList->list[i] == pList->list[j]) {
1349 return i;
1350 }
1351 }
1352 }
1353
1354 return -1;
1355}
1356
1357
1358/*
1359 * Determine whether "child" appears in the list of objects associated
1360 * with the Monitor in "parent". If "parent" is a thin lock, we return
1361 * false immediately.
1362 */
1363static bool objectInChildList(const Object* parent, Object* child)
1364{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001365 u4 lock = parent->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001366 if (!IS_LOCK_FAT(&lock)) {
1367 //LOGI("on thin\n");
1368 return false;
1369 }
1370
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001371 return expandObjHas(&LW_MONITOR(lock)->historyChildren, child);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001372}
1373
1374/*
1375 * Print the child list.
1376 */
1377static void dumpKids(Object* parent)
1378{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001379 Monitor* mon = LW_MONITOR(parent->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001380
1381 printf("Children of %p:", parent);
1382 expandObjDump(&mon->historyChildren);
1383 printf("\n");
1384}
1385
1386/*
1387 * Add "child" to the list of children in "parent", and add "parent" to
1388 * the list of parents in "child".
1389 */
1390static void linkParentToChild(Object* parent, Object* child)
1391{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001392 //assert(LW_MONITOR(parent->lock)->owner == dvmThreadSelf()); // !owned for merge
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001393 assert(IS_LOCK_FAT(&parent->lock));
1394 assert(IS_LOCK_FAT(&child->lock));
1395 assert(parent != child);
1396 Monitor* mon;
1397
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001398 mon = LW_MONITOR(parent->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001399 assert(!expandObjHas(&mon->historyChildren, child));
1400 expandObjAddEntry(&mon->historyChildren, child);
1401
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001402 mon = LW_MONITOR(child->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001403 assert(!expandObjHas(&mon->historyParents, parent));
1404 expandObjAddEntry(&mon->historyParents, parent);
1405}
1406
1407
1408/*
1409 * Remove "child" from the list of children in "parent".
1410 */
1411static void unlinkParentFromChild(Object* parent, Object* child)
1412{
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001413 //assert(LW_MONITOR(parent->lock)->owner == dvmThreadSelf()); // !owned for GC
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001414 assert(IS_LOCK_FAT(&parent->lock));
1415 assert(IS_LOCK_FAT(&child->lock));
1416 assert(parent != child);
1417 Monitor* mon;
1418
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001419 mon = LW_MONITOR(parent->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001420 if (!expandObjRemoveEntry(&mon->historyChildren, child)) {
1421 LOGW("WARNING: child %p not found in parent %p\n", child, parent);
1422 }
1423 assert(!expandObjHas(&mon->historyChildren, child));
1424 assert(expandObjCheckForDuplicates(&mon->historyChildren) < 0);
1425
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001426 mon = LW_MONITOR(child->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001427 if (!expandObjRemoveEntry(&mon->historyParents, parent)) {
1428 LOGW("WARNING: parent %p not found in child %p\n", parent, child);
1429 }
1430 assert(!expandObjHas(&mon->historyParents, parent));
1431 assert(expandObjCheckForDuplicates(&mon->historyParents) < 0);
1432}
1433
1434
1435/*
1436 * Log the monitors held by the current thread. This is done as part of
1437 * flagging an error.
1438 */
1439static void logHeldMonitors(Thread* self)
1440{
1441 char* name = NULL;
1442
1443 name = dvmGetThreadName(self);
1444 LOGW("Monitors currently held by thread (threadid=%d '%s')\n",
1445 self->threadId, name);
1446 LOGW("(most-recently-acquired on top):\n");
1447 free(name);
1448
1449 LockedObjectData* lod = self->pLockedObjects;
1450 while (lod != NULL) {
1451 LOGW("--- object %p[%d] (%s)\n",
1452 lod->obj, lod->recursionCount, lod->obj->clazz->descriptor);
1453 dvmLogRawStackTrace(lod->rawStackTrace, lod->stackDepth);
1454
1455 lod = lod->next;
1456 }
1457}
1458
1459/*
1460 * Recursively traverse the object hierarchy starting at "obj". We mark
1461 * ourselves on entry and clear the mark on exit. If we ever encounter
1462 * a marked object, we have a cycle.
1463 *
1464 * Returns "true" if all is well, "false" if we found a cycle.
1465 */
1466static bool traverseTree(Thread* self, const Object* obj)
1467{
1468 assert(IS_LOCK_FAT(&obj->lock));
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001469 Monitor* mon = LW_MONITOR(obj->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001470
1471 /*
1472 * Have we been here before?
1473 */
1474 if (mon->historyMark) {
1475 int* rawStackTrace;
1476 int stackDepth;
1477
1478 LOGW("%s\n", kStartBanner);
1479 LOGW("Illegal lock attempt:\n");
1480 LOGW("--- object %p (%s)\n", obj, obj->clazz->descriptor);
1481
1482 rawStackTrace = dvmFillInStackTraceRaw(self, &stackDepth);
1483 dvmLogRawStackTrace(rawStackTrace, stackDepth);
1484 free(rawStackTrace);
1485
1486 LOGW(" ");
1487 logHeldMonitors(self);
1488
1489 LOGW(" ");
1490 LOGW("Earlier, the following lock order (from last to first) was\n");
1491 LOGW("established -- stack trace is from first successful lock):\n");
1492 return false;
1493 }
1494 mon->historyMark = true;
1495
1496 /*
1497 * Examine the children. We do NOT hold these locks, so they might
1498 * very well transition from thin to fat or change ownership while
1499 * we work.
1500 *
1501 * NOTE: we rely on the fact that they cannot revert from fat to thin
1502 * while we work. This is currently a safe assumption.
1503 *
1504 * We can safely ignore thin-locked children, because by definition
1505 * they have no history and are leaf nodes. In the current
1506 * implementation we always fatten the locks to provide a place to
1507 * hang the stack trace.
1508 */
1509 ExpandingObjectList* pList = &mon->historyChildren;
1510 int i;
1511 for (i = expandBufGetCount(pList)-1; i >= 0; i--) {
1512 const Object* child = expandBufGetEntry(pList, i);
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001513 u4 lock = child->lock;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001514 if (!IS_LOCK_FAT(&lock))
1515 continue;
1516 if (!traverseTree(self, child)) {
1517 LOGW("--- object %p (%s)\n", obj, obj->clazz->descriptor);
1518 dvmLogRawStackTrace(mon->historyRawStackTrace,
1519 mon->historyStackDepth);
1520 mon->historyMark = false;
1521 return false;
1522 }
1523 }
1524
1525 mon->historyMark = false;
1526
1527 return true;
1528}
1529
1530/*
1531 * Update the deadlock prediction tree, based on the current thread
1532 * acquiring "acqObj". This must be called before the object is added to
1533 * the thread's list of held monitors.
1534 *
1535 * If the thread already holds the lock (recursion), or this is a known
1536 * lock configuration, we return without doing anything. Otherwise, we add
1537 * a link from the most-recently-acquired lock in this thread to "acqObj"
1538 * after ensuring that the parent lock is "fat".
1539 *
1540 * This MUST NOT be called while a GC is in progress in another thread,
1541 * because we assume exclusive access to history trees in owned monitors.
1542 */
1543static void updateDeadlockPrediction(Thread* self, Object* acqObj)
1544{
1545 LockedObjectData* lod;
1546 LockedObjectData* mrl;
1547
1548 /*
1549 * Quick check for recursive access.
1550 */
1551 lod = dvmFindInMonitorList(self, acqObj);
1552 if (lod != NULL) {
1553 LOGV("+++ DP: recursive %p\n", acqObj);
1554 return;
1555 }
1556
1557 /*
1558 * Make the newly-acquired object's monitor "fat". In some ways this
1559 * isn't strictly necessary, but we need the GC to tell us when
1560 * "interesting" objects go away, and right now the only way to make
1561 * an object look interesting is to give it a monitor.
1562 *
1563 * This also gives us a place to hang a stack trace.
1564 *
1565 * Our thread holds the lock, so we're allowed to rewrite the lock
1566 * without worrying that something will change out from under us.
1567 */
1568 if (!IS_LOCK_FAT(&acqObj->lock)) {
1569 LOGVV("fattening lockee %p (recur=%d)\n",
Carl Shapiro94338aa2009-12-21 11:42:59 -08001570 acqObj, LW_LOCK_COUNT(acqObj->lock.thin));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001571 Monitor* newMon = dvmCreateMonitor(acqObj);
1572 lockMonitor(self, newMon); // can't stall, don't need VMWAIT
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001573 newMon->lockCount += LW_LOCK_COUNT(acqObj->lock);
1574 u4 hashState = LW_HASH_STATE(acqObj->lock) << LW_HASH_STATE_SHIFT;
1575 acqObj->lock = (u4)newMon | hashState | LW_SHAPE_FAT;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001576 }
1577
1578 /* if we don't have a stack trace for this monitor, establish one */
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001579 if (LW_MONITOR(acqObj->lock)->historyRawStackTrace == NULL) {
1580 Monitor* mon = LW_MONITOR(acqObj->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001581 mon->historyRawStackTrace = dvmFillInStackTraceRaw(self,
1582 &mon->historyStackDepth);
1583 }
1584
1585 /*
1586 * We need to examine and perhaps modify the most-recently-locked
1587 * monitor. We own that, so there's no risk of another thread
1588 * stepping on us.
1589 *
1590 * Retrieve the most-recently-locked entry from our thread.
1591 */
1592 mrl = self->pLockedObjects;
1593 if (mrl == NULL)
1594 return; /* no other locks held */
1595
1596 /*
1597 * Do a quick check to see if "acqObj" is a direct descendant. We can do
1598 * this without holding the global lock because of our assertion that
1599 * a GC is not running in parallel -- nobody except the GC can
1600 * modify a history list in a Monitor they don't own, and we own "mrl".
1601 * (There might be concurrent *reads*, but no concurrent *writes.)
1602 *
1603 * If we find it, this is a known good configuration, and we're done.
1604 */
1605 if (objectInChildList(mrl->obj, acqObj))
1606 return;
1607
1608 /*
1609 * "mrl" is going to need to have a history tree. If it's currently
1610 * a thin lock, we make it fat now. The thin lock might have a
1611 * nonzero recursive lock count, which we need to carry over.
1612 *
1613 * Our thread holds the lock, so we're allowed to rewrite the lock
1614 * without worrying that something will change out from under us.
1615 */
1616 if (!IS_LOCK_FAT(&mrl->obj->lock)) {
1617 LOGVV("fattening parent %p f/b/o child %p (recur=%d)\n",
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001618 mrl->obj, acqObj, LW_LOCK_COUNT(mrl->obj->lock));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001619 Monitor* newMon = dvmCreateMonitor(mrl->obj);
1620 lockMonitor(self, newMon); // can't stall, don't need VMWAIT
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001621 newMon->lockCount += LW_LOCK_COUNT(mrl->obj->lock);
1622 u4 hashState = LW_HASH_STATE(mrl->obj->lock) << LW_HASH_STATE_SHIFT;
1623 mrl->obj->lock = (u4)newMon | hashState | LW_SHAPE_FAT;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001624 }
1625
1626 /*
1627 * We haven't seen this configuration before. We need to scan down
1628 * acqObj's tree to see if any of the monitors in self->pLockedObjects
1629 * appear. We grab a global lock before traversing or updating the
1630 * history list.
1631 *
1632 * If we find a match for any of our held locks, we know that the lock
1633 * has previously been acquired *after* acqObj, and we throw an error.
1634 *
1635 * The easiest way to do this is to create a link from "mrl" to "acqObj"
1636 * and do a recursive traversal, marking nodes as we cross them. If
1637 * we cross one a second time, we have a cycle and can throw an error.
1638 * (We do the flag-clearing traversal before adding the new link, so
1639 * that we're guaranteed to terminate.)
1640 *
1641 * If "acqObj" is a thin lock, it has no history, and we can create a
1642 * link to it without additional checks. [ We now guarantee that it's
1643 * always fat. ]
1644 */
1645 bool failed = false;
1646 dvmLockMutex(&gDvm.deadlockHistoryLock);
1647 linkParentToChild(mrl->obj, acqObj);
1648 if (!traverseTree(self, acqObj)) {
1649 LOGW("%s\n", kEndBanner);
1650 failed = true;
1651
1652 /* remove the entry so we're still okay when in "warning" mode */
1653 unlinkParentFromChild(mrl->obj, acqObj);
1654 }
1655 dvmUnlockMutex(&gDvm.deadlockHistoryLock);
1656
1657 if (failed) {
1658 switch (gDvm.deadlockPredictMode) {
1659 case kDPErr:
1660 dvmThrowException("Ldalvik/system/PotentialDeadlockError;", NULL);
1661 break;
1662 case kDPAbort:
1663 LOGE("Aborting due to potential deadlock\n");
1664 dvmAbort();
1665 break;
1666 default:
1667 /* warn only */
1668 break;
1669 }
1670 }
1671}
1672
1673/*
1674 * We're removing "child" from existence. We want to pull all of
1675 * child's children into "parent", filtering out duplicates. This is
1676 * called during the GC.
1677 *
1678 * This does not modify "child", which might have multiple parents.
1679 */
1680static void mergeChildren(Object* parent, const Object* child)
1681{
1682 Monitor* mon;
1683 int i;
1684
1685 assert(IS_LOCK_FAT(&child->lock));
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001686 mon = LW_MONITOR(child->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001687 ExpandingObjectList* pList = &mon->historyChildren;
1688
1689 for (i = expandBufGetCount(pList)-1; i >= 0; i--) {
1690 Object* grandChild = expandBufGetEntry(pList, i);
1691
1692 if (!objectInChildList(parent, grandChild)) {
1693 LOGVV("+++ migrating %p link to %p\n", grandChild, parent);
1694 linkParentToChild(parent, grandChild);
1695 } else {
1696 LOGVV("+++ parent %p already links to %p\n", parent, grandChild);
1697 }
1698 }
1699}
1700
1701/*
1702 * An object with a fat lock is being collected during a GC pass. We
1703 * want to remove it from any lock history trees that it is a part of.
1704 *
1705 * This may require updating the history trees in several monitors. The
1706 * monitor semantics guarantee that no other thread will be accessing
1707 * the history trees at the same time.
1708 */
1709static void removeCollectedObject(Object* obj)
1710{
1711 Monitor* mon;
1712
1713 LOGVV("+++ collecting %p\n", obj);
1714
1715#if 0
1716 /*
1717 * We're currently running through the entire set of known monitors.
1718 * This can be somewhat slow. We may want to keep lists of parents
1719 * in each child to speed up GC.
1720 */
1721 mon = gDvm.monitorList;
1722 while (mon != NULL) {
1723 Object* parent = mon->obj;
1724 if (parent != NULL) { /* value nulled for deleted entries */
1725 if (objectInChildList(parent, obj)) {
1726 LOGVV("removing child %p from parent %p\n", obj, parent);
1727 unlinkParentFromChild(parent, obj);
1728 mergeChildren(parent, obj);
1729 }
1730 }
1731 mon = mon->next;
1732 }
1733#endif
1734
1735 /*
1736 * For every parent of this object:
1737 * - merge all of our children into the parent's child list (creates
1738 * a two-way link between parent and child)
1739 * - remove ourselves from the parent's child list
1740 */
1741 ExpandingObjectList* pList;
1742 int i;
1743
1744 assert(IS_LOCK_FAT(&obj->lock));
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001745 mon = LW_MONITOR(obj->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001746 pList = &mon->historyParents;
1747 for (i = expandBufGetCount(pList)-1; i >= 0; i--) {
1748 Object* parent = expandBufGetEntry(pList, i);
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001749 Monitor* parentMon = LW_MONITOR(parent->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001750
1751 if (!expandObjRemoveEntry(&parentMon->historyChildren, obj)) {
1752 LOGW("WARNING: child %p not found in parent %p\n", obj, parent);
1753 }
1754 assert(!expandObjHas(&parentMon->historyChildren, obj));
1755
1756 mergeChildren(parent, obj);
1757 }
1758
1759 /*
1760 * For every child of this object:
1761 * - remove ourselves from the child's parent list
1762 */
1763 pList = &mon->historyChildren;
1764 for (i = expandBufGetCount(pList)-1; i >= 0; i--) {
1765 Object* child = expandBufGetEntry(pList, i);
Carl Shapiro8d7f9b22009-12-21 20:23:45 -08001766 Monitor* childMon = LW_MONITOR(child->lock);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001767
1768 if (!expandObjRemoveEntry(&childMon->historyParents, obj)) {
1769 LOGW("WARNING: parent %p not found in child %p\n", obj, child);
1770 }
1771 assert(!expandObjHas(&childMon->historyParents, obj));
1772 }
1773}
1774
1775#endif /*WITH_DEADLOCK_PREDICTION*/
1776