blob: dde67ea9da05c243f009889305dc08296727acd6 [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 Hughes044288f2012-06-25 14:46:39 -070035#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070036
37namespace art {
38
39/*
40 * Every Object has a monitor associated with it, but not every Object is
41 * actually locked. Even the ones that are locked do not need a
42 * full-fledged monitor until a) there is actual contention or b) wait()
43 * is called on the Object.
44 *
45 * For Android, we have implemented a scheme similar to the one described
46 * in Bacon et al.'s "Thin locks: featherweight synchronization for Java"
47 * (ACM 1998). Things are even easier for us, though, because we have
48 * a full 32 bits to work with.
49 *
50 * The two states of an Object's lock are referred to as "thin" and
51 * "fat". A lock may transition from the "thin" state to the "fat"
52 * state and this transition is referred to as inflation. Once a lock
53 * has been inflated it remains in the "fat" state indefinitely.
54 *
55 * The lock value itself is stored in Object.lock. The LSB of the
56 * lock encodes its state. When cleared, the lock is in the "thin"
57 * state and its bits are formatted as follows:
58 *
59 * [31 ---- 19] [18 ---- 3] [2 ---- 1] [0]
60 * lock count thread id hash state 0
61 *
62 * When set, the lock is in the "fat" state and its bits are formatted
63 * as follows:
64 *
65 * [31 ---- 3] [2 ---- 1] [0]
66 * pointer hash state 1
67 *
68 * For an in-depth description of the mechanics of thin-vs-fat locking,
69 * read the paper referred to above.
Elliott Hughes54e7df12011-09-16 11:47:04 -070070 *
Elliott Hughes5f791332011-09-15 17:45:30 -070071 * Monitors provide:
72 * - mutually exclusive access to resources
73 * - a way for multiple threads to wait for notification
74 *
75 * In effect, they fill the role of both mutexes and condition variables.
76 *
77 * Only one thread can own the monitor at any time. There may be several
78 * threads waiting on it (the wait call unlocks it). One or more waiting
79 * threads may be getting interrupted or notified at any given time.
80 *
81 * TODO: the various members of monitor are not SMP-safe.
82 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070083
84
85/*
86 * Monitor accessor. Extracts a monitor structure pointer from a fat
87 * lock. Performs no error checking.
88 */
89#define LW_MONITOR(x) \
Elliott Hughes398f64b2012-03-26 18:05:48 -070090 (reinterpret_cast<Monitor*>((x) & ~((LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT) | LW_SHAPE_MASK)))
Elliott Hughes54e7df12011-09-16 11:47:04 -070091
92/*
93 * Lock recursion count field. Contains a count of the number of times
94 * a lock has been recursively acquired.
95 */
96#define LW_LOCK_COUNT_MASK 0x1fff
97#define LW_LOCK_COUNT_SHIFT 19
98#define LW_LOCK_COUNT(x) (((x) >> LW_LOCK_COUNT_SHIFT) & LW_LOCK_COUNT_MASK)
99
Elliott Hughesfc861622011-10-17 17:57:47 -0700100bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -0700101uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700102
Elliott Hughesfc861622011-10-17 17:57:47 -0700103bool Monitor::IsSensitiveThread() {
104 if (is_sensitive_thread_hook_ != NULL) {
105 return (*is_sensitive_thread_hook_)();
106 }
107 return false;
108}
109
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800110void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughesfc861622011-10-17 17:57:47 -0700111 lock_profiling_threshold_ = lock_profiling_threshold;
112 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700113}
114
Elliott Hughes5f791332011-09-15 17:45:30 -0700115Monitor::Monitor(Object* obj)
116 : owner_(NULL),
117 lock_count_(0),
118 obj_(obj),
119 wait_set_(NULL),
120 lock_("a monitor lock"),
jeffhao33dc7712011-11-09 17:54:24 -0800121 locking_method_(NULL),
Ian Rogers0399dde2012-06-06 17:09:28 -0700122 locking_dex_pc_(0) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700123}
124
125Monitor::~Monitor() {
126 DCHECK(obj_ != NULL);
127 DCHECK_EQ(LW_SHAPE(*obj_->GetRawLockWordAddress()), LW_SHAPE_FAT);
Elliott Hughes5f791332011-09-15 17:45:30 -0700128}
129
130/*
131 * Links a thread into a monitor's wait set. The monitor lock must be
132 * held by the caller of this routine.
133 */
134void Monitor::AppendToWaitSet(Thread* thread) {
135 DCHECK(owner_ == Thread::Current());
136 DCHECK(thread != NULL);
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700137 DCHECK(thread->wait_next_ == NULL) << thread->wait_next_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700138 if (wait_set_ == NULL) {
139 wait_set_ = thread;
140 return;
141 }
142
143 // push_back.
144 Thread* t = wait_set_;
145 while (t->wait_next_ != NULL) {
146 t = t->wait_next_;
147 }
148 t->wait_next_ = thread;
149}
150
151/*
152 * Unlinks a thread from a monitor's wait set. The monitor lock must
153 * be held by the caller of this routine.
154 */
155void Monitor::RemoveFromWaitSet(Thread *thread) {
156 DCHECK(owner_ == Thread::Current());
157 DCHECK(thread != NULL);
158 if (wait_set_ == NULL) {
159 return;
160 }
161 if (wait_set_ == thread) {
162 wait_set_ = thread->wait_next_;
163 thread->wait_next_ = NULL;
164 return;
165 }
166
167 Thread* t = wait_set_;
168 while (t->wait_next_ != NULL) {
169 if (t->wait_next_ == thread) {
170 t->wait_next_ = thread->wait_next_;
171 thread->wait_next_ = NULL;
172 return;
173 }
174 t = t->wait_next_;
175 }
176}
177
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700178Object* Monitor::GetObject() {
179 return obj_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700180}
181
Elliott Hughes5f791332011-09-15 17:45:30 -0700182void Monitor::Lock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700183 if (owner_ == self) {
184 lock_count_++;
185 return;
186 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700187
Elliott Hughes5f791332011-09-15 17:45:30 -0700188 if (!lock_.TryLock()) {
Mathieu Chartier2542d662012-06-21 17:14:11 -0700189 uint64_t waitStart = 0;
190 uint64_t waitEnd = 0;
Elliott Hughesfc861622011-10-17 17:57:47 -0700191 uint32_t wait_threshold = lock_profiling_threshold_;
jeffhao33dc7712011-11-09 17:54:24 -0800192 const Method* current_locking_method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700193 uint32_t current_locking_dex_pc = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700194 {
Elliott Hughes34e06962012-04-09 13:55:55 -0700195 ScopedThreadStateChange tsc(self, kBlocked);
Elliott Hughesfc861622011-10-17 17:57:47 -0700196 if (wait_threshold != 0) {
197 waitStart = NanoTime() / 1000;
198 }
jeffhao33dc7712011-11-09 17:54:24 -0800199 current_locking_method = locking_method_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700200 current_locking_dex_pc = locking_dex_pc_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700201
202 lock_.Lock();
Elliott Hughesfc861622011-10-17 17:57:47 -0700203 if (wait_threshold != 0) {
204 waitEnd = NanoTime() / 1000;
205 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700206 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700207
208 if (wait_threshold != 0) {
209 uint64_t wait_ms = (waitEnd - waitStart) / 1000;
210 uint32_t sample_percent;
211 if (wait_ms >= wait_threshold) {
212 sample_percent = 100;
213 } else {
214 sample_percent = 100 * wait_ms / wait_threshold;
215 }
216 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
jeffhao33dc7712011-11-09 17:54:24 -0800217 const char* current_locking_filename;
218 uint32_t current_locking_line_number;
Ian Rogers0399dde2012-06-06 17:09:28 -0700219 TranslateLocation(current_locking_method, current_locking_dex_pc,
jeffhao33dc7712011-11-09 17:54:24 -0800220 current_locking_filename, current_locking_line_number);
221 LogContentionEvent(self, wait_ms, sample_percent, current_locking_filename, current_locking_line_number);
Elliott Hughesfc861622011-10-17 17:57:47 -0700222 }
223 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700224 }
225 owner_ = self;
226 DCHECK_EQ(lock_count_, 0);
227
228 // When debugging, save the current monitor holder for future
229 // acquisition failures to use in sampled logging.
Elliott Hughesfc861622011-10-17 17:57:47 -0700230 if (lock_profiling_threshold_ != 0) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700231 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
Elliott Hughesfc861622011-10-17 17:57:47 -0700232 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700233}
234
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800235static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
236 __attribute__((format(printf, 1, 2)));
237
238static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...) {
239 va_list args;
240 va_start(args, fmt);
241 Thread::Current()->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Brian Carlstrom64277f32012-03-26 23:53:34 -0700242 if (!Runtime::Current()->IsStarted()) {
243 std::ostringstream ss;
244 Thread::Current()->Dump(ss);
245 std::string str(ss.str());
246 LOG(ERROR) << "IllegalMonitorStateException: " << str;
247 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800248 va_end(args);
249}
250
Elliott Hughesd4237412012-02-21 11:24:45 -0800251static std::string ThreadToString(Thread* thread) {
252 if (thread == NULL) {
253 return "NULL";
254 }
255 std::ostringstream oss;
256 // TODO: alternatively, we could just return the thread's name.
257 oss << *thread;
258 return oss.str();
259}
260
Elliott Hughesffb465f2012-03-01 18:46:05 -0800261void Monitor::FailedUnlock(Object* o, Thread* expected_owner, Thread* found_owner,
262 Monitor* monitor) {
263 Thread* current_owner = NULL;
264 std::string current_owner_string;
265 std::string expected_owner_string;
266 std::string found_owner_string;
267 {
268 // TODO: isn't this too late to prevent threads from disappearing?
269 // Acquire thread list lock so threads won't disappear from under us.
270 ScopedThreadListLock thread_list_lock;
271 // Re-read owner now that we hold lock.
272 current_owner = (monitor != NULL) ? monitor->owner_ : NULL;
273 // Get short descriptions of the threads involved.
274 current_owner_string = ThreadToString(current_owner);
275 expected_owner_string = ThreadToString(expected_owner);
276 found_owner_string = ThreadToString(found_owner);
277 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800278 if (current_owner == NULL) {
279 if (found_owner == NULL) {
280 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
281 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800282 PrettyTypeOf(o).c_str(),
283 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800284 } else {
285 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800286 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
287 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800288 found_owner_string.c_str(),
289 PrettyTypeOf(o).c_str(),
290 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800291 }
292 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800293 if (found_owner == NULL) {
294 // Race: originally there was no owner, there is now
295 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
296 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800297 current_owner_string.c_str(),
298 PrettyTypeOf(o).c_str(),
299 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800300 } else {
301 if (found_owner != current_owner) {
302 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800303 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
304 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800305 found_owner_string.c_str(),
306 current_owner_string.c_str(),
307 PrettyTypeOf(o).c_str(),
308 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800309 } else {
310 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
311 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800312 current_owner_string.c_str(),
313 PrettyTypeOf(o).c_str(),
314 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800315 }
316 }
317 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700318}
319
320bool Monitor::Unlock(Thread* self) {
321 DCHECK(self != NULL);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800322 Thread* owner = owner_;
323 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700324 // We own the monitor, so nobody else can be in here.
325 if (lock_count_ == 0) {
326 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800327 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700328 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700329 lock_.Unlock();
330 } else {
331 --lock_count_;
332 }
333 } else {
334 // We don't own this, so we're not allowed to unlock it.
335 // The JNI spec says that we should throw IllegalMonitorStateException
336 // in this case.
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800337 FailedUnlock(obj_, self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700338 return false;
339 }
340 return true;
341}
342
Elliott Hughes8f751ab2012-05-15 17:12:40 -0700343// Converts the given waiting time (relative to "now") into an absolute time in 'ts'.
344static void ToAbsoluteTime(int64_t ms, int32_t ns, timespec* ts) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700345 int64_t endSec;
346
347#ifdef HAVE_TIMEDWAIT_MONOTONIC
348 clock_gettime(CLOCK_MONOTONIC, ts);
349#else
350 {
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700351 timeval tv;
Elliott Hughes5f791332011-09-15 17:45:30 -0700352 gettimeofday(&tv, NULL);
353 ts->tv_sec = tv.tv_sec;
354 ts->tv_nsec = tv.tv_usec * 1000;
355 }
356#endif
357 endSec = ts->tv_sec + ms / 1000;
358 if (endSec >= 0x7fffffff) {
Elliott Hughes8f751ab2012-05-15 17:12:40 -0700359 std::ostringstream ss;
360 Thread::Current()->Dump(ss);
361 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
Elliott Hughes5f791332011-09-15 17:45:30 -0700362 endSec = 0x7ffffffe;
363 }
364 ts->tv_sec = endSec;
365 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
366
367 // Catch rollover.
368 if (ts->tv_nsec >= 1000000000L) {
369 ts->tv_sec++;
370 ts->tv_nsec -= 1000000000L;
371 }
372}
373
Elliott Hughes5f791332011-09-15 17:45:30 -0700374/*
375 * Wait on a monitor until timeout, interrupt, or notification. Used for
376 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
377 *
378 * If another thread calls Thread.interrupt(), we throw InterruptedException
379 * and return immediately if one of the following are true:
380 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
381 * - blocked in join(), join(long), or join(long, int) methods of Thread
382 * - blocked in sleep(long), or sleep(long, int) methods of Thread
383 * Otherwise, we set the "interrupted" flag.
384 *
385 * Checks to make sure that "ns" is in the range 0-999999
386 * (i.e. fractions of a millisecond) and throws the appropriate
387 * exception if it isn't.
388 *
389 * The spec allows "spurious wakeups", and recommends that all code using
390 * Object.wait() do so in a loop. This appears to derive from concerns
391 * about pthread_cond_wait() on multiprocessor systems. Some commentary
392 * on the web casts doubt on whether these can/should occur.
393 *
394 * Since we're allowed to wake up "early", we clamp extremely long durations
395 * to return at the end of the 32-bit time epoch.
396 */
397void Monitor::Wait(Thread* self, int64_t ms, int32_t ns, bool interruptShouldThrow) {
398 DCHECK(self != NULL);
399
400 // Make sure that we hold the lock.
401 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800402 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700403 return;
404 }
405
406 // Enforce the timeout range.
407 if (ms < 0 || ns < 0 || ns > 999999) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700408 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Elliott Hughes5f791332011-09-15 17:45:30 -0700409 "timeout arguments out of range: ms=%lld ns=%d", ms, ns);
410 return;
411 }
412
413 // Compute absolute wakeup time, if necessary.
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700414 timespec ts;
Elliott Hughes5f791332011-09-15 17:45:30 -0700415 bool timed = false;
416 if (ms != 0 || ns != 0) {
417 ToAbsoluteTime(ms, ns, &ts);
418 timed = true;
419 }
420
421 /*
422 * Add ourselves to the set of threads waiting on this monitor, and
423 * release our hold. We need to let it go even if we're a few levels
424 * deep in a recursive lock, and we need to restore that later.
425 *
426 * We append to the wait set ahead of clearing the count and owner
427 * fields so the subroutine can check that the calling thread owns
428 * the monitor. Aside from that, the order of member updates is
429 * not order sensitive as we hold the pthread mutex.
430 */
431 AppendToWaitSet(self);
Ian Rogers0399dde2012-06-06 17:09:28 -0700432 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700433 lock_count_ = 0;
434 owner_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700435 const Method* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800436 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700437 uintptr_t saved_dex_pc = locking_dex_pc_;
438 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700439
440 /*
441 * Update thread status. If the GC wakes up, it'll ignore us, knowing
442 * that we won't touch any references in this state, and we'll check
443 * our suspend mode before we transition out.
444 */
445 if (timed) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700446 self->SetState(kTimedWaiting);
Elliott Hughes5f791332011-09-15 17:45:30 -0700447 } else {
Elliott Hughes34e06962012-04-09 13:55:55 -0700448 self->SetState(kWaiting);
Elliott Hughes5f791332011-09-15 17:45:30 -0700449 }
450
Elliott Hughes85d15452011-09-16 17:33:01 -0700451 self->wait_mutex_->Lock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700452
453 /*
454 * Set wait_monitor_ to the monitor object we will be waiting on.
455 * When wait_monitor_ is non-NULL a notifying or interrupting thread
456 * must signal the thread's wait_cond_ to wake it up.
457 */
458 DCHECK(self->wait_monitor_ == NULL);
459 self->wait_monitor_ = this;
460
461 /*
462 * Handle the case where the thread was interrupted before we called
463 * wait().
464 */
465 bool wasInterrupted = false;
466 if (self->interrupted_) {
467 wasInterrupted = true;
468 self->wait_monitor_ = NULL;
Elliott Hughes85d15452011-09-16 17:33:01 -0700469 self->wait_mutex_->Unlock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700470 goto done;
471 }
472
473 /*
474 * Release the monitor lock and wait for a notification or
475 * a timeout to occur.
476 */
477 lock_.Unlock();
478
479 if (!timed) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700480 self->wait_cond_->Wait(*self->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700481 } else {
Elliott Hughes85d15452011-09-16 17:33:01 -0700482 self->wait_cond_->TimedWait(*self->wait_mutex_, ts);
Elliott Hughes5f791332011-09-15 17:45:30 -0700483 }
484 if (self->interrupted_) {
485 wasInterrupted = true;
486 }
487
488 self->interrupted_ = false;
489 self->wait_monitor_ = NULL;
Elliott Hughes85d15452011-09-16 17:33:01 -0700490 self->wait_mutex_->Unlock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700491
492 // Reacquire the monitor lock.
493 Lock(self);
494
Elliott Hughesa21039c2012-06-21 12:09:25 -0700495 done:
Elliott Hughes5f791332011-09-15 17:45:30 -0700496 /*
497 * We remove our thread from wait set after restoring the count
498 * and owner fields so the subroutine can check that the calling
499 * thread owns the monitor. Aside from that, the order of member
500 * updates is not order sensitive as we hold the pthread mutex.
501 */
502 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700503 lock_count_ = prev_lock_count;
504 locking_method_ = saved_method;
505 locking_dex_pc_ = saved_dex_pc;
Elliott Hughes5f791332011-09-15 17:45:30 -0700506 RemoveFromWaitSet(self);
507
Elliott Hughes34e06962012-04-09 13:55:55 -0700508 /* set self->status back to kRunnable, and self-suspend if needed */
509 self->SetState(kRunnable);
Elliott Hughes5f791332011-09-15 17:45:30 -0700510
511 if (wasInterrupted) {
512 /*
513 * We were interrupted while waiting, or somebody interrupted an
514 * un-interruptible thread earlier and we're bailing out immediately.
515 *
516 * The doc sayeth: "The interrupted status of the current thread is
517 * cleared when this exception is thrown."
518 */
519 self->interrupted_ = false;
520 if (interruptShouldThrow) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700521 Thread::Current()->ThrowNewException("Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700522 }
523 }
524}
525
526void Monitor::Notify(Thread* self) {
527 DCHECK(self != NULL);
528
529 // Make sure that we hold the lock.
530 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800531 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700532 return;
533 }
534 // Signal the first waiting thread in the wait set.
535 while (wait_set_ != NULL) {
536 Thread* thread = wait_set_;
537 wait_set_ = thread->wait_next_;
538 thread->wait_next_ = NULL;
539
540 // Check to see if the thread is still waiting.
Elliott Hughes85d15452011-09-16 17:33:01 -0700541 MutexLock mu(*thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700542 if (thread->wait_monitor_ != NULL) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700543 thread->wait_cond_->Signal();
Elliott Hughes5f791332011-09-15 17:45:30 -0700544 return;
545 }
546 }
547}
548
549void Monitor::NotifyAll(Thread* self) {
550 DCHECK(self != NULL);
551
552 // Make sure that we hold the lock.
553 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800554 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700555 return;
556 }
557 // Signal all threads in the wait set.
558 while (wait_set_ != NULL) {
559 Thread* thread = wait_set_;
560 wait_set_ = thread->wait_next_;
561 thread->wait_next_ = NULL;
562 thread->Notify();
563 }
564}
565
566/*
567 * Changes the shape of a monitor from thin to fat, preserving the
568 * internal lock state. The calling thread must own the lock.
569 */
570void Monitor::Inflate(Thread* self, Object* obj) {
571 DCHECK(self != NULL);
572 DCHECK(obj != NULL);
573 DCHECK_EQ(LW_SHAPE(*obj->GetRawLockWordAddress()), LW_SHAPE_THIN);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700574 DCHECK_EQ(LW_LOCK_OWNER(*obj->GetRawLockWordAddress()), static_cast<int32_t>(self->GetThinLockId()));
Elliott Hughes5f791332011-09-15 17:45:30 -0700575
576 // Allocate and acquire a new monitor.
577 Monitor* m = new Monitor(obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800578 VLOG(monitor) << "monitor: thread " << self->GetThinLockId()
579 << " created monitor " << m << " for object " << obj;
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700580 Runtime::Current()->GetMonitorList()->Add(m);
Elliott Hughes5f791332011-09-15 17:45:30 -0700581 m->Lock(self);
582 // Propagate the lock state.
583 uint32_t thin = *obj->GetRawLockWordAddress();
584 m->lock_count_ = LW_LOCK_COUNT(thin);
585 thin &= LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT;
586 thin |= reinterpret_cast<uint32_t>(m) | LW_SHAPE_FAT;
587 // Publish the updated lock word.
588 android_atomic_release_store(thin, obj->GetRawLockWordAddress());
589}
590
591void Monitor::MonitorEnter(Thread* self, Object* obj) {
592 volatile int32_t* thinp = obj->GetRawLockWordAddress();
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700593 timespec tm;
Elliott Hughes398f64b2012-03-26 18:05:48 -0700594 uint32_t sleepDelayNs;
595 uint32_t minSleepDelayNs = 1000000; /* 1 millisecond */
596 uint32_t maxSleepDelayNs = 1000000000; /* 1 second */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700597 uint32_t thin, newThin;
Elliott Hughes5f791332011-09-15 17:45:30 -0700598
Elliott Hughes4681c802011-09-25 18:04:37 -0700599 DCHECK(self != NULL);
600 DCHECK(obj != NULL);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700601 uint32_t threadId = self->GetThinLockId();
Elliott Hughesa21039c2012-06-21 12:09:25 -0700602 retry:
Elliott Hughes5f791332011-09-15 17:45:30 -0700603 thin = *thinp;
604 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
605 /*
606 * The lock is a thin lock. The owner field is used to
607 * determine the acquire method, ordered by cost.
608 */
609 if (LW_LOCK_OWNER(thin) == threadId) {
610 /*
611 * The calling thread owns the lock. Increment the
612 * value of the recursion count field.
613 */
614 *thinp += 1 << LW_LOCK_COUNT_SHIFT;
615 if (LW_LOCK_COUNT(*thinp) == LW_LOCK_COUNT_MASK) {
616 /*
617 * The reacquisition limit has been reached. Inflate
618 * the lock so the next acquire will not overflow the
619 * recursion count field.
620 */
621 Inflate(self, obj);
622 }
623 } else if (LW_LOCK_OWNER(thin) == 0) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700624 // The lock is unowned. Install the thread id of the calling thread into the owner field.
625 // This is the common case: compiled code will have tried this before calling back into
626 // the runtime.
Elliott Hughes5f791332011-09-15 17:45:30 -0700627 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
628 if (android_atomic_acquire_cas(thin, newThin, thinp) != 0) {
629 // The acquire failed. Try again.
630 goto retry;
631 }
632 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800633 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p (a %s) owned by %d",
Elliott Hughes81ff3182012-03-23 20:35:56 -0700634 threadId, thinp, PrettyTypeOf(obj).c_str(), LW_LOCK_OWNER(thin));
635 // The lock is owned by another thread. Notify the runtime that we are about to wait.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700636 self->monitor_enter_object_ = obj;
Elliott Hughes34e06962012-04-09 13:55:55 -0700637 ThreadState oldStatus = self->SetState(kBlocked);
Elliott Hughes5f791332011-09-15 17:45:30 -0700638 // Spin until the thin lock is released or inflated.
639 sleepDelayNs = 0;
640 for (;;) {
641 thin = *thinp;
642 // Check the shape of the lock word. Another thread
643 // may have inflated the lock while we were waiting.
644 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
645 if (LW_LOCK_OWNER(thin) == 0) {
646 // The lock has been released. Install the thread id of the
647 // calling thread into the owner field.
648 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
649 if (android_atomic_acquire_cas(thin, newThin, thinp) == 0) {
650 // The acquire succeed. Break out of the loop and proceed to inflate the lock.
651 break;
652 }
653 } else {
654 // The lock has not been released. Yield so the owning thread can run.
655 if (sleepDelayNs == 0) {
656 sched_yield();
657 sleepDelayNs = minSleepDelayNs;
658 } else {
659 tm.tv_sec = 0;
660 tm.tv_nsec = sleepDelayNs;
661 nanosleep(&tm, NULL);
662 // Prepare the next delay value. Wrap to avoid once a second polls for eternity.
663 if (sleepDelayNs < maxSleepDelayNs / 2) {
664 sleepDelayNs *= 2;
665 } else {
666 sleepDelayNs = minSleepDelayNs;
667 }
668 }
669 }
670 } else {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700671 // The thin lock was inflated by another thread. Let the runtime know we are no longer
Elliott Hughes5f791332011-09-15 17:45:30 -0700672 // waiting and try again.
Elliott Hughes398f64b2012-03-26 18:05:48 -0700673 VLOG(monitor) << StringPrintf("monitor: thread %d found lock %p surprise-fattened by another thread", threadId, thinp);
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700674 self->monitor_enter_object_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700675 self->SetState(oldStatus);
676 goto retry;
677 }
678 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800679 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p done", threadId, thinp);
Elliott Hughes81ff3182012-03-23 20:35:56 -0700680 // We have acquired the thin lock. Let the runtime know that we are no longer waiting.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700681 self->monitor_enter_object_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700682 self->SetState(oldStatus);
683 // Fatten the lock.
684 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800685 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p", threadId, thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700686 }
687 } else {
688 // The lock is a fat lock.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800689 VLOG(monitor) << StringPrintf("monitor: thread %d locking fat lock %p (%p) %p on a %s",
Elliott Hughes398f64b2012-03-26 18:05:48 -0700690 threadId, thinp, LW_MONITOR(*thinp),
691 reinterpret_cast<void*>(*thinp), PrettyTypeOf(obj).c_str());
Elliott Hughes5f791332011-09-15 17:45:30 -0700692 DCHECK(LW_MONITOR(*thinp) != NULL);
693 LW_MONITOR(*thinp)->Lock(self);
694 }
695}
696
697bool Monitor::MonitorExit(Thread* self, Object* obj) {
698 volatile int32_t* thinp = obj->GetRawLockWordAddress();
699
700 DCHECK(self != NULL);
Elliott Hughes34e06962012-04-09 13:55:55 -0700701 //DCHECK_EQ(self->GetState(), kRunnable);
Elliott Hughes5f791332011-09-15 17:45:30 -0700702 DCHECK(obj != NULL);
703
704 /*
705 * Cache the lock word as its value can change while we are
706 * examining its state.
707 */
708 uint32_t thin = *thinp;
709 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
710 /*
711 * The lock is thin. We must ensure that the lock is owned
712 * by the given thread before unlocking it.
713 */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700714 if (LW_LOCK_OWNER(thin) == self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700715 /*
716 * We are the lock owner. It is safe to update the lock
717 * without CAS as lock ownership guards the lock itself.
718 */
719 if (LW_LOCK_COUNT(thin) == 0) {
720 /*
721 * The lock was not recursively acquired, the common
722 * case. Unlock by clearing all bits except for the
723 * hash state.
724 */
725 thin &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
726 android_atomic_release_store(thin, thinp);
727 } else {
728 /*
729 * The object was recursively acquired. Decrement the
730 * lock recursion count field.
731 */
732 *thinp -= 1 << LW_LOCK_COUNT_SHIFT;
733 }
734 } else {
735 /*
736 * We do not own the lock. The JVM spec requires that we
737 * throw an exception in this case.
738 */
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800739 FailedUnlock(obj, self, NULL, NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700740 return false;
741 }
742 } else {
743 /*
744 * The lock is fat. We must check to see if Unlock has
745 * raised any exceptions before continuing.
746 */
747 DCHECK(LW_MONITOR(*thinp) != NULL);
748 if (!LW_MONITOR(*thinp)->Unlock(self)) {
749 // An exception has been raised. Do not fall through.
750 return false;
751 }
752 }
753 return true;
754}
755
756/*
757 * Object.wait(). Also called for class init.
758 */
759void Monitor::Wait(Thread* self, Object *obj, int64_t ms, int32_t ns, bool interruptShouldThrow) {
760 volatile int32_t* thinp = obj->GetRawLockWordAddress();
761
762 // If the lock is still thin, we need to fatten it.
763 uint32_t thin = *thinp;
764 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
765 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700766 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800767 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700768 return;
769 }
770
771 /* This thread holds the lock. We need to fatten the lock
772 * so 'self' can block on it. Don't update the object lock
773 * field yet, because 'self' needs to acquire the lock before
774 * any other thread gets a chance.
775 */
776 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800777 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p by wait()", self->GetThinLockId(), thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700778 }
779 LW_MONITOR(*thinp)->Wait(self, ms, ns, interruptShouldThrow);
780}
781
782void Monitor::Notify(Thread* self, Object *obj) {
783 uint32_t thin = *obj->GetRawLockWordAddress();
784
785 // If the lock is still thin, there aren't any waiters;
786 // waiting on an object forces lock fattening.
787 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
788 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700789 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800790 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700791 return;
792 }
793 // no-op; there are no waiters to notify.
794 } else {
795 // It's a fat lock.
796 LW_MONITOR(thin)->Notify(self);
797 }
798}
799
800void Monitor::NotifyAll(Thread* self, Object *obj) {
801 uint32_t thin = *obj->GetRawLockWordAddress();
802
803 // If the lock is still thin, there aren't any waiters;
804 // waiting on an object forces lock fattening.
805 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
806 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700807 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800808 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700809 return;
810 }
811 // no-op; there are no waiters to notify.
812 } else {
813 // It's a fat lock.
814 LW_MONITOR(thin)->NotifyAll(self);
815 }
816}
817
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700818uint32_t Monitor::GetThinLockId(uint32_t raw_lock_word) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700819 if (LW_SHAPE(raw_lock_word) == LW_SHAPE_THIN) {
820 return LW_LOCK_OWNER(raw_lock_word);
821 } else {
822 Thread* owner = LW_MONITOR(raw_lock_word)->owner_;
823 return owner ? owner->GetThinLockId() : 0;
824 }
825}
826
Elliott Hughes044288f2012-06-25 14:46:39 -0700827static uint32_t LockOwnerFromThreadLock(Object* thread_lock) {
828 if (thread_lock == NULL || thread_lock->GetClass() != WellKnownClasses::ToClass(WellKnownClasses::java_lang_ThreadLock)) {
829 return ThreadList::kInvalidId;
830 }
831 Field* thread_field = DecodeField(WellKnownClasses::java_lang_ThreadLock_thread);
832 Object* managed_thread = thread_field->GetObject(thread_lock);
833 if (managed_thread == NULL) {
834 return ThreadList::kInvalidId;
835 }
836 Field* vmData_field = DecodeField(WellKnownClasses::java_lang_Thread_vmData);
837 uintptr_t vmData = static_cast<uintptr_t>(vmData_field->GetInt(managed_thread));
838 Thread* thread = reinterpret_cast<Thread*>(vmData);
839 if (thread == NULL) {
840 return ThreadList::kInvalidId;
841 }
842 return thread->GetThinLockId();
843}
844
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700845void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700846 ThreadState state = thread->GetState();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700847
848 Object* object = NULL;
849 uint32_t lock_owner = ThreadList::kInvalidId;
Elliott Hughes34e06962012-04-09 13:55:55 -0700850 if (state == kWaiting || state == kTimedWaiting) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700851 os << " - waiting on ";
852 Monitor* monitor = thread->wait_monitor_;
853 if (monitor != NULL) {
854 object = monitor->obj_;
855 }
Elliott Hughes044288f2012-06-25 14:46:39 -0700856 lock_owner = LockOwnerFromThreadLock(object);
Elliott Hughes34e06962012-04-09 13:55:55 -0700857 } else if (state == kBlocked) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700858 os << " - waiting to lock ";
859 object = thread->monitor_enter_object_;
860 if (object != NULL) {
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700861 lock_owner = object->GetThinLockId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700862 }
863 } else {
864 // We're not waiting on anything.
865 return;
866 }
867 os << "<" << object << ">";
868
869 // - waiting on <0x613f83d8> (a java.lang.ThreadLock) held by thread 5
870 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
871 os << " (a " << PrettyTypeOf(object) << ")";
872
873 if (lock_owner != ThreadList::kInvalidId) {
874 os << " held by thread " << lock_owner;
875 }
876
877 os << "\n";
878}
879
Ian Rogers0399dde2012-06-06 17:09:28 -0700880void Monitor::TranslateLocation(const Method* method, uint32_t dex_pc,
jeffhao33dc7712011-11-09 17:54:24 -0800881 const char*& source_file, uint32_t& line_number) const {
882 // If method is null, location is unknown
883 if (method == NULL) {
Elliott Hughes12c51e32012-01-17 20:25:05 -0800884 source_file = "";
jeffhao33dc7712011-11-09 17:54:24 -0800885 line_number = 0;
886 return;
887 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800888 MethodHelper mh(method);
889 source_file = mh.GetDeclaringClassSourceFile();
Elliott Hughes12c51e32012-01-17 20:25:05 -0800890 if (source_file == NULL) {
891 source_file = "";
892 }
Ian Rogers0399dde2012-06-06 17:09:28 -0700893 line_number = mh.GetLineNumFromDexPC(dex_pc);
jeffhao33dc7712011-11-09 17:54:24 -0800894}
895
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700896MonitorList::MonitorList() : lock_("MonitorList lock") {
897}
898
899MonitorList::~MonitorList() {
900 MutexLock mu(lock_);
901 STLDeleteElements(&list_);
902}
903
904void MonitorList::Add(Monitor* m) {
905 MutexLock mu(lock_);
906 list_.push_front(m);
907}
908
909void MonitorList::SweepMonitorList(Heap::IsMarkedTester is_marked, void* arg) {
910 MutexLock mu(lock_);
911 typedef std::list<Monitor*>::iterator It; // TODO: C++0x auto
912 It it = list_.begin();
913 while (it != list_.end()) {
914 Monitor* m = *it;
915 if (!is_marked(m->GetObject(), arg)) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800916 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object " << m->GetObject();
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700917 delete m;
918 it = list_.erase(it);
919 } else {
920 ++it;
921 }
922 }
923}
924
Elliott Hughes5f791332011-09-15 17:45:30 -0700925} // namespace art