blob: e3c98bba672ce476b41fc5673e18b7a0cbe5e8cc [file] [log] [blame]
Elliott Hughes5f791332011-09-15 17:45:30 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Elliott Hughes54e7df12011-09-16 11:47:04 -070017#include "monitor.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070018
19#include <errno.h>
20#include <fcntl.h>
21#include <pthread.h>
22#include <stdlib.h>
23#include <sys/time.h>
24#include <time.h>
25#include <unistd.h>
26
jeffhao33dc7712011-11-09 17:54:24 -080027#include "class_linker.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070028#include "mutex.h"
29#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080030#include "object_utils.h"
Elliott Hughesc33a32b2011-10-11 18:18:07 -070031#include "stl_util.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070032#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070033#include "thread_list.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070034
35namespace art {
36
37/*
38 * Every Object has a monitor associated with it, but not every Object is
39 * actually locked. Even the ones that are locked do not need a
40 * full-fledged monitor until a) there is actual contention or b) wait()
41 * is called on the Object.
42 *
43 * For Android, we have implemented a scheme similar to the one described
44 * in Bacon et al.'s "Thin locks: featherweight synchronization for Java"
45 * (ACM 1998). Things are even easier for us, though, because we have
46 * a full 32 bits to work with.
47 *
48 * The two states of an Object's lock are referred to as "thin" and
49 * "fat". A lock may transition from the "thin" state to the "fat"
50 * state and this transition is referred to as inflation. Once a lock
51 * has been inflated it remains in the "fat" state indefinitely.
52 *
53 * The lock value itself is stored in Object.lock. The LSB of the
54 * lock encodes its state. When cleared, the lock is in the "thin"
55 * state and its bits are formatted as follows:
56 *
57 * [31 ---- 19] [18 ---- 3] [2 ---- 1] [0]
58 * lock count thread id hash state 0
59 *
60 * When set, the lock is in the "fat" state and its bits are formatted
61 * as follows:
62 *
63 * [31 ---- 3] [2 ---- 1] [0]
64 * pointer hash state 1
65 *
66 * For an in-depth description of the mechanics of thin-vs-fat locking,
67 * read the paper referred to above.
Elliott Hughes54e7df12011-09-16 11:47:04 -070068 *
Elliott Hughes5f791332011-09-15 17:45:30 -070069 * Monitors provide:
70 * - mutually exclusive access to resources
71 * - a way for multiple threads to wait for notification
72 *
73 * In effect, they fill the role of both mutexes and condition variables.
74 *
75 * Only one thread can own the monitor at any time. There may be several
76 * threads waiting on it (the wait call unlocks it). One or more waiting
77 * threads may be getting interrupted or notified at any given time.
78 *
79 * TODO: the various members of monitor are not SMP-safe.
80 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070081
82
83/*
84 * Monitor accessor. Extracts a monitor structure pointer from a fat
85 * lock. Performs no error checking.
86 */
87#define LW_MONITOR(x) \
88 ((Monitor*)((x) & ~((LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT) | LW_SHAPE_MASK)))
89
90/*
91 * Lock recursion count field. Contains a count of the number of times
92 * a lock has been recursively acquired.
93 */
94#define LW_LOCK_COUNT_MASK 0x1fff
95#define LW_LOCK_COUNT_SHIFT 19
96#define LW_LOCK_COUNT(x) (((x) >> LW_LOCK_COUNT_SHIFT) & LW_LOCK_COUNT_MASK)
97
Elliott Hughesfc861622011-10-17 17:57:47 -070098bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -070099uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700100
Elliott Hughesfc861622011-10-17 17:57:47 -0700101bool Monitor::IsSensitiveThread() {
102 if (is_sensitive_thread_hook_ != NULL) {
103 return (*is_sensitive_thread_hook_)();
104 }
105 return false;
106}
107
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800108void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughesfc861622011-10-17 17:57:47 -0700109 lock_profiling_threshold_ = lock_profiling_threshold;
110 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700111}
112
Elliott Hughes5f791332011-09-15 17:45:30 -0700113Monitor::Monitor(Object* obj)
114 : owner_(NULL),
115 lock_count_(0),
116 obj_(obj),
117 wait_set_(NULL),
118 lock_("a monitor lock"),
jeffhao33dc7712011-11-09 17:54:24 -0800119 locking_method_(NULL),
120 locking_pc_(0) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700121}
122
123Monitor::~Monitor() {
124 DCHECK(obj_ != NULL);
125 DCHECK_EQ(LW_SHAPE(*obj_->GetRawLockWordAddress()), LW_SHAPE_FAT);
Elliott Hughes5f791332011-09-15 17:45:30 -0700126}
127
128/*
129 * Links a thread into a monitor's wait set. The monitor lock must be
130 * held by the caller of this routine.
131 */
132void Monitor::AppendToWaitSet(Thread* thread) {
133 DCHECK(owner_ == Thread::Current());
134 DCHECK(thread != NULL);
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700135 DCHECK(thread->wait_next_ == NULL) << thread->wait_next_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700136 if (wait_set_ == NULL) {
137 wait_set_ = thread;
138 return;
139 }
140
141 // push_back.
142 Thread* t = wait_set_;
143 while (t->wait_next_ != NULL) {
144 t = t->wait_next_;
145 }
146 t->wait_next_ = thread;
147}
148
149/*
150 * Unlinks a thread from a monitor's wait set. The monitor lock must
151 * be held by the caller of this routine.
152 */
153void Monitor::RemoveFromWaitSet(Thread *thread) {
154 DCHECK(owner_ == Thread::Current());
155 DCHECK(thread != NULL);
156 if (wait_set_ == NULL) {
157 return;
158 }
159 if (wait_set_ == thread) {
160 wait_set_ = thread->wait_next_;
161 thread->wait_next_ = NULL;
162 return;
163 }
164
165 Thread* t = wait_set_;
166 while (t->wait_next_ != NULL) {
167 if (t->wait_next_ == thread) {
168 t->wait_next_ = thread->wait_next_;
169 thread->wait_next_ = NULL;
170 return;
171 }
172 t = t->wait_next_;
173 }
174}
175
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700176Object* Monitor::GetObject() {
177 return obj_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700178}
179
Elliott Hughes5f791332011-09-15 17:45:30 -0700180void Monitor::Lock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700181 if (owner_ == self) {
182 lock_count_++;
183 return;
184 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700185
186 uint64_t waitStart, waitEnd;
Elliott Hughes5f791332011-09-15 17:45:30 -0700187 if (!lock_.TryLock()) {
Elliott Hughesfc861622011-10-17 17:57:47 -0700188 uint32_t wait_threshold = lock_profiling_threshold_;
jeffhao33dc7712011-11-09 17:54:24 -0800189 const Method* current_locking_method = NULL;
Elliott Hughese65a6c92012-01-18 23:48:31 -0800190 uintptr_t current_locking_pc = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700191 {
192 ScopedThreadStateChange tsc(self, Thread::kBlocked);
Elliott Hughesfc861622011-10-17 17:57:47 -0700193 if (wait_threshold != 0) {
194 waitStart = NanoTime() / 1000;
195 }
jeffhao33dc7712011-11-09 17:54:24 -0800196 current_locking_method = locking_method_;
197 current_locking_pc = locking_pc_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700198
199 lock_.Lock();
Elliott Hughesfc861622011-10-17 17:57:47 -0700200 if (wait_threshold != 0) {
201 waitEnd = NanoTime() / 1000;
202 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700203 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700204
205 if (wait_threshold != 0) {
206 uint64_t wait_ms = (waitEnd - waitStart) / 1000;
207 uint32_t sample_percent;
208 if (wait_ms >= wait_threshold) {
209 sample_percent = 100;
210 } else {
211 sample_percent = 100 * wait_ms / wait_threshold;
212 }
213 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
jeffhao33dc7712011-11-09 17:54:24 -0800214 const char* current_locking_filename;
215 uint32_t current_locking_line_number;
216 TranslateLocation(current_locking_method, current_locking_pc,
217 current_locking_filename, current_locking_line_number);
218 LogContentionEvent(self, wait_ms, sample_percent, current_locking_filename, current_locking_line_number);
Elliott Hughesfc861622011-10-17 17:57:47 -0700219 }
220 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700221 }
222 owner_ = self;
223 DCHECK_EQ(lock_count_, 0);
224
225 // When debugging, save the current monitor holder for future
226 // acquisition failures to use in sampled logging.
Elliott Hughesfc861622011-10-17 17:57:47 -0700227 if (lock_profiling_threshold_ != 0) {
Elliott Hughesd07986f2011-12-06 18:27:45 -0800228 locking_method_ = self->GetCurrentMethod(&locking_pc_);
Elliott Hughesfc861622011-10-17 17:57:47 -0700229 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700230}
231
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800232static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
233 __attribute__((format(printf, 1, 2)));
234
235static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...) {
236 va_list args;
237 va_start(args, fmt);
238 Thread::Current()->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
239 va_end(args);
240}
241
Elliott Hughesd4237412012-02-21 11:24:45 -0800242static std::string ThreadToString(Thread* thread) {
243 if (thread == NULL) {
244 return "NULL";
245 }
246 std::ostringstream oss;
247 // TODO: alternatively, we could just return the thread's name.
248 oss << *thread;
249 return oss.str();
250}
251
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800252void Monitor::FailedUnlock(Object* obj, Thread* expected_owner, Thread* found_owner,
253 Monitor* mon) {
254 // Acquire thread list lock so threads won't disappear from under us
Elliott Hughesb8d2eeb2012-02-29 16:44:41 -0800255 ScopedThreadListLock thread_list_lock;
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800256 // Re-read owner now that we hold lock
257 Thread* current_owner = mon != NULL ? mon->owner_ : NULL;
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800258 if (current_owner == NULL) {
259 if (found_owner == NULL) {
260 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
261 " on thread '%s'",
Elliott Hughesd4237412012-02-21 11:24:45 -0800262 PrettyTypeOf(obj).c_str(),
263 ThreadToString(expected_owner).c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800264 } else {
265 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800266 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
267 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesd4237412012-02-21 11:24:45 -0800268 ThreadToString(found_owner).c_str(),
269 PrettyTypeOf(obj).c_str(),
270 ThreadToString(expected_owner).c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800271 }
272 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800273 if (found_owner == NULL) {
274 // Race: originally there was no owner, there is now
275 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
276 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesd4237412012-02-21 11:24:45 -0800277 ThreadToString(current_owner).c_str(),
278 PrettyTypeOf(obj).c_str(),
279 ThreadToString(expected_owner).c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800280 } else {
281 if (found_owner != current_owner) {
282 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800283 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
284 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesd4237412012-02-21 11:24:45 -0800285 ThreadToString(found_owner).c_str(),
286 ThreadToString(current_owner).c_str(),
287 PrettyTypeOf(obj).c_str(),
288 ThreadToString(expected_owner).c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800289 } else {
290 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
291 " on thread '%s",
Elliott Hughesd4237412012-02-21 11:24:45 -0800292 ThreadToString(current_owner).c_str(),
293 PrettyTypeOf(obj).c_str(),
294 ThreadToString(expected_owner).c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800295 }
296 }
297 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700298}
299
300bool Monitor::Unlock(Thread* self) {
301 DCHECK(self != NULL);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800302 Thread* owner = owner_;
303 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700304 // We own the monitor, so nobody else can be in here.
305 if (lock_count_ == 0) {
306 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800307 locking_method_ = NULL;
308 locking_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700309 lock_.Unlock();
310 } else {
311 --lock_count_;
312 }
313 } else {
314 // We don't own this, so we're not allowed to unlock it.
315 // The JNI spec says that we should throw IllegalMonitorStateException
316 // in this case.
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800317 FailedUnlock(obj_, self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700318 return false;
319 }
320 return true;
321}
322
323/*
324 * Converts the given relative waiting time into an absolute time.
325 */
Elliott Hughesb8d2eeb2012-02-29 16:44:41 -0800326static void ToAbsoluteTime(int64_t ms, int32_t ns, struct timespec *ts) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700327 int64_t endSec;
328
329#ifdef HAVE_TIMEDWAIT_MONOTONIC
330 clock_gettime(CLOCK_MONOTONIC, ts);
331#else
332 {
333 struct timeval tv;
334 gettimeofday(&tv, NULL);
335 ts->tv_sec = tv.tv_sec;
336 ts->tv_nsec = tv.tv_usec * 1000;
337 }
338#endif
339 endSec = ts->tv_sec + ms / 1000;
340 if (endSec >= 0x7fffffff) {
341 LOG(INFO) << "Note: end time exceeds epoch";
342 endSec = 0x7ffffffe;
343 }
344 ts->tv_sec = endSec;
345 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
346
347 // Catch rollover.
348 if (ts->tv_nsec >= 1000000000L) {
349 ts->tv_sec++;
350 ts->tv_nsec -= 1000000000L;
351 }
352}
353
Elliott Hughes5f791332011-09-15 17:45:30 -0700354/*
355 * Wait on a monitor until timeout, interrupt, or notification. Used for
356 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
357 *
358 * If another thread calls Thread.interrupt(), we throw InterruptedException
359 * and return immediately if one of the following are true:
360 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
361 * - blocked in join(), join(long), or join(long, int) methods of Thread
362 * - blocked in sleep(long), or sleep(long, int) methods of Thread
363 * Otherwise, we set the "interrupted" flag.
364 *
365 * Checks to make sure that "ns" is in the range 0-999999
366 * (i.e. fractions of a millisecond) and throws the appropriate
367 * exception if it isn't.
368 *
369 * The spec allows "spurious wakeups", and recommends that all code using
370 * Object.wait() do so in a loop. This appears to derive from concerns
371 * about pthread_cond_wait() on multiprocessor systems. Some commentary
372 * on the web casts doubt on whether these can/should occur.
373 *
374 * Since we're allowed to wake up "early", we clamp extremely long durations
375 * to return at the end of the 32-bit time epoch.
376 */
377void Monitor::Wait(Thread* self, int64_t ms, int32_t ns, bool interruptShouldThrow) {
378 DCHECK(self != NULL);
379
380 // Make sure that we hold the lock.
381 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800382 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700383 return;
384 }
385
386 // Enforce the timeout range.
387 if (ms < 0 || ns < 0 || ns > 999999) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700388 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Elliott Hughes5f791332011-09-15 17:45:30 -0700389 "timeout arguments out of range: ms=%lld ns=%d", ms, ns);
390 return;
391 }
392
393 // Compute absolute wakeup time, if necessary.
394 struct timespec ts;
395 bool timed = false;
396 if (ms != 0 || ns != 0) {
397 ToAbsoluteTime(ms, ns, &ts);
398 timed = true;
399 }
400
401 /*
402 * Add ourselves to the set of threads waiting on this monitor, and
403 * release our hold. We need to let it go even if we're a few levels
404 * deep in a recursive lock, and we need to restore that later.
405 *
406 * We append to the wait set ahead of clearing the count and owner
407 * fields so the subroutine can check that the calling thread owns
408 * the monitor. Aside from that, the order of member updates is
409 * not order sensitive as we hold the pthread mutex.
410 */
411 AppendToWaitSet(self);
412 int prevLockCount = lock_count_;
413 lock_count_ = 0;
414 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800415 const Method* savedMethod = locking_method_;
416 locking_method_ = NULL;
Elliott Hughese65a6c92012-01-18 23:48:31 -0800417 uintptr_t savedPc = locking_pc_;
jeffhao33dc7712011-11-09 17:54:24 -0800418 locking_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700419
420 /*
421 * Update thread status. If the GC wakes up, it'll ignore us, knowing
422 * that we won't touch any references in this state, and we'll check
423 * our suspend mode before we transition out.
424 */
425 if (timed) {
426 self->SetState(Thread::kTimedWaiting);
427 } else {
428 self->SetState(Thread::kWaiting);
429 }
430
Elliott Hughes85d15452011-09-16 17:33:01 -0700431 self->wait_mutex_->Lock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700432
433 /*
434 * Set wait_monitor_ to the monitor object we will be waiting on.
435 * When wait_monitor_ is non-NULL a notifying or interrupting thread
436 * must signal the thread's wait_cond_ to wake it up.
437 */
438 DCHECK(self->wait_monitor_ == NULL);
439 self->wait_monitor_ = this;
440
441 /*
442 * Handle the case where the thread was interrupted before we called
443 * wait().
444 */
445 bool wasInterrupted = false;
446 if (self->interrupted_) {
447 wasInterrupted = true;
448 self->wait_monitor_ = NULL;
Elliott Hughes85d15452011-09-16 17:33:01 -0700449 self->wait_mutex_->Unlock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700450 goto done;
451 }
452
453 /*
454 * Release the monitor lock and wait for a notification or
455 * a timeout to occur.
456 */
457 lock_.Unlock();
458
459 if (!timed) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700460 self->wait_cond_->Wait(*self->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700461 } else {
Elliott Hughes85d15452011-09-16 17:33:01 -0700462 self->wait_cond_->TimedWait(*self->wait_mutex_, ts);
Elliott Hughes5f791332011-09-15 17:45:30 -0700463 }
464 if (self->interrupted_) {
465 wasInterrupted = true;
466 }
467
468 self->interrupted_ = false;
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
472 // Reacquire the monitor lock.
473 Lock(self);
474
475done:
476 /*
477 * We remove our thread from wait set after restoring the count
478 * and owner fields so the subroutine can check that the calling
479 * thread owns the monitor. Aside from that, the order of member
480 * updates is not order sensitive as we hold the pthread mutex.
481 */
482 owner_ = self;
483 lock_count_ = prevLockCount;
jeffhao33dc7712011-11-09 17:54:24 -0800484 locking_method_ = savedMethod;
485 locking_pc_ = savedPc;
Elliott Hughes5f791332011-09-15 17:45:30 -0700486 RemoveFromWaitSet(self);
487
488 /* set self->status back to Thread::kRunnable, and self-suspend if needed */
489 self->SetState(Thread::kRunnable);
490
491 if (wasInterrupted) {
492 /*
493 * We were interrupted while waiting, or somebody interrupted an
494 * un-interruptible thread earlier and we're bailing out immediately.
495 *
496 * The doc sayeth: "The interrupted status of the current thread is
497 * cleared when this exception is thrown."
498 */
499 self->interrupted_ = false;
500 if (interruptShouldThrow) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700501 Thread::Current()->ThrowNewException("Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700502 }
503 }
504}
505
506void Monitor::Notify(Thread* self) {
507 DCHECK(self != NULL);
508
509 // Make sure that we hold the lock.
510 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800511 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700512 return;
513 }
514 // Signal the first waiting thread in the wait set.
515 while (wait_set_ != NULL) {
516 Thread* thread = wait_set_;
517 wait_set_ = thread->wait_next_;
518 thread->wait_next_ = NULL;
519
520 // Check to see if the thread is still waiting.
Elliott Hughes85d15452011-09-16 17:33:01 -0700521 MutexLock mu(*thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700522 if (thread->wait_monitor_ != NULL) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700523 thread->wait_cond_->Signal();
Elliott Hughes5f791332011-09-15 17:45:30 -0700524 return;
525 }
526 }
527}
528
529void Monitor::NotifyAll(Thread* self) {
530 DCHECK(self != NULL);
531
532 // Make sure that we hold the lock.
533 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800534 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700535 return;
536 }
537 // Signal all threads in the wait set.
538 while (wait_set_ != NULL) {
539 Thread* thread = wait_set_;
540 wait_set_ = thread->wait_next_;
541 thread->wait_next_ = NULL;
542 thread->Notify();
543 }
544}
545
546/*
547 * Changes the shape of a monitor from thin to fat, preserving the
548 * internal lock state. The calling thread must own the lock.
549 */
550void Monitor::Inflate(Thread* self, Object* obj) {
551 DCHECK(self != NULL);
552 DCHECK(obj != NULL);
553 DCHECK_EQ(LW_SHAPE(*obj->GetRawLockWordAddress()), LW_SHAPE_THIN);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700554 DCHECK_EQ(LW_LOCK_OWNER(*obj->GetRawLockWordAddress()), static_cast<int32_t>(self->GetThinLockId()));
Elliott Hughes5f791332011-09-15 17:45:30 -0700555
556 // Allocate and acquire a new monitor.
557 Monitor* m = new Monitor(obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800558 VLOG(monitor) << "monitor: thread " << self->GetThinLockId()
559 << " created monitor " << m << " for object " << obj;
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700560 Runtime::Current()->GetMonitorList()->Add(m);
Elliott Hughes5f791332011-09-15 17:45:30 -0700561 m->Lock(self);
562 // Propagate the lock state.
563 uint32_t thin = *obj->GetRawLockWordAddress();
564 m->lock_count_ = LW_LOCK_COUNT(thin);
565 thin &= LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT;
566 thin |= reinterpret_cast<uint32_t>(m) | LW_SHAPE_FAT;
567 // Publish the updated lock word.
568 android_atomic_release_store(thin, obj->GetRawLockWordAddress());
569}
570
571void Monitor::MonitorEnter(Thread* self, Object* obj) {
572 volatile int32_t* thinp = obj->GetRawLockWordAddress();
573 struct timespec tm;
574 long sleepDelayNs;
575 long minSleepDelayNs = 1000000; /* 1 millisecond */
576 long maxSleepDelayNs = 1000000000; /* 1 second */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700577 uint32_t thin, newThin;
Elliott Hughes5f791332011-09-15 17:45:30 -0700578
Elliott Hughes4681c802011-09-25 18:04:37 -0700579 DCHECK(self != NULL);
580 DCHECK(obj != NULL);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700581 uint32_t threadId = self->GetThinLockId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700582retry:
583 thin = *thinp;
584 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
585 /*
586 * The lock is a thin lock. The owner field is used to
587 * determine the acquire method, ordered by cost.
588 */
589 if (LW_LOCK_OWNER(thin) == threadId) {
590 /*
591 * The calling thread owns the lock. Increment the
592 * value of the recursion count field.
593 */
594 *thinp += 1 << LW_LOCK_COUNT_SHIFT;
595 if (LW_LOCK_COUNT(*thinp) == LW_LOCK_COUNT_MASK) {
596 /*
597 * The reacquisition limit has been reached. Inflate
598 * the lock so the next acquire will not overflow the
599 * recursion count field.
600 */
601 Inflate(self, obj);
602 }
603 } else if (LW_LOCK_OWNER(thin) == 0) {
604 /*
605 * The lock is unowned. Install the thread id of the
606 * calling thread into the owner field. This is the
607 * common case. In performance critical code the JIT
608 * will have tried this before calling out to the VM.
609 */
610 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
611 if (android_atomic_acquire_cas(thin, newThin, thinp) != 0) {
612 // The acquire failed. Try again.
613 goto retry;
614 }
615 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800616 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p (a %s) owned by %d",
617 threadId, thinp, PrettyTypeOf(obj).c_str(), LW_LOCK_OWNER(thin));
Elliott Hughes5f791332011-09-15 17:45:30 -0700618 // The lock is owned by another thread. Notify the VM that we are about to wait.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700619 self->monitor_enter_object_ = obj;
Elliott Hughes5f791332011-09-15 17:45:30 -0700620 Thread::State oldStatus = self->SetState(Thread::kBlocked);
621 // Spin until the thin lock is released or inflated.
622 sleepDelayNs = 0;
623 for (;;) {
624 thin = *thinp;
625 // Check the shape of the lock word. Another thread
626 // may have inflated the lock while we were waiting.
627 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
628 if (LW_LOCK_OWNER(thin) == 0) {
629 // The lock has been released. Install the thread id of the
630 // calling thread into the owner field.
631 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
632 if (android_atomic_acquire_cas(thin, newThin, thinp) == 0) {
633 // The acquire succeed. Break out of the loop and proceed to inflate the lock.
634 break;
635 }
636 } else {
637 // The lock has not been released. Yield so the owning thread can run.
638 if (sleepDelayNs == 0) {
639 sched_yield();
640 sleepDelayNs = minSleepDelayNs;
641 } else {
642 tm.tv_sec = 0;
643 tm.tv_nsec = sleepDelayNs;
644 nanosleep(&tm, NULL);
645 // Prepare the next delay value. Wrap to avoid once a second polls for eternity.
646 if (sleepDelayNs < maxSleepDelayNs / 2) {
647 sleepDelayNs *= 2;
648 } else {
649 sleepDelayNs = minSleepDelayNs;
650 }
651 }
652 }
653 } else {
654 // The thin lock was inflated by another thread. Let the VM know we are no longer
655 // waiting and try again.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800656 VLOG(monitor) << "monitor: thread " << threadId
657 << " found lock " << (void*) thinp << " surprise-fattened by another thread";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700658 self->monitor_enter_object_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700659 self->SetState(oldStatus);
660 goto retry;
661 }
662 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800663 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p done", threadId, thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700664 // We have acquired the thin lock. Let the VM know that we are no longer waiting.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700665 self->monitor_enter_object_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700666 self->SetState(oldStatus);
667 // Fatten the lock.
668 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800669 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p", threadId, thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700670 }
671 } else {
672 // The lock is a fat lock.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800673 VLOG(monitor) << StringPrintf("monitor: thread %d locking fat lock %p (%p) %p on a %s",
Elliott Hughesf8e01272011-10-17 11:29:05 -0700674 threadId, thinp, LW_MONITOR(*thinp), (void*)*thinp, PrettyTypeOf(obj).c_str());
Elliott Hughes5f791332011-09-15 17:45:30 -0700675 DCHECK(LW_MONITOR(*thinp) != NULL);
676 LW_MONITOR(*thinp)->Lock(self);
677 }
678}
679
680bool Monitor::MonitorExit(Thread* self, Object* obj) {
681 volatile int32_t* thinp = obj->GetRawLockWordAddress();
682
683 DCHECK(self != NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -0700684 //DCHECK_EQ(self->GetState(), Thread::kRunnable);
Elliott Hughes5f791332011-09-15 17:45:30 -0700685 DCHECK(obj != NULL);
686
687 /*
688 * Cache the lock word as its value can change while we are
689 * examining its state.
690 */
691 uint32_t thin = *thinp;
692 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
693 /*
694 * The lock is thin. We must ensure that the lock is owned
695 * by the given thread before unlocking it.
696 */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700697 if (LW_LOCK_OWNER(thin) == self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700698 /*
699 * We are the lock owner. It is safe to update the lock
700 * without CAS as lock ownership guards the lock itself.
701 */
702 if (LW_LOCK_COUNT(thin) == 0) {
703 /*
704 * The lock was not recursively acquired, the common
705 * case. Unlock by clearing all bits except for the
706 * hash state.
707 */
708 thin &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
709 android_atomic_release_store(thin, thinp);
710 } else {
711 /*
712 * The object was recursively acquired. Decrement the
713 * lock recursion count field.
714 */
715 *thinp -= 1 << LW_LOCK_COUNT_SHIFT;
716 }
717 } else {
718 /*
719 * We do not own the lock. The JVM spec requires that we
720 * throw an exception in this case.
721 */
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800722 FailedUnlock(obj, self, NULL, NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700723 return false;
724 }
725 } else {
726 /*
727 * The lock is fat. We must check to see if Unlock has
728 * raised any exceptions before continuing.
729 */
730 DCHECK(LW_MONITOR(*thinp) != NULL);
731 if (!LW_MONITOR(*thinp)->Unlock(self)) {
732 // An exception has been raised. Do not fall through.
733 return false;
734 }
735 }
736 return true;
737}
738
739/*
740 * Object.wait(). Also called for class init.
741 */
742void Monitor::Wait(Thread* self, Object *obj, int64_t ms, int32_t ns, bool interruptShouldThrow) {
743 volatile int32_t* thinp = obj->GetRawLockWordAddress();
744
745 // If the lock is still thin, we need to fatten it.
746 uint32_t thin = *thinp;
747 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
748 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700749 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800750 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700751 return;
752 }
753
754 /* This thread holds the lock. We need to fatten the lock
755 * so 'self' can block on it. Don't update the object lock
756 * field yet, because 'self' needs to acquire the lock before
757 * any other thread gets a chance.
758 */
759 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800760 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p by wait()", self->GetThinLockId(), thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700761 }
762 LW_MONITOR(*thinp)->Wait(self, ms, ns, interruptShouldThrow);
763}
764
765void Monitor::Notify(Thread* self, Object *obj) {
766 uint32_t thin = *obj->GetRawLockWordAddress();
767
768 // If the lock is still thin, there aren't any waiters;
769 // waiting on an object forces lock fattening.
770 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
771 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700772 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800773 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700774 return;
775 }
776 // no-op; there are no waiters to notify.
777 } else {
778 // It's a fat lock.
779 LW_MONITOR(thin)->Notify(self);
780 }
781}
782
783void Monitor::NotifyAll(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 notifyAll()");
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)->NotifyAll(self);
798 }
799}
800
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700801uint32_t Monitor::GetThinLockId(uint32_t raw_lock_word) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700802 if (LW_SHAPE(raw_lock_word) == LW_SHAPE_THIN) {
803 return LW_LOCK_OWNER(raw_lock_word);
804 } else {
805 Thread* owner = LW_MONITOR(raw_lock_word)->owner_;
806 return owner ? owner->GetThinLockId() : 0;
807 }
808}
809
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700810void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
811 Thread::State state = thread->GetState();
812
813 Object* object = NULL;
814 uint32_t lock_owner = ThreadList::kInvalidId;
815 if (state == Thread::kWaiting || state == Thread::kTimedWaiting) {
816 os << " - waiting on ";
817 Monitor* monitor = thread->wait_monitor_;
818 if (monitor != NULL) {
819 object = monitor->obj_;
820 }
821 lock_owner = Thread::LockOwnerFromThreadLock(object);
822 } else if (state == Thread::kBlocked) {
823 os << " - waiting to lock ";
824 object = thread->monitor_enter_object_;
825 if (object != NULL) {
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700826 lock_owner = object->GetThinLockId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700827 }
828 } else {
829 // We're not waiting on anything.
830 return;
831 }
832 os << "<" << object << ">";
833
834 // - waiting on <0x613f83d8> (a java.lang.ThreadLock) held by thread 5
835 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
836 os << " (a " << PrettyTypeOf(object) << ")";
837
838 if (lock_owner != ThreadList::kInvalidId) {
839 os << " held by thread " << lock_owner;
840 }
841
842 os << "\n";
843}
844
jeffhao33dc7712011-11-09 17:54:24 -0800845void Monitor::TranslateLocation(const Method* method, uint32_t pc,
846 const char*& source_file, uint32_t& line_number) const {
847 // If method is null, location is unknown
848 if (method == NULL) {
Elliott Hughes12c51e32012-01-17 20:25:05 -0800849 source_file = "";
jeffhao33dc7712011-11-09 17:54:24 -0800850 line_number = 0;
851 return;
852 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800853 MethodHelper mh(method);
854 source_file = mh.GetDeclaringClassSourceFile();
Elliott Hughes12c51e32012-01-17 20:25:05 -0800855 if (source_file == NULL) {
856 source_file = "";
857 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800858 line_number = mh.GetLineNumFromNativePC(pc);
jeffhao33dc7712011-11-09 17:54:24 -0800859}
860
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700861MonitorList::MonitorList() : lock_("MonitorList lock") {
862}
863
864MonitorList::~MonitorList() {
865 MutexLock mu(lock_);
866 STLDeleteElements(&list_);
867}
868
869void MonitorList::Add(Monitor* m) {
870 MutexLock mu(lock_);
871 list_.push_front(m);
872}
873
874void MonitorList::SweepMonitorList(Heap::IsMarkedTester is_marked, void* arg) {
875 MutexLock mu(lock_);
876 typedef std::list<Monitor*>::iterator It; // TODO: C++0x auto
877 It it = list_.begin();
878 while (it != list_.end()) {
879 Monitor* m = *it;
880 if (!is_marked(m->GetObject(), arg)) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800881 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object " << m->GetObject();
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700882 delete m;
883 it = list_.erase(it);
884 } else {
885 ++it;
886 }
887 }
888}
889
Elliott Hughes5f791332011-09-15 17:45:30 -0700890} // namespace art