blob: b9a94590f32b86ff90bfa770a8f806c03c8d08b6 [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"
Elliott Hughesc33a32b2011-10-11 18:18:07 -070030#include "stl_util.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070031#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070032#include "thread_list.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070033
34namespace art {
35
36/*
37 * Every Object has a monitor associated with it, but not every Object is
38 * actually locked. Even the ones that are locked do not need a
39 * full-fledged monitor until a) there is actual contention or b) wait()
40 * is called on the Object.
41 *
42 * For Android, we have implemented a scheme similar to the one described
43 * in Bacon et al.'s "Thin locks: featherweight synchronization for Java"
44 * (ACM 1998). Things are even easier for us, though, because we have
45 * a full 32 bits to work with.
46 *
47 * The two states of an Object's lock are referred to as "thin" and
48 * "fat". A lock may transition from the "thin" state to the "fat"
49 * state and this transition is referred to as inflation. Once a lock
50 * has been inflated it remains in the "fat" state indefinitely.
51 *
52 * The lock value itself is stored in Object.lock. The LSB of the
53 * lock encodes its state. When cleared, the lock is in the "thin"
54 * state and its bits are formatted as follows:
55 *
56 * [31 ---- 19] [18 ---- 3] [2 ---- 1] [0]
57 * lock count thread id hash state 0
58 *
59 * When set, the lock is in the "fat" state and its bits are formatted
60 * as follows:
61 *
62 * [31 ---- 3] [2 ---- 1] [0]
63 * pointer hash state 1
64 *
65 * For an in-depth description of the mechanics of thin-vs-fat locking,
66 * read the paper referred to above.
Elliott Hughes54e7df12011-09-16 11:47:04 -070067 *
Elliott Hughes5f791332011-09-15 17:45:30 -070068 * Monitors provide:
69 * - mutually exclusive access to resources
70 * - a way for multiple threads to wait for notification
71 *
72 * In effect, they fill the role of both mutexes and condition variables.
73 *
74 * Only one thread can own the monitor at any time. There may be several
75 * threads waiting on it (the wait call unlocks it). One or more waiting
76 * threads may be getting interrupted or notified at any given time.
77 *
78 * TODO: the various members of monitor are not SMP-safe.
79 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070080
81
82/*
83 * Monitor accessor. Extracts a monitor structure pointer from a fat
84 * lock. Performs no error checking.
85 */
86#define LW_MONITOR(x) \
87 ((Monitor*)((x) & ~((LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT) | LW_SHAPE_MASK)))
88
89/*
90 * Lock recursion count field. Contains a count of the number of times
91 * a lock has been recursively acquired.
92 */
93#define LW_LOCK_COUNT_MASK 0x1fff
94#define LW_LOCK_COUNT_SHIFT 19
95#define LW_LOCK_COUNT(x) (((x) >> LW_LOCK_COUNT_SHIFT) & LW_LOCK_COUNT_MASK)
96
Elliott Hughesfc861622011-10-17 17:57:47 -070097bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070098bool Monitor::is_verbose_ = false;
Elliott Hughesfc861622011-10-17 17:57:47 -070099uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700100
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700101bool Monitor::IsVerbose() {
102 return is_verbose_;
103}
104
Elliott Hughesfc861622011-10-17 17:57:47 -0700105bool Monitor::IsSensitiveThread() {
106 if (is_sensitive_thread_hook_ != NULL) {
107 return (*is_sensitive_thread_hook_)();
108 }
109 return false;
110}
111
112void Monitor::Init(bool is_verbose, uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700113 is_verbose_ = is_verbose;
Elliott Hughesfc861622011-10-17 17:57:47 -0700114 lock_profiling_threshold_ = lock_profiling_threshold;
115 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700116}
117
Elliott Hughes5f791332011-09-15 17:45:30 -0700118Monitor::Monitor(Object* obj)
119 : owner_(NULL),
120 lock_count_(0),
121 obj_(obj),
122 wait_set_(NULL),
123 lock_("a monitor lock"),
jeffhao33dc7712011-11-09 17:54:24 -0800124 locking_method_(NULL),
125 locking_pc_(0) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700126}
127
128Monitor::~Monitor() {
129 DCHECK(obj_ != NULL);
130 DCHECK_EQ(LW_SHAPE(*obj_->GetRawLockWordAddress()), LW_SHAPE_FAT);
131
132#ifndef NDEBUG
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700133 // This lock is associated with an object that's being swept.
134 bool locked = lock_.TryLock();
135 DCHECK(locked) << obj_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700136 lock_.Unlock();
137#endif
138}
139
140/*
141 * Links a thread into a monitor's wait set. The monitor lock must be
142 * held by the caller of this routine.
143 */
144void Monitor::AppendToWaitSet(Thread* thread) {
145 DCHECK(owner_ == Thread::Current());
146 DCHECK(thread != NULL);
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700147 DCHECK(thread->wait_next_ == NULL) << thread->wait_next_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700148 if (wait_set_ == NULL) {
149 wait_set_ = thread;
150 return;
151 }
152
153 // push_back.
154 Thread* t = wait_set_;
155 while (t->wait_next_ != NULL) {
156 t = t->wait_next_;
157 }
158 t->wait_next_ = thread;
159}
160
161/*
162 * Unlinks a thread from a monitor's wait set. The monitor lock must
163 * be held by the caller of this routine.
164 */
165void Monitor::RemoveFromWaitSet(Thread *thread) {
166 DCHECK(owner_ == Thread::Current());
167 DCHECK(thread != NULL);
168 if (wait_set_ == NULL) {
169 return;
170 }
171 if (wait_set_ == thread) {
172 wait_set_ = thread->wait_next_;
173 thread->wait_next_ = NULL;
174 return;
175 }
176
177 Thread* t = wait_set_;
178 while (t->wait_next_ != NULL) {
179 if (t->wait_next_ == thread) {
180 t->wait_next_ = thread->wait_next_;
181 thread->wait_next_ = NULL;
182 return;
183 }
184 t = t->wait_next_;
185 }
186}
187
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700188Object* Monitor::GetObject() {
189 return obj_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700190}
191
Elliott Hughes5f791332011-09-15 17:45:30 -0700192void Monitor::Lock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700193 if (owner_ == self) {
194 lock_count_++;
195 return;
196 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700197
198 uint64_t waitStart, waitEnd;
Elliott Hughes5f791332011-09-15 17:45:30 -0700199 if (!lock_.TryLock()) {
Elliott Hughesfc861622011-10-17 17:57:47 -0700200 uint32_t wait_threshold = lock_profiling_threshold_;
jeffhao33dc7712011-11-09 17:54:24 -0800201 const Method* current_locking_method = NULL;
202 uint32_t current_locking_pc = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700203 {
204 ScopedThreadStateChange tsc(self, Thread::kBlocked);
Elliott Hughesfc861622011-10-17 17:57:47 -0700205 if (wait_threshold != 0) {
206 waitStart = NanoTime() / 1000;
207 }
jeffhao33dc7712011-11-09 17:54:24 -0800208 current_locking_method = locking_method_;
209 current_locking_pc = locking_pc_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700210
211 lock_.Lock();
Elliott Hughesfc861622011-10-17 17:57:47 -0700212 if (wait_threshold != 0) {
213 waitEnd = NanoTime() / 1000;
214 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700215 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700216
217 if (wait_threshold != 0) {
218 uint64_t wait_ms = (waitEnd - waitStart) / 1000;
219 uint32_t sample_percent;
220 if (wait_ms >= wait_threshold) {
221 sample_percent = 100;
222 } else {
223 sample_percent = 100 * wait_ms / wait_threshold;
224 }
225 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
jeffhao33dc7712011-11-09 17:54:24 -0800226 const char* current_locking_filename;
227 uint32_t current_locking_line_number;
228 TranslateLocation(current_locking_method, current_locking_pc,
229 current_locking_filename, current_locking_line_number);
230 LogContentionEvent(self, wait_ms, sample_percent, current_locking_filename, current_locking_line_number);
Elliott Hughesfc861622011-10-17 17:57:47 -0700231 }
232 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700233 }
234 owner_ = self;
235 DCHECK_EQ(lock_count_, 0);
236
237 // When debugging, save the current monitor holder for future
238 // acquisition failures to use in sampled logging.
Elliott Hughesfc861622011-10-17 17:57:47 -0700239 if (lock_profiling_threshold_ != 0) {
jeffhao33dc7712011-11-09 17:54:24 -0800240 locking_method_ = self->GetCurrentMethod();
241 locking_pc_ = self->GetCurrentReturnPc();
Elliott Hughesfc861622011-10-17 17:57:47 -0700242 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700243}
244
245void ThrowIllegalMonitorStateException(const char* msg) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700246 Thread::Current()->ThrowNewException("Ljava/lang/IllegalMonitorStateException;", msg);
Elliott Hughes5f791332011-09-15 17:45:30 -0700247}
248
249bool Monitor::Unlock(Thread* self) {
250 DCHECK(self != NULL);
251 if (owner_ == self) {
252 // We own the monitor, so nobody else can be in here.
253 if (lock_count_ == 0) {
254 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800255 locking_method_ = NULL;
256 locking_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700257 lock_.Unlock();
258 } else {
259 --lock_count_;
260 }
261 } else {
262 // We don't own this, so we're not allowed to unlock it.
263 // The JNI spec says that we should throw IllegalMonitorStateException
264 // in this case.
265 ThrowIllegalMonitorStateException("unlock of unowned monitor");
266 return false;
267 }
268 return true;
269}
270
271/*
272 * Converts the given relative waiting time into an absolute time.
273 */
274void ToAbsoluteTime(int64_t ms, int32_t ns, struct timespec *ts) {
275 int64_t endSec;
276
277#ifdef HAVE_TIMEDWAIT_MONOTONIC
278 clock_gettime(CLOCK_MONOTONIC, ts);
279#else
280 {
281 struct timeval tv;
282 gettimeofday(&tv, NULL);
283 ts->tv_sec = tv.tv_sec;
284 ts->tv_nsec = tv.tv_usec * 1000;
285 }
286#endif
287 endSec = ts->tv_sec + ms / 1000;
288 if (endSec >= 0x7fffffff) {
289 LOG(INFO) << "Note: end time exceeds epoch";
290 endSec = 0x7ffffffe;
291 }
292 ts->tv_sec = endSec;
293 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
294
295 // Catch rollover.
296 if (ts->tv_nsec >= 1000000000L) {
297 ts->tv_sec++;
298 ts->tv_nsec -= 1000000000L;
299 }
300}
301
302int dvmRelativeCondWait(pthread_cond_t* cond, pthread_mutex_t* mutex, int64_t ms, int32_t ns) {
303 struct timespec ts;
304 ToAbsoluteTime(ms, ns, &ts);
305#if defined(HAVE_TIMEDWAIT_MONOTONIC)
306 int rc = pthread_cond_timedwait_monotonic(cond, mutex, &ts);
307#else
308 int rc = pthread_cond_timedwait(cond, mutex, &ts);
309#endif
310 DCHECK(rc == 0 || rc == ETIMEDOUT);
311 return rc;
312}
313
314/*
315 * Wait on a monitor until timeout, interrupt, or notification. Used for
316 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
317 *
318 * If another thread calls Thread.interrupt(), we throw InterruptedException
319 * and return immediately if one of the following are true:
320 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
321 * - blocked in join(), join(long), or join(long, int) methods of Thread
322 * - blocked in sleep(long), or sleep(long, int) methods of Thread
323 * Otherwise, we set the "interrupted" flag.
324 *
325 * Checks to make sure that "ns" is in the range 0-999999
326 * (i.e. fractions of a millisecond) and throws the appropriate
327 * exception if it isn't.
328 *
329 * The spec allows "spurious wakeups", and recommends that all code using
330 * Object.wait() do so in a loop. This appears to derive from concerns
331 * about pthread_cond_wait() on multiprocessor systems. Some commentary
332 * on the web casts doubt on whether these can/should occur.
333 *
334 * Since we're allowed to wake up "early", we clamp extremely long durations
335 * to return at the end of the 32-bit time epoch.
336 */
337void Monitor::Wait(Thread* self, int64_t ms, int32_t ns, bool interruptShouldThrow) {
338 DCHECK(self != NULL);
339
340 // Make sure that we hold the lock.
341 if (owner_ != self) {
342 ThrowIllegalMonitorStateException("object not locked by thread before wait()");
343 return;
344 }
345
346 // Enforce the timeout range.
347 if (ms < 0 || ns < 0 || ns > 999999) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700348 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Elliott Hughes5f791332011-09-15 17:45:30 -0700349 "timeout arguments out of range: ms=%lld ns=%d", ms, ns);
350 return;
351 }
352
353 // Compute absolute wakeup time, if necessary.
354 struct timespec ts;
355 bool timed = false;
356 if (ms != 0 || ns != 0) {
357 ToAbsoluteTime(ms, ns, &ts);
358 timed = true;
359 }
360
361 /*
362 * Add ourselves to the set of threads waiting on this monitor, and
363 * release our hold. We need to let it go even if we're a few levels
364 * deep in a recursive lock, and we need to restore that later.
365 *
366 * We append to the wait set ahead of clearing the count and owner
367 * fields so the subroutine can check that the calling thread owns
368 * the monitor. Aside from that, the order of member updates is
369 * not order sensitive as we hold the pthread mutex.
370 */
371 AppendToWaitSet(self);
372 int prevLockCount = lock_count_;
373 lock_count_ = 0;
374 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800375 const Method* savedMethod = locking_method_;
376 locking_method_ = NULL;
377 uint32_t savedPc = locking_pc_;
378 locking_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700379
380 /*
381 * Update thread status. If the GC wakes up, it'll ignore us, knowing
382 * that we won't touch any references in this state, and we'll check
383 * our suspend mode before we transition out.
384 */
385 if (timed) {
386 self->SetState(Thread::kTimedWaiting);
387 } else {
388 self->SetState(Thread::kWaiting);
389 }
390
Elliott Hughes85d15452011-09-16 17:33:01 -0700391 self->wait_mutex_->Lock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700392
393 /*
394 * Set wait_monitor_ to the monitor object we will be waiting on.
395 * When wait_monitor_ is non-NULL a notifying or interrupting thread
396 * must signal the thread's wait_cond_ to wake it up.
397 */
398 DCHECK(self->wait_monitor_ == NULL);
399 self->wait_monitor_ = this;
400
401 /*
402 * Handle the case where the thread was interrupted before we called
403 * wait().
404 */
405 bool wasInterrupted = false;
406 if (self->interrupted_) {
407 wasInterrupted = true;
408 self->wait_monitor_ = NULL;
Elliott Hughes85d15452011-09-16 17:33:01 -0700409 self->wait_mutex_->Unlock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700410 goto done;
411 }
412
413 /*
414 * Release the monitor lock and wait for a notification or
415 * a timeout to occur.
416 */
417 lock_.Unlock();
418
419 if (!timed) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700420 self->wait_cond_->Wait(*self->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700421 } else {
Elliott Hughes85d15452011-09-16 17:33:01 -0700422 self->wait_cond_->TimedWait(*self->wait_mutex_, ts);
Elliott Hughes5f791332011-09-15 17:45:30 -0700423 }
424 if (self->interrupted_) {
425 wasInterrupted = true;
426 }
427
428 self->interrupted_ = false;
429 self->wait_monitor_ = NULL;
Elliott Hughes85d15452011-09-16 17:33:01 -0700430 self->wait_mutex_->Unlock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700431
432 // Reacquire the monitor lock.
433 Lock(self);
434
435done:
436 /*
437 * We remove our thread from wait set after restoring the count
438 * and owner fields so the subroutine can check that the calling
439 * thread owns the monitor. Aside from that, the order of member
440 * updates is not order sensitive as we hold the pthread mutex.
441 */
442 owner_ = self;
443 lock_count_ = prevLockCount;
jeffhao33dc7712011-11-09 17:54:24 -0800444 locking_method_ = savedMethod;
445 locking_pc_ = savedPc;
Elliott Hughes5f791332011-09-15 17:45:30 -0700446 RemoveFromWaitSet(self);
447
448 /* set self->status back to Thread::kRunnable, and self-suspend if needed */
449 self->SetState(Thread::kRunnable);
450
451 if (wasInterrupted) {
452 /*
453 * We were interrupted while waiting, or somebody interrupted an
454 * un-interruptible thread earlier and we're bailing out immediately.
455 *
456 * The doc sayeth: "The interrupted status of the current thread is
457 * cleared when this exception is thrown."
458 */
459 self->interrupted_ = false;
460 if (interruptShouldThrow) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700461 Thread::Current()->ThrowNewException("Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700462 }
463 }
464}
465
466void Monitor::Notify(Thread* self) {
467 DCHECK(self != NULL);
468
469 // Make sure that we hold the lock.
470 if (owner_ != self) {
471 ThrowIllegalMonitorStateException("object not locked by thread before notify()");
472 return;
473 }
474 // Signal the first waiting thread in the wait set.
475 while (wait_set_ != NULL) {
476 Thread* thread = wait_set_;
477 wait_set_ = thread->wait_next_;
478 thread->wait_next_ = NULL;
479
480 // Check to see if the thread is still waiting.
Elliott Hughes85d15452011-09-16 17:33:01 -0700481 MutexLock mu(*thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700482 if (thread->wait_monitor_ != NULL) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700483 thread->wait_cond_->Signal();
Elliott Hughes5f791332011-09-15 17:45:30 -0700484 return;
485 }
486 }
487}
488
489void Monitor::NotifyAll(Thread* self) {
490 DCHECK(self != NULL);
491
492 // Make sure that we hold the lock.
493 if (owner_ != self) {
494 ThrowIllegalMonitorStateException("object not locked by thread before notifyAll()");
495 return;
496 }
497 // Signal all threads in the wait set.
498 while (wait_set_ != NULL) {
499 Thread* thread = wait_set_;
500 wait_set_ = thread->wait_next_;
501 thread->wait_next_ = NULL;
502 thread->Notify();
503 }
504}
505
506/*
507 * Changes the shape of a monitor from thin to fat, preserving the
508 * internal lock state. The calling thread must own the lock.
509 */
510void Monitor::Inflate(Thread* self, Object* obj) {
511 DCHECK(self != NULL);
512 DCHECK(obj != NULL);
513 DCHECK_EQ(LW_SHAPE(*obj->GetRawLockWordAddress()), LW_SHAPE_THIN);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700514 DCHECK_EQ(LW_LOCK_OWNER(*obj->GetRawLockWordAddress()), static_cast<int32_t>(self->GetThinLockId()));
Elliott Hughes5f791332011-09-15 17:45:30 -0700515
516 // Allocate and acquire a new monitor.
517 Monitor* m = new Monitor(obj);
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700518 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700519 LOG(INFO) << "monitor: thread " << self->GetThinLockId()
520 << " created monitor " << m << " for object " << obj;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700521 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700522 Runtime::Current()->GetMonitorList()->Add(m);
Elliott Hughes5f791332011-09-15 17:45:30 -0700523 m->Lock(self);
524 // Propagate the lock state.
525 uint32_t thin = *obj->GetRawLockWordAddress();
526 m->lock_count_ = LW_LOCK_COUNT(thin);
527 thin &= LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT;
528 thin |= reinterpret_cast<uint32_t>(m) | LW_SHAPE_FAT;
529 // Publish the updated lock word.
530 android_atomic_release_store(thin, obj->GetRawLockWordAddress());
531}
532
533void Monitor::MonitorEnter(Thread* self, Object* obj) {
534 volatile int32_t* thinp = obj->GetRawLockWordAddress();
535 struct timespec tm;
536 long sleepDelayNs;
537 long minSleepDelayNs = 1000000; /* 1 millisecond */
538 long maxSleepDelayNs = 1000000000; /* 1 second */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700539 uint32_t thin, newThin;
Elliott Hughes5f791332011-09-15 17:45:30 -0700540
Elliott Hughes4681c802011-09-25 18:04:37 -0700541 DCHECK(self != NULL);
542 DCHECK(obj != NULL);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700543 uint32_t threadId = self->GetThinLockId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700544retry:
545 thin = *thinp;
546 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
547 /*
548 * The lock is a thin lock. The owner field is used to
549 * determine the acquire method, ordered by cost.
550 */
551 if (LW_LOCK_OWNER(thin) == threadId) {
552 /*
553 * The calling thread owns the lock. Increment the
554 * value of the recursion count field.
555 */
556 *thinp += 1 << LW_LOCK_COUNT_SHIFT;
557 if (LW_LOCK_COUNT(*thinp) == LW_LOCK_COUNT_MASK) {
558 /*
559 * The reacquisition limit has been reached. Inflate
560 * the lock so the next acquire will not overflow the
561 * recursion count field.
562 */
563 Inflate(self, obj);
564 }
565 } else if (LW_LOCK_OWNER(thin) == 0) {
566 /*
567 * The lock is unowned. Install the thread id of the
568 * calling thread into the owner field. This is the
569 * common case. In performance critical code the JIT
570 * will have tried this before calling out to the VM.
571 */
572 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
573 if (android_atomic_acquire_cas(thin, newThin, thinp) != 0) {
574 // The acquire failed. Try again.
575 goto retry;
576 }
577 } else {
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700578 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700579 LOG(INFO) << StringPrintf("monitor: thread %d spin on lock %p (a %s) owned by %d",
580 threadId, thinp, PrettyTypeOf(obj).c_str(), LW_LOCK_OWNER(thin));
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700581 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700582 // The lock is owned by another thread. Notify the VM that we are about to wait.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700583 self->monitor_enter_object_ = obj;
Elliott Hughes5f791332011-09-15 17:45:30 -0700584 Thread::State oldStatus = self->SetState(Thread::kBlocked);
585 // Spin until the thin lock is released or inflated.
586 sleepDelayNs = 0;
587 for (;;) {
588 thin = *thinp;
589 // Check the shape of the lock word. Another thread
590 // may have inflated the lock while we were waiting.
591 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
592 if (LW_LOCK_OWNER(thin) == 0) {
593 // The lock has been released. Install the thread id of the
594 // calling thread into the owner field.
595 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
596 if (android_atomic_acquire_cas(thin, newThin, thinp) == 0) {
597 // The acquire succeed. Break out of the loop and proceed to inflate the lock.
598 break;
599 }
600 } else {
601 // The lock has not been released. Yield so the owning thread can run.
602 if (sleepDelayNs == 0) {
603 sched_yield();
604 sleepDelayNs = minSleepDelayNs;
605 } else {
606 tm.tv_sec = 0;
607 tm.tv_nsec = sleepDelayNs;
608 nanosleep(&tm, NULL);
609 // Prepare the next delay value. Wrap to avoid once a second polls for eternity.
610 if (sleepDelayNs < maxSleepDelayNs / 2) {
611 sleepDelayNs *= 2;
612 } else {
613 sleepDelayNs = minSleepDelayNs;
614 }
615 }
616 }
617 } else {
618 // The thin lock was inflated by another thread. Let the VM know we are no longer
619 // waiting and try again.
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700620 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700621 LOG(INFO) << "monitor: thread " << threadId
622 << " found lock " << (void*) thinp << " surprise-fattened by another thread";
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700623 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700624 self->monitor_enter_object_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700625 self->SetState(oldStatus);
626 goto retry;
627 }
628 }
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700629 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700630 LOG(INFO) << StringPrintf("monitor: thread %d spin on lock %p done", threadId, thinp);
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700631 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700632 // We have acquired the thin lock. Let the VM know that we are no longer waiting.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700633 self->monitor_enter_object_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700634 self->SetState(oldStatus);
635 // Fatten the lock.
636 Inflate(self, obj);
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700637 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700638 LOG(INFO) << StringPrintf("monitor: thread %d fattened lock %p", threadId, thinp);
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700639 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700640 }
641 } else {
642 // The lock is a fat lock.
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700643 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700644 LOG(INFO) << StringPrintf("monitor: thread %d locking fat lock %p (%p) %p on a %s",
645 threadId, thinp, LW_MONITOR(*thinp), (void*)*thinp, PrettyTypeOf(obj).c_str());
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700646 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700647 DCHECK(LW_MONITOR(*thinp) != NULL);
648 LW_MONITOR(*thinp)->Lock(self);
649 }
650}
651
652bool Monitor::MonitorExit(Thread* self, Object* obj) {
653 volatile int32_t* thinp = obj->GetRawLockWordAddress();
654
655 DCHECK(self != NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -0700656 //DCHECK_EQ(self->GetState(), Thread::kRunnable);
Elliott Hughes5f791332011-09-15 17:45:30 -0700657 DCHECK(obj != NULL);
658
659 /*
660 * Cache the lock word as its value can change while we are
661 * examining its state.
662 */
663 uint32_t thin = *thinp;
664 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
665 /*
666 * The lock is thin. We must ensure that the lock is owned
667 * by the given thread before unlocking it.
668 */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700669 if (LW_LOCK_OWNER(thin) == self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700670 /*
671 * We are the lock owner. It is safe to update the lock
672 * without CAS as lock ownership guards the lock itself.
673 */
674 if (LW_LOCK_COUNT(thin) == 0) {
675 /*
676 * The lock was not recursively acquired, the common
677 * case. Unlock by clearing all bits except for the
678 * hash state.
679 */
680 thin &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
681 android_atomic_release_store(thin, thinp);
682 } else {
683 /*
684 * The object was recursively acquired. Decrement the
685 * lock recursion count field.
686 */
687 *thinp -= 1 << LW_LOCK_COUNT_SHIFT;
688 }
689 } else {
690 /*
691 * We do not own the lock. The JVM spec requires that we
692 * throw an exception in this case.
693 */
694 ThrowIllegalMonitorStateException("unlock of unowned monitor");
695 return false;
696 }
697 } else {
698 /*
699 * The lock is fat. We must check to see if Unlock has
700 * raised any exceptions before continuing.
701 */
702 DCHECK(LW_MONITOR(*thinp) != NULL);
703 if (!LW_MONITOR(*thinp)->Unlock(self)) {
704 // An exception has been raised. Do not fall through.
705 return false;
706 }
707 }
708 return true;
709}
710
711/*
712 * Object.wait(). Also called for class init.
713 */
714void Monitor::Wait(Thread* self, Object *obj, int64_t ms, int32_t ns, bool interruptShouldThrow) {
715 volatile int32_t* thinp = obj->GetRawLockWordAddress();
716
717 // If the lock is still thin, we need to fatten it.
718 uint32_t thin = *thinp;
719 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
720 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700721 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700722 ThrowIllegalMonitorStateException("object not locked by thread before wait()");
723 return;
724 }
725
726 /* This thread holds the lock. We need to fatten the lock
727 * so 'self' can block on it. Don't update the object lock
728 * field yet, because 'self' needs to acquire the lock before
729 * any other thread gets a chance.
730 */
731 Inflate(self, obj);
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700732 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700733 LOG(INFO) << StringPrintf("monitor: thread %d fattened lock %p by wait()", self->GetThinLockId(), thinp);
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700734 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700735 }
736 LW_MONITOR(*thinp)->Wait(self, ms, ns, interruptShouldThrow);
737}
738
739void Monitor::Notify(Thread* self, Object *obj) {
740 uint32_t thin = *obj->GetRawLockWordAddress();
741
742 // If the lock is still thin, there aren't any waiters;
743 // waiting on an object forces lock fattening.
744 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
745 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700746 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700747 ThrowIllegalMonitorStateException("object not locked by thread before notify()");
748 return;
749 }
750 // no-op; there are no waiters to notify.
751 } else {
752 // It's a fat lock.
753 LW_MONITOR(thin)->Notify(self);
754 }
755}
756
757void Monitor::NotifyAll(Thread* self, Object *obj) {
758 uint32_t thin = *obj->GetRawLockWordAddress();
759
760 // If the lock is still thin, there aren't any waiters;
761 // waiting on an object forces lock fattening.
762 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
763 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700764 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700765 ThrowIllegalMonitorStateException("object not locked by thread before notifyAll()");
766 return;
767 }
768 // no-op; there are no waiters to notify.
769 } else {
770 // It's a fat lock.
771 LW_MONITOR(thin)->NotifyAll(self);
772 }
773}
774
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700775uint32_t Monitor::GetThinLockId(uint32_t raw_lock_word) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700776 if (LW_SHAPE(raw_lock_word) == LW_SHAPE_THIN) {
777 return LW_LOCK_OWNER(raw_lock_word);
778 } else {
779 Thread* owner = LW_MONITOR(raw_lock_word)->owner_;
780 return owner ? owner->GetThinLockId() : 0;
781 }
782}
783
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700784void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
785 Thread::State state = thread->GetState();
786
787 Object* object = NULL;
788 uint32_t lock_owner = ThreadList::kInvalidId;
789 if (state == Thread::kWaiting || state == Thread::kTimedWaiting) {
790 os << " - waiting on ";
791 Monitor* monitor = thread->wait_monitor_;
792 if (monitor != NULL) {
793 object = monitor->obj_;
794 }
795 lock_owner = Thread::LockOwnerFromThreadLock(object);
796 } else if (state == Thread::kBlocked) {
797 os << " - waiting to lock ";
798 object = thread->monitor_enter_object_;
799 if (object != NULL) {
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700800 lock_owner = object->GetThinLockId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700801 }
802 } else {
803 // We're not waiting on anything.
804 return;
805 }
806 os << "<" << object << ">";
807
808 // - waiting on <0x613f83d8> (a java.lang.ThreadLock) held by thread 5
809 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
810 os << " (a " << PrettyTypeOf(object) << ")";
811
812 if (lock_owner != ThreadList::kInvalidId) {
813 os << " held by thread " << lock_owner;
814 }
815
816 os << "\n";
817}
818
jeffhao33dc7712011-11-09 17:54:24 -0800819void Monitor::TranslateLocation(const Method* method, uint32_t pc,
820 const char*& source_file, uint32_t& line_number) const {
821 // If method is null, location is unknown
822 if (method == NULL) {
823 source_file = "unknown";
824 line_number = 0;
825 return;
826 }
827
828 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
829 Class* c = method->GetDeclaringClass();
830 DexCache* dex_cache = c->GetDexCache();
831 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
832 const DexFile::ClassDef* class_def = dex_file.FindClassDef(c->GetDescriptor()->ToModifiedUtf8());
833
834 source_file = dex_file.dexGetSourceFile(*class_def);
835 line_number = dex_file.GetLineNumFromPC(method, method->ToDexPC(pc));
836}
837
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700838MonitorList::MonitorList() : lock_("MonitorList lock") {
839}
840
841MonitorList::~MonitorList() {
842 MutexLock mu(lock_);
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700843
844 // In case there is a daemon thread with the monitor locked, clear
845 // the owner here so we can destroy the mutex, which will otherwise
846 // fail in pthread_mutex_destroy.
847 typedef std::list<Monitor*>::iterator It; // TODO: C++0x auto
848 for (It it = list_.begin(); it != list_.end(); it++) {
849 Monitor* monitor = *it;
850 Mutex& lock = monitor->lock_;
851 if (lock.GetOwner() != 0) {
852 DCHECK_EQ(lock.GetOwner(), monitor->owner_->GetTid());
853 lock.ClearOwner();
854 }
855 }
856
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700857 STLDeleteElements(&list_);
858}
859
860void MonitorList::Add(Monitor* m) {
861 MutexLock mu(lock_);
862 list_.push_front(m);
863}
864
865void MonitorList::SweepMonitorList(Heap::IsMarkedTester is_marked, void* arg) {
866 MutexLock mu(lock_);
867 typedef std::list<Monitor*>::iterator It; // TODO: C++0x auto
868 It it = list_.begin();
869 while (it != list_.end()) {
870 Monitor* m = *it;
871 if (!is_marked(m->GetObject(), arg)) {
872 if (Monitor::IsVerbose()) {
873 LOG(INFO) << "freeing monitor " << m << " belonging to unmarked object " << m->GetObject();
874 }
875 delete m;
876 it = list_.erase(it);
877 } else {
878 ++it;
879 }
880 }
881}
882
Elliott Hughes5f791332011-09-15 17:45:30 -0700883} // namespace art