blob: 68870109f7ccd8b7787f5f262653724ed097f0b1 [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 Hughes88c5c352012-03-15 18:49:48 -070031#include "scoped_thread_list_lock.h"
Elliott Hughesc33a32b2011-10-11 18:18:07 -070032#include "stl_util.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070033#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070034#include "thread_list.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070035
36namespace art {
37
38/*
39 * Every Object has a monitor associated with it, but not every Object is
40 * actually locked. Even the ones that are locked do not need a
41 * full-fledged monitor until a) there is actual contention or b) wait()
42 * is called on the Object.
43 *
44 * For Android, we have implemented a scheme similar to the one described
45 * in Bacon et al.'s "Thin locks: featherweight synchronization for Java"
46 * (ACM 1998). Things are even easier for us, though, because we have
47 * a full 32 bits to work with.
48 *
49 * The two states of an Object's lock are referred to as "thin" and
50 * "fat". A lock may transition from the "thin" state to the "fat"
51 * state and this transition is referred to as inflation. Once a lock
52 * has been inflated it remains in the "fat" state indefinitely.
53 *
54 * The lock value itself is stored in Object.lock. The LSB of the
55 * lock encodes its state. When cleared, the lock is in the "thin"
56 * state and its bits are formatted as follows:
57 *
58 * [31 ---- 19] [18 ---- 3] [2 ---- 1] [0]
59 * lock count thread id hash state 0
60 *
61 * When set, the lock is in the "fat" state and its bits are formatted
62 * as follows:
63 *
64 * [31 ---- 3] [2 ---- 1] [0]
65 * pointer hash state 1
66 *
67 * For an in-depth description of the mechanics of thin-vs-fat locking,
68 * read the paper referred to above.
Elliott Hughes54e7df12011-09-16 11:47:04 -070069 *
Elliott Hughes5f791332011-09-15 17:45:30 -070070 * Monitors provide:
71 * - mutually exclusive access to resources
72 * - a way for multiple threads to wait for notification
73 *
74 * In effect, they fill the role of both mutexes and condition variables.
75 *
76 * Only one thread can own the monitor at any time. There may be several
77 * threads waiting on it (the wait call unlocks it). One or more waiting
78 * threads may be getting interrupted or notified at any given time.
79 *
80 * TODO: the various members of monitor are not SMP-safe.
81 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070082
83
84/*
85 * Monitor accessor. Extracts a monitor structure pointer from a fat
86 * lock. Performs no error checking.
87 */
88#define LW_MONITOR(x) \
Elliott Hughes398f64b2012-03-26 18:05:48 -070089 (reinterpret_cast<Monitor*>((x) & ~((LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT) | LW_SHAPE_MASK)))
Elliott Hughes54e7df12011-09-16 11:47:04 -070090
91/*
92 * Lock recursion count field. Contains a count of the number of times
93 * a lock has been recursively acquired.
94 */
95#define LW_LOCK_COUNT_MASK 0x1fff
96#define LW_LOCK_COUNT_SHIFT 19
97#define LW_LOCK_COUNT(x) (((x) >> LW_LOCK_COUNT_SHIFT) & LW_LOCK_COUNT_MASK)
98
Elliott Hughesfc861622011-10-17 17:57:47 -070099bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -0700100uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700101
Elliott Hughesfc861622011-10-17 17:57:47 -0700102bool Monitor::IsSensitiveThread() {
103 if (is_sensitive_thread_hook_ != NULL) {
104 return (*is_sensitive_thread_hook_)();
105 }
106 return false;
107}
108
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800109void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughesfc861622011-10-17 17:57:47 -0700110 lock_profiling_threshold_ = lock_profiling_threshold;
111 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700112}
113
Elliott Hughes5f791332011-09-15 17:45:30 -0700114Monitor::Monitor(Object* obj)
115 : owner_(NULL),
116 lock_count_(0),
117 obj_(obj),
118 wait_set_(NULL),
119 lock_("a monitor lock"),
jeffhao33dc7712011-11-09 17:54:24 -0800120 locking_method_(NULL),
121 locking_pc_(0) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700122}
123
124Monitor::~Monitor() {
125 DCHECK(obj_ != NULL);
126 DCHECK_EQ(LW_SHAPE(*obj_->GetRawLockWordAddress()), LW_SHAPE_FAT);
Elliott Hughes5f791332011-09-15 17:45:30 -0700127}
128
129/*
130 * Links a thread into a monitor's wait set. The monitor lock must be
131 * held by the caller of this routine.
132 */
133void Monitor::AppendToWaitSet(Thread* thread) {
134 DCHECK(owner_ == Thread::Current());
135 DCHECK(thread != NULL);
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700136 DCHECK(thread->wait_next_ == NULL) << thread->wait_next_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700137 if (wait_set_ == NULL) {
138 wait_set_ = thread;
139 return;
140 }
141
142 // push_back.
143 Thread* t = wait_set_;
144 while (t->wait_next_ != NULL) {
145 t = t->wait_next_;
146 }
147 t->wait_next_ = thread;
148}
149
150/*
151 * Unlinks a thread from a monitor's wait set. The monitor lock must
152 * be held by the caller of this routine.
153 */
154void Monitor::RemoveFromWaitSet(Thread *thread) {
155 DCHECK(owner_ == Thread::Current());
156 DCHECK(thread != NULL);
157 if (wait_set_ == NULL) {
158 return;
159 }
160 if (wait_set_ == thread) {
161 wait_set_ = thread->wait_next_;
162 thread->wait_next_ = NULL;
163 return;
164 }
165
166 Thread* t = wait_set_;
167 while (t->wait_next_ != NULL) {
168 if (t->wait_next_ == thread) {
169 t->wait_next_ = thread->wait_next_;
170 thread->wait_next_ = NULL;
171 return;
172 }
173 t = t->wait_next_;
174 }
175}
176
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700177Object* Monitor::GetObject() {
178 return obj_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700179}
180
Elliott Hughes5f791332011-09-15 17:45:30 -0700181void Monitor::Lock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700182 if (owner_ == self) {
183 lock_count_++;
184 return;
185 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700186
187 uint64_t waitStart, waitEnd;
Elliott Hughes5f791332011-09-15 17:45:30 -0700188 if (!lock_.TryLock()) {
Elliott Hughesfc861622011-10-17 17:57:47 -0700189 uint32_t wait_threshold = lock_profiling_threshold_;
jeffhao33dc7712011-11-09 17:54:24 -0800190 const Method* current_locking_method = NULL;
Elliott Hughese65a6c92012-01-18 23:48:31 -0800191 uintptr_t current_locking_pc = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700192 {
193 ScopedThreadStateChange tsc(self, Thread::kBlocked);
Elliott Hughesfc861622011-10-17 17:57:47 -0700194 if (wait_threshold != 0) {
195 waitStart = NanoTime() / 1000;
196 }
jeffhao33dc7712011-11-09 17:54:24 -0800197 current_locking_method = locking_method_;
198 current_locking_pc = locking_pc_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700199
200 lock_.Lock();
Elliott Hughesfc861622011-10-17 17:57:47 -0700201 if (wait_threshold != 0) {
202 waitEnd = NanoTime() / 1000;
203 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700204 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700205
206 if (wait_threshold != 0) {
207 uint64_t wait_ms = (waitEnd - waitStart) / 1000;
208 uint32_t sample_percent;
209 if (wait_ms >= wait_threshold) {
210 sample_percent = 100;
211 } else {
212 sample_percent = 100 * wait_ms / wait_threshold;
213 }
214 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
jeffhao33dc7712011-11-09 17:54:24 -0800215 const char* current_locking_filename;
216 uint32_t current_locking_line_number;
217 TranslateLocation(current_locking_method, current_locking_pc,
218 current_locking_filename, current_locking_line_number);
219 LogContentionEvent(self, wait_ms, sample_percent, current_locking_filename, current_locking_line_number);
Elliott Hughesfc861622011-10-17 17:57:47 -0700220 }
221 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700222 }
223 owner_ = self;
224 DCHECK_EQ(lock_count_, 0);
225
226 // When debugging, save the current monitor holder for future
227 // acquisition failures to use in sampled logging.
Elliott Hughesfc861622011-10-17 17:57:47 -0700228 if (lock_profiling_threshold_ != 0) {
Elliott Hughesd07986f2011-12-06 18:27:45 -0800229 locking_method_ = self->GetCurrentMethod(&locking_pc_);
Elliott Hughesfc861622011-10-17 17:57:47 -0700230 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700231}
232
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800233static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
234 __attribute__((format(printf, 1, 2)));
235
236static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...) {
237 va_list args;
238 va_start(args, fmt);
239 Thread::Current()->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
240 va_end(args);
241}
242
Elliott Hughesd4237412012-02-21 11:24:45 -0800243static std::string ThreadToString(Thread* thread) {
244 if (thread == NULL) {
245 return "NULL";
246 }
247 std::ostringstream oss;
248 // TODO: alternatively, we could just return the thread's name.
249 oss << *thread;
250 return oss.str();
251}
252
Elliott Hughesffb465f2012-03-01 18:46:05 -0800253void Monitor::FailedUnlock(Object* o, Thread* expected_owner, Thread* found_owner,
254 Monitor* monitor) {
255 Thread* current_owner = NULL;
256 std::string current_owner_string;
257 std::string expected_owner_string;
258 std::string found_owner_string;
259 {
260 // TODO: isn't this too late to prevent threads from disappearing?
261 // Acquire thread list lock so threads won't disappear from under us.
262 ScopedThreadListLock thread_list_lock;
263 // Re-read owner now that we hold lock.
264 current_owner = (monitor != NULL) ? monitor->owner_ : NULL;
265 // Get short descriptions of the threads involved.
266 current_owner_string = ThreadToString(current_owner);
267 expected_owner_string = ThreadToString(expected_owner);
268 found_owner_string = ThreadToString(found_owner);
269 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800270 if (current_owner == NULL) {
271 if (found_owner == NULL) {
272 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
273 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800274 PrettyTypeOf(o).c_str(),
275 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800276 } else {
277 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800278 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
279 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800280 found_owner_string.c_str(),
281 PrettyTypeOf(o).c_str(),
282 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800283 }
284 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800285 if (found_owner == NULL) {
286 // Race: originally there was no owner, there is now
287 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
288 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800289 current_owner_string.c_str(),
290 PrettyTypeOf(o).c_str(),
291 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800292 } else {
293 if (found_owner != current_owner) {
294 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800295 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
296 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800297 found_owner_string.c_str(),
298 current_owner_string.c_str(),
299 PrettyTypeOf(o).c_str(),
300 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800301 } else {
302 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
303 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800304 current_owner_string.c_str(),
305 PrettyTypeOf(o).c_str(),
306 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800307 }
308 }
309 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700310}
311
312bool Monitor::Unlock(Thread* self) {
313 DCHECK(self != NULL);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800314 Thread* owner = owner_;
315 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700316 // We own the monitor, so nobody else can be in here.
317 if (lock_count_ == 0) {
318 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800319 locking_method_ = NULL;
320 locking_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700321 lock_.Unlock();
322 } else {
323 --lock_count_;
324 }
325 } else {
326 // We don't own this, so we're not allowed to unlock it.
327 // The JNI spec says that we should throw IllegalMonitorStateException
328 // in this case.
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800329 FailedUnlock(obj_, self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700330 return false;
331 }
332 return true;
333}
334
335/*
336 * Converts the given relative waiting time into an absolute time.
337 */
Elliott Hughesb8d2eeb2012-02-29 16:44:41 -0800338static void ToAbsoluteTime(int64_t ms, int32_t ns, struct timespec *ts) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700339 int64_t endSec;
340
341#ifdef HAVE_TIMEDWAIT_MONOTONIC
342 clock_gettime(CLOCK_MONOTONIC, ts);
343#else
344 {
345 struct timeval tv;
346 gettimeofday(&tv, NULL);
347 ts->tv_sec = tv.tv_sec;
348 ts->tv_nsec = tv.tv_usec * 1000;
349 }
350#endif
351 endSec = ts->tv_sec + ms / 1000;
352 if (endSec >= 0x7fffffff) {
353 LOG(INFO) << "Note: end time exceeds epoch";
354 endSec = 0x7ffffffe;
355 }
356 ts->tv_sec = endSec;
357 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
358
359 // Catch rollover.
360 if (ts->tv_nsec >= 1000000000L) {
361 ts->tv_sec++;
362 ts->tv_nsec -= 1000000000L;
363 }
364}
365
Elliott Hughes5f791332011-09-15 17:45:30 -0700366/*
367 * Wait on a monitor until timeout, interrupt, or notification. Used for
368 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
369 *
370 * If another thread calls Thread.interrupt(), we throw InterruptedException
371 * and return immediately if one of the following are true:
372 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
373 * - blocked in join(), join(long), or join(long, int) methods of Thread
374 * - blocked in sleep(long), or sleep(long, int) methods of Thread
375 * Otherwise, we set the "interrupted" flag.
376 *
377 * Checks to make sure that "ns" is in the range 0-999999
378 * (i.e. fractions of a millisecond) and throws the appropriate
379 * exception if it isn't.
380 *
381 * The spec allows "spurious wakeups", and recommends that all code using
382 * Object.wait() do so in a loop. This appears to derive from concerns
383 * about pthread_cond_wait() on multiprocessor systems. Some commentary
384 * on the web casts doubt on whether these can/should occur.
385 *
386 * Since we're allowed to wake up "early", we clamp extremely long durations
387 * to return at the end of the 32-bit time epoch.
388 */
389void Monitor::Wait(Thread* self, int64_t ms, int32_t ns, bool interruptShouldThrow) {
390 DCHECK(self != NULL);
391
392 // Make sure that we hold the lock.
393 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800394 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700395 return;
396 }
397
398 // Enforce the timeout range.
399 if (ms < 0 || ns < 0 || ns > 999999) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700400 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Elliott Hughes5f791332011-09-15 17:45:30 -0700401 "timeout arguments out of range: ms=%lld ns=%d", ms, ns);
402 return;
403 }
404
405 // Compute absolute wakeup time, if necessary.
406 struct timespec ts;
407 bool timed = false;
408 if (ms != 0 || ns != 0) {
409 ToAbsoluteTime(ms, ns, &ts);
410 timed = true;
411 }
412
413 /*
414 * Add ourselves to the set of threads waiting on this monitor, and
415 * release our hold. We need to let it go even if we're a few levels
416 * deep in a recursive lock, and we need to restore that later.
417 *
418 * We append to the wait set ahead of clearing the count and owner
419 * fields so the subroutine can check that the calling thread owns
420 * the monitor. Aside from that, the order of member updates is
421 * not order sensitive as we hold the pthread mutex.
422 */
423 AppendToWaitSet(self);
424 int prevLockCount = lock_count_;
425 lock_count_ = 0;
426 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800427 const Method* savedMethod = locking_method_;
428 locking_method_ = NULL;
Elliott Hughese65a6c92012-01-18 23:48:31 -0800429 uintptr_t savedPc = locking_pc_;
jeffhao33dc7712011-11-09 17:54:24 -0800430 locking_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700431
432 /*
433 * Update thread status. If the GC wakes up, it'll ignore us, knowing
434 * that we won't touch any references in this state, and we'll check
435 * our suspend mode before we transition out.
436 */
437 if (timed) {
438 self->SetState(Thread::kTimedWaiting);
439 } else {
440 self->SetState(Thread::kWaiting);
441 }
442
Elliott Hughes85d15452011-09-16 17:33:01 -0700443 self->wait_mutex_->Lock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700444
445 /*
446 * Set wait_monitor_ to the monitor object we will be waiting on.
447 * When wait_monitor_ is non-NULL a notifying or interrupting thread
448 * must signal the thread's wait_cond_ to wake it up.
449 */
450 DCHECK(self->wait_monitor_ == NULL);
451 self->wait_monitor_ = this;
452
453 /*
454 * Handle the case where the thread was interrupted before we called
455 * wait().
456 */
457 bool wasInterrupted = false;
458 if (self->interrupted_) {
459 wasInterrupted = true;
460 self->wait_monitor_ = NULL;
Elliott Hughes85d15452011-09-16 17:33:01 -0700461 self->wait_mutex_->Unlock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700462 goto done;
463 }
464
465 /*
466 * Release the monitor lock and wait for a notification or
467 * a timeout to occur.
468 */
469 lock_.Unlock();
470
471 if (!timed) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700472 self->wait_cond_->Wait(*self->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700473 } else {
Elliott Hughes85d15452011-09-16 17:33:01 -0700474 self->wait_cond_->TimedWait(*self->wait_mutex_, ts);
Elliott Hughes5f791332011-09-15 17:45:30 -0700475 }
476 if (self->interrupted_) {
477 wasInterrupted = true;
478 }
479
480 self->interrupted_ = false;
481 self->wait_monitor_ = NULL;
Elliott Hughes85d15452011-09-16 17:33:01 -0700482 self->wait_mutex_->Unlock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700483
484 // Reacquire the monitor lock.
485 Lock(self);
486
487done:
488 /*
489 * We remove our thread from wait set after restoring the count
490 * and owner fields so the subroutine can check that the calling
491 * thread owns the monitor. Aside from that, the order of member
492 * updates is not order sensitive as we hold the pthread mutex.
493 */
494 owner_ = self;
495 lock_count_ = prevLockCount;
jeffhao33dc7712011-11-09 17:54:24 -0800496 locking_method_ = savedMethod;
497 locking_pc_ = savedPc;
Elliott Hughes5f791332011-09-15 17:45:30 -0700498 RemoveFromWaitSet(self);
499
500 /* set self->status back to Thread::kRunnable, and self-suspend if needed */
501 self->SetState(Thread::kRunnable);
502
503 if (wasInterrupted) {
504 /*
505 * We were interrupted while waiting, or somebody interrupted an
506 * un-interruptible thread earlier and we're bailing out immediately.
507 *
508 * The doc sayeth: "The interrupted status of the current thread is
509 * cleared when this exception is thrown."
510 */
511 self->interrupted_ = false;
512 if (interruptShouldThrow) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700513 Thread::Current()->ThrowNewException("Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700514 }
515 }
516}
517
518void Monitor::Notify(Thread* self) {
519 DCHECK(self != NULL);
520
521 // Make sure that we hold the lock.
522 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800523 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700524 return;
525 }
526 // Signal the first waiting thread in the wait set.
527 while (wait_set_ != NULL) {
528 Thread* thread = wait_set_;
529 wait_set_ = thread->wait_next_;
530 thread->wait_next_ = NULL;
531
532 // Check to see if the thread is still waiting.
Elliott Hughes85d15452011-09-16 17:33:01 -0700533 MutexLock mu(*thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700534 if (thread->wait_monitor_ != NULL) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700535 thread->wait_cond_->Signal();
Elliott Hughes5f791332011-09-15 17:45:30 -0700536 return;
537 }
538 }
539}
540
541void Monitor::NotifyAll(Thread* self) {
542 DCHECK(self != NULL);
543
544 // Make sure that we hold the lock.
545 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800546 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700547 return;
548 }
549 // Signal all threads in the wait set.
550 while (wait_set_ != NULL) {
551 Thread* thread = wait_set_;
552 wait_set_ = thread->wait_next_;
553 thread->wait_next_ = NULL;
554 thread->Notify();
555 }
556}
557
558/*
559 * Changes the shape of a monitor from thin to fat, preserving the
560 * internal lock state. The calling thread must own the lock.
561 */
562void Monitor::Inflate(Thread* self, Object* obj) {
563 DCHECK(self != NULL);
564 DCHECK(obj != NULL);
565 DCHECK_EQ(LW_SHAPE(*obj->GetRawLockWordAddress()), LW_SHAPE_THIN);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700566 DCHECK_EQ(LW_LOCK_OWNER(*obj->GetRawLockWordAddress()), static_cast<int32_t>(self->GetThinLockId()));
Elliott Hughes5f791332011-09-15 17:45:30 -0700567
568 // Allocate and acquire a new monitor.
569 Monitor* m = new Monitor(obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800570 VLOG(monitor) << "monitor: thread " << self->GetThinLockId()
571 << " created monitor " << m << " for object " << obj;
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700572 Runtime::Current()->GetMonitorList()->Add(m);
Elliott Hughes5f791332011-09-15 17:45:30 -0700573 m->Lock(self);
574 // Propagate the lock state.
575 uint32_t thin = *obj->GetRawLockWordAddress();
576 m->lock_count_ = LW_LOCK_COUNT(thin);
577 thin &= LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT;
578 thin |= reinterpret_cast<uint32_t>(m) | LW_SHAPE_FAT;
579 // Publish the updated lock word.
580 android_atomic_release_store(thin, obj->GetRawLockWordAddress());
581}
582
583void Monitor::MonitorEnter(Thread* self, Object* obj) {
584 volatile int32_t* thinp = obj->GetRawLockWordAddress();
585 struct timespec tm;
Elliott Hughes398f64b2012-03-26 18:05:48 -0700586 uint32_t sleepDelayNs;
587 uint32_t minSleepDelayNs = 1000000; /* 1 millisecond */
588 uint32_t maxSleepDelayNs = 1000000000; /* 1 second */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700589 uint32_t thin, newThin;
Elliott Hughes5f791332011-09-15 17:45:30 -0700590
Elliott Hughes4681c802011-09-25 18:04:37 -0700591 DCHECK(self != NULL);
592 DCHECK(obj != NULL);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700593 uint32_t threadId = self->GetThinLockId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700594retry:
595 thin = *thinp;
596 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
597 /*
598 * The lock is a thin lock. The owner field is used to
599 * determine the acquire method, ordered by cost.
600 */
601 if (LW_LOCK_OWNER(thin) == threadId) {
602 /*
603 * The calling thread owns the lock. Increment the
604 * value of the recursion count field.
605 */
606 *thinp += 1 << LW_LOCK_COUNT_SHIFT;
607 if (LW_LOCK_COUNT(*thinp) == LW_LOCK_COUNT_MASK) {
608 /*
609 * The reacquisition limit has been reached. Inflate
610 * the lock so the next acquire will not overflow the
611 * recursion count field.
612 */
613 Inflate(self, obj);
614 }
615 } else if (LW_LOCK_OWNER(thin) == 0) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700616 // The lock is unowned. Install the thread id of the calling thread into the owner field.
617 // This is the common case: compiled code will have tried this before calling back into
618 // the runtime.
Elliott Hughes5f791332011-09-15 17:45:30 -0700619 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
620 if (android_atomic_acquire_cas(thin, newThin, thinp) != 0) {
621 // The acquire failed. Try again.
622 goto retry;
623 }
624 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800625 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p (a %s) owned by %d",
Elliott Hughes81ff3182012-03-23 20:35:56 -0700626 threadId, thinp, PrettyTypeOf(obj).c_str(), LW_LOCK_OWNER(thin));
627 // The lock is owned by another thread. Notify the runtime that we are about to wait.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700628 self->monitor_enter_object_ = obj;
Elliott Hughes5f791332011-09-15 17:45:30 -0700629 Thread::State oldStatus = self->SetState(Thread::kBlocked);
630 // Spin until the thin lock is released or inflated.
631 sleepDelayNs = 0;
632 for (;;) {
633 thin = *thinp;
634 // Check the shape of the lock word. Another thread
635 // may have inflated the lock while we were waiting.
636 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
637 if (LW_LOCK_OWNER(thin) == 0) {
638 // The lock has been released. Install the thread id of the
639 // calling thread into the owner field.
640 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
641 if (android_atomic_acquire_cas(thin, newThin, thinp) == 0) {
642 // The acquire succeed. Break out of the loop and proceed to inflate the lock.
643 break;
644 }
645 } else {
646 // The lock has not been released. Yield so the owning thread can run.
647 if (sleepDelayNs == 0) {
648 sched_yield();
649 sleepDelayNs = minSleepDelayNs;
650 } else {
651 tm.tv_sec = 0;
652 tm.tv_nsec = sleepDelayNs;
653 nanosleep(&tm, NULL);
654 // Prepare the next delay value. Wrap to avoid once a second polls for eternity.
655 if (sleepDelayNs < maxSleepDelayNs / 2) {
656 sleepDelayNs *= 2;
657 } else {
658 sleepDelayNs = minSleepDelayNs;
659 }
660 }
661 }
662 } else {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700663 // The thin lock was inflated by another thread. Let the runtime know we are no longer
Elliott Hughes5f791332011-09-15 17:45:30 -0700664 // waiting and try again.
Elliott Hughes398f64b2012-03-26 18:05:48 -0700665 VLOG(monitor) << StringPrintf("monitor: thread %d found lock %p surprise-fattened by another thread", threadId, thinp);
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700666 self->monitor_enter_object_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700667 self->SetState(oldStatus);
668 goto retry;
669 }
670 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800671 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p done", threadId, thinp);
Elliott Hughes81ff3182012-03-23 20:35:56 -0700672 // We have acquired the thin lock. Let the runtime know that we are no longer waiting.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700673 self->monitor_enter_object_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700674 self->SetState(oldStatus);
675 // Fatten the lock.
676 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800677 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p", threadId, thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700678 }
679 } else {
680 // The lock is a fat lock.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800681 VLOG(monitor) << StringPrintf("monitor: thread %d locking fat lock %p (%p) %p on a %s",
Elliott Hughes398f64b2012-03-26 18:05:48 -0700682 threadId, thinp, LW_MONITOR(*thinp),
683 reinterpret_cast<void*>(*thinp), PrettyTypeOf(obj).c_str());
Elliott Hughes5f791332011-09-15 17:45:30 -0700684 DCHECK(LW_MONITOR(*thinp) != NULL);
685 LW_MONITOR(*thinp)->Lock(self);
686 }
687}
688
689bool Monitor::MonitorExit(Thread* self, Object* obj) {
690 volatile int32_t* thinp = obj->GetRawLockWordAddress();
691
692 DCHECK(self != NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -0700693 //DCHECK_EQ(self->GetState(), Thread::kRunnable);
Elliott Hughes5f791332011-09-15 17:45:30 -0700694 DCHECK(obj != NULL);
695
696 /*
697 * Cache the lock word as its value can change while we are
698 * examining its state.
699 */
700 uint32_t thin = *thinp;
701 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
702 /*
703 * The lock is thin. We must ensure that the lock is owned
704 * by the given thread before unlocking it.
705 */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700706 if (LW_LOCK_OWNER(thin) == self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700707 /*
708 * We are the lock owner. It is safe to update the lock
709 * without CAS as lock ownership guards the lock itself.
710 */
711 if (LW_LOCK_COUNT(thin) == 0) {
712 /*
713 * The lock was not recursively acquired, the common
714 * case. Unlock by clearing all bits except for the
715 * hash state.
716 */
717 thin &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
718 android_atomic_release_store(thin, thinp);
719 } else {
720 /*
721 * The object was recursively acquired. Decrement the
722 * lock recursion count field.
723 */
724 *thinp -= 1 << LW_LOCK_COUNT_SHIFT;
725 }
726 } else {
727 /*
728 * We do not own the lock. The JVM spec requires that we
729 * throw an exception in this case.
730 */
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800731 FailedUnlock(obj, self, NULL, NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700732 return false;
733 }
734 } else {
735 /*
736 * The lock is fat. We must check to see if Unlock has
737 * raised any exceptions before continuing.
738 */
739 DCHECK(LW_MONITOR(*thinp) != NULL);
740 if (!LW_MONITOR(*thinp)->Unlock(self)) {
741 // An exception has been raised. Do not fall through.
742 return false;
743 }
744 }
745 return true;
746}
747
748/*
749 * Object.wait(). Also called for class init.
750 */
751void Monitor::Wait(Thread* self, Object *obj, int64_t ms, int32_t ns, bool interruptShouldThrow) {
752 volatile int32_t* thinp = obj->GetRawLockWordAddress();
753
754 // If the lock is still thin, we need to fatten it.
755 uint32_t thin = *thinp;
756 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
757 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700758 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800759 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700760 return;
761 }
762
763 /* This thread holds the lock. We need to fatten the lock
764 * so 'self' can block on it. Don't update the object lock
765 * field yet, because 'self' needs to acquire the lock before
766 * any other thread gets a chance.
767 */
768 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800769 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p by wait()", self->GetThinLockId(), thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700770 }
771 LW_MONITOR(*thinp)->Wait(self, ms, ns, interruptShouldThrow);
772}
773
774void Monitor::Notify(Thread* self, Object *obj) {
775 uint32_t thin = *obj->GetRawLockWordAddress();
776
777 // If the lock is still thin, there aren't any waiters;
778 // waiting on an object forces lock fattening.
779 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
780 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700781 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800782 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700783 return;
784 }
785 // no-op; there are no waiters to notify.
786 } else {
787 // It's a fat lock.
788 LW_MONITOR(thin)->Notify(self);
789 }
790}
791
792void Monitor::NotifyAll(Thread* self, Object *obj) {
793 uint32_t thin = *obj->GetRawLockWordAddress();
794
795 // If the lock is still thin, there aren't any waiters;
796 // waiting on an object forces lock fattening.
797 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
798 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700799 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800800 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700801 return;
802 }
803 // no-op; there are no waiters to notify.
804 } else {
805 // It's a fat lock.
806 LW_MONITOR(thin)->NotifyAll(self);
807 }
808}
809
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700810uint32_t Monitor::GetThinLockId(uint32_t raw_lock_word) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700811 if (LW_SHAPE(raw_lock_word) == LW_SHAPE_THIN) {
812 return LW_LOCK_OWNER(raw_lock_word);
813 } else {
814 Thread* owner = LW_MONITOR(raw_lock_word)->owner_;
815 return owner ? owner->GetThinLockId() : 0;
816 }
817}
818
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700819void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
820 Thread::State state = thread->GetState();
821
822 Object* object = NULL;
823 uint32_t lock_owner = ThreadList::kInvalidId;
824 if (state == Thread::kWaiting || state == Thread::kTimedWaiting) {
825 os << " - waiting on ";
826 Monitor* monitor = thread->wait_monitor_;
827 if (monitor != NULL) {
828 object = monitor->obj_;
829 }
830 lock_owner = Thread::LockOwnerFromThreadLock(object);
831 } else if (state == Thread::kBlocked) {
832 os << " - waiting to lock ";
833 object = thread->monitor_enter_object_;
834 if (object != NULL) {
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700835 lock_owner = object->GetThinLockId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700836 }
837 } else {
838 // We're not waiting on anything.
839 return;
840 }
841 os << "<" << object << ">";
842
843 // - waiting on <0x613f83d8> (a java.lang.ThreadLock) held by thread 5
844 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
845 os << " (a " << PrettyTypeOf(object) << ")";
846
847 if (lock_owner != ThreadList::kInvalidId) {
848 os << " held by thread " << lock_owner;
849 }
850
851 os << "\n";
852}
853
jeffhao33dc7712011-11-09 17:54:24 -0800854void Monitor::TranslateLocation(const Method* method, uint32_t pc,
855 const char*& source_file, uint32_t& line_number) const {
856 // If method is null, location is unknown
857 if (method == NULL) {
Elliott Hughes12c51e32012-01-17 20:25:05 -0800858 source_file = "";
jeffhao33dc7712011-11-09 17:54:24 -0800859 line_number = 0;
860 return;
861 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800862 MethodHelper mh(method);
863 source_file = mh.GetDeclaringClassSourceFile();
Elliott Hughes12c51e32012-01-17 20:25:05 -0800864 if (source_file == NULL) {
865 source_file = "";
866 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800867 line_number = mh.GetLineNumFromNativePC(pc);
jeffhao33dc7712011-11-09 17:54:24 -0800868}
869
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700870MonitorList::MonitorList() : lock_("MonitorList lock") {
871}
872
873MonitorList::~MonitorList() {
874 MutexLock mu(lock_);
875 STLDeleteElements(&list_);
876}
877
878void MonitorList::Add(Monitor* m) {
879 MutexLock mu(lock_);
880 list_.push_front(m);
881}
882
883void MonitorList::SweepMonitorList(Heap::IsMarkedTester is_marked, void* arg) {
884 MutexLock mu(lock_);
885 typedef std::list<Monitor*>::iterator It; // TODO: C++0x auto
886 It it = list_.begin();
887 while (it != list_.end()) {
888 Monitor* m = *it;
889 if (!is_marked(m->GetObject(), arg)) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800890 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object " << m->GetObject();
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700891 delete m;
892 it = list_.erase(it);
893 } else {
894 ++it;
895 }
896 }
897}
898
Elliott Hughes5f791332011-09-15 17:45:30 -0700899} // namespace art