blob: caaa11618a5f4becc37242ede8181d47b8ce22b8 [file] [log] [blame]
Elliott Hughes5f791332011-09-15 17:45:30 -07001/*
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 */
16
Elliott Hughes54e7df12011-09-16 11:47:04 -070017#include "monitor.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070018
19#include <errno.h>
20#include <fcntl.h>
21#include <pthread.h>
22#include <stdlib.h>
23#include <sys/time.h>
24#include <time.h>
25#include <unistd.h>
26
jeffhao33dc7712011-11-09 17:54:24 -080027#include "class_linker.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070028#include "mutex.h"
29#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080030#include "object_utils.h"
Elliott Hughesc33a32b2011-10-11 18:18:07 -070031#include "stl_util.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070032#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070033#include "thread_list.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070034
35namespace art {
36
37/*
38 * Every Object has a monitor associated with it, but not every Object is
39 * actually locked. Even the ones that are locked do not need a
40 * full-fledged monitor until a) there is actual contention or b) wait()
41 * is called on the Object.
42 *
43 * For Android, we have implemented a scheme similar to the one described
44 * in Bacon et al.'s "Thin locks: featherweight synchronization for Java"
45 * (ACM 1998). Things are even easier for us, though, because we have
46 * a full 32 bits to work with.
47 *
48 * The two states of an Object's lock are referred to as "thin" and
49 * "fat". A lock may transition from the "thin" state to the "fat"
50 * state and this transition is referred to as inflation. Once a lock
51 * has been inflated it remains in the "fat" state indefinitely.
52 *
53 * The lock value itself is stored in Object.lock. The LSB of the
54 * lock encodes its state. When cleared, the lock is in the "thin"
55 * state and its bits are formatted as follows:
56 *
57 * [31 ---- 19] [18 ---- 3] [2 ---- 1] [0]
58 * lock count thread id hash state 0
59 *
60 * When set, the lock is in the "fat" state and its bits are formatted
61 * as follows:
62 *
63 * [31 ---- 3] [2 ---- 1] [0]
64 * pointer hash state 1
65 *
66 * For an in-depth description of the mechanics of thin-vs-fat locking,
67 * read the paper referred to above.
Elliott Hughes54e7df12011-09-16 11:47:04 -070068 *
Elliott Hughes5f791332011-09-15 17:45:30 -070069 * Monitors provide:
70 * - mutually exclusive access to resources
71 * - a way for multiple threads to wait for notification
72 *
73 * In effect, they fill the role of both mutexes and condition variables.
74 *
75 * Only one thread can own the monitor at any time. There may be several
76 * threads waiting on it (the wait call unlocks it). One or more waiting
77 * threads may be getting interrupted or notified at any given time.
78 *
79 * TODO: the various members of monitor are not SMP-safe.
80 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070081
82
83/*
84 * Monitor accessor. Extracts a monitor structure pointer from a fat
85 * lock. Performs no error checking.
86 */
87#define LW_MONITOR(x) \
88 ((Monitor*)((x) & ~((LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT) | LW_SHAPE_MASK)))
89
90/*
91 * Lock recursion count field. Contains a count of the number of times
92 * a lock has been recursively acquired.
93 */
94#define LW_LOCK_COUNT_MASK 0x1fff
95#define LW_LOCK_COUNT_SHIFT 19
96#define LW_LOCK_COUNT(x) (((x) >> LW_LOCK_COUNT_SHIFT) & LW_LOCK_COUNT_MASK)
97
Elliott Hughesfc861622011-10-17 17:57:47 -070098bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -070099uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700100
Elliott Hughesfc861622011-10-17 17:57:47 -0700101bool Monitor::IsSensitiveThread() {
102 if (is_sensitive_thread_hook_ != NULL) {
103 return (*is_sensitive_thread_hook_)();
104 }
105 return false;
106}
107
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800108void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughesfc861622011-10-17 17:57:47 -0700109 lock_profiling_threshold_ = lock_profiling_threshold;
110 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700111}
112
Elliott Hughes5f791332011-09-15 17:45:30 -0700113Monitor::Monitor(Object* obj)
114 : owner_(NULL),
115 lock_count_(0),
116 obj_(obj),
117 wait_set_(NULL),
118 lock_("a monitor lock"),
jeffhao33dc7712011-11-09 17:54:24 -0800119 locking_method_(NULL),
120 locking_pc_(0) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700121}
122
123Monitor::~Monitor() {
124 DCHECK(obj_ != NULL);
125 DCHECK_EQ(LW_SHAPE(*obj_->GetRawLockWordAddress()), LW_SHAPE_FAT);
126
127#ifndef NDEBUG
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700128 // This lock is associated with an object that's being swept.
129 bool locked = lock_.TryLock();
130 DCHECK(locked) << obj_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700131 lock_.Unlock();
132#endif
133}
134
135/*
136 * Links a thread into a monitor's wait set. The monitor lock must be
137 * held by the caller of this routine.
138 */
139void Monitor::AppendToWaitSet(Thread* thread) {
140 DCHECK(owner_ == Thread::Current());
141 DCHECK(thread != NULL);
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700142 DCHECK(thread->wait_next_ == NULL) << thread->wait_next_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700143 if (wait_set_ == NULL) {
144 wait_set_ = thread;
145 return;
146 }
147
148 // push_back.
149 Thread* t = wait_set_;
150 while (t->wait_next_ != NULL) {
151 t = t->wait_next_;
152 }
153 t->wait_next_ = thread;
154}
155
156/*
157 * Unlinks a thread from a monitor's wait set. The monitor lock must
158 * be held by the caller of this routine.
159 */
160void Monitor::RemoveFromWaitSet(Thread *thread) {
161 DCHECK(owner_ == Thread::Current());
162 DCHECK(thread != NULL);
163 if (wait_set_ == NULL) {
164 return;
165 }
166 if (wait_set_ == thread) {
167 wait_set_ = thread->wait_next_;
168 thread->wait_next_ = NULL;
169 return;
170 }
171
172 Thread* t = wait_set_;
173 while (t->wait_next_ != NULL) {
174 if (t->wait_next_ == thread) {
175 t->wait_next_ = thread->wait_next_;
176 thread->wait_next_ = NULL;
177 return;
178 }
179 t = t->wait_next_;
180 }
181}
182
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700183Object* Monitor::GetObject() {
184 return obj_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700185}
186
Elliott Hughes5f791332011-09-15 17:45:30 -0700187void Monitor::Lock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700188 if (owner_ == self) {
189 lock_count_++;
190 return;
191 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700192
193 uint64_t waitStart, waitEnd;
Elliott Hughes5f791332011-09-15 17:45:30 -0700194 if (!lock_.TryLock()) {
Elliott Hughesfc861622011-10-17 17:57:47 -0700195 uint32_t wait_threshold = lock_profiling_threshold_;
jeffhao33dc7712011-11-09 17:54:24 -0800196 const Method* current_locking_method = NULL;
197 uint32_t current_locking_pc = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700198 {
199 ScopedThreadStateChange tsc(self, Thread::kBlocked);
Elliott Hughesfc861622011-10-17 17:57:47 -0700200 if (wait_threshold != 0) {
201 waitStart = NanoTime() / 1000;
202 }
jeffhao33dc7712011-11-09 17:54:24 -0800203 current_locking_method = locking_method_;
204 current_locking_pc = locking_pc_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700205
206 lock_.Lock();
Elliott Hughesfc861622011-10-17 17:57:47 -0700207 if (wait_threshold != 0) {
208 waitEnd = NanoTime() / 1000;
209 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700210 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700211
212 if (wait_threshold != 0) {
213 uint64_t wait_ms = (waitEnd - waitStart) / 1000;
214 uint32_t sample_percent;
215 if (wait_ms >= wait_threshold) {
216 sample_percent = 100;
217 } else {
218 sample_percent = 100 * wait_ms / wait_threshold;
219 }
220 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
jeffhao33dc7712011-11-09 17:54:24 -0800221 const char* current_locking_filename;
222 uint32_t current_locking_line_number;
223 TranslateLocation(current_locking_method, current_locking_pc,
224 current_locking_filename, current_locking_line_number);
225 LogContentionEvent(self, wait_ms, sample_percent, current_locking_filename, current_locking_line_number);
Elliott Hughesfc861622011-10-17 17:57:47 -0700226 }
227 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700228 }
229 owner_ = self;
230 DCHECK_EQ(lock_count_, 0);
231
232 // When debugging, save the current monitor holder for future
233 // acquisition failures to use in sampled logging.
Elliott Hughesfc861622011-10-17 17:57:47 -0700234 if (lock_profiling_threshold_ != 0) {
Elliott Hughesd07986f2011-12-06 18:27:45 -0800235 locking_method_ = self->GetCurrentMethod(&locking_pc_);
Elliott Hughesfc861622011-10-17 17:57:47 -0700236 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700237}
238
239void ThrowIllegalMonitorStateException(const char* msg) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700240 Thread::Current()->ThrowNewException("Ljava/lang/IllegalMonitorStateException;", msg);
Elliott Hughes5f791332011-09-15 17:45:30 -0700241}
242
243bool Monitor::Unlock(Thread* self) {
244 DCHECK(self != NULL);
245 if (owner_ == self) {
246 // We own the monitor, so nobody else can be in here.
247 if (lock_count_ == 0) {
248 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800249 locking_method_ = NULL;
250 locking_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700251 lock_.Unlock();
252 } else {
253 --lock_count_;
254 }
255 } else {
256 // We don't own this, so we're not allowed to unlock it.
257 // The JNI spec says that we should throw IllegalMonitorStateException
258 // in this case.
259 ThrowIllegalMonitorStateException("unlock of unowned monitor");
260 return false;
261 }
262 return true;
263}
264
265/*
266 * Converts the given relative waiting time into an absolute time.
267 */
268void ToAbsoluteTime(int64_t ms, int32_t ns, struct timespec *ts) {
269 int64_t endSec;
270
271#ifdef HAVE_TIMEDWAIT_MONOTONIC
272 clock_gettime(CLOCK_MONOTONIC, ts);
273#else
274 {
275 struct timeval tv;
276 gettimeofday(&tv, NULL);
277 ts->tv_sec = tv.tv_sec;
278 ts->tv_nsec = tv.tv_usec * 1000;
279 }
280#endif
281 endSec = ts->tv_sec + ms / 1000;
282 if (endSec >= 0x7fffffff) {
283 LOG(INFO) << "Note: end time exceeds epoch";
284 endSec = 0x7ffffffe;
285 }
286 ts->tv_sec = endSec;
287 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
288
289 // Catch rollover.
290 if (ts->tv_nsec >= 1000000000L) {
291 ts->tv_sec++;
292 ts->tv_nsec -= 1000000000L;
293 }
294}
295
296int dvmRelativeCondWait(pthread_cond_t* cond, pthread_mutex_t* mutex, int64_t ms, int32_t ns) {
297 struct timespec ts;
298 ToAbsoluteTime(ms, ns, &ts);
299#if defined(HAVE_TIMEDWAIT_MONOTONIC)
300 int rc = pthread_cond_timedwait_monotonic(cond, mutex, &ts);
301#else
302 int rc = pthread_cond_timedwait(cond, mutex, &ts);
303#endif
304 DCHECK(rc == 0 || rc == ETIMEDOUT);
305 return rc;
306}
307
308/*
309 * Wait on a monitor until timeout, interrupt, or notification. Used for
310 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
311 *
312 * If another thread calls Thread.interrupt(), we throw InterruptedException
313 * and return immediately if one of the following are true:
314 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
315 * - blocked in join(), join(long), or join(long, int) methods of Thread
316 * - blocked in sleep(long), or sleep(long, int) methods of Thread
317 * Otherwise, we set the "interrupted" flag.
318 *
319 * Checks to make sure that "ns" is in the range 0-999999
320 * (i.e. fractions of a millisecond) and throws the appropriate
321 * exception if it isn't.
322 *
323 * The spec allows "spurious wakeups", and recommends that all code using
324 * Object.wait() do so in a loop. This appears to derive from concerns
325 * about pthread_cond_wait() on multiprocessor systems. Some commentary
326 * on the web casts doubt on whether these can/should occur.
327 *
328 * Since we're allowed to wake up "early", we clamp extremely long durations
329 * to return at the end of the 32-bit time epoch.
330 */
331void Monitor::Wait(Thread* self, int64_t ms, int32_t ns, bool interruptShouldThrow) {
332 DCHECK(self != NULL);
333
334 // Make sure that we hold the lock.
335 if (owner_ != self) {
336 ThrowIllegalMonitorStateException("object not locked by thread before wait()");
337 return;
338 }
339
340 // Enforce the timeout range.
341 if (ms < 0 || ns < 0 || ns > 999999) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700342 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Elliott Hughes5f791332011-09-15 17:45:30 -0700343 "timeout arguments out of range: ms=%lld ns=%d", ms, ns);
344 return;
345 }
346
347 // Compute absolute wakeup time, if necessary.
348 struct timespec ts;
349 bool timed = false;
350 if (ms != 0 || ns != 0) {
351 ToAbsoluteTime(ms, ns, &ts);
352 timed = true;
353 }
354
355 /*
356 * Add ourselves to the set of threads waiting on this monitor, and
357 * release our hold. We need to let it go even if we're a few levels
358 * deep in a recursive lock, and we need to restore that later.
359 *
360 * We append to the wait set ahead of clearing the count and owner
361 * fields so the subroutine can check that the calling thread owns
362 * the monitor. Aside from that, the order of member updates is
363 * not order sensitive as we hold the pthread mutex.
364 */
365 AppendToWaitSet(self);
366 int prevLockCount = lock_count_;
367 lock_count_ = 0;
368 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800369 const Method* savedMethod = locking_method_;
370 locking_method_ = NULL;
371 uint32_t savedPc = locking_pc_;
372 locking_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700373
374 /*
375 * Update thread status. If the GC wakes up, it'll ignore us, knowing
376 * that we won't touch any references in this state, and we'll check
377 * our suspend mode before we transition out.
378 */
379 if (timed) {
380 self->SetState(Thread::kTimedWaiting);
381 } else {
382 self->SetState(Thread::kWaiting);
383 }
384
Elliott Hughes85d15452011-09-16 17:33:01 -0700385 self->wait_mutex_->Lock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700386
387 /*
388 * Set wait_monitor_ to the monitor object we will be waiting on.
389 * When wait_monitor_ is non-NULL a notifying or interrupting thread
390 * must signal the thread's wait_cond_ to wake it up.
391 */
392 DCHECK(self->wait_monitor_ == NULL);
393 self->wait_monitor_ = this;
394
395 /*
396 * Handle the case where the thread was interrupted before we called
397 * wait().
398 */
399 bool wasInterrupted = false;
400 if (self->interrupted_) {
401 wasInterrupted = true;
402 self->wait_monitor_ = NULL;
Elliott Hughes85d15452011-09-16 17:33:01 -0700403 self->wait_mutex_->Unlock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700404 goto done;
405 }
406
407 /*
408 * Release the monitor lock and wait for a notification or
409 * a timeout to occur.
410 */
411 lock_.Unlock();
412
413 if (!timed) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700414 self->wait_cond_->Wait(*self->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700415 } else {
Elliott Hughes85d15452011-09-16 17:33:01 -0700416 self->wait_cond_->TimedWait(*self->wait_mutex_, ts);
Elliott Hughes5f791332011-09-15 17:45:30 -0700417 }
418 if (self->interrupted_) {
419 wasInterrupted = true;
420 }
421
422 self->interrupted_ = false;
423 self->wait_monitor_ = NULL;
Elliott Hughes85d15452011-09-16 17:33:01 -0700424 self->wait_mutex_->Unlock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700425
426 // Reacquire the monitor lock.
427 Lock(self);
428
429done:
430 /*
431 * We remove our thread from wait set after restoring the count
432 * and owner fields so the subroutine can check that the calling
433 * thread owns the monitor. Aside from that, the order of member
434 * updates is not order sensitive as we hold the pthread mutex.
435 */
436 owner_ = self;
437 lock_count_ = prevLockCount;
jeffhao33dc7712011-11-09 17:54:24 -0800438 locking_method_ = savedMethod;
439 locking_pc_ = savedPc;
Elliott Hughes5f791332011-09-15 17:45:30 -0700440 RemoveFromWaitSet(self);
441
442 /* set self->status back to Thread::kRunnable, and self-suspend if needed */
443 self->SetState(Thread::kRunnable);
444
445 if (wasInterrupted) {
446 /*
447 * We were interrupted while waiting, or somebody interrupted an
448 * un-interruptible thread earlier and we're bailing out immediately.
449 *
450 * The doc sayeth: "The interrupted status of the current thread is
451 * cleared when this exception is thrown."
452 */
453 self->interrupted_ = false;
454 if (interruptShouldThrow) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700455 Thread::Current()->ThrowNewException("Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700456 }
457 }
458}
459
460void Monitor::Notify(Thread* self) {
461 DCHECK(self != NULL);
462
463 // Make sure that we hold the lock.
464 if (owner_ != self) {
465 ThrowIllegalMonitorStateException("object not locked by thread before notify()");
466 return;
467 }
468 // Signal the first waiting thread in the wait set.
469 while (wait_set_ != NULL) {
470 Thread* thread = wait_set_;
471 wait_set_ = thread->wait_next_;
472 thread->wait_next_ = NULL;
473
474 // Check to see if the thread is still waiting.
Elliott Hughes85d15452011-09-16 17:33:01 -0700475 MutexLock mu(*thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700476 if (thread->wait_monitor_ != NULL) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700477 thread->wait_cond_->Signal();
Elliott Hughes5f791332011-09-15 17:45:30 -0700478 return;
479 }
480 }
481}
482
483void Monitor::NotifyAll(Thread* self) {
484 DCHECK(self != NULL);
485
486 // Make sure that we hold the lock.
487 if (owner_ != self) {
488 ThrowIllegalMonitorStateException("object not locked by thread before notifyAll()");
489 return;
490 }
491 // Signal all threads in the wait set.
492 while (wait_set_ != NULL) {
493 Thread* thread = wait_set_;
494 wait_set_ = thread->wait_next_;
495 thread->wait_next_ = NULL;
496 thread->Notify();
497 }
498}
499
500/*
501 * Changes the shape of a monitor from thin to fat, preserving the
502 * internal lock state. The calling thread must own the lock.
503 */
504void Monitor::Inflate(Thread* self, Object* obj) {
505 DCHECK(self != NULL);
506 DCHECK(obj != NULL);
507 DCHECK_EQ(LW_SHAPE(*obj->GetRawLockWordAddress()), LW_SHAPE_THIN);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700508 DCHECK_EQ(LW_LOCK_OWNER(*obj->GetRawLockWordAddress()), static_cast<int32_t>(self->GetThinLockId()));
Elliott Hughes5f791332011-09-15 17:45:30 -0700509
510 // Allocate and acquire a new monitor.
511 Monitor* m = new Monitor(obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800512 VLOG(monitor) << "monitor: thread " << self->GetThinLockId()
513 << " created monitor " << m << " for object " << obj;
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700514 Runtime::Current()->GetMonitorList()->Add(m);
Elliott Hughes5f791332011-09-15 17:45:30 -0700515 m->Lock(self);
516 // Propagate the lock state.
517 uint32_t thin = *obj->GetRawLockWordAddress();
518 m->lock_count_ = LW_LOCK_COUNT(thin);
519 thin &= LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT;
520 thin |= reinterpret_cast<uint32_t>(m) | LW_SHAPE_FAT;
521 // Publish the updated lock word.
522 android_atomic_release_store(thin, obj->GetRawLockWordAddress());
523}
524
525void Monitor::MonitorEnter(Thread* self, Object* obj) {
526 volatile int32_t* thinp = obj->GetRawLockWordAddress();
527 struct timespec tm;
528 long sleepDelayNs;
529 long minSleepDelayNs = 1000000; /* 1 millisecond */
530 long maxSleepDelayNs = 1000000000; /* 1 second */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700531 uint32_t thin, newThin;
Elliott Hughes5f791332011-09-15 17:45:30 -0700532
Elliott Hughes4681c802011-09-25 18:04:37 -0700533 DCHECK(self != NULL);
534 DCHECK(obj != NULL);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700535 uint32_t threadId = self->GetThinLockId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700536retry:
537 thin = *thinp;
538 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
539 /*
540 * The lock is a thin lock. The owner field is used to
541 * determine the acquire method, ordered by cost.
542 */
543 if (LW_LOCK_OWNER(thin) == threadId) {
544 /*
545 * The calling thread owns the lock. Increment the
546 * value of the recursion count field.
547 */
548 *thinp += 1 << LW_LOCK_COUNT_SHIFT;
549 if (LW_LOCK_COUNT(*thinp) == LW_LOCK_COUNT_MASK) {
550 /*
551 * The reacquisition limit has been reached. Inflate
552 * the lock so the next acquire will not overflow the
553 * recursion count field.
554 */
555 Inflate(self, obj);
556 }
557 } else if (LW_LOCK_OWNER(thin) == 0) {
558 /*
559 * The lock is unowned. Install the thread id of the
560 * calling thread into the owner field. This is the
561 * common case. In performance critical code the JIT
562 * will have tried this before calling out to the VM.
563 */
564 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
565 if (android_atomic_acquire_cas(thin, newThin, thinp) != 0) {
566 // The acquire failed. Try again.
567 goto retry;
568 }
569 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800570 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p (a %s) owned by %d",
571 threadId, thinp, PrettyTypeOf(obj).c_str(), LW_LOCK_OWNER(thin));
Elliott Hughes5f791332011-09-15 17:45:30 -0700572 // The lock is owned by another thread. Notify the VM that we are about to wait.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700573 self->monitor_enter_object_ = obj;
Elliott Hughes5f791332011-09-15 17:45:30 -0700574 Thread::State oldStatus = self->SetState(Thread::kBlocked);
575 // Spin until the thin lock is released or inflated.
576 sleepDelayNs = 0;
577 for (;;) {
578 thin = *thinp;
579 // Check the shape of the lock word. Another thread
580 // may have inflated the lock while we were waiting.
581 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
582 if (LW_LOCK_OWNER(thin) == 0) {
583 // The lock has been released. Install the thread id of the
584 // calling thread into the owner field.
585 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
586 if (android_atomic_acquire_cas(thin, newThin, thinp) == 0) {
587 // The acquire succeed. Break out of the loop and proceed to inflate the lock.
588 break;
589 }
590 } else {
591 // The lock has not been released. Yield so the owning thread can run.
592 if (sleepDelayNs == 0) {
593 sched_yield();
594 sleepDelayNs = minSleepDelayNs;
595 } else {
596 tm.tv_sec = 0;
597 tm.tv_nsec = sleepDelayNs;
598 nanosleep(&tm, NULL);
599 // Prepare the next delay value. Wrap to avoid once a second polls for eternity.
600 if (sleepDelayNs < maxSleepDelayNs / 2) {
601 sleepDelayNs *= 2;
602 } else {
603 sleepDelayNs = minSleepDelayNs;
604 }
605 }
606 }
607 } else {
608 // The thin lock was inflated by another thread. Let the VM know we are no longer
609 // waiting and try again.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800610 VLOG(monitor) << "monitor: thread " << threadId
611 << " found lock " << (void*) thinp << " surprise-fattened by another thread";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700612 self->monitor_enter_object_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700613 self->SetState(oldStatus);
614 goto retry;
615 }
616 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800617 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p done", threadId, thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700618 // We have acquired the thin lock. Let the VM know that we are no longer waiting.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700619 self->monitor_enter_object_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700620 self->SetState(oldStatus);
621 // Fatten the lock.
622 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800623 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p", threadId, thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700624 }
625 } else {
626 // The lock is a fat lock.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800627 VLOG(monitor) << StringPrintf("monitor: thread %d locking fat lock %p (%p) %p on a %s",
Elliott Hughesf8e01272011-10-17 11:29:05 -0700628 threadId, thinp, LW_MONITOR(*thinp), (void*)*thinp, PrettyTypeOf(obj).c_str());
Elliott Hughes5f791332011-09-15 17:45:30 -0700629 DCHECK(LW_MONITOR(*thinp) != NULL);
630 LW_MONITOR(*thinp)->Lock(self);
631 }
632}
633
634bool Monitor::MonitorExit(Thread* self, Object* obj) {
635 volatile int32_t* thinp = obj->GetRawLockWordAddress();
636
637 DCHECK(self != NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -0700638 //DCHECK_EQ(self->GetState(), Thread::kRunnable);
Elliott Hughes5f791332011-09-15 17:45:30 -0700639 DCHECK(obj != NULL);
640
641 /*
642 * Cache the lock word as its value can change while we are
643 * examining its state.
644 */
645 uint32_t thin = *thinp;
646 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
647 /*
648 * The lock is thin. We must ensure that the lock is owned
649 * by the given thread before unlocking it.
650 */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700651 if (LW_LOCK_OWNER(thin) == self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700652 /*
653 * We are the lock owner. It is safe to update the lock
654 * without CAS as lock ownership guards the lock itself.
655 */
656 if (LW_LOCK_COUNT(thin) == 0) {
657 /*
658 * The lock was not recursively acquired, the common
659 * case. Unlock by clearing all bits except for the
660 * hash state.
661 */
662 thin &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
663 android_atomic_release_store(thin, thinp);
664 } else {
665 /*
666 * The object was recursively acquired. Decrement the
667 * lock recursion count field.
668 */
669 *thinp -= 1 << LW_LOCK_COUNT_SHIFT;
670 }
671 } else {
672 /*
673 * We do not own the lock. The JVM spec requires that we
674 * throw an exception in this case.
675 */
676 ThrowIllegalMonitorStateException("unlock of unowned monitor");
677 return false;
678 }
679 } else {
680 /*
681 * The lock is fat. We must check to see if Unlock has
682 * raised any exceptions before continuing.
683 */
684 DCHECK(LW_MONITOR(*thinp) != NULL);
685 if (!LW_MONITOR(*thinp)->Unlock(self)) {
686 // An exception has been raised. Do not fall through.
687 return false;
688 }
689 }
690 return true;
691}
692
693/*
694 * Object.wait(). Also called for class init.
695 */
696void Monitor::Wait(Thread* self, Object *obj, int64_t ms, int32_t ns, bool interruptShouldThrow) {
697 volatile int32_t* thinp = obj->GetRawLockWordAddress();
698
699 // If the lock is still thin, we need to fatten it.
700 uint32_t thin = *thinp;
701 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
702 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700703 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700704 ThrowIllegalMonitorStateException("object not locked by thread before wait()");
705 return;
706 }
707
708 /* This thread holds the lock. We need to fatten the lock
709 * so 'self' can block on it. Don't update the object lock
710 * field yet, because 'self' needs to acquire the lock before
711 * any other thread gets a chance.
712 */
713 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800714 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p by wait()", self->GetThinLockId(), thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700715 }
716 LW_MONITOR(*thinp)->Wait(self, ms, ns, interruptShouldThrow);
717}
718
719void Monitor::Notify(Thread* self, Object *obj) {
720 uint32_t thin = *obj->GetRawLockWordAddress();
721
722 // If the lock is still thin, there aren't any waiters;
723 // waiting on an object forces lock fattening.
724 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
725 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700726 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700727 ThrowIllegalMonitorStateException("object not locked by thread before notify()");
728 return;
729 }
730 // no-op; there are no waiters to notify.
731 } else {
732 // It's a fat lock.
733 LW_MONITOR(thin)->Notify(self);
734 }
735}
736
737void Monitor::NotifyAll(Thread* self, Object *obj) {
738 uint32_t thin = *obj->GetRawLockWordAddress();
739
740 // If the lock is still thin, there aren't any waiters;
741 // waiting on an object forces lock fattening.
742 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
743 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700744 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700745 ThrowIllegalMonitorStateException("object not locked by thread before notifyAll()");
746 return;
747 }
748 // no-op; there are no waiters to notify.
749 } else {
750 // It's a fat lock.
751 LW_MONITOR(thin)->NotifyAll(self);
752 }
753}
754
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700755uint32_t Monitor::GetThinLockId(uint32_t raw_lock_word) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700756 if (LW_SHAPE(raw_lock_word) == LW_SHAPE_THIN) {
757 return LW_LOCK_OWNER(raw_lock_word);
758 } else {
759 Thread* owner = LW_MONITOR(raw_lock_word)->owner_;
760 return owner ? owner->GetThinLockId() : 0;
761 }
762}
763
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700764void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
765 Thread::State state = thread->GetState();
766
767 Object* object = NULL;
768 uint32_t lock_owner = ThreadList::kInvalidId;
769 if (state == Thread::kWaiting || state == Thread::kTimedWaiting) {
770 os << " - waiting on ";
771 Monitor* monitor = thread->wait_monitor_;
772 if (monitor != NULL) {
773 object = monitor->obj_;
774 }
775 lock_owner = Thread::LockOwnerFromThreadLock(object);
776 } else if (state == Thread::kBlocked) {
777 os << " - waiting to lock ";
778 object = thread->monitor_enter_object_;
779 if (object != NULL) {
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700780 lock_owner = object->GetThinLockId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700781 }
782 } else {
783 // We're not waiting on anything.
784 return;
785 }
786 os << "<" << object << ">";
787
788 // - waiting on <0x613f83d8> (a java.lang.ThreadLock) held by thread 5
789 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
790 os << " (a " << PrettyTypeOf(object) << ")";
791
792 if (lock_owner != ThreadList::kInvalidId) {
793 os << " held by thread " << lock_owner;
794 }
795
796 os << "\n";
797}
798
jeffhao33dc7712011-11-09 17:54:24 -0800799void Monitor::TranslateLocation(const Method* method, uint32_t pc,
800 const char*& source_file, uint32_t& line_number) const {
801 // If method is null, location is unknown
802 if (method == NULL) {
803 source_file = "unknown";
804 line_number = 0;
805 return;
806 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800807 MethodHelper mh(method);
808 source_file = mh.GetDeclaringClassSourceFile();
809 line_number = mh.GetLineNumFromNativePC(pc);
jeffhao33dc7712011-11-09 17:54:24 -0800810}
811
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700812MonitorList::MonitorList() : lock_("MonitorList lock") {
813}
814
815MonitorList::~MonitorList() {
816 MutexLock mu(lock_);
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700817
818 // In case there is a daemon thread with the monitor locked, clear
819 // the owner here so we can destroy the mutex, which will otherwise
820 // fail in pthread_mutex_destroy.
821 typedef std::list<Monitor*>::iterator It; // TODO: C++0x auto
822 for (It it = list_.begin(); it != list_.end(); it++) {
823 Monitor* monitor = *it;
824 Mutex& lock = monitor->lock_;
825 if (lock.GetOwner() != 0) {
826 DCHECK_EQ(lock.GetOwner(), monitor->owner_->GetTid());
827 lock.ClearOwner();
828 }
829 }
830
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700831 STLDeleteElements(&list_);
832}
833
834void MonitorList::Add(Monitor* m) {
835 MutexLock mu(lock_);
836 list_.push_front(m);
837}
838
839void MonitorList::SweepMonitorList(Heap::IsMarkedTester is_marked, void* arg) {
840 MutexLock mu(lock_);
841 typedef std::list<Monitor*>::iterator It; // TODO: C++0x auto
842 It it = list_.begin();
843 while (it != list_.end()) {
844 Monitor* m = *it;
845 if (!is_marked(m->GetObject(), arg)) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800846 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object " << m->GetObject();
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700847 delete m;
848 it = list_.erase(it);
849 } else {
850 ++it;
851 }
852 }
853}
854
Elliott Hughes5f791332011-09-15 17:45:30 -0700855} // namespace art