blob: de08b8844752c33c77326883933d3cddbe6b9169 [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"
Ian Rogers365c1022012-06-22 15:05:28 -070031#include "scoped_jni_thread_state.h"
Elliott Hughes88c5c352012-03-15 18:49:48 -070032#include "scoped_thread_list_lock.h"
Elliott Hughesc33a32b2011-10-11 18:18:07 -070033#include "stl_util.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070034#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070035#include "thread_list.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070036#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070037
38namespace art {
39
40/*
41 * Every Object has a monitor associated with it, but not every Object is
42 * actually locked. Even the ones that are locked do not need a
43 * full-fledged monitor until a) there is actual contention or b) wait()
44 * is called on the Object.
45 *
46 * For Android, we have implemented a scheme similar to the one described
47 * in Bacon et al.'s "Thin locks: featherweight synchronization for Java"
48 * (ACM 1998). Things are even easier for us, though, because we have
49 * a full 32 bits to work with.
50 *
51 * The two states of an Object's lock are referred to as "thin" and
52 * "fat". A lock may transition from the "thin" state to the "fat"
53 * state and this transition is referred to as inflation. Once a lock
54 * has been inflated it remains in the "fat" state indefinitely.
55 *
56 * The lock value itself is stored in Object.lock. The LSB of the
57 * lock encodes its state. When cleared, the lock is in the "thin"
58 * state and its bits are formatted as follows:
59 *
60 * [31 ---- 19] [18 ---- 3] [2 ---- 1] [0]
61 * lock count thread id hash state 0
62 *
63 * When set, the lock is in the "fat" state and its bits are formatted
64 * as follows:
65 *
66 * [31 ---- 3] [2 ---- 1] [0]
67 * pointer hash state 1
68 *
69 * For an in-depth description of the mechanics of thin-vs-fat locking,
70 * read the paper referred to above.
Elliott Hughes54e7df12011-09-16 11:47:04 -070071 *
Elliott Hughes5f791332011-09-15 17:45:30 -070072 * Monitors provide:
73 * - mutually exclusive access to resources
74 * - a way for multiple threads to wait for notification
75 *
76 * In effect, they fill the role of both mutexes and condition variables.
77 *
78 * Only one thread can own the monitor at any time. There may be several
79 * threads waiting on it (the wait call unlocks it). One or more waiting
80 * threads may be getting interrupted or notified at any given time.
81 *
82 * TODO: the various members of monitor are not SMP-safe.
83 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070084
85
86/*
87 * Monitor accessor. Extracts a monitor structure pointer from a fat
88 * lock. Performs no error checking.
89 */
90#define LW_MONITOR(x) \
Elliott Hughes398f64b2012-03-26 18:05:48 -070091 (reinterpret_cast<Monitor*>((x) & ~((LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT) | LW_SHAPE_MASK)))
Elliott Hughes54e7df12011-09-16 11:47:04 -070092
93/*
94 * Lock recursion count field. Contains a count of the number of times
95 * a lock has been recursively acquired.
96 */
97#define LW_LOCK_COUNT_MASK 0x1fff
98#define LW_LOCK_COUNT_SHIFT 19
99#define LW_LOCK_COUNT(x) (((x) >> LW_LOCK_COUNT_SHIFT) & LW_LOCK_COUNT_MASK)
100
Elliott Hughesfc861622011-10-17 17:57:47 -0700101bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -0700102uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700103
Elliott Hughesfc861622011-10-17 17:57:47 -0700104bool Monitor::IsSensitiveThread() {
105 if (is_sensitive_thread_hook_ != NULL) {
106 return (*is_sensitive_thread_hook_)();
107 }
108 return false;
109}
110
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800111void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughesfc861622011-10-17 17:57:47 -0700112 lock_profiling_threshold_ = lock_profiling_threshold;
113 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700114}
115
Elliott Hughes5f791332011-09-15 17:45:30 -0700116Monitor::Monitor(Object* obj)
117 : owner_(NULL),
118 lock_count_(0),
119 obj_(obj),
120 wait_set_(NULL),
121 lock_("a monitor lock"),
jeffhao33dc7712011-11-09 17:54:24 -0800122 locking_method_(NULL),
Ian Rogers0399dde2012-06-06 17:09:28 -0700123 locking_dex_pc_(0) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700124}
125
126Monitor::~Monitor() {
127 DCHECK(obj_ != NULL);
128 DCHECK_EQ(LW_SHAPE(*obj_->GetRawLockWordAddress()), LW_SHAPE_FAT);
Elliott Hughes5f791332011-09-15 17:45:30 -0700129}
130
131/*
132 * Links a thread into a monitor's wait set. The monitor lock must be
133 * held by the caller of this routine.
134 */
135void Monitor::AppendToWaitSet(Thread* thread) {
136 DCHECK(owner_ == Thread::Current());
137 DCHECK(thread != NULL);
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700138 DCHECK(thread->wait_next_ == NULL) << thread->wait_next_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700139 if (wait_set_ == NULL) {
140 wait_set_ = thread;
141 return;
142 }
143
144 // push_back.
145 Thread* t = wait_set_;
146 while (t->wait_next_ != NULL) {
147 t = t->wait_next_;
148 }
149 t->wait_next_ = thread;
150}
151
152/*
153 * Unlinks a thread from a monitor's wait set. The monitor lock must
154 * be held by the caller of this routine.
155 */
156void Monitor::RemoveFromWaitSet(Thread *thread) {
157 DCHECK(owner_ == Thread::Current());
158 DCHECK(thread != NULL);
159 if (wait_set_ == NULL) {
160 return;
161 }
162 if (wait_set_ == thread) {
163 wait_set_ = thread->wait_next_;
164 thread->wait_next_ = NULL;
165 return;
166 }
167
168 Thread* t = wait_set_;
169 while (t->wait_next_ != NULL) {
170 if (t->wait_next_ == thread) {
171 t->wait_next_ = thread->wait_next_;
172 thread->wait_next_ = NULL;
173 return;
174 }
175 t = t->wait_next_;
176 }
177}
178
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700179Object* Monitor::GetObject() {
180 return obj_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700181}
182
Elliott Hughes5f791332011-09-15 17:45:30 -0700183void Monitor::Lock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700184 if (owner_ == self) {
185 lock_count_++;
186 return;
187 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700188
Elliott Hughes5f791332011-09-15 17:45:30 -0700189 if (!lock_.TryLock()) {
Mathieu Chartier2542d662012-06-21 17:14:11 -0700190 uint64_t waitStart = 0;
191 uint64_t waitEnd = 0;
Elliott Hughesfc861622011-10-17 17:57:47 -0700192 uint32_t wait_threshold = lock_profiling_threshold_;
jeffhao33dc7712011-11-09 17:54:24 -0800193 const Method* current_locking_method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700194 uint32_t current_locking_dex_pc = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700195 {
Elliott Hughes34e06962012-04-09 13:55:55 -0700196 ScopedThreadStateChange tsc(self, kBlocked);
Elliott Hughesfc861622011-10-17 17:57:47 -0700197 if (wait_threshold != 0) {
198 waitStart = NanoTime() / 1000;
199 }
jeffhao33dc7712011-11-09 17:54:24 -0800200 current_locking_method = locking_method_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700201 current_locking_dex_pc = locking_dex_pc_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700202
203 lock_.Lock();
Elliott Hughesfc861622011-10-17 17:57:47 -0700204 if (wait_threshold != 0) {
205 waitEnd = NanoTime() / 1000;
206 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700207 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700208
209 if (wait_threshold != 0) {
210 uint64_t wait_ms = (waitEnd - waitStart) / 1000;
211 uint32_t sample_percent;
212 if (wait_ms >= wait_threshold) {
213 sample_percent = 100;
214 } else {
215 sample_percent = 100 * wait_ms / wait_threshold;
216 }
217 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
jeffhao33dc7712011-11-09 17:54:24 -0800218 const char* current_locking_filename;
219 uint32_t current_locking_line_number;
Ian Rogers0399dde2012-06-06 17:09:28 -0700220 TranslateLocation(current_locking_method, current_locking_dex_pc,
jeffhao33dc7712011-11-09 17:54:24 -0800221 current_locking_filename, current_locking_line_number);
222 LogContentionEvent(self, wait_ms, sample_percent, current_locking_filename, current_locking_line_number);
Elliott Hughesfc861622011-10-17 17:57:47 -0700223 }
224 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700225 }
226 owner_ = self;
227 DCHECK_EQ(lock_count_, 0);
228
229 // When debugging, save the current monitor holder for future
230 // acquisition failures to use in sampled logging.
Elliott Hughesfc861622011-10-17 17:57:47 -0700231 if (lock_profiling_threshold_ != 0) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700232 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
Elliott Hughesfc861622011-10-17 17:57:47 -0700233 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700234}
235
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800236static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
237 __attribute__((format(printf, 1, 2)));
238
239static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...) {
240 va_list args;
241 va_start(args, fmt);
242 Thread::Current()->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Brian Carlstrom64277f32012-03-26 23:53:34 -0700243 if (!Runtime::Current()->IsStarted()) {
244 std::ostringstream ss;
245 Thread::Current()->Dump(ss);
246 std::string str(ss.str());
247 LOG(ERROR) << "IllegalMonitorStateException: " << str;
248 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800249 va_end(args);
250}
251
Elliott Hughesd4237412012-02-21 11:24:45 -0800252static std::string ThreadToString(Thread* thread) {
253 if (thread == NULL) {
254 return "NULL";
255 }
256 std::ostringstream oss;
257 // TODO: alternatively, we could just return the thread's name.
258 oss << *thread;
259 return oss.str();
260}
261
Elliott Hughesffb465f2012-03-01 18:46:05 -0800262void Monitor::FailedUnlock(Object* o, Thread* expected_owner, Thread* found_owner,
263 Monitor* monitor) {
264 Thread* current_owner = NULL;
265 std::string current_owner_string;
266 std::string expected_owner_string;
267 std::string found_owner_string;
268 {
269 // TODO: isn't this too late to prevent threads from disappearing?
270 // Acquire thread list lock so threads won't disappear from under us.
271 ScopedThreadListLock thread_list_lock;
272 // Re-read owner now that we hold lock.
273 current_owner = (monitor != NULL) ? monitor->owner_ : NULL;
274 // Get short descriptions of the threads involved.
275 current_owner_string = ThreadToString(current_owner);
276 expected_owner_string = ThreadToString(expected_owner);
277 found_owner_string = ThreadToString(found_owner);
278 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800279 if (current_owner == NULL) {
280 if (found_owner == NULL) {
281 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
282 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800283 PrettyTypeOf(o).c_str(),
284 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800285 } else {
286 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800287 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
288 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800289 found_owner_string.c_str(),
290 PrettyTypeOf(o).c_str(),
291 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800292 }
293 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800294 if (found_owner == NULL) {
295 // Race: originally there was no owner, there is now
296 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
297 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800298 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 if (found_owner != current_owner) {
303 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800304 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
305 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800306 found_owner_string.c_str(),
307 current_owner_string.c_str(),
308 PrettyTypeOf(o).c_str(),
309 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800310 } else {
311 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
312 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800313 current_owner_string.c_str(),
314 PrettyTypeOf(o).c_str(),
315 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800316 }
317 }
318 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700319}
320
321bool Monitor::Unlock(Thread* self) {
322 DCHECK(self != NULL);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800323 Thread* owner = owner_;
324 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700325 // We own the monitor, so nobody else can be in here.
326 if (lock_count_ == 0) {
327 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800328 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700329 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700330 lock_.Unlock();
331 } else {
332 --lock_count_;
333 }
334 } else {
335 // We don't own this, so we're not allowed to unlock it.
336 // The JNI spec says that we should throw IllegalMonitorStateException
337 // in this case.
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800338 FailedUnlock(obj_, self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700339 return false;
340 }
341 return true;
342}
343
Elliott Hughes8f751ab2012-05-15 17:12:40 -0700344// Converts the given waiting time (relative to "now") into an absolute time in 'ts'.
345static void ToAbsoluteTime(int64_t ms, int32_t ns, timespec* ts) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700346 int64_t endSec;
347
348#ifdef HAVE_TIMEDWAIT_MONOTONIC
349 clock_gettime(CLOCK_MONOTONIC, ts);
350#else
351 {
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700352 timeval tv;
Elliott Hughes5f791332011-09-15 17:45:30 -0700353 gettimeofday(&tv, NULL);
354 ts->tv_sec = tv.tv_sec;
355 ts->tv_nsec = tv.tv_usec * 1000;
356 }
357#endif
358 endSec = ts->tv_sec + ms / 1000;
359 if (endSec >= 0x7fffffff) {
Elliott Hughes8f751ab2012-05-15 17:12:40 -0700360 std::ostringstream ss;
361 Thread::Current()->Dump(ss);
362 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
Elliott Hughes5f791332011-09-15 17:45:30 -0700363 endSec = 0x7ffffffe;
364 }
365 ts->tv_sec = endSec;
366 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
367
368 // Catch rollover.
369 if (ts->tv_nsec >= 1000000000L) {
370 ts->tv_sec++;
371 ts->tv_nsec -= 1000000000L;
372 }
373}
374
Elliott Hughes5f791332011-09-15 17:45:30 -0700375/*
376 * Wait on a monitor until timeout, interrupt, or notification. Used for
377 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
378 *
379 * If another thread calls Thread.interrupt(), we throw InterruptedException
380 * and return immediately if one of the following are true:
381 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
382 * - blocked in join(), join(long), or join(long, int) methods of Thread
383 * - blocked in sleep(long), or sleep(long, int) methods of Thread
384 * Otherwise, we set the "interrupted" flag.
385 *
386 * Checks to make sure that "ns" is in the range 0-999999
387 * (i.e. fractions of a millisecond) and throws the appropriate
388 * exception if it isn't.
389 *
390 * The spec allows "spurious wakeups", and recommends that all code using
391 * Object.wait() do so in a loop. This appears to derive from concerns
392 * about pthread_cond_wait() on multiprocessor systems. Some commentary
393 * on the web casts doubt on whether these can/should occur.
394 *
395 * Since we're allowed to wake up "early", we clamp extremely long durations
396 * to return at the end of the 32-bit time epoch.
397 */
398void Monitor::Wait(Thread* self, int64_t ms, int32_t ns, bool interruptShouldThrow) {
399 DCHECK(self != NULL);
400
401 // Make sure that we hold the lock.
402 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800403 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700404 return;
405 }
406
407 // Enforce the timeout range.
408 if (ms < 0 || ns < 0 || ns > 999999) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700409 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Elliott Hughes5f791332011-09-15 17:45:30 -0700410 "timeout arguments out of range: ms=%lld ns=%d", ms, ns);
411 return;
412 }
413
414 // Compute absolute wakeup time, if necessary.
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700415 timespec ts;
Elliott Hughes5f791332011-09-15 17:45:30 -0700416 bool timed = false;
417 if (ms != 0 || ns != 0) {
418 ToAbsoluteTime(ms, ns, &ts);
419 timed = true;
420 }
421
422 /*
423 * Add ourselves to the set of threads waiting on this monitor, and
424 * release our hold. We need to let it go even if we're a few levels
425 * deep in a recursive lock, and we need to restore that later.
426 *
427 * We append to the wait set ahead of clearing the count and owner
428 * fields so the subroutine can check that the calling thread owns
429 * the monitor. Aside from that, the order of member updates is
430 * not order sensitive as we hold the pthread mutex.
431 */
432 AppendToWaitSet(self);
Ian Rogers0399dde2012-06-06 17:09:28 -0700433 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700434 lock_count_ = 0;
435 owner_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700436 const Method* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800437 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700438 uintptr_t saved_dex_pc = locking_dex_pc_;
439 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700440
441 /*
442 * Update thread status. If the GC wakes up, it'll ignore us, knowing
443 * that we won't touch any references in this state, and we'll check
444 * our suspend mode before we transition out.
445 */
446 if (timed) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700447 self->SetState(kTimedWaiting);
Elliott Hughes5f791332011-09-15 17:45:30 -0700448 } else {
Elliott Hughes34e06962012-04-09 13:55:55 -0700449 self->SetState(kWaiting);
Elliott Hughes5f791332011-09-15 17:45:30 -0700450 }
451
Elliott Hughes85d15452011-09-16 17:33:01 -0700452 self->wait_mutex_->Lock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700453
454 /*
455 * Set wait_monitor_ to the monitor object we will be waiting on.
456 * When wait_monitor_ is non-NULL a notifying or interrupting thread
457 * must signal the thread's wait_cond_ to wake it up.
458 */
459 DCHECK(self->wait_monitor_ == NULL);
460 self->wait_monitor_ = this;
461
462 /*
463 * Handle the case where the thread was interrupted before we called
464 * wait().
465 */
466 bool wasInterrupted = false;
467 if (self->interrupted_) {
468 wasInterrupted = true;
469 self->wait_monitor_ = NULL;
Elliott Hughes85d15452011-09-16 17:33:01 -0700470 self->wait_mutex_->Unlock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700471 goto done;
472 }
473
474 /*
475 * Release the monitor lock and wait for a notification or
476 * a timeout to occur.
477 */
478 lock_.Unlock();
479
480 if (!timed) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700481 self->wait_cond_->Wait(*self->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700482 } else {
Elliott Hughes85d15452011-09-16 17:33:01 -0700483 self->wait_cond_->TimedWait(*self->wait_mutex_, ts);
Elliott Hughes5f791332011-09-15 17:45:30 -0700484 }
485 if (self->interrupted_) {
486 wasInterrupted = true;
487 }
488
489 self->interrupted_ = false;
490 self->wait_monitor_ = NULL;
Elliott Hughes85d15452011-09-16 17:33:01 -0700491 self->wait_mutex_->Unlock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700492
493 // Reacquire the monitor lock.
494 Lock(self);
495
Elliott Hughesa21039c2012-06-21 12:09:25 -0700496 done:
Elliott Hughes5f791332011-09-15 17:45:30 -0700497 /*
498 * We remove our thread from wait set after restoring the count
499 * and owner fields so the subroutine can check that the calling
500 * thread owns the monitor. Aside from that, the order of member
501 * updates is not order sensitive as we hold the pthread mutex.
502 */
503 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700504 lock_count_ = prev_lock_count;
505 locking_method_ = saved_method;
506 locking_dex_pc_ = saved_dex_pc;
Elliott Hughes5f791332011-09-15 17:45:30 -0700507 RemoveFromWaitSet(self);
508
Elliott Hughes34e06962012-04-09 13:55:55 -0700509 /* set self->status back to kRunnable, and self-suspend if needed */
510 self->SetState(kRunnable);
Elliott Hughes5f791332011-09-15 17:45:30 -0700511
512 if (wasInterrupted) {
513 /*
514 * We were interrupted while waiting, or somebody interrupted an
515 * un-interruptible thread earlier and we're bailing out immediately.
516 *
517 * The doc sayeth: "The interrupted status of the current thread is
518 * cleared when this exception is thrown."
519 */
520 self->interrupted_ = false;
521 if (interruptShouldThrow) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700522 Thread::Current()->ThrowNewException("Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700523 }
524 }
525}
526
527void Monitor::Notify(Thread* self) {
528 DCHECK(self != NULL);
529
530 // Make sure that we hold the lock.
531 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800532 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700533 return;
534 }
535 // Signal the first waiting thread in the wait set.
536 while (wait_set_ != NULL) {
537 Thread* thread = wait_set_;
538 wait_set_ = thread->wait_next_;
539 thread->wait_next_ = NULL;
540
541 // Check to see if the thread is still waiting.
Elliott Hughes85d15452011-09-16 17:33:01 -0700542 MutexLock mu(*thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700543 if (thread->wait_monitor_ != NULL) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700544 thread->wait_cond_->Signal();
Elliott Hughes5f791332011-09-15 17:45:30 -0700545 return;
546 }
547 }
548}
549
550void Monitor::NotifyAll(Thread* self) {
551 DCHECK(self != NULL);
552
553 // Make sure that we hold the lock.
554 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800555 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700556 return;
557 }
558 // Signal all threads in the wait set.
559 while (wait_set_ != NULL) {
560 Thread* thread = wait_set_;
561 wait_set_ = thread->wait_next_;
562 thread->wait_next_ = NULL;
563 thread->Notify();
564 }
565}
566
567/*
568 * Changes the shape of a monitor from thin to fat, preserving the
569 * internal lock state. The calling thread must own the lock.
570 */
571void Monitor::Inflate(Thread* self, Object* obj) {
572 DCHECK(self != NULL);
573 DCHECK(obj != NULL);
574 DCHECK_EQ(LW_SHAPE(*obj->GetRawLockWordAddress()), LW_SHAPE_THIN);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700575 DCHECK_EQ(LW_LOCK_OWNER(*obj->GetRawLockWordAddress()), static_cast<int32_t>(self->GetThinLockId()));
Elliott Hughes5f791332011-09-15 17:45:30 -0700576
577 // Allocate and acquire a new monitor.
578 Monitor* m = new Monitor(obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800579 VLOG(monitor) << "monitor: thread " << self->GetThinLockId()
580 << " created monitor " << m << " for object " << obj;
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700581 Runtime::Current()->GetMonitorList()->Add(m);
Elliott Hughes5f791332011-09-15 17:45:30 -0700582 m->Lock(self);
583 // Propagate the lock state.
584 uint32_t thin = *obj->GetRawLockWordAddress();
585 m->lock_count_ = LW_LOCK_COUNT(thin);
586 thin &= LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT;
587 thin |= reinterpret_cast<uint32_t>(m) | LW_SHAPE_FAT;
588 // Publish the updated lock word.
589 android_atomic_release_store(thin, obj->GetRawLockWordAddress());
590}
591
592void Monitor::MonitorEnter(Thread* self, Object* obj) {
593 volatile int32_t* thinp = obj->GetRawLockWordAddress();
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700594 timespec tm;
Elliott Hughes398f64b2012-03-26 18:05:48 -0700595 uint32_t sleepDelayNs;
596 uint32_t minSleepDelayNs = 1000000; /* 1 millisecond */
597 uint32_t maxSleepDelayNs = 1000000000; /* 1 second */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700598 uint32_t thin, newThin;
Elliott Hughes5f791332011-09-15 17:45:30 -0700599
Elliott Hughes4681c802011-09-25 18:04:37 -0700600 DCHECK(self != NULL);
601 DCHECK(obj != NULL);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700602 uint32_t threadId = self->GetThinLockId();
Elliott Hughesa21039c2012-06-21 12:09:25 -0700603 retry:
Elliott Hughes5f791332011-09-15 17:45:30 -0700604 thin = *thinp;
605 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
606 /*
607 * The lock is a thin lock. The owner field is used to
608 * determine the acquire method, ordered by cost.
609 */
610 if (LW_LOCK_OWNER(thin) == threadId) {
611 /*
612 * The calling thread owns the lock. Increment the
613 * value of the recursion count field.
614 */
615 *thinp += 1 << LW_LOCK_COUNT_SHIFT;
616 if (LW_LOCK_COUNT(*thinp) == LW_LOCK_COUNT_MASK) {
617 /*
618 * The reacquisition limit has been reached. Inflate
619 * the lock so the next acquire will not overflow the
620 * recursion count field.
621 */
622 Inflate(self, obj);
623 }
624 } else if (LW_LOCK_OWNER(thin) == 0) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700625 // The lock is unowned. Install the thread id of the calling thread into the owner field.
626 // This is the common case: compiled code will have tried this before calling back into
627 // the runtime.
Elliott Hughes5f791332011-09-15 17:45:30 -0700628 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
629 if (android_atomic_acquire_cas(thin, newThin, thinp) != 0) {
630 // The acquire failed. Try again.
631 goto retry;
632 }
633 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800634 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p (a %s) owned by %d",
Elliott Hughes81ff3182012-03-23 20:35:56 -0700635 threadId, thinp, PrettyTypeOf(obj).c_str(), LW_LOCK_OWNER(thin));
636 // The lock is owned by another thread. Notify the runtime that we are about to wait.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700637 self->monitor_enter_object_ = obj;
Elliott Hughes34e06962012-04-09 13:55:55 -0700638 ThreadState oldStatus = self->SetState(kBlocked);
Elliott Hughes5f791332011-09-15 17:45:30 -0700639 // Spin until the thin lock is released or inflated.
640 sleepDelayNs = 0;
641 for (;;) {
642 thin = *thinp;
643 // Check the shape of the lock word. Another thread
644 // may have inflated the lock while we were waiting.
645 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
646 if (LW_LOCK_OWNER(thin) == 0) {
647 // The lock has been released. Install the thread id of the
648 // calling thread into the owner field.
649 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
650 if (android_atomic_acquire_cas(thin, newThin, thinp) == 0) {
651 // The acquire succeed. Break out of the loop and proceed to inflate the lock.
652 break;
653 }
654 } else {
655 // The lock has not been released. Yield so the owning thread can run.
656 if (sleepDelayNs == 0) {
657 sched_yield();
658 sleepDelayNs = minSleepDelayNs;
659 } else {
660 tm.tv_sec = 0;
661 tm.tv_nsec = sleepDelayNs;
662 nanosleep(&tm, NULL);
663 // Prepare the next delay value. Wrap to avoid once a second polls for eternity.
664 if (sleepDelayNs < maxSleepDelayNs / 2) {
665 sleepDelayNs *= 2;
666 } else {
667 sleepDelayNs = minSleepDelayNs;
668 }
669 }
670 }
671 } else {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700672 // The thin lock was inflated by another thread. Let the runtime know we are no longer
Elliott Hughes5f791332011-09-15 17:45:30 -0700673 // waiting and try again.
Elliott Hughes398f64b2012-03-26 18:05:48 -0700674 VLOG(monitor) << StringPrintf("monitor: thread %d found lock %p surprise-fattened by another thread", threadId, thinp);
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700675 self->monitor_enter_object_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700676 self->SetState(oldStatus);
677 goto retry;
678 }
679 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800680 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p done", threadId, thinp);
Elliott Hughes81ff3182012-03-23 20:35:56 -0700681 // We have acquired the thin lock. Let the runtime know that we are no longer waiting.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700682 self->monitor_enter_object_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700683 self->SetState(oldStatus);
684 // Fatten the lock.
685 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800686 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p", threadId, thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700687 }
688 } else {
689 // The lock is a fat lock.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800690 VLOG(monitor) << StringPrintf("monitor: thread %d locking fat lock %p (%p) %p on a %s",
Elliott Hughes398f64b2012-03-26 18:05:48 -0700691 threadId, thinp, LW_MONITOR(*thinp),
692 reinterpret_cast<void*>(*thinp), PrettyTypeOf(obj).c_str());
Elliott Hughes5f791332011-09-15 17:45:30 -0700693 DCHECK(LW_MONITOR(*thinp) != NULL);
694 LW_MONITOR(*thinp)->Lock(self);
695 }
696}
697
698bool Monitor::MonitorExit(Thread* self, Object* obj) {
699 volatile int32_t* thinp = obj->GetRawLockWordAddress();
700
701 DCHECK(self != NULL);
Elliott Hughes34e06962012-04-09 13:55:55 -0700702 //DCHECK_EQ(self->GetState(), kRunnable);
Elliott Hughes5f791332011-09-15 17:45:30 -0700703 DCHECK(obj != NULL);
704
705 /*
706 * Cache the lock word as its value can change while we are
707 * examining its state.
708 */
709 uint32_t thin = *thinp;
710 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
711 /*
712 * The lock is thin. We must ensure that the lock is owned
713 * by the given thread before unlocking it.
714 */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700715 if (LW_LOCK_OWNER(thin) == self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700716 /*
717 * We are the lock owner. It is safe to update the lock
718 * without CAS as lock ownership guards the lock itself.
719 */
720 if (LW_LOCK_COUNT(thin) == 0) {
721 /*
722 * The lock was not recursively acquired, the common
723 * case. Unlock by clearing all bits except for the
724 * hash state.
725 */
726 thin &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
727 android_atomic_release_store(thin, thinp);
728 } else {
729 /*
730 * The object was recursively acquired. Decrement the
731 * lock recursion count field.
732 */
733 *thinp -= 1 << LW_LOCK_COUNT_SHIFT;
734 }
735 } else {
736 /*
737 * We do not own the lock. The JVM spec requires that we
738 * throw an exception in this case.
739 */
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800740 FailedUnlock(obj, self, NULL, NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700741 return false;
742 }
743 } else {
744 /*
745 * The lock is fat. We must check to see if Unlock has
746 * raised any exceptions before continuing.
747 */
748 DCHECK(LW_MONITOR(*thinp) != NULL);
749 if (!LW_MONITOR(*thinp)->Unlock(self)) {
750 // An exception has been raised. Do not fall through.
751 return false;
752 }
753 }
754 return true;
755}
756
757/*
758 * Object.wait(). Also called for class init.
759 */
760void Monitor::Wait(Thread* self, Object *obj, int64_t ms, int32_t ns, bool interruptShouldThrow) {
761 volatile int32_t* thinp = obj->GetRawLockWordAddress();
762
763 // If the lock is still thin, we need to fatten it.
764 uint32_t thin = *thinp;
765 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
766 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700767 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800768 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700769 return;
770 }
771
772 /* This thread holds the lock. We need to fatten the lock
773 * so 'self' can block on it. Don't update the object lock
774 * field yet, because 'self' needs to acquire the lock before
775 * any other thread gets a chance.
776 */
777 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800778 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p by wait()", self->GetThinLockId(), thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700779 }
780 LW_MONITOR(*thinp)->Wait(self, ms, ns, interruptShouldThrow);
781}
782
783void Monitor::Notify(Thread* self, Object *obj) {
784 uint32_t thin = *obj->GetRawLockWordAddress();
785
786 // If the lock is still thin, there aren't any waiters;
787 // waiting on an object forces lock fattening.
788 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
789 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700790 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800791 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700792 return;
793 }
794 // no-op; there are no waiters to notify.
795 } else {
796 // It's a fat lock.
797 LW_MONITOR(thin)->Notify(self);
798 }
799}
800
801void Monitor::NotifyAll(Thread* self, Object *obj) {
802 uint32_t thin = *obj->GetRawLockWordAddress();
803
804 // If the lock is still thin, there aren't any waiters;
805 // waiting on an object forces lock fattening.
806 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
807 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700808 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800809 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700810 return;
811 }
812 // no-op; there are no waiters to notify.
813 } else {
814 // It's a fat lock.
815 LW_MONITOR(thin)->NotifyAll(self);
816 }
817}
818
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700819uint32_t Monitor::GetThinLockId(uint32_t raw_lock_word) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700820 if (LW_SHAPE(raw_lock_word) == LW_SHAPE_THIN) {
821 return LW_LOCK_OWNER(raw_lock_word);
822 } else {
823 Thread* owner = LW_MONITOR(raw_lock_word)->owner_;
824 return owner ? owner->GetThinLockId() : 0;
825 }
826}
827
Elliott Hughes044288f2012-06-25 14:46:39 -0700828static uint32_t LockOwnerFromThreadLock(Object* thread_lock) {
Ian Rogers365c1022012-06-22 15:05:28 -0700829 ScopedJniThreadState ts(Thread::Current());
830 if (thread_lock == NULL ||
831 thread_lock->GetClass() != ts.Decode<Class*>(WellKnownClasses::java_lang_ThreadLock)) {
Elliott Hughes044288f2012-06-25 14:46:39 -0700832 return ThreadList::kInvalidId;
833 }
Ian Rogers365c1022012-06-22 15:05:28 -0700834 Field* thread_field = ts.DecodeField(WellKnownClasses::java_lang_ThreadLock_thread);
Elliott Hughes044288f2012-06-25 14:46:39 -0700835 Object* managed_thread = thread_field->GetObject(thread_lock);
836 if (managed_thread == NULL) {
837 return ThreadList::kInvalidId;
838 }
Ian Rogers365c1022012-06-22 15:05:28 -0700839 Field* vmData_field = ts.DecodeField(WellKnownClasses::java_lang_Thread_vmData);
Elliott Hughes044288f2012-06-25 14:46:39 -0700840 uintptr_t vmData = static_cast<uintptr_t>(vmData_field->GetInt(managed_thread));
841 Thread* thread = reinterpret_cast<Thread*>(vmData);
842 if (thread == NULL) {
843 return ThreadList::kInvalidId;
844 }
845 return thread->GetThinLockId();
846}
847
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700848void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700849 ThreadState state = thread->GetState();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700850
851 Object* object = NULL;
852 uint32_t lock_owner = ThreadList::kInvalidId;
Elliott Hughes34e06962012-04-09 13:55:55 -0700853 if (state == kWaiting || state == kTimedWaiting) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700854 os << " - waiting on ";
855 Monitor* monitor = thread->wait_monitor_;
856 if (monitor != NULL) {
857 object = monitor->obj_;
858 }
Elliott Hughes044288f2012-06-25 14:46:39 -0700859 lock_owner = LockOwnerFromThreadLock(object);
Elliott Hughes34e06962012-04-09 13:55:55 -0700860 } else if (state == kBlocked) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700861 os << " - waiting to lock ";
862 object = thread->monitor_enter_object_;
863 if (object != NULL) {
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700864 lock_owner = object->GetThinLockId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700865 }
866 } else {
867 // We're not waiting on anything.
868 return;
869 }
870 os << "<" << object << ">";
871
872 // - waiting on <0x613f83d8> (a java.lang.ThreadLock) held by thread 5
873 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
874 os << " (a " << PrettyTypeOf(object) << ")";
875
876 if (lock_owner != ThreadList::kInvalidId) {
877 os << " held by thread " << lock_owner;
878 }
879
880 os << "\n";
881}
882
Ian Rogers0399dde2012-06-06 17:09:28 -0700883void Monitor::TranslateLocation(const Method* method, uint32_t dex_pc,
jeffhao33dc7712011-11-09 17:54:24 -0800884 const char*& source_file, uint32_t& line_number) const {
885 // If method is null, location is unknown
886 if (method == NULL) {
Elliott Hughes12c51e32012-01-17 20:25:05 -0800887 source_file = "";
jeffhao33dc7712011-11-09 17:54:24 -0800888 line_number = 0;
889 return;
890 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800891 MethodHelper mh(method);
892 source_file = mh.GetDeclaringClassSourceFile();
Elliott Hughes12c51e32012-01-17 20:25:05 -0800893 if (source_file == NULL) {
894 source_file = "";
895 }
Ian Rogers0399dde2012-06-06 17:09:28 -0700896 line_number = mh.GetLineNumFromDexPC(dex_pc);
jeffhao33dc7712011-11-09 17:54:24 -0800897}
898
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700899MonitorList::MonitorList() : lock_("MonitorList lock") {
900}
901
902MonitorList::~MonitorList() {
903 MutexLock mu(lock_);
904 STLDeleteElements(&list_);
905}
906
907void MonitorList::Add(Monitor* m) {
908 MutexLock mu(lock_);
909 list_.push_front(m);
910}
911
912void MonitorList::SweepMonitorList(Heap::IsMarkedTester is_marked, void* arg) {
913 MutexLock mu(lock_);
914 typedef std::list<Monitor*>::iterator It; // TODO: C++0x auto
915 It it = list_.begin();
916 while (it != list_.end()) {
917 Monitor* m = *it;
918 if (!is_marked(m->GetObject(), arg)) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800919 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object " << m->GetObject();
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700920 delete m;
921 it = list_.erase(it);
922 } else {
923 ++it;
924 }
925 }
926}
927
Elliott Hughes5f791332011-09-15 17:45:30 -0700928} // namespace art