2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
27 * Every Object has a monitor associated with it, but not every Object is
28 * actually locked. Even the ones that are locked do not need a
29 * full-fledged monitor until a) there is actual contention or b) wait()
30 * is called on the Object.
32 * For Dalvik, we have implemented a scheme similar to the one described
33 * in Bacon et al.'s "Thin locks: featherweight synchronization for Java"
34 * (ACM 1998). Things are even easier for us, though, because we have
35 * a full 32 bits to work with.
37 * The two states of an Object's lock are referred to as "thin" and
38 * "fat". A lock may transition from the "thin" state to the "fat"
39 * state and this transition is referred to as inflation. Once a lock
40 * has been inflated it remains in the "fat" state indefinitely.
42 * The lock value itself is stored in Object.lock. The LSB of the
43 * lock encodes its state. When cleared, the lock is in the "thin"
44 * state and its bits are formatted as follows:
46 * [31 ---- 19] [18 ---- 3] [2 ---- 1] [0]
47 * lock count thread id hash state 0
49 * When set, the lock is in the "fat" state and its bits are formatted
52 * [31 ---- 3] [2 ---- 1] [0]
53 * pointer hash state 1
55 * For an in-depth description of the mechanics of thin-vs-fat locking,
56 * read the paper referred to above.
61 * - mutually exclusive access to resources
62 * - a way for multiple threads to wait for notification
64 * In effect, they fill the role of both mutexes and condition variables.
66 * Only one thread can own the monitor at any time. There may be several
67 * threads waiting on it (the wait call unlocks it). One or more waiting
68 * threads may be getting interrupted or notified at any given time.
70 * TODO: the various members of monitor are not SMP-safe.
73 Thread* owner; /* which thread currently owns the lock? */
74 int lockCount; /* owner's recursive lock depth */
75 Object* obj; /* what object are we part of [debug only] */
77 Thread* waitSet; /* threads currently waiting on this monitor */
84 * Who last acquired this monitor, when lock sampling is enabled.
85 * Even when enabled, ownerMethod may be NULL.
87 const Method* ownerMethod;
93 * Create and initialize a monitor.
95 Monitor* dvmCreateMonitor(Object* obj)
99 mon = (Monitor*) calloc(1, sizeof(Monitor));
101 ALOGE("Unable to allocate monitor");
104 if (((u4)mon & 7) != 0) {
105 ALOGE("Misaligned monitor: %p", mon);
109 dvmInitMutex(&mon->lock);
111 /* replace the head of the list with the new monitor */
113 mon->next = gDvm.monitorList;
114 } while (android_atomic_release_cas((int32_t)mon->next, (int32_t)mon,
115 (int32_t*)(void*)&gDvm.monitorList) != 0);
121 * Free the monitor list. Only used when shutting the VM down.
123 void dvmFreeMonitorList()
128 mon = gDvm.monitorList;
129 while (mon != NULL) {
137 * Get the object that a monitor is part of.
139 Object* dvmGetMonitorObject(Monitor* mon)
148 * Returns the thread id of the thread owning the given lock.
150 static u4 lockOwner(Object* obj)
157 * Since we're reading the lock value multiple times, latch it so
158 * that it doesn't change out from under us if we get preempted.
161 if (LW_SHAPE(lock) == LW_SHAPE_THIN) {
162 return LW_LOCK_OWNER(lock);
164 owner = LW_MONITOR(lock)->owner;
165 return owner ? owner->threadId : 0;
170 * Get the thread that holds the lock on the specified object. The
171 * object may be unlocked, thin-locked, or fat-locked.
173 * The caller must lock the thread list before calling here.
175 Thread* dvmGetObjectLockHolder(Object* obj)
177 u4 threadId = lockOwner(obj);
181 return dvmGetThreadByThreadId(threadId);
185 * Checks whether the given thread holds the given
188 bool dvmHoldsLock(Thread* thread, Object* obj)
190 if (thread == NULL || obj == NULL) {
193 return thread->threadId == lockOwner(obj);
198 * Free the monitor associated with an object and make the object's lock
199 * thin again. This is called during garbage collection.
201 static void freeMonitor(Monitor *mon)
204 assert(mon->obj != NULL);
205 assert(LW_SHAPE(mon->obj->lock) == LW_SHAPE_FAT);
207 /* This lock is associated with an object
208 * that's being swept. The only possible way
209 * anyone could be holding this lock would be
210 * if some JNI code locked but didn't unlock
211 * the object, in which case we've got some bad
212 * native code somewhere.
214 assert(pthread_mutex_trylock(&mon->lock) == 0);
215 assert(pthread_mutex_unlock(&mon->lock) == 0);
216 dvmDestroyMutex(&mon->lock);
221 * Frees monitor objects belonging to unmarked objects.
223 void dvmSweepMonitorList(Monitor** mon, int (*isUnmarkedObject)(void*))
226 Monitor *prev, *curr;
230 assert(isUnmarkedObject != NULL);
232 prev->next = curr = *mon;
233 while (curr != NULL) {
235 if (obj != NULL && (*isUnmarkedObject)(obj) != 0) {
236 prev->next = curr->next;
247 static char *logWriteInt(char *dst, int value)
249 *dst++ = EVENT_TYPE_INT;
250 set4LE((u1 *)dst, value);
254 static char *logWriteString(char *dst, const char *value, size_t len)
256 *dst++ = EVENT_TYPE_STRING;
257 len = len < 32 ? len : 32;
258 set4LE((u1 *)dst, len);
260 memcpy(dst, value, len);
264 #define EVENT_LOG_TAG_dvm_lock_sample 20003
266 static void logContentionEvent(Thread *self, u4 waitMs, u4 samplePercent,
267 const char *ownerFileName, u4 ownerLineNumber)
269 const StackSaveArea *saveArea;
272 char eventBuffer[174];
273 const char *fileName;
279 /* When a thread is being destroyed it is normal that the frame depth is zero */
280 if (self->interpSave.curFrame == NULL) {
284 saveArea = SAVEAREA_FROM_FP(self->interpSave.curFrame);
285 meth = saveArea->method;
288 /* Emit the event list length, 1 byte. */
291 /* Emit the process name, <= 37 bytes. */
292 fd = open("/proc/self/cmdline", O_RDONLY);
293 memset(procName, 0, sizeof(procName));
294 read(fd, procName, sizeof(procName) - 1);
296 len = strlen(procName);
297 cp = logWriteString(cp, procName, len);
299 /* Emit the sensitive thread ("main thread") status, 5 bytes. */
300 bool isSensitive = false;
301 if (gDvm.isSensitiveThreadHook != NULL) {
302 isSensitive = gDvm.isSensitiveThreadHook();
304 cp = logWriteInt(cp, isSensitive);
306 /* Emit self thread name string, <= 37 bytes. */
307 std::string selfName = dvmGetThreadName(self);
308 cp = logWriteString(cp, selfName.c_str(), selfName.size());
310 /* Emit the wait time, 5 bytes. */
311 cp = logWriteInt(cp, waitMs);
313 /* Emit the source code file name, <= 37 bytes. */
314 fileName = dvmGetMethodSourceFile(meth);
315 if (fileName == NULL) fileName = "";
316 cp = logWriteString(cp, fileName, strlen(fileName));
318 /* Emit the source code line number, 5 bytes. */
319 relativePc = saveArea->xtra.currentPc - saveArea->method->insns;
320 cp = logWriteInt(cp, dvmLineNumFromPC(meth, relativePc));
322 /* Emit the lock owner source code file name, <= 37 bytes. */
323 if (ownerFileName == NULL) {
325 } else if (strcmp(fileName, ownerFileName) == 0) {
326 /* Common case, so save on log space. */
329 cp = logWriteString(cp, ownerFileName, strlen(ownerFileName));
331 /* Emit the source code line number, 5 bytes. */
332 cp = logWriteInt(cp, ownerLineNumber);
334 /* Emit the sample percentage, 5 bytes. */
335 cp = logWriteInt(cp, samplePercent);
337 assert((size_t)(cp - eventBuffer) <= sizeof(eventBuffer));
338 android_btWriteLog(EVENT_LOG_TAG_dvm_lock_sample,
341 (size_t)(cp - eventBuffer));
347 static void lockMonitor(Thread* self, Monitor* mon)
349 ThreadStatus oldStatus;
350 u4 waitThreshold, samplePercent;
351 u8 waitStart, waitEnd, waitMs;
353 if (mon->owner == self) {
357 if (dvmTryLockMutex(&mon->lock) != 0) {
358 oldStatus = dvmChangeStatus(self, THREAD_MONITOR);
359 waitThreshold = gDvm.lockProfThreshold;
361 waitStart = dvmGetRelativeTimeUsec();
364 const Method* currentOwnerMethod = mon->ownerMethod;
365 u4 currentOwnerPc = mon->ownerPc;
367 dvmLockMutex(&mon->lock);
369 waitEnd = dvmGetRelativeTimeUsec();
371 dvmChangeStatus(self, oldStatus);
373 waitMs = (waitEnd - waitStart) / 1000;
374 if (waitMs >= waitThreshold) {
377 samplePercent = 100 * waitMs / waitThreshold;
379 if (samplePercent != 0 && ((u4)rand() % 100 < samplePercent)) {
380 const char* currentOwnerFileName = "no_method";
381 u4 currentOwnerLineNumber = 0;
382 if (currentOwnerMethod != NULL) {
383 currentOwnerFileName = dvmGetMethodSourceFile(currentOwnerMethod);
384 if (currentOwnerFileName == NULL) {
385 currentOwnerFileName = "no_method_file";
387 currentOwnerLineNumber = dvmLineNumFromPC(currentOwnerMethod, currentOwnerPc);
389 logContentionEvent(self, waitMs, samplePercent,
390 currentOwnerFileName, currentOwnerLineNumber);
395 assert(mon->lockCount == 0);
397 // When debugging, save the current monitor holder for future
398 // acquisition failures to use in sampled logging.
399 if (gDvm.lockProfThreshold > 0) {
400 mon->ownerMethod = NULL;
402 if (self->interpSave.curFrame == NULL) {
405 const StackSaveArea* saveArea = SAVEAREA_FROM_FP(self->interpSave.curFrame);
406 if (saveArea == NULL) {
409 mon->ownerMethod = saveArea->method;
410 mon->ownerPc = (saveArea->xtra.currentPc - saveArea->method->insns);
415 * Try to lock a monitor.
417 * Returns "true" on success.
419 #ifdef WITH_COPYING_GC
420 static bool tryLockMonitor(Thread* self, Monitor* mon)
422 if (mon->owner == self) {
426 if (dvmTryLockMutex(&mon->lock) == 0) {
428 assert(mon->lockCount == 0);
440 * Returns true if the unlock succeeded.
441 * If the unlock failed, an exception will be pending.
443 static bool unlockMonitor(Thread* self, Monitor* mon)
445 assert(self != NULL);
447 if (mon->owner == self) {
449 * We own the monitor, so nobody else can be in here.
451 if (mon->lockCount == 0) {
453 mon->ownerMethod = NULL;
455 dvmUnlockMutex(&mon->lock);
461 * We don't own this, so we're not allowed to unlock it.
462 * The JNI spec says that we should throw IllegalMonitorStateException
465 dvmThrowIllegalMonitorStateException("unlock of unowned monitor");
472 * Checks the wait set for circular structure. Returns 0 if the list
473 * is not circular. Otherwise, returns 1. Used only by asserts.
476 static int waitSetCheck(Monitor *mon)
482 fast = slow = mon->waitSet;
485 if (fast == NULL) return 0;
486 if (fast->waitNext == NULL) return 0;
487 if (fast == slow && n > 0) return 1;
489 fast = fast->waitNext->waitNext;
490 slow = slow->waitNext;
496 * Links a thread into a monitor's wait set. The monitor lock must be
497 * held by the caller of this routine.
499 static void waitSetAppend(Monitor *mon, Thread *thread)
504 assert(mon->owner == dvmThreadSelf());
505 assert(thread != NULL);
506 assert(thread->waitNext == NULL);
507 assert(waitSetCheck(mon) == 0);
508 if (mon->waitSet == NULL) {
509 mon->waitSet = thread;
513 while (elt->waitNext != NULL) {
516 elt->waitNext = thread;
520 * Unlinks a thread from a monitor's wait set. The monitor lock must
521 * be held by the caller of this routine.
523 static void waitSetRemove(Monitor *mon, Thread *thread)
528 assert(mon->owner == dvmThreadSelf());
529 assert(thread != NULL);
530 assert(waitSetCheck(mon) == 0);
531 if (mon->waitSet == NULL) {
534 if (mon->waitSet == thread) {
535 mon->waitSet = thread->waitNext;
536 thread->waitNext = NULL;
540 while (elt->waitNext != NULL) {
541 if (elt->waitNext == thread) {
542 elt->waitNext = thread->waitNext;
543 thread->waitNext = NULL;
551 * Converts the given relative waiting time into an absolute time.
553 static void absoluteTime(s8 msec, s4 nsec, struct timespec *ts)
557 #ifdef HAVE_TIMEDWAIT_MONOTONIC
558 clock_gettime(CLOCK_MONOTONIC, ts);
562 gettimeofday(&tv, NULL);
563 ts->tv_sec = tv.tv_sec;
564 ts->tv_nsec = tv.tv_usec * 1000;
567 endSec = ts->tv_sec + msec / 1000;
568 if (endSec >= 0x7fffffff) {
569 ALOGV("NOTE: end time exceeds epoch");
573 ts->tv_nsec = (ts->tv_nsec + (msec % 1000) * 1000000) + nsec;
576 if (ts->tv_nsec >= 1000000000L) {
578 ts->tv_nsec -= 1000000000L;
582 int dvmRelativeCondWait(pthread_cond_t* cond, pthread_mutex_t* mutex,
587 absoluteTime(msec, nsec, &ts);
588 #if defined(HAVE_TIMEDWAIT_MONOTONIC)
589 ret = pthread_cond_timedwait_monotonic(cond, mutex, &ts);
591 ret = pthread_cond_timedwait(cond, mutex, &ts);
593 assert(ret == 0 || ret == ETIMEDOUT);
598 * Wait on a monitor until timeout, interrupt, or notification. Used for
599 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
601 * If another thread calls Thread.interrupt(), we throw InterruptedException
602 * and return immediately if one of the following are true:
603 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
604 * - blocked in join(), join(long), or join(long, int) methods of Thread
605 * - blocked in sleep(long), or sleep(long, int) methods of Thread
606 * Otherwise, we set the "interrupted" flag.
608 * Checks to make sure that "nsec" is in the range 0-999999
609 * (i.e. fractions of a millisecond) and throws the appropriate
610 * exception if it isn't.
612 * The spec allows "spurious wakeups", and recommends that all code using
613 * Object.wait() do so in a loop. This appears to derive from concerns
614 * about pthread_cond_wait() on multiprocessor systems. Some commentary
615 * on the web casts doubt on whether these can/should occur.
617 * Since we're allowed to wake up "early", we clamp extremely long durations
618 * to return at the end of the 32-bit time epoch.
620 static void waitMonitor(Thread* self, Monitor* mon, s8 msec, s4 nsec,
621 bool interruptShouldThrow)
624 bool wasInterrupted = false;
628 assert(self != NULL);
631 /* Make sure that we hold the lock. */
632 if (mon->owner != self) {
633 dvmThrowIllegalMonitorStateException(
634 "object not locked by thread before wait()");
639 * Enforce the timeout range.
641 if (msec < 0 || nsec < 0 || nsec > 999999) {
642 dvmThrowIllegalArgumentException("timeout arguments out of range");
647 * Compute absolute wakeup time, if necessary.
649 if (msec == 0 && nsec == 0) {
652 absoluteTime(msec, nsec, &ts);
657 * Add ourselves to the set of threads waiting on this monitor, and
658 * release our hold. We need to let it go even if we're a few levels
659 * deep in a recursive lock, and we need to restore that later.
661 * We append to the wait set ahead of clearing the count and owner
662 * fields so the subroutine can check that the calling thread owns
663 * the monitor. Aside from that, the order of member updates is
664 * not order sensitive as we hold the pthread mutex.
666 waitSetAppend(mon, self);
667 int prevLockCount = mon->lockCount;
671 const Method* savedMethod = mon->ownerMethod;
672 u4 savedPc = mon->ownerPc;
673 mon->ownerMethod = NULL;
677 * Update thread status. If the GC wakes up, it'll ignore us, knowing
678 * that we won't touch any references in this state, and we'll check
679 * our suspend mode before we transition out.
682 dvmChangeStatus(self, THREAD_TIMED_WAIT);
684 dvmChangeStatus(self, THREAD_WAIT);
686 dvmLockMutex(&self->waitMutex);
689 * Set waitMonitor to the monitor object we will be waiting on.
690 * When waitMonitor is non-NULL a notifying or interrupting thread
691 * must signal the thread's waitCond to wake it up.
693 assert(self->waitMonitor == NULL);
694 self->waitMonitor = mon;
697 * Handle the case where the thread was interrupted before we called
700 if (self->interrupted) {
701 wasInterrupted = true;
702 self->waitMonitor = NULL;
703 dvmUnlockMutex(&self->waitMutex);
708 * Release the monitor lock and wait for a notification or
709 * a timeout to occur.
711 dvmUnlockMutex(&mon->lock);
714 ret = pthread_cond_wait(&self->waitCond, &self->waitMutex);
717 #ifdef HAVE_TIMEDWAIT_MONOTONIC
718 ret = pthread_cond_timedwait_monotonic(&self->waitCond, &self->waitMutex, &ts);
720 ret = pthread_cond_timedwait(&self->waitCond, &self->waitMutex, &ts);
722 assert(ret == 0 || ret == ETIMEDOUT);
724 if (self->interrupted) {
725 wasInterrupted = true;
728 self->interrupted = false;
729 self->waitMonitor = NULL;
731 dvmUnlockMutex(&self->waitMutex);
733 /* Reacquire the monitor lock. */
734 lockMonitor(self, mon);
738 * We remove our thread from wait set after restoring the count
739 * and owner fields so the subroutine can check that the calling
740 * thread owns the monitor. Aside from that, the order of member
741 * updates is not order sensitive as we hold the pthread mutex.
744 mon->lockCount = prevLockCount;
745 mon->ownerMethod = savedMethod;
746 mon->ownerPc = savedPc;
747 waitSetRemove(mon, self);
749 /* set self->status back to THREAD_RUNNING, and self-suspend if needed */
750 dvmChangeStatus(self, THREAD_RUNNING);
752 if (wasInterrupted) {
754 * We were interrupted while waiting, or somebody interrupted an
755 * un-interruptible thread earlier and we're bailing out immediately.
757 * The doc sayeth: "The interrupted status of the current thread is
758 * cleared when this exception is thrown."
760 self->interrupted = false;
761 if (interruptShouldThrow) {
762 dvmThrowInterruptedException(NULL);
768 * Notify one thread waiting on this monitor.
770 static void notifyMonitor(Thread* self, Monitor* mon)
774 assert(self != NULL);
777 /* Make sure that we hold the lock. */
778 if (mon->owner != self) {
779 dvmThrowIllegalMonitorStateException(
780 "object not locked by thread before notify()");
783 /* Signal the first waiting thread in the wait set. */
784 while (mon->waitSet != NULL) {
785 thread = mon->waitSet;
786 mon->waitSet = thread->waitNext;
787 thread->waitNext = NULL;
788 dvmLockMutex(&thread->waitMutex);
789 /* Check to see if the thread is still waiting. */
790 if (thread->waitMonitor != NULL) {
791 pthread_cond_signal(&thread->waitCond);
792 dvmUnlockMutex(&thread->waitMutex);
795 dvmUnlockMutex(&thread->waitMutex);
800 * Notify all threads waiting on this monitor.
802 static void notifyAllMonitor(Thread* self, Monitor* mon)
806 assert(self != NULL);
809 /* Make sure that we hold the lock. */
810 if (mon->owner != self) {
811 dvmThrowIllegalMonitorStateException(
812 "object not locked by thread before notifyAll()");
815 /* Signal all threads in the wait set. */
816 while (mon->waitSet != NULL) {
817 thread = mon->waitSet;
818 mon->waitSet = thread->waitNext;
819 thread->waitNext = NULL;
820 dvmLockMutex(&thread->waitMutex);
821 /* Check to see if the thread is still waiting. */
822 if (thread->waitMonitor != NULL) {
823 pthread_cond_signal(&thread->waitCond);
825 dvmUnlockMutex(&thread->waitMutex);
830 * Changes the shape of a monitor from thin to fat, preserving the
831 * internal lock state. The calling thread must own the lock.
833 static void inflateMonitor(Thread *self, Object *obj)
838 assert(self != NULL);
840 assert(LW_SHAPE(obj->lock) == LW_SHAPE_THIN);
841 assert(LW_LOCK_OWNER(obj->lock) == self->threadId);
842 /* Allocate and acquire a new monitor. */
843 mon = dvmCreateMonitor(obj);
844 lockMonitor(self, mon);
845 /* Propagate the lock state. */
847 mon->lockCount = LW_LOCK_COUNT(thin);
848 thin &= LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT;
849 thin |= (u4)mon | LW_SHAPE_FAT;
850 /* Publish the updated lock word. */
851 android_atomic_release_store(thin, (int32_t *)&obj->lock);
855 * Implements monitorenter for "synchronized" stuff.
857 * This does not fail or throw an exception (unless deadlock prediction
858 * is enabled and set to "err" mode).
860 void dvmLockObject(Thread* self, Object *obj)
863 ThreadStatus oldStatus;
866 long minSleepDelayNs = 1000000; /* 1 millisecond */
867 long maxSleepDelayNs = 1000000000; /* 1 second */
868 u4 thin, newThin, threadId;
870 assert(self != NULL);
872 threadId = self->threadId;
876 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
878 * The lock is a thin lock. The owner field is used to
879 * determine the acquire method, ordered by cost.
881 if (LW_LOCK_OWNER(thin) == threadId) {
883 * The calling thread owns the lock. Increment the
884 * value of the recursion count field.
886 obj->lock += 1 << LW_LOCK_COUNT_SHIFT;
887 if (LW_LOCK_COUNT(obj->lock) == LW_LOCK_COUNT_MASK) {
889 * The reacquisition limit has been reached. Inflate
890 * the lock so the next acquire will not overflow the
891 * recursion count field.
893 inflateMonitor(self, obj);
895 } else if (LW_LOCK_OWNER(thin) == 0) {
897 * The lock is unowned. Install the thread id of the
898 * calling thread into the owner field. This is the
899 * common case. In performance critical code the JIT
900 * will have tried this before calling out to the VM.
902 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
903 if (android_atomic_acquire_cas(thin, newThin,
904 (int32_t*)thinp) != 0) {
906 * The acquire failed. Try again.
911 ALOGV("(%d) spin on lock %p: %#x (%#x) %#x",
912 threadId, &obj->lock, 0, *thinp, thin);
914 * The lock is owned by another thread. Notify the VM
915 * that we are about to wait.
917 oldStatus = dvmChangeStatus(self, THREAD_MONITOR);
919 * Spin until the thin lock is released or inflated.
925 * Check the shape of the lock word. Another thread
926 * may have inflated the lock while we were waiting.
928 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
929 if (LW_LOCK_OWNER(thin) == 0) {
931 * The lock has been released. Install the
932 * thread id of the calling thread into the
935 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
936 if (android_atomic_acquire_cas(thin, newThin,
937 (int32_t *)thinp) == 0) {
939 * The acquire succeed. Break out of the
940 * loop and proceed to inflate the lock.
946 * The lock has not been released. Yield so
947 * the owning thread can run.
949 if (sleepDelayNs == 0) {
951 sleepDelayNs = minSleepDelayNs;
954 tm.tv_nsec = sleepDelayNs;
955 nanosleep(&tm, NULL);
957 * Prepare the next delay value. Wrap to
958 * avoid once a second polls for eternity.
960 if (sleepDelayNs < maxSleepDelayNs / 2) {
963 sleepDelayNs = minSleepDelayNs;
969 * The thin lock was inflated by another thread.
970 * Let the VM know we are no longer waiting and
973 ALOGV("(%d) lock %p surprise-fattened",
974 threadId, &obj->lock);
975 dvmChangeStatus(self, oldStatus);
979 ALOGV("(%d) spin on lock done %p: %#x (%#x) %#x",
980 threadId, &obj->lock, 0, *thinp, thin);
982 * We have acquired the thin lock. Let the VM know that
983 * we are no longer waiting.
985 dvmChangeStatus(self, oldStatus);
989 inflateMonitor(self, obj);
990 ALOGV("(%d) lock %p fattened", threadId, &obj->lock);
994 * The lock is a fat lock.
996 assert(LW_MONITOR(obj->lock) != NULL);
997 lockMonitor(self, LW_MONITOR(obj->lock));
1002 * Implements monitorexit for "synchronized" stuff.
1004 * On failure, throws an exception and returns "false".
1006 bool dvmUnlockObject(Thread* self, Object *obj)
1010 assert(self != NULL);
1011 assert(self->status == THREAD_RUNNING);
1012 assert(obj != NULL);
1014 * Cache the lock word as its value can change while we are
1015 * examining its state.
1017 thin = *(volatile u4 *)&obj->lock;
1018 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
1020 * The lock is thin. We must ensure that the lock is owned
1021 * by the given thread before unlocking it.
1023 if (LW_LOCK_OWNER(thin) == self->threadId) {
1025 * We are the lock owner. It is safe to update the lock
1026 * without CAS as lock ownership guards the lock itself.
1028 if (LW_LOCK_COUNT(thin) == 0) {
1030 * The lock was not recursively acquired, the common
1031 * case. Unlock by clearing all bits except for the
1034 thin &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
1035 android_atomic_release_store(thin, (int32_t*)&obj->lock);
1038 * The object was recursively acquired. Decrement the
1039 * lock recursion count field.
1041 obj->lock -= 1 << LW_LOCK_COUNT_SHIFT;
1045 * We do not own the lock. The JVM spec requires that we
1046 * throw an exception in this case.
1048 dvmThrowIllegalMonitorStateException("unlock of unowned monitor");
1053 * The lock is fat. We must check to see if unlockMonitor has
1054 * raised any exceptions before continuing.
1056 assert(LW_MONITOR(obj->lock) != NULL);
1057 if (!unlockMonitor(self, LW_MONITOR(obj->lock))) {
1059 * An exception has been raised. Do not fall through.
1068 * Object.wait(). Also called for class init.
1070 void dvmObjectWait(Thread* self, Object *obj, s8 msec, s4 nsec,
1071 bool interruptShouldThrow)
1074 u4 thin = *(volatile u4 *)&obj->lock;
1076 /* If the lock is still thin, we need to fatten it.
1078 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
1079 /* Make sure that 'self' holds the lock.
1081 if (LW_LOCK_OWNER(thin) != self->threadId) {
1082 dvmThrowIllegalMonitorStateException(
1083 "object not locked by thread before wait()");
1087 /* This thread holds the lock. We need to fatten the lock
1088 * so 'self' can block on it. Don't update the object lock
1089 * field yet, because 'self' needs to acquire the lock before
1090 * any other thread gets a chance.
1092 inflateMonitor(self, obj);
1093 ALOGV("(%d) lock %p fattened by wait()", self->threadId, &obj->lock);
1095 mon = LW_MONITOR(obj->lock);
1096 waitMonitor(self, mon, msec, nsec, interruptShouldThrow);
1102 void dvmObjectNotify(Thread* self, Object *obj)
1104 u4 thin = *(volatile u4 *)&obj->lock;
1106 /* If the lock is still thin, there aren't any waiters;
1107 * waiting on an object forces lock fattening.
1109 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
1110 /* Make sure that 'self' holds the lock.
1112 if (LW_LOCK_OWNER(thin) != self->threadId) {
1113 dvmThrowIllegalMonitorStateException(
1114 "object not locked by thread before notify()");
1118 /* no-op; there are no waiters to notify.
1123 notifyMonitor(self, LW_MONITOR(thin));
1128 * Object.notifyAll().
1130 void dvmObjectNotifyAll(Thread* self, Object *obj)
1132 u4 thin = *(volatile u4 *)&obj->lock;
1134 /* If the lock is still thin, there aren't any waiters;
1135 * waiting on an object forces lock fattening.
1137 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
1138 /* Make sure that 'self' holds the lock.
1140 if (LW_LOCK_OWNER(thin) != self->threadId) {
1141 dvmThrowIllegalMonitorStateException(
1142 "object not locked by thread before notifyAll()");
1146 /* no-op; there are no waiters to notify.
1151 notifyAllMonitor(self, LW_MONITOR(thin));
1156 * This implements java.lang.Thread.sleep(long msec, int nsec).
1158 * The sleep is interruptible by other threads, which means we can't just
1159 * plop into an OS sleep call. (We probably could if we wanted to send
1160 * signals around and rely on EINTR, but that's inefficient and relies
1161 * on native code respecting our signal mask.)
1163 * We have to do all of this stuff for Object.wait() as well, so it's
1164 * easiest to just sleep on a private Monitor.
1166 * It appears that we want sleep(0,0) to go through the motions of sleeping
1167 * for a very short duration, rather than just returning.
1169 void dvmThreadSleep(u8 msec, u4 nsec)
1171 Thread* self = dvmThreadSelf();
1172 Monitor* mon = gDvm.threadSleepMon;
1174 /* sleep(0,0) wakes up immediately, wait(0,0) means wait forever; adjust */
1175 if (msec == 0 && nsec == 0)
1178 lockMonitor(self, mon);
1179 waitMonitor(self, mon, msec, nsec, true);
1180 unlockMonitor(self, mon);
1184 * Implement java.lang.Thread.interrupt().
1186 void dvmThreadInterrupt(Thread* thread)
1188 assert(thread != NULL);
1190 dvmLockMutex(&thread->waitMutex);
1193 * If the interrupted flag is already set no additional action is
1196 if (thread->interrupted == true) {
1197 dvmUnlockMutex(&thread->waitMutex);
1202 * Raise the "interrupted" flag. This will cause it to bail early out
1203 * of the next wait() attempt, if it's not currently waiting on
1206 thread->interrupted = true;
1209 * Is the thread waiting?
1211 * Note that fat vs. thin doesn't matter here; waitMonitor
1212 * is only set when a thread actually waits on a monitor,
1213 * which implies that the monitor has already been fattened.
1215 if (thread->waitMonitor != NULL) {
1216 pthread_cond_signal(&thread->waitCond);
1219 dvmUnlockMutex(&thread->waitMutex);
1222 #ifndef WITH_COPYING_GC
1223 u4 dvmIdentityHashCode(Object *obj)
1229 * Returns the identity hash code of the given object.
1231 u4 dvmIdentityHashCode(Object *obj)
1233 Thread *self, *thread;
1236 u4 lock, owner, hashState;
1240 * Null is defined to have an identity hash code of 0.
1246 hashState = LW_HASH_STATE(*lw);
1247 if (hashState == LW_HASH_STATE_HASHED) {
1249 * The object has been hashed but has not had its hash code
1250 * relocated by the garbage collector. Use the raw object
1253 return (u4)obj >> 3;
1254 } else if (hashState == LW_HASH_STATE_HASHED_AND_MOVED) {
1256 * The object has been hashed and its hash code has been
1257 * relocated by the collector. Use the value of the naturally
1258 * aligned word following the instance data.
1260 assert(!dvmIsClassObject(obj));
1261 if (IS_CLASS_FLAG_SET(obj->clazz, CLASS_ISARRAY)) {
1262 size = dvmArrayObjectSize((ArrayObject *)obj);
1263 size = (size + 2) & ~2;
1265 size = obj->clazz->objectSize;
1267 return *(u4 *)(((char *)obj) + size);
1268 } else if (hashState == LW_HASH_STATE_UNHASHED) {
1270 * The object has never been hashed. Change the hash state to
1271 * hashed and use the raw object address.
1273 self = dvmThreadSelf();
1274 if (self->threadId == lockOwner(obj)) {
1276 * We already own the lock so we can update the hash state
1279 *lw |= (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1280 return (u4)obj >> 3;
1283 * We do not own the lock. Try acquiring the lock. Should
1284 * this fail, we must suspend the owning thread.
1286 if (LW_SHAPE(*lw) == LW_SHAPE_THIN) {
1288 * If the lock is thin assume it is unowned. We simulate
1289 * an acquire, update, and release with a single CAS.
1291 lock = (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1292 if (android_atomic_acquire_cas(
1295 (int32_t *)lw) == 0) {
1297 * A new lockword has been installed with a hash state
1298 * of hashed. Use the raw object address.
1300 return (u4)obj >> 3;
1303 if (tryLockMonitor(self, LW_MONITOR(*lw))) {
1305 * The monitor lock has been acquired. Change the
1306 * hash state to hashed and use the raw object
1309 *lw |= (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1310 unlockMonitor(self, LW_MONITOR(*lw));
1311 return (u4)obj >> 3;
1315 * At this point we have failed to acquire the lock. We must
1316 * identify the owning thread and suspend it.
1318 dvmLockThreadList(self);
1320 * Cache the lock word as its value can change between
1321 * determining its shape and retrieving its owner.
1324 if (LW_SHAPE(lock) == LW_SHAPE_THIN) {
1326 * Find the thread with the corresponding thread id.
1328 owner = LW_LOCK_OWNER(lock);
1329 assert(owner != self->threadId);
1331 * If the lock has no owner do not bother scanning the
1332 * thread list and fall through to the failure handler.
1334 thread = owner ? gDvm.threadList : NULL;
1335 while (thread != NULL) {
1336 if (thread->threadId == owner) {
1339 thread = thread->next;
1342 thread = LW_MONITOR(lock)->owner;
1345 * If thread is NULL the object has been released since the
1346 * thread list lock was acquired. Try again.
1348 if (thread == NULL) {
1349 dvmUnlockThreadList();
1353 * Wait for the owning thread to suspend.
1355 dvmSuspendThread(thread);
1356 if (dvmHoldsLock(thread, obj)) {
1358 * The owning thread has been suspended. We can safely
1359 * change the hash state to hashed.
1361 *lw |= (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1362 dvmResumeThread(thread);
1363 dvmUnlockThreadList();
1364 return (u4)obj >> 3;
1367 * The wrong thread has been suspended. Try again.
1369 dvmResumeThread(thread);
1370 dvmUnlockThreadList();
1373 ALOGE("object %p has an unknown hash state %#x", obj, hashState);
1374 dvmDumpThread(dvmThreadSelf(), false);
1376 return 0; /* Quiet the compiler. */
1378 #endif /* WITH_COPYING_GC */