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, ownerFileName may be NULL.
87 const char* ownerFileName;
93 * Create and initialize a monitor.
95 Monitor* dvmCreateMonitor(Object* obj)
99 mon = (Monitor*) calloc(1, sizeof(Monitor));
101 LOGE("Unable to allocate monitor");
104 if (((u4)mon & 7) != 0) {
105 LOGE("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 saveArea = SAVEAREA_FROM_FP(self->interpSave.curFrame);
280 meth = saveArea->method;
283 /* Emit the event list length, 1 byte. */
286 /* Emit the process name, <= 37 bytes. */
287 fd = open("/proc/self/cmdline", O_RDONLY);
288 memset(procName, 0, sizeof(procName));
289 read(fd, procName, sizeof(procName) - 1);
291 len = strlen(procName);
292 cp = logWriteString(cp, procName, len);
294 /* Emit the sensitive thread ("main thread") status, 5 bytes. */
295 bool isSensitive = false;
296 if (gDvm.isSensitiveThreadHook != NULL) {
297 isSensitive = gDvm.isSensitiveThreadHook();
299 cp = logWriteInt(cp, isSensitive);
301 /* Emit self thread name string, <= 37 bytes. */
302 std::string selfName = dvmGetThreadName(self);
303 cp = logWriteString(cp, selfName.c_str(), selfName.size());
305 /* Emit the wait time, 5 bytes. */
306 cp = logWriteInt(cp, waitMs);
308 /* Emit the source code file name, <= 37 bytes. */
309 fileName = dvmGetMethodSourceFile(meth);
310 if (fileName == NULL) fileName = "";
311 cp = logWriteString(cp, fileName, strlen(fileName));
313 /* Emit the source code line number, 5 bytes. */
314 relativePc = saveArea->xtra.currentPc - saveArea->method->insns;
315 cp = logWriteInt(cp, dvmLineNumFromPC(meth, relativePc));
317 /* Emit the lock owner source code file name, <= 37 bytes. */
318 if (ownerFileName == NULL) {
320 } else if (strcmp(fileName, ownerFileName) == 0) {
321 /* Common case, so save on log space. */
324 cp = logWriteString(cp, ownerFileName, strlen(ownerFileName));
326 /* Emit the source code line number, 5 bytes. */
327 cp = logWriteInt(cp, ownerLineNumber);
329 /* Emit the sample percentage, 5 bytes. */
330 cp = logWriteInt(cp, samplePercent);
332 assert((size_t)(cp - eventBuffer) <= sizeof(eventBuffer));
333 android_btWriteLog(EVENT_LOG_TAG_dvm_lock_sample,
336 (size_t)(cp - eventBuffer));
342 static void lockMonitor(Thread* self, Monitor* mon)
344 ThreadStatus oldStatus;
345 u4 waitThreshold, samplePercent;
346 u8 waitStart, waitEnd, waitMs;
348 if (mon->owner == self) {
352 if (dvmTryLockMutex(&mon->lock) != 0) {
353 oldStatus = dvmChangeStatus(self, THREAD_MONITOR);
354 waitThreshold = gDvm.lockProfThreshold;
356 waitStart = dvmGetRelativeTimeUsec();
358 const char* currentOwnerFileName = mon->ownerFileName;
359 u4 currentOwnerLineNumber = mon->ownerLineNumber;
361 dvmLockMutex(&mon->lock);
363 waitEnd = dvmGetRelativeTimeUsec();
365 dvmChangeStatus(self, oldStatus);
367 waitMs = (waitEnd - waitStart) / 1000;
368 if (waitMs >= waitThreshold) {
371 samplePercent = 100 * waitMs / waitThreshold;
373 if (samplePercent != 0 && ((u4)rand() % 100 < samplePercent)) {
374 logContentionEvent(self, waitMs, samplePercent,
375 currentOwnerFileName, currentOwnerLineNumber);
380 assert(mon->lockCount == 0);
382 // When debugging, save the current monitor holder for future
383 // acquisition failures to use in sampled logging.
384 if (gDvm.lockProfThreshold > 0) {
385 const StackSaveArea *saveArea;
387 mon->ownerLineNumber = 0;
388 if (self->interpSave.curFrame == NULL) {
389 mon->ownerFileName = "no_frame";
390 } else if ((saveArea =
391 SAVEAREA_FROM_FP(self->interpSave.curFrame)) == NULL) {
392 mon->ownerFileName = "no_save_area";
393 } else if ((meth = saveArea->method) == NULL) {
394 mon->ownerFileName = "no_method";
396 u4 relativePc = saveArea->xtra.currentPc - saveArea->method->insns;
397 mon->ownerFileName = (char*) dvmGetMethodSourceFile(meth);
398 if (mon->ownerFileName == NULL) {
399 mon->ownerFileName = "no_method_file";
401 mon->ownerLineNumber = dvmLineNumFromPC(meth, relativePc);
408 * Try to lock a monitor.
410 * Returns "true" on success.
412 #ifdef WITH_COPYING_GC
413 static bool tryLockMonitor(Thread* self, Monitor* mon)
415 if (mon->owner == self) {
419 if (dvmTryLockMutex(&mon->lock) == 0) {
421 assert(mon->lockCount == 0);
433 * Returns true if the unlock succeeded.
434 * If the unlock failed, an exception will be pending.
436 static bool unlockMonitor(Thread* self, Monitor* mon)
438 assert(self != NULL);
440 if (mon->owner == self) {
442 * We own the monitor, so nobody else can be in here.
444 if (mon->lockCount == 0) {
446 mon->ownerFileName = "unlocked";
447 mon->ownerLineNumber = 0;
448 dvmUnlockMutex(&mon->lock);
454 * We don't own this, so we're not allowed to unlock it.
455 * The JNI spec says that we should throw IllegalMonitorStateException
458 dvmThrowIllegalMonitorStateException("unlock of unowned monitor");
465 * Checks the wait set for circular structure. Returns 0 if the list
466 * is not circular. Otherwise, returns 1. Used only by asserts.
469 static int waitSetCheck(Monitor *mon)
475 fast = slow = mon->waitSet;
478 if (fast == NULL) return 0;
479 if (fast->waitNext == NULL) return 0;
480 if (fast == slow && n > 0) return 1;
482 fast = fast->waitNext->waitNext;
483 slow = slow->waitNext;
489 * Links a thread into a monitor's wait set. The monitor lock must be
490 * held by the caller of this routine.
492 static void waitSetAppend(Monitor *mon, Thread *thread)
497 assert(mon->owner == dvmThreadSelf());
498 assert(thread != NULL);
499 assert(thread->waitNext == NULL);
500 assert(waitSetCheck(mon) == 0);
501 if (mon->waitSet == NULL) {
502 mon->waitSet = thread;
506 while (elt->waitNext != NULL) {
509 elt->waitNext = thread;
513 * Unlinks a thread from a monitor's wait set. The monitor lock must
514 * be held by the caller of this routine.
516 static void waitSetRemove(Monitor *mon, Thread *thread)
521 assert(mon->owner == dvmThreadSelf());
522 assert(thread != NULL);
523 assert(waitSetCheck(mon) == 0);
524 if (mon->waitSet == NULL) {
527 if (mon->waitSet == thread) {
528 mon->waitSet = thread->waitNext;
529 thread->waitNext = NULL;
533 while (elt->waitNext != NULL) {
534 if (elt->waitNext == thread) {
535 elt->waitNext = thread->waitNext;
536 thread->waitNext = NULL;
544 * Converts the given relative waiting time into an absolute time.
546 static void absoluteTime(s8 msec, s4 nsec, struct timespec *ts)
550 #ifdef HAVE_TIMEDWAIT_MONOTONIC
551 clock_gettime(CLOCK_MONOTONIC, ts);
555 gettimeofday(&tv, NULL);
556 ts->tv_sec = tv.tv_sec;
557 ts->tv_nsec = tv.tv_usec * 1000;
560 endSec = ts->tv_sec + msec / 1000;
561 if (endSec >= 0x7fffffff) {
562 LOGV("NOTE: end time exceeds epoch");
566 ts->tv_nsec = (ts->tv_nsec + (msec % 1000) * 1000000) + nsec;
569 if (ts->tv_nsec >= 1000000000L) {
571 ts->tv_nsec -= 1000000000L;
575 int dvmRelativeCondWait(pthread_cond_t* cond, pthread_mutex_t* mutex,
580 absoluteTime(msec, nsec, &ts);
581 #if defined(HAVE_TIMEDWAIT_MONOTONIC)
582 ret = pthread_cond_timedwait_monotonic(cond, mutex, &ts);
584 ret = pthread_cond_timedwait(cond, mutex, &ts);
586 assert(ret == 0 || ret == ETIMEDOUT);
591 * Wait on a monitor until timeout, interrupt, or notification. Used for
592 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
594 * If another thread calls Thread.interrupt(), we throw InterruptedException
595 * and return immediately if one of the following are true:
596 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
597 * - blocked in join(), join(long), or join(long, int) methods of Thread
598 * - blocked in sleep(long), or sleep(long, int) methods of Thread
599 * Otherwise, we set the "interrupted" flag.
601 * Checks to make sure that "nsec" is in the range 0-999999
602 * (i.e. fractions of a millisecond) and throws the appropriate
603 * exception if it isn't.
605 * The spec allows "spurious wakeups", and recommends that all code using
606 * Object.wait() do so in a loop. This appears to derive from concerns
607 * about pthread_cond_wait() on multiprocessor systems. Some commentary
608 * on the web casts doubt on whether these can/should occur.
610 * Since we're allowed to wake up "early", we clamp extremely long durations
611 * to return at the end of the 32-bit time epoch.
613 static void waitMonitor(Thread* self, Monitor* mon, s8 msec, s4 nsec,
614 bool interruptShouldThrow)
617 bool wasInterrupted = false;
620 const char *savedFileName;
623 assert(self != NULL);
626 /* Make sure that we hold the lock. */
627 if (mon->owner != self) {
628 dvmThrowIllegalMonitorStateException(
629 "object not locked by thread before wait()");
634 * Enforce the timeout range.
636 if (msec < 0 || nsec < 0 || nsec > 999999) {
637 dvmThrowIllegalArgumentException("timeout arguments out of range");
642 * Compute absolute wakeup time, if necessary.
644 if (msec == 0 && nsec == 0) {
647 absoluteTime(msec, nsec, &ts);
652 * Add ourselves to the set of threads waiting on this monitor, and
653 * release our hold. We need to let it go even if we're a few levels
654 * deep in a recursive lock, and we need to restore that later.
656 * We append to the wait set ahead of clearing the count and owner
657 * fields so the subroutine can check that the calling thread owns
658 * the monitor. Aside from that, the order of member updates is
659 * not order sensitive as we hold the pthread mutex.
661 waitSetAppend(mon, self);
662 int prevLockCount = mon->lockCount;
665 savedFileName = mon->ownerFileName;
666 mon->ownerFileName = NULL;
667 savedLineNumber = mon->ownerLineNumber;
668 mon->ownerLineNumber = 0;
671 * Update thread status. If the GC wakes up, it'll ignore us, knowing
672 * that we won't touch any references in this state, and we'll check
673 * our suspend mode before we transition out.
676 dvmChangeStatus(self, THREAD_TIMED_WAIT);
678 dvmChangeStatus(self, THREAD_WAIT);
680 dvmLockMutex(&self->waitMutex);
683 * Set waitMonitor to the monitor object we will be waiting on.
684 * When waitMonitor is non-NULL a notifying or interrupting thread
685 * must signal the thread's waitCond to wake it up.
687 assert(self->waitMonitor == NULL);
688 self->waitMonitor = mon;
691 * Handle the case where the thread was interrupted before we called
694 if (self->interrupted) {
695 wasInterrupted = true;
696 self->waitMonitor = NULL;
697 dvmUnlockMutex(&self->waitMutex);
702 * Release the monitor lock and wait for a notification or
703 * a timeout to occur.
705 dvmUnlockMutex(&mon->lock);
708 ret = pthread_cond_wait(&self->waitCond, &self->waitMutex);
711 #ifdef HAVE_TIMEDWAIT_MONOTONIC
712 ret = pthread_cond_timedwait_monotonic(&self->waitCond, &self->waitMutex, &ts);
714 ret = pthread_cond_timedwait(&self->waitCond, &self->waitMutex, &ts);
716 assert(ret == 0 || ret == ETIMEDOUT);
718 if (self->interrupted) {
719 wasInterrupted = true;
722 self->interrupted = false;
723 self->waitMonitor = NULL;
725 dvmUnlockMutex(&self->waitMutex);
727 /* Reacquire the monitor lock. */
728 lockMonitor(self, mon);
732 * We remove our thread from wait set after restoring the count
733 * and owner fields so the subroutine can check that the calling
734 * thread owns the monitor. Aside from that, the order of member
735 * updates is not order sensitive as we hold the pthread mutex.
738 mon->lockCount = prevLockCount;
739 mon->ownerFileName = savedFileName;
740 mon->ownerLineNumber = savedLineNumber;
741 waitSetRemove(mon, self);
743 /* set self->status back to THREAD_RUNNING, and self-suspend if needed */
744 dvmChangeStatus(self, THREAD_RUNNING);
746 if (wasInterrupted) {
748 * We were interrupted while waiting, or somebody interrupted an
749 * un-interruptible thread earlier and we're bailing out immediately.
751 * The doc sayeth: "The interrupted status of the current thread is
752 * cleared when this exception is thrown."
754 self->interrupted = false;
755 if (interruptShouldThrow) {
756 dvmThrowInterruptedException(NULL);
762 * Notify one thread waiting on this monitor.
764 static void notifyMonitor(Thread* self, Monitor* mon)
768 assert(self != NULL);
771 /* Make sure that we hold the lock. */
772 if (mon->owner != self) {
773 dvmThrowIllegalMonitorStateException(
774 "object not locked by thread before notify()");
777 /* Signal the first waiting thread in the wait set. */
778 while (mon->waitSet != NULL) {
779 thread = mon->waitSet;
780 mon->waitSet = thread->waitNext;
781 thread->waitNext = NULL;
782 dvmLockMutex(&thread->waitMutex);
783 /* Check to see if the thread is still waiting. */
784 if (thread->waitMonitor != NULL) {
785 pthread_cond_signal(&thread->waitCond);
786 dvmUnlockMutex(&thread->waitMutex);
789 dvmUnlockMutex(&thread->waitMutex);
794 * Notify all threads waiting on this monitor.
796 static void notifyAllMonitor(Thread* self, Monitor* mon)
800 assert(self != NULL);
803 /* Make sure that we hold the lock. */
804 if (mon->owner != self) {
805 dvmThrowIllegalMonitorStateException(
806 "object not locked by thread before notifyAll()");
809 /* Signal all threads in the wait set. */
810 while (mon->waitSet != NULL) {
811 thread = mon->waitSet;
812 mon->waitSet = thread->waitNext;
813 thread->waitNext = NULL;
814 dvmLockMutex(&thread->waitMutex);
815 /* Check to see if the thread is still waiting. */
816 if (thread->waitMonitor != NULL) {
817 pthread_cond_signal(&thread->waitCond);
819 dvmUnlockMutex(&thread->waitMutex);
824 * Changes the shape of a monitor from thin to fat, preserving the
825 * internal lock state. The calling thread must own the lock.
827 static void inflateMonitor(Thread *self, Object *obj)
832 assert(self != NULL);
834 assert(LW_SHAPE(obj->lock) == LW_SHAPE_THIN);
835 assert(LW_LOCK_OWNER(obj->lock) == self->threadId);
836 /* Allocate and acquire a new monitor. */
837 mon = dvmCreateMonitor(obj);
838 lockMonitor(self, mon);
839 /* Propagate the lock state. */
841 mon->lockCount = LW_LOCK_COUNT(thin);
842 thin &= LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT;
843 thin |= (u4)mon | LW_SHAPE_FAT;
844 /* Publish the updated lock word. */
845 android_atomic_release_store(thin, (int32_t *)&obj->lock);
849 * Implements monitorenter for "synchronized" stuff.
851 * This does not fail or throw an exception (unless deadlock prediction
852 * is enabled and set to "err" mode).
854 void dvmLockObject(Thread* self, Object *obj)
857 ThreadStatus oldStatus;
860 long minSleepDelayNs = 1000000; /* 1 millisecond */
861 long maxSleepDelayNs = 1000000000; /* 1 second */
862 u4 thin, newThin, threadId;
864 assert(self != NULL);
866 threadId = self->threadId;
870 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
872 * The lock is a thin lock. The owner field is used to
873 * determine the acquire method, ordered by cost.
875 if (LW_LOCK_OWNER(thin) == threadId) {
877 * The calling thread owns the lock. Increment the
878 * value of the recursion count field.
880 obj->lock += 1 << LW_LOCK_COUNT_SHIFT;
881 if (LW_LOCK_COUNT(obj->lock) == LW_LOCK_COUNT_MASK) {
883 * The reacquisition limit has been reached. Inflate
884 * the lock so the next acquire will not overflow the
885 * recursion count field.
887 inflateMonitor(self, obj);
889 } else if (LW_LOCK_OWNER(thin) == 0) {
891 * The lock is unowned. Install the thread id of the
892 * calling thread into the owner field. This is the
893 * common case. In performance critical code the JIT
894 * will have tried this before calling out to the VM.
896 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
897 if (android_atomic_acquire_cas(thin, newThin,
898 (int32_t*)thinp) != 0) {
900 * The acquire failed. Try again.
905 LOGV("(%d) spin on lock %p: %#x (%#x) %#x",
906 threadId, &obj->lock, 0, *thinp, thin);
908 * The lock is owned by another thread. Notify the VM
909 * that we are about to wait.
911 oldStatus = dvmChangeStatus(self, THREAD_MONITOR);
913 * Spin until the thin lock is released or inflated.
919 * Check the shape of the lock word. Another thread
920 * may have inflated the lock while we were waiting.
922 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
923 if (LW_LOCK_OWNER(thin) == 0) {
925 * The lock has been released. Install the
926 * thread id of the calling thread into the
929 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
930 if (android_atomic_acquire_cas(thin, newThin,
931 (int32_t *)thinp) == 0) {
933 * The acquire succeed. Break out of the
934 * loop and proceed to inflate the lock.
940 * The lock has not been released. Yield so
941 * the owning thread can run.
943 if (sleepDelayNs == 0) {
945 sleepDelayNs = minSleepDelayNs;
948 tm.tv_nsec = sleepDelayNs;
949 nanosleep(&tm, NULL);
951 * Prepare the next delay value. Wrap to
952 * avoid once a second polls for eternity.
954 if (sleepDelayNs < maxSleepDelayNs / 2) {
957 sleepDelayNs = minSleepDelayNs;
963 * The thin lock was inflated by another thread.
964 * Let the VM know we are no longer waiting and
967 LOGV("(%d) lock %p surprise-fattened",
968 threadId, &obj->lock);
969 dvmChangeStatus(self, oldStatus);
973 LOGV("(%d) spin on lock done %p: %#x (%#x) %#x",
974 threadId, &obj->lock, 0, *thinp, thin);
976 * We have acquired the thin lock. Let the VM know that
977 * we are no longer waiting.
979 dvmChangeStatus(self, oldStatus);
983 inflateMonitor(self, obj);
984 LOGV("(%d) lock %p fattened", threadId, &obj->lock);
988 * The lock is a fat lock.
990 assert(LW_MONITOR(obj->lock) != NULL);
991 lockMonitor(self, LW_MONITOR(obj->lock));
996 * Implements monitorexit for "synchronized" stuff.
998 * On failure, throws an exception and returns "false".
1000 bool dvmUnlockObject(Thread* self, Object *obj)
1004 assert(self != NULL);
1005 assert(self->status == THREAD_RUNNING);
1006 assert(obj != NULL);
1008 * Cache the lock word as its value can change while we are
1009 * examining its state.
1012 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
1014 * The lock is thin. We must ensure that the lock is owned
1015 * by the given thread before unlocking it.
1017 if (LW_LOCK_OWNER(thin) == self->threadId) {
1019 * We are the lock owner. It is safe to update the lock
1020 * without CAS as lock ownership guards the lock itself.
1022 if (LW_LOCK_COUNT(thin) == 0) {
1024 * The lock was not recursively acquired, the common
1025 * case. Unlock by clearing all bits except for the
1028 obj->lock &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
1031 * The object was recursively acquired. Decrement the
1032 * lock recursion count field.
1034 obj->lock -= 1 << LW_LOCK_COUNT_SHIFT;
1038 * We do not own the lock. The JVM spec requires that we
1039 * throw an exception in this case.
1041 dvmThrowIllegalMonitorStateException("unlock of unowned monitor");
1046 * The lock is fat. We must check to see if unlockMonitor has
1047 * raised any exceptions before continuing.
1049 assert(LW_MONITOR(obj->lock) != NULL);
1050 if (!unlockMonitor(self, LW_MONITOR(obj->lock))) {
1052 * An exception has been raised. Do not fall through.
1061 * Object.wait(). Also called for class init.
1063 void dvmObjectWait(Thread* self, Object *obj, s8 msec, s4 nsec,
1064 bool interruptShouldThrow)
1067 u4 thin = obj->lock;
1069 /* If the lock is still thin, we need to fatten it.
1071 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
1072 /* Make sure that 'self' holds the lock.
1074 if (LW_LOCK_OWNER(thin) != self->threadId) {
1075 dvmThrowIllegalMonitorStateException(
1076 "object not locked by thread before wait()");
1080 /* This thread holds the lock. We need to fatten the lock
1081 * so 'self' can block on it. Don't update the object lock
1082 * field yet, because 'self' needs to acquire the lock before
1083 * any other thread gets a chance.
1085 inflateMonitor(self, obj);
1086 LOGV("(%d) lock %p fattened by wait()", self->threadId, &obj->lock);
1088 mon = LW_MONITOR(obj->lock);
1089 waitMonitor(self, mon, msec, nsec, interruptShouldThrow);
1095 void dvmObjectNotify(Thread* self, Object *obj)
1097 u4 thin = obj->lock;
1099 /* If the lock is still thin, there aren't any waiters;
1100 * waiting on an object forces lock fattening.
1102 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
1103 /* Make sure that 'self' holds the lock.
1105 if (LW_LOCK_OWNER(thin) != self->threadId) {
1106 dvmThrowIllegalMonitorStateException(
1107 "object not locked by thread before notify()");
1111 /* no-op; there are no waiters to notify.
1116 notifyMonitor(self, LW_MONITOR(thin));
1121 * Object.notifyAll().
1123 void dvmObjectNotifyAll(Thread* self, Object *obj)
1125 u4 thin = obj->lock;
1127 /* If the lock is still thin, there aren't any waiters;
1128 * waiting on an object forces lock fattening.
1130 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
1131 /* Make sure that 'self' holds the lock.
1133 if (LW_LOCK_OWNER(thin) != self->threadId) {
1134 dvmThrowIllegalMonitorStateException(
1135 "object not locked by thread before notifyAll()");
1139 /* no-op; there are no waiters to notify.
1144 notifyAllMonitor(self, LW_MONITOR(thin));
1149 * This implements java.lang.Thread.sleep(long msec, int nsec).
1151 * The sleep is interruptible by other threads, which means we can't just
1152 * plop into an OS sleep call. (We probably could if we wanted to send
1153 * signals around and rely on EINTR, but that's inefficient and relies
1154 * on native code respecting our signal mask.)
1156 * We have to do all of this stuff for Object.wait() as well, so it's
1157 * easiest to just sleep on a private Monitor.
1159 * It appears that we want sleep(0,0) to go through the motions of sleeping
1160 * for a very short duration, rather than just returning.
1162 void dvmThreadSleep(u8 msec, u4 nsec)
1164 Thread* self = dvmThreadSelf();
1165 Monitor* mon = gDvm.threadSleepMon;
1167 /* sleep(0,0) wakes up immediately, wait(0,0) means wait forever; adjust */
1168 if (msec == 0 && nsec == 0)
1171 lockMonitor(self, mon);
1172 waitMonitor(self, mon, msec, nsec, true);
1173 unlockMonitor(self, mon);
1177 * Implement java.lang.Thread.interrupt().
1179 void dvmThreadInterrupt(Thread* thread)
1181 assert(thread != NULL);
1183 dvmLockMutex(&thread->waitMutex);
1186 * If the interrupted flag is already set no additional action is
1189 if (thread->interrupted == true) {
1190 dvmUnlockMutex(&thread->waitMutex);
1195 * Raise the "interrupted" flag. This will cause it to bail early out
1196 * of the next wait() attempt, if it's not currently waiting on
1199 thread->interrupted = true;
1202 * Is the thread waiting?
1204 * Note that fat vs. thin doesn't matter here; waitMonitor
1205 * is only set when a thread actually waits on a monitor,
1206 * which implies that the monitor has already been fattened.
1208 if (thread->waitMonitor != NULL) {
1209 pthread_cond_signal(&thread->waitCond);
1212 dvmUnlockMutex(&thread->waitMutex);
1215 #ifndef WITH_COPYING_GC
1216 u4 dvmIdentityHashCode(Object *obj)
1222 * Returns the identity hash code of the given object.
1224 u4 dvmIdentityHashCode(Object *obj)
1226 Thread *self, *thread;
1229 u4 lock, owner, hashState;
1233 * Null is defined to have an identity hash code of 0.
1239 hashState = LW_HASH_STATE(*lw);
1240 if (hashState == LW_HASH_STATE_HASHED) {
1242 * The object has been hashed but has not had its hash code
1243 * relocated by the garbage collector. Use the raw object
1246 return (u4)obj >> 3;
1247 } else if (hashState == LW_HASH_STATE_HASHED_AND_MOVED) {
1249 * The object has been hashed and its hash code has been
1250 * relocated by the collector. Use the value of the naturally
1251 * aligned word following the instance data.
1253 assert(!dvmIsClassObject(obj));
1254 if (IS_CLASS_FLAG_SET(obj->clazz, CLASS_ISARRAY)) {
1255 size = dvmArrayObjectSize((ArrayObject *)obj);
1256 size = (size + 2) & ~2;
1258 size = obj->clazz->objectSize;
1260 return *(u4 *)(((char *)obj) + size);
1261 } else if (hashState == LW_HASH_STATE_UNHASHED) {
1263 * The object has never been hashed. Change the hash state to
1264 * hashed and use the raw object address.
1266 self = dvmThreadSelf();
1267 if (self->threadId == lockOwner(obj)) {
1269 * We already own the lock so we can update the hash state
1272 *lw |= (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1273 return (u4)obj >> 3;
1276 * We do not own the lock. Try acquiring the lock. Should
1277 * this fail, we must suspend the owning thread.
1279 if (LW_SHAPE(*lw) == LW_SHAPE_THIN) {
1281 * If the lock is thin assume it is unowned. We simulate
1282 * an acquire, update, and release with a single CAS.
1284 lock = (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1285 if (android_atomic_acquire_cas(
1288 (int32_t *)lw) == 0) {
1290 * A new lockword has been installed with a hash state
1291 * of hashed. Use the raw object address.
1293 return (u4)obj >> 3;
1296 if (tryLockMonitor(self, LW_MONITOR(*lw))) {
1298 * The monitor lock has been acquired. Change the
1299 * hash state to hashed and use the raw object
1302 *lw |= (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1303 unlockMonitor(self, LW_MONITOR(*lw));
1304 return (u4)obj >> 3;
1308 * At this point we have failed to acquire the lock. We must
1309 * identify the owning thread and suspend it.
1311 dvmLockThreadList(self);
1313 * Cache the lock word as its value can change between
1314 * determining its shape and retrieving its owner.
1317 if (LW_SHAPE(lock) == LW_SHAPE_THIN) {
1319 * Find the thread with the corresponding thread id.
1321 owner = LW_LOCK_OWNER(lock);
1322 assert(owner != self->threadId);
1324 * If the lock has no owner do not bother scanning the
1325 * thread list and fall through to the failure handler.
1327 thread = owner ? gDvm.threadList : NULL;
1328 while (thread != NULL) {
1329 if (thread->threadId == owner) {
1332 thread = thread->next;
1335 thread = LW_MONITOR(lock)->owner;
1338 * If thread is NULL the object has been released since the
1339 * thread list lock was acquired. Try again.
1341 if (thread == NULL) {
1342 dvmUnlockThreadList();
1346 * Wait for the owning thread to suspend.
1348 dvmSuspendThread(thread);
1349 if (dvmHoldsLock(thread, obj)) {
1351 * The owning thread has been suspended. We can safely
1352 * change the hash state to hashed.
1354 *lw |= (LW_HASH_STATE_HASHED << LW_HASH_STATE_SHIFT);
1355 dvmResumeThread(thread);
1356 dvmUnlockThreadList();
1357 return (u4)obj >> 3;
1360 * The wrong thread has been suspended. Try again.
1362 dvmResumeThread(thread);
1363 dvmUnlockThreadList();
1366 LOGE("object %p has an unknown hash state %#x", obj, hashState);
1367 dvmDumpThread(dvmThreadSelf(), false);
1369 return 0; /* Quiet the compiler. */
1371 #endif /* WITH_COPYING_GC */