blob: 8d6bd1904dcaf34d5bec5831741f635926513a18 [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);
Elliott Hughes5f791332011-09-15 17:45:30 -0700126}
127
128/*
129 * Links a thread into a monitor's wait set. The monitor lock must be
130 * held by the caller of this routine.
131 */
132void Monitor::AppendToWaitSet(Thread* thread) {
133 DCHECK(owner_ == Thread::Current());
134 DCHECK(thread != NULL);
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700135 DCHECK(thread->wait_next_ == NULL) << thread->wait_next_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700136 if (wait_set_ == NULL) {
137 wait_set_ = thread;
138 return;
139 }
140
141 // push_back.
142 Thread* t = wait_set_;
143 while (t->wait_next_ != NULL) {
144 t = t->wait_next_;
145 }
146 t->wait_next_ = thread;
147}
148
149/*
150 * Unlinks a thread from a monitor's wait set. The monitor lock must
151 * be held by the caller of this routine.
152 */
153void Monitor::RemoveFromWaitSet(Thread *thread) {
154 DCHECK(owner_ == Thread::Current());
155 DCHECK(thread != NULL);
156 if (wait_set_ == NULL) {
157 return;
158 }
159 if (wait_set_ == thread) {
160 wait_set_ = thread->wait_next_;
161 thread->wait_next_ = NULL;
162 return;
163 }
164
165 Thread* t = wait_set_;
166 while (t->wait_next_ != NULL) {
167 if (t->wait_next_ == thread) {
168 t->wait_next_ = thread->wait_next_;
169 thread->wait_next_ = NULL;
170 return;
171 }
172 t = t->wait_next_;
173 }
174}
175
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700176Object* Monitor::GetObject() {
177 return obj_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700178}
179
Elliott Hughes5f791332011-09-15 17:45:30 -0700180void Monitor::Lock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700181 if (owner_ == self) {
182 lock_count_++;
183 return;
184 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700185
186 uint64_t waitStart, waitEnd;
Elliott Hughes5f791332011-09-15 17:45:30 -0700187 if (!lock_.TryLock()) {
Elliott Hughesfc861622011-10-17 17:57:47 -0700188 uint32_t wait_threshold = lock_profiling_threshold_;
jeffhao33dc7712011-11-09 17:54:24 -0800189 const Method* current_locking_method = NULL;
Elliott Hughese65a6c92012-01-18 23:48:31 -0800190 uintptr_t current_locking_pc = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700191 {
192 ScopedThreadStateChange tsc(self, Thread::kBlocked);
Elliott Hughesfc861622011-10-17 17:57:47 -0700193 if (wait_threshold != 0) {
194 waitStart = NanoTime() / 1000;
195 }
jeffhao33dc7712011-11-09 17:54:24 -0800196 current_locking_method = locking_method_;
197 current_locking_pc = locking_pc_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700198
199 lock_.Lock();
Elliott Hughesfc861622011-10-17 17:57:47 -0700200 if (wait_threshold != 0) {
201 waitEnd = NanoTime() / 1000;
202 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700203 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700204
205 if (wait_threshold != 0) {
206 uint64_t wait_ms = (waitEnd - waitStart) / 1000;
207 uint32_t sample_percent;
208 if (wait_ms >= wait_threshold) {
209 sample_percent = 100;
210 } else {
211 sample_percent = 100 * wait_ms / wait_threshold;
212 }
213 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
jeffhao33dc7712011-11-09 17:54:24 -0800214 const char* current_locking_filename;
215 uint32_t current_locking_line_number;
216 TranslateLocation(current_locking_method, current_locking_pc,
217 current_locking_filename, current_locking_line_number);
218 LogContentionEvent(self, wait_ms, sample_percent, current_locking_filename, current_locking_line_number);
Elliott Hughesfc861622011-10-17 17:57:47 -0700219 }
220 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700221 }
222 owner_ = self;
223 DCHECK_EQ(lock_count_, 0);
224
225 // When debugging, save the current monitor holder for future
226 // acquisition failures to use in sampled logging.
Elliott Hughesfc861622011-10-17 17:57:47 -0700227 if (lock_profiling_threshold_ != 0) {
Elliott Hughesd07986f2011-12-06 18:27:45 -0800228 locking_method_ = self->GetCurrentMethod(&locking_pc_);
Elliott Hughesfc861622011-10-17 17:57:47 -0700229 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700230}
231
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800232static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
233 __attribute__((format(printf, 1, 2)));
234
235static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...) {
236 va_list args;
237 va_start(args, fmt);
238 Thread::Current()->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
239 va_end(args);
240}
241
242void Monitor::FailedUnlock(Object* obj, Thread* expected_owner, Thread* found_owner,
243 Monitor* mon) {
244 // Acquire thread list lock so threads won't disappear from under us
245 ScopedThreadListLock tll;
246 // Re-read owner now that we hold lock
247 Thread* current_owner = mon != NULL ? mon->owner_ : NULL;
248 std::ostringstream expected_ss;
249 expected_ss << expected_owner;
250 if (current_owner == NULL) {
251 if (found_owner == NULL) {
252 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
253 " on thread '%s'",
254 PrettyTypeOf(obj).c_str(), expected_ss.str().c_str());
255 } else {
256 // Race: the original read found an owner but now there is none
257 std::ostringstream found_ss;
258 found_ss << found_owner;
259 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
260 " (where now the monitor appears unowned) on thread '%s'",
261 found_ss.str().c_str(), PrettyTypeOf(obj).c_str(),
262 expected_ss.str().c_str());
263 }
264 } else {
265 std::ostringstream current_ss;
266 current_ss << current_owner;
267 if (found_owner == NULL) {
268 // Race: originally there was no owner, there is now
269 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
270 " (originally believed to be unowned) on thread '%s'",
271 current_ss.str().c_str(), PrettyTypeOf(obj).c_str(),
272 expected_ss.str().c_str());
273 } else {
274 if (found_owner != current_owner) {
275 // Race: originally found and current owner have changed
276 std::ostringstream found_ss;
277 found_ss << found_owner;
278 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
279 " owned by '%s') on object of type '%s' on thread '%s'",
280 found_ss.str().c_str(), current_ss.str().c_str(),
281 PrettyTypeOf(obj).c_str(), expected_ss.str().c_str());
282 } else {
283 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
284 " on thread '%s",
285 current_ss.str().c_str(), PrettyTypeOf(obj).c_str(),
286 expected_ss.str().c_str());
287 }
288 }
289 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700290}
291
292bool Monitor::Unlock(Thread* self) {
293 DCHECK(self != NULL);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800294 Thread* owner = owner_;
295 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700296 // We own the monitor, so nobody else can be in here.
297 if (lock_count_ == 0) {
298 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800299 locking_method_ = NULL;
300 locking_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700301 lock_.Unlock();
302 } else {
303 --lock_count_;
304 }
305 } else {
306 // We don't own this, so we're not allowed to unlock it.
307 // The JNI spec says that we should throw IllegalMonitorStateException
308 // in this case.
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800309 FailedUnlock(obj_, self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700310 return false;
311 }
312 return true;
313}
314
315/*
316 * Converts the given relative waiting time into an absolute time.
317 */
318void ToAbsoluteTime(int64_t ms, int32_t ns, struct timespec *ts) {
319 int64_t endSec;
320
321#ifdef HAVE_TIMEDWAIT_MONOTONIC
322 clock_gettime(CLOCK_MONOTONIC, ts);
323#else
324 {
325 struct timeval tv;
326 gettimeofday(&tv, NULL);
327 ts->tv_sec = tv.tv_sec;
328 ts->tv_nsec = tv.tv_usec * 1000;
329 }
330#endif
331 endSec = ts->tv_sec + ms / 1000;
332 if (endSec >= 0x7fffffff) {
333 LOG(INFO) << "Note: end time exceeds epoch";
334 endSec = 0x7ffffffe;
335 }
336 ts->tv_sec = endSec;
337 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
338
339 // Catch rollover.
340 if (ts->tv_nsec >= 1000000000L) {
341 ts->tv_sec++;
342 ts->tv_nsec -= 1000000000L;
343 }
344}
345
346int dvmRelativeCondWait(pthread_cond_t* cond, pthread_mutex_t* mutex, int64_t ms, int32_t ns) {
347 struct timespec ts;
348 ToAbsoluteTime(ms, ns, &ts);
349#if defined(HAVE_TIMEDWAIT_MONOTONIC)
350 int rc = pthread_cond_timedwait_monotonic(cond, mutex, &ts);
351#else
352 int rc = pthread_cond_timedwait(cond, mutex, &ts);
353#endif
354 DCHECK(rc == 0 || rc == ETIMEDOUT);
355 return rc;
356}
357
358/*
359 * Wait on a monitor until timeout, interrupt, or notification. Used for
360 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
361 *
362 * If another thread calls Thread.interrupt(), we throw InterruptedException
363 * and return immediately if one of the following are true:
364 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
365 * - blocked in join(), join(long), or join(long, int) methods of Thread
366 * - blocked in sleep(long), or sleep(long, int) methods of Thread
367 * Otherwise, we set the "interrupted" flag.
368 *
369 * Checks to make sure that "ns" is in the range 0-999999
370 * (i.e. fractions of a millisecond) and throws the appropriate
371 * exception if it isn't.
372 *
373 * The spec allows "spurious wakeups", and recommends that all code using
374 * Object.wait() do so in a loop. This appears to derive from concerns
375 * about pthread_cond_wait() on multiprocessor systems. Some commentary
376 * on the web casts doubt on whether these can/should occur.
377 *
378 * Since we're allowed to wake up "early", we clamp extremely long durations
379 * to return at the end of the 32-bit time epoch.
380 */
381void Monitor::Wait(Thread* self, int64_t ms, int32_t ns, bool interruptShouldThrow) {
382 DCHECK(self != NULL);
383
384 // Make sure that we hold the lock.
385 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800386 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700387 return;
388 }
389
390 // Enforce the timeout range.
391 if (ms < 0 || ns < 0 || ns > 999999) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700392 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Elliott Hughes5f791332011-09-15 17:45:30 -0700393 "timeout arguments out of range: ms=%lld ns=%d", ms, ns);
394 return;
395 }
396
397 // Compute absolute wakeup time, if necessary.
398 struct timespec ts;
399 bool timed = false;
400 if (ms != 0 || ns != 0) {
401 ToAbsoluteTime(ms, ns, &ts);
402 timed = true;
403 }
404
405 /*
406 * Add ourselves to the set of threads waiting on this monitor, and
407 * release our hold. We need to let it go even if we're a few levels
408 * deep in a recursive lock, and we need to restore that later.
409 *
410 * We append to the wait set ahead of clearing the count and owner
411 * fields so the subroutine can check that the calling thread owns
412 * the monitor. Aside from that, the order of member updates is
413 * not order sensitive as we hold the pthread mutex.
414 */
415 AppendToWaitSet(self);
416 int prevLockCount = lock_count_;
417 lock_count_ = 0;
418 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800419 const Method* savedMethod = locking_method_;
420 locking_method_ = NULL;
Elliott Hughese65a6c92012-01-18 23:48:31 -0800421 uintptr_t savedPc = locking_pc_;
jeffhao33dc7712011-11-09 17:54:24 -0800422 locking_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700423
424 /*
425 * Update thread status. If the GC wakes up, it'll ignore us, knowing
426 * that we won't touch any references in this state, and we'll check
427 * our suspend mode before we transition out.
428 */
429 if (timed) {
430 self->SetState(Thread::kTimedWaiting);
431 } else {
432 self->SetState(Thread::kWaiting);
433 }
434
Elliott Hughes85d15452011-09-16 17:33:01 -0700435 self->wait_mutex_->Lock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700436
437 /*
438 * Set wait_monitor_ to the monitor object we will be waiting on.
439 * When wait_monitor_ is non-NULL a notifying or interrupting thread
440 * must signal the thread's wait_cond_ to wake it up.
441 */
442 DCHECK(self->wait_monitor_ == NULL);
443 self->wait_monitor_ = this;
444
445 /*
446 * Handle the case where the thread was interrupted before we called
447 * wait().
448 */
449 bool wasInterrupted = false;
450 if (self->interrupted_) {
451 wasInterrupted = true;
452 self->wait_monitor_ = NULL;
Elliott Hughes85d15452011-09-16 17:33:01 -0700453 self->wait_mutex_->Unlock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700454 goto done;
455 }
456
457 /*
458 * Release the monitor lock and wait for a notification or
459 * a timeout to occur.
460 */
461 lock_.Unlock();
462
463 if (!timed) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700464 self->wait_cond_->Wait(*self->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700465 } else {
Elliott Hughes85d15452011-09-16 17:33:01 -0700466 self->wait_cond_->TimedWait(*self->wait_mutex_, ts);
Elliott Hughes5f791332011-09-15 17:45:30 -0700467 }
468 if (self->interrupted_) {
469 wasInterrupted = true;
470 }
471
472 self->interrupted_ = false;
473 self->wait_monitor_ = NULL;
Elliott Hughes85d15452011-09-16 17:33:01 -0700474 self->wait_mutex_->Unlock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700475
476 // Reacquire the monitor lock.
477 Lock(self);
478
479done:
480 /*
481 * We remove our thread from wait set after restoring the count
482 * and owner fields so the subroutine can check that the calling
483 * thread owns the monitor. Aside from that, the order of member
484 * updates is not order sensitive as we hold the pthread mutex.
485 */
486 owner_ = self;
487 lock_count_ = prevLockCount;
jeffhao33dc7712011-11-09 17:54:24 -0800488 locking_method_ = savedMethod;
489 locking_pc_ = savedPc;
Elliott Hughes5f791332011-09-15 17:45:30 -0700490 RemoveFromWaitSet(self);
491
492 /* set self->status back to Thread::kRunnable, and self-suspend if needed */
493 self->SetState(Thread::kRunnable);
494
495 if (wasInterrupted) {
496 /*
497 * We were interrupted while waiting, or somebody interrupted an
498 * un-interruptible thread earlier and we're bailing out immediately.
499 *
500 * The doc sayeth: "The interrupted status of the current thread is
501 * cleared when this exception is thrown."
502 */
503 self->interrupted_ = false;
504 if (interruptShouldThrow) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700505 Thread::Current()->ThrowNewException("Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700506 }
507 }
508}
509
510void Monitor::Notify(Thread* self) {
511 DCHECK(self != NULL);
512
513 // Make sure that we hold the lock.
514 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800515 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700516 return;
517 }
518 // Signal the first waiting thread in the wait set.
519 while (wait_set_ != NULL) {
520 Thread* thread = wait_set_;
521 wait_set_ = thread->wait_next_;
522 thread->wait_next_ = NULL;
523
524 // Check to see if the thread is still waiting.
Elliott Hughes85d15452011-09-16 17:33:01 -0700525 MutexLock mu(*thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700526 if (thread->wait_monitor_ != NULL) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700527 thread->wait_cond_->Signal();
Elliott Hughes5f791332011-09-15 17:45:30 -0700528 return;
529 }
530 }
531}
532
533void Monitor::NotifyAll(Thread* self) {
534 DCHECK(self != NULL);
535
536 // Make sure that we hold the lock.
537 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800538 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700539 return;
540 }
541 // Signal all threads in the wait set.
542 while (wait_set_ != NULL) {
543 Thread* thread = wait_set_;
544 wait_set_ = thread->wait_next_;
545 thread->wait_next_ = NULL;
546 thread->Notify();
547 }
548}
549
550/*
551 * Changes the shape of a monitor from thin to fat, preserving the
552 * internal lock state. The calling thread must own the lock.
553 */
554void Monitor::Inflate(Thread* self, Object* obj) {
555 DCHECK(self != NULL);
556 DCHECK(obj != NULL);
557 DCHECK_EQ(LW_SHAPE(*obj->GetRawLockWordAddress()), LW_SHAPE_THIN);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700558 DCHECK_EQ(LW_LOCK_OWNER(*obj->GetRawLockWordAddress()), static_cast<int32_t>(self->GetThinLockId()));
Elliott Hughes5f791332011-09-15 17:45:30 -0700559
560 // Allocate and acquire a new monitor.
561 Monitor* m = new Monitor(obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800562 VLOG(monitor) << "monitor: thread " << self->GetThinLockId()
563 << " created monitor " << m << " for object " << obj;
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700564 Runtime::Current()->GetMonitorList()->Add(m);
Elliott Hughes5f791332011-09-15 17:45:30 -0700565 m->Lock(self);
566 // Propagate the lock state.
567 uint32_t thin = *obj->GetRawLockWordAddress();
568 m->lock_count_ = LW_LOCK_COUNT(thin);
569 thin &= LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT;
570 thin |= reinterpret_cast<uint32_t>(m) | LW_SHAPE_FAT;
571 // Publish the updated lock word.
572 android_atomic_release_store(thin, obj->GetRawLockWordAddress());
573}
574
575void Monitor::MonitorEnter(Thread* self, Object* obj) {
576 volatile int32_t* thinp = obj->GetRawLockWordAddress();
577 struct timespec tm;
578 long sleepDelayNs;
579 long minSleepDelayNs = 1000000; /* 1 millisecond */
580 long maxSleepDelayNs = 1000000000; /* 1 second */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700581 uint32_t thin, newThin;
Elliott Hughes5f791332011-09-15 17:45:30 -0700582
Elliott Hughes4681c802011-09-25 18:04:37 -0700583 DCHECK(self != NULL);
584 DCHECK(obj != NULL);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700585 uint32_t threadId = self->GetThinLockId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700586retry:
587 thin = *thinp;
588 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
589 /*
590 * The lock is a thin lock. The owner field is used to
591 * determine the acquire method, ordered by cost.
592 */
593 if (LW_LOCK_OWNER(thin) == threadId) {
594 /*
595 * The calling thread owns the lock. Increment the
596 * value of the recursion count field.
597 */
598 *thinp += 1 << LW_LOCK_COUNT_SHIFT;
599 if (LW_LOCK_COUNT(*thinp) == LW_LOCK_COUNT_MASK) {
600 /*
601 * The reacquisition limit has been reached. Inflate
602 * the lock so the next acquire will not overflow the
603 * recursion count field.
604 */
605 Inflate(self, obj);
606 }
607 } else if (LW_LOCK_OWNER(thin) == 0) {
608 /*
609 * The lock is unowned. Install the thread id of the
610 * calling thread into the owner field. This is the
611 * common case. In performance critical code the JIT
612 * will have tried this before calling out to the VM.
613 */
614 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
615 if (android_atomic_acquire_cas(thin, newThin, thinp) != 0) {
616 // The acquire failed. Try again.
617 goto retry;
618 }
619 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800620 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p (a %s) owned by %d",
621 threadId, thinp, PrettyTypeOf(obj).c_str(), LW_LOCK_OWNER(thin));
Elliott Hughes5f791332011-09-15 17:45:30 -0700622 // The lock is owned by another thread. Notify the VM that we are about to wait.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700623 self->monitor_enter_object_ = obj;
Elliott Hughes5f791332011-09-15 17:45:30 -0700624 Thread::State oldStatus = self->SetState(Thread::kBlocked);
625 // Spin until the thin lock is released or inflated.
626 sleepDelayNs = 0;
627 for (;;) {
628 thin = *thinp;
629 // Check the shape of the lock word. Another thread
630 // may have inflated the lock while we were waiting.
631 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
632 if (LW_LOCK_OWNER(thin) == 0) {
633 // The lock has been released. Install the thread id of the
634 // calling thread into the owner field.
635 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
636 if (android_atomic_acquire_cas(thin, newThin, thinp) == 0) {
637 // The acquire succeed. Break out of the loop and proceed to inflate the lock.
638 break;
639 }
640 } else {
641 // The lock has not been released. Yield so the owning thread can run.
642 if (sleepDelayNs == 0) {
643 sched_yield();
644 sleepDelayNs = minSleepDelayNs;
645 } else {
646 tm.tv_sec = 0;
647 tm.tv_nsec = sleepDelayNs;
648 nanosleep(&tm, NULL);
649 // Prepare the next delay value. Wrap to avoid once a second polls for eternity.
650 if (sleepDelayNs < maxSleepDelayNs / 2) {
651 sleepDelayNs *= 2;
652 } else {
653 sleepDelayNs = minSleepDelayNs;
654 }
655 }
656 }
657 } else {
658 // The thin lock was inflated by another thread. Let the VM know we are no longer
659 // waiting and try again.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800660 VLOG(monitor) << "monitor: thread " << threadId
661 << " found lock " << (void*) thinp << " surprise-fattened by another thread";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700662 self->monitor_enter_object_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700663 self->SetState(oldStatus);
664 goto retry;
665 }
666 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800667 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p done", threadId, thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700668 // We have acquired the thin lock. Let the VM know that we are no longer waiting.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700669 self->monitor_enter_object_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700670 self->SetState(oldStatus);
671 // Fatten the lock.
672 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800673 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p", threadId, thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700674 }
675 } else {
676 // The lock is a fat lock.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800677 VLOG(monitor) << StringPrintf("monitor: thread %d locking fat lock %p (%p) %p on a %s",
Elliott Hughesf8e01272011-10-17 11:29:05 -0700678 threadId, thinp, LW_MONITOR(*thinp), (void*)*thinp, PrettyTypeOf(obj).c_str());
Elliott Hughes5f791332011-09-15 17:45:30 -0700679 DCHECK(LW_MONITOR(*thinp) != NULL);
680 LW_MONITOR(*thinp)->Lock(self);
681 }
682}
683
684bool Monitor::MonitorExit(Thread* self, Object* obj) {
685 volatile int32_t* thinp = obj->GetRawLockWordAddress();
686
687 DCHECK(self != NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -0700688 //DCHECK_EQ(self->GetState(), Thread::kRunnable);
Elliott Hughes5f791332011-09-15 17:45:30 -0700689 DCHECK(obj != NULL);
690
691 /*
692 * Cache the lock word as its value can change while we are
693 * examining its state.
694 */
695 uint32_t thin = *thinp;
696 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
697 /*
698 * The lock is thin. We must ensure that the lock is owned
699 * by the given thread before unlocking it.
700 */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700701 if (LW_LOCK_OWNER(thin) == self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700702 /*
703 * We are the lock owner. It is safe to update the lock
704 * without CAS as lock ownership guards the lock itself.
705 */
706 if (LW_LOCK_COUNT(thin) == 0) {
707 /*
708 * The lock was not recursively acquired, the common
709 * case. Unlock by clearing all bits except for the
710 * hash state.
711 */
712 thin &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
713 android_atomic_release_store(thin, thinp);
714 } else {
715 /*
716 * The object was recursively acquired. Decrement the
717 * lock recursion count field.
718 */
719 *thinp -= 1 << LW_LOCK_COUNT_SHIFT;
720 }
721 } else {
722 /*
723 * We do not own the lock. The JVM spec requires that we
724 * throw an exception in this case.
725 */
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800726 FailedUnlock(obj, self, NULL, NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700727 return false;
728 }
729 } else {
730 /*
731 * The lock is fat. We must check to see if Unlock has
732 * raised any exceptions before continuing.
733 */
734 DCHECK(LW_MONITOR(*thinp) != NULL);
735 if (!LW_MONITOR(*thinp)->Unlock(self)) {
736 // An exception has been raised. Do not fall through.
737 return false;
738 }
739 }
740 return true;
741}
742
743/*
744 * Object.wait(). Also called for class init.
745 */
746void Monitor::Wait(Thread* self, Object *obj, int64_t ms, int32_t ns, bool interruptShouldThrow) {
747 volatile int32_t* thinp = obj->GetRawLockWordAddress();
748
749 // If the lock is still thin, we need to fatten it.
750 uint32_t thin = *thinp;
751 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
752 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700753 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800754 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700755 return;
756 }
757
758 /* This thread holds the lock. We need to fatten the lock
759 * so 'self' can block on it. Don't update the object lock
760 * field yet, because 'self' needs to acquire the lock before
761 * any other thread gets a chance.
762 */
763 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800764 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p by wait()", self->GetThinLockId(), thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700765 }
766 LW_MONITOR(*thinp)->Wait(self, ms, ns, interruptShouldThrow);
767}
768
769void Monitor::Notify(Thread* self, Object *obj) {
770 uint32_t thin = *obj->GetRawLockWordAddress();
771
772 // If the lock is still thin, there aren't any waiters;
773 // waiting on an object forces lock fattening.
774 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
775 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700776 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800777 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700778 return;
779 }
780 // no-op; there are no waiters to notify.
781 } else {
782 // It's a fat lock.
783 LW_MONITOR(thin)->Notify(self);
784 }
785}
786
787void Monitor::NotifyAll(Thread* self, Object *obj) {
788 uint32_t thin = *obj->GetRawLockWordAddress();
789
790 // If the lock is still thin, there aren't any waiters;
791 // waiting on an object forces lock fattening.
792 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
793 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700794 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800795 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700796 return;
797 }
798 // no-op; there are no waiters to notify.
799 } else {
800 // It's a fat lock.
801 LW_MONITOR(thin)->NotifyAll(self);
802 }
803}
804
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700805uint32_t Monitor::GetThinLockId(uint32_t raw_lock_word) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700806 if (LW_SHAPE(raw_lock_word) == LW_SHAPE_THIN) {
807 return LW_LOCK_OWNER(raw_lock_word);
808 } else {
809 Thread* owner = LW_MONITOR(raw_lock_word)->owner_;
810 return owner ? owner->GetThinLockId() : 0;
811 }
812}
813
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700814void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
815 Thread::State state = thread->GetState();
816
817 Object* object = NULL;
818 uint32_t lock_owner = ThreadList::kInvalidId;
819 if (state == Thread::kWaiting || state == Thread::kTimedWaiting) {
820 os << " - waiting on ";
821 Monitor* monitor = thread->wait_monitor_;
822 if (monitor != NULL) {
823 object = monitor->obj_;
824 }
825 lock_owner = Thread::LockOwnerFromThreadLock(object);
826 } else if (state == Thread::kBlocked) {
827 os << " - waiting to lock ";
828 object = thread->monitor_enter_object_;
829 if (object != NULL) {
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700830 lock_owner = object->GetThinLockId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700831 }
832 } else {
833 // We're not waiting on anything.
834 return;
835 }
836 os << "<" << object << ">";
837
838 // - waiting on <0x613f83d8> (a java.lang.ThreadLock) held by thread 5
839 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
840 os << " (a " << PrettyTypeOf(object) << ")";
841
842 if (lock_owner != ThreadList::kInvalidId) {
843 os << " held by thread " << lock_owner;
844 }
845
846 os << "\n";
847}
848
jeffhao33dc7712011-11-09 17:54:24 -0800849void Monitor::TranslateLocation(const Method* method, uint32_t pc,
850 const char*& source_file, uint32_t& line_number) const {
851 // If method is null, location is unknown
852 if (method == NULL) {
Elliott Hughes12c51e32012-01-17 20:25:05 -0800853 source_file = "";
jeffhao33dc7712011-11-09 17:54:24 -0800854 line_number = 0;
855 return;
856 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800857 MethodHelper mh(method);
858 source_file = mh.GetDeclaringClassSourceFile();
Elliott Hughes12c51e32012-01-17 20:25:05 -0800859 if (source_file == NULL) {
860 source_file = "";
861 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800862 line_number = mh.GetLineNumFromNativePC(pc);
jeffhao33dc7712011-11-09 17:54:24 -0800863}
864
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700865MonitorList::MonitorList() : lock_("MonitorList lock") {
866}
867
868MonitorList::~MonitorList() {
869 MutexLock mu(lock_);
870 STLDeleteElements(&list_);
871}
872
873void MonitorList::Add(Monitor* m) {
874 MutexLock mu(lock_);
875 list_.push_front(m);
876}
877
878void MonitorList::SweepMonitorList(Heap::IsMarkedTester is_marked, void* arg) {
879 MutexLock mu(lock_);
880 typedef std::list<Monitor*>::iterator It; // TODO: C++0x auto
881 It it = list_.begin();
882 while (it != list_.end()) {
883 Monitor* m = *it;
884 if (!is_marked(m->GetObject(), arg)) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800885 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object " << m->GetObject();
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700886 delete m;
887 it = list_.erase(it);
888 } else {
889 ++it;
890 }
891 }
892}
893
Elliott Hughes5f791332011-09-15 17:45:30 -0700894} // namespace art