blob: 69eb9ba4687f4a083fb8230b14f79425de076b79 [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 Hughes32d6e1e2011-10-11 14:47:44 -070099bool Monitor::is_verbose_ = false;
Elliott Hughesfc861622011-10-17 17:57:47 -0700100uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700101
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700102bool Monitor::IsVerbose() {
103 return is_verbose_;
104}
105
Elliott Hughesfc861622011-10-17 17:57:47 -0700106bool Monitor::IsSensitiveThread() {
107 if (is_sensitive_thread_hook_ != NULL) {
108 return (*is_sensitive_thread_hook_)();
109 }
110 return false;
111}
112
113void Monitor::Init(bool is_verbose, uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700114 is_verbose_ = is_verbose;
Elliott Hughesfc861622011-10-17 17:57:47 -0700115 lock_profiling_threshold_ = lock_profiling_threshold;
116 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700117}
118
Elliott Hughes5f791332011-09-15 17:45:30 -0700119Monitor::Monitor(Object* obj)
120 : owner_(NULL),
121 lock_count_(0),
122 obj_(obj),
123 wait_set_(NULL),
124 lock_("a monitor lock"),
jeffhao33dc7712011-11-09 17:54:24 -0800125 locking_method_(NULL),
126 locking_pc_(0) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700127}
128
129Monitor::~Monitor() {
130 DCHECK(obj_ != NULL);
131 DCHECK_EQ(LW_SHAPE(*obj_->GetRawLockWordAddress()), LW_SHAPE_FAT);
132
133#ifndef NDEBUG
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700134 // This lock is associated with an object that's being swept.
135 bool locked = lock_.TryLock();
136 DCHECK(locked) << obj_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700137 lock_.Unlock();
138#endif
139}
140
141/*
142 * Links a thread into a monitor's wait set. The monitor lock must be
143 * held by the caller of this routine.
144 */
145void Monitor::AppendToWaitSet(Thread* thread) {
146 DCHECK(owner_ == Thread::Current());
147 DCHECK(thread != NULL);
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700148 DCHECK(thread->wait_next_ == NULL) << thread->wait_next_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700149 if (wait_set_ == NULL) {
150 wait_set_ = thread;
151 return;
152 }
153
154 // push_back.
155 Thread* t = wait_set_;
156 while (t->wait_next_ != NULL) {
157 t = t->wait_next_;
158 }
159 t->wait_next_ = thread;
160}
161
162/*
163 * Unlinks a thread from a monitor's wait set. The monitor lock must
164 * be held by the caller of this routine.
165 */
166void Monitor::RemoveFromWaitSet(Thread *thread) {
167 DCHECK(owner_ == Thread::Current());
168 DCHECK(thread != NULL);
169 if (wait_set_ == NULL) {
170 return;
171 }
172 if (wait_set_ == thread) {
173 wait_set_ = thread->wait_next_;
174 thread->wait_next_ = NULL;
175 return;
176 }
177
178 Thread* t = wait_set_;
179 while (t->wait_next_ != NULL) {
180 if (t->wait_next_ == thread) {
181 t->wait_next_ = thread->wait_next_;
182 thread->wait_next_ = NULL;
183 return;
184 }
185 t = t->wait_next_;
186 }
187}
188
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700189Object* Monitor::GetObject() {
190 return obj_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700191}
192
Elliott Hughes5f791332011-09-15 17:45:30 -0700193void Monitor::Lock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700194 if (owner_ == self) {
195 lock_count_++;
196 return;
197 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700198
199 uint64_t waitStart, waitEnd;
Elliott Hughes5f791332011-09-15 17:45:30 -0700200 if (!lock_.TryLock()) {
Elliott Hughesfc861622011-10-17 17:57:47 -0700201 uint32_t wait_threshold = lock_profiling_threshold_;
jeffhao33dc7712011-11-09 17:54:24 -0800202 const Method* current_locking_method = NULL;
203 uint32_t current_locking_pc = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700204 {
205 ScopedThreadStateChange tsc(self, Thread::kBlocked);
Elliott Hughesfc861622011-10-17 17:57:47 -0700206 if (wait_threshold != 0) {
207 waitStart = NanoTime() / 1000;
208 }
jeffhao33dc7712011-11-09 17:54:24 -0800209 current_locking_method = locking_method_;
210 current_locking_pc = locking_pc_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700211
212 lock_.Lock();
Elliott Hughesfc861622011-10-17 17:57:47 -0700213 if (wait_threshold != 0) {
214 waitEnd = NanoTime() / 1000;
215 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700216 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700217
218 if (wait_threshold != 0) {
219 uint64_t wait_ms = (waitEnd - waitStart) / 1000;
220 uint32_t sample_percent;
221 if (wait_ms >= wait_threshold) {
222 sample_percent = 100;
223 } else {
224 sample_percent = 100 * wait_ms / wait_threshold;
225 }
226 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
jeffhao33dc7712011-11-09 17:54:24 -0800227 const char* current_locking_filename;
228 uint32_t current_locking_line_number;
229 TranslateLocation(current_locking_method, current_locking_pc,
230 current_locking_filename, current_locking_line_number);
231 LogContentionEvent(self, wait_ms, sample_percent, current_locking_filename, current_locking_line_number);
Elliott Hughesfc861622011-10-17 17:57:47 -0700232 }
233 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700234 }
235 owner_ = self;
236 DCHECK_EQ(lock_count_, 0);
237
238 // When debugging, save the current monitor holder for future
239 // acquisition failures to use in sampled logging.
Elliott Hughesfc861622011-10-17 17:57:47 -0700240 if (lock_profiling_threshold_ != 0) {
jeffhao33dc7712011-11-09 17:54:24 -0800241 locking_method_ = self->GetCurrentMethod();
242 locking_pc_ = self->GetCurrentReturnPc();
Elliott Hughesfc861622011-10-17 17:57:47 -0700243 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700244}
245
246void ThrowIllegalMonitorStateException(const char* msg) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700247 Thread::Current()->ThrowNewException("Ljava/lang/IllegalMonitorStateException;", msg);
Elliott Hughes5f791332011-09-15 17:45:30 -0700248}
249
250bool Monitor::Unlock(Thread* self) {
251 DCHECK(self != NULL);
252 if (owner_ == self) {
253 // We own the monitor, so nobody else can be in here.
254 if (lock_count_ == 0) {
255 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800256 locking_method_ = NULL;
257 locking_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700258 lock_.Unlock();
259 } else {
260 --lock_count_;
261 }
262 } else {
263 // We don't own this, so we're not allowed to unlock it.
264 // The JNI spec says that we should throw IllegalMonitorStateException
265 // in this case.
266 ThrowIllegalMonitorStateException("unlock of unowned monitor");
267 return false;
268 }
269 return true;
270}
271
272/*
273 * Converts the given relative waiting time into an absolute time.
274 */
275void ToAbsoluteTime(int64_t ms, int32_t ns, struct timespec *ts) {
276 int64_t endSec;
277
278#ifdef HAVE_TIMEDWAIT_MONOTONIC
279 clock_gettime(CLOCK_MONOTONIC, ts);
280#else
281 {
282 struct timeval tv;
283 gettimeofday(&tv, NULL);
284 ts->tv_sec = tv.tv_sec;
285 ts->tv_nsec = tv.tv_usec * 1000;
286 }
287#endif
288 endSec = ts->tv_sec + ms / 1000;
289 if (endSec >= 0x7fffffff) {
290 LOG(INFO) << "Note: end time exceeds epoch";
291 endSec = 0x7ffffffe;
292 }
293 ts->tv_sec = endSec;
294 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
295
296 // Catch rollover.
297 if (ts->tv_nsec >= 1000000000L) {
298 ts->tv_sec++;
299 ts->tv_nsec -= 1000000000L;
300 }
301}
302
303int dvmRelativeCondWait(pthread_cond_t* cond, pthread_mutex_t* mutex, int64_t ms, int32_t ns) {
304 struct timespec ts;
305 ToAbsoluteTime(ms, ns, &ts);
306#if defined(HAVE_TIMEDWAIT_MONOTONIC)
307 int rc = pthread_cond_timedwait_monotonic(cond, mutex, &ts);
308#else
309 int rc = pthread_cond_timedwait(cond, mutex, &ts);
310#endif
311 DCHECK(rc == 0 || rc == ETIMEDOUT);
312 return rc;
313}
314
315/*
316 * Wait on a monitor until timeout, interrupt, or notification. Used for
317 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
318 *
319 * If another thread calls Thread.interrupt(), we throw InterruptedException
320 * and return immediately if one of the following are true:
321 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
322 * - blocked in join(), join(long), or join(long, int) methods of Thread
323 * - blocked in sleep(long), or sleep(long, int) methods of Thread
324 * Otherwise, we set the "interrupted" flag.
325 *
326 * Checks to make sure that "ns" is in the range 0-999999
327 * (i.e. fractions of a millisecond) and throws the appropriate
328 * exception if it isn't.
329 *
330 * The spec allows "spurious wakeups", and recommends that all code using
331 * Object.wait() do so in a loop. This appears to derive from concerns
332 * about pthread_cond_wait() on multiprocessor systems. Some commentary
333 * on the web casts doubt on whether these can/should occur.
334 *
335 * Since we're allowed to wake up "early", we clamp extremely long durations
336 * to return at the end of the 32-bit time epoch.
337 */
338void Monitor::Wait(Thread* self, int64_t ms, int32_t ns, bool interruptShouldThrow) {
339 DCHECK(self != NULL);
340
341 // Make sure that we hold the lock.
342 if (owner_ != self) {
343 ThrowIllegalMonitorStateException("object not locked by thread before wait()");
344 return;
345 }
346
347 // Enforce the timeout range.
348 if (ms < 0 || ns < 0 || ns > 999999) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700349 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Elliott Hughes5f791332011-09-15 17:45:30 -0700350 "timeout arguments out of range: ms=%lld ns=%d", ms, ns);
351 return;
352 }
353
354 // Compute absolute wakeup time, if necessary.
355 struct timespec ts;
356 bool timed = false;
357 if (ms != 0 || ns != 0) {
358 ToAbsoluteTime(ms, ns, &ts);
359 timed = true;
360 }
361
362 /*
363 * Add ourselves to the set of threads waiting on this monitor, and
364 * release our hold. We need to let it go even if we're a few levels
365 * deep in a recursive lock, and we need to restore that later.
366 *
367 * We append to the wait set ahead of clearing the count and owner
368 * fields so the subroutine can check that the calling thread owns
369 * the monitor. Aside from that, the order of member updates is
370 * not order sensitive as we hold the pthread mutex.
371 */
372 AppendToWaitSet(self);
373 int prevLockCount = lock_count_;
374 lock_count_ = 0;
375 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800376 const Method* savedMethod = locking_method_;
377 locking_method_ = NULL;
378 uint32_t savedPc = locking_pc_;
379 locking_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700380
381 /*
382 * Update thread status. If the GC wakes up, it'll ignore us, knowing
383 * that we won't touch any references in this state, and we'll check
384 * our suspend mode before we transition out.
385 */
386 if (timed) {
387 self->SetState(Thread::kTimedWaiting);
388 } else {
389 self->SetState(Thread::kWaiting);
390 }
391
Elliott Hughes85d15452011-09-16 17:33:01 -0700392 self->wait_mutex_->Lock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700393
394 /*
395 * Set wait_monitor_ to the monitor object we will be waiting on.
396 * When wait_monitor_ is non-NULL a notifying or interrupting thread
397 * must signal the thread's wait_cond_ to wake it up.
398 */
399 DCHECK(self->wait_monitor_ == NULL);
400 self->wait_monitor_ = this;
401
402 /*
403 * Handle the case where the thread was interrupted before we called
404 * wait().
405 */
406 bool wasInterrupted = false;
407 if (self->interrupted_) {
408 wasInterrupted = true;
409 self->wait_monitor_ = NULL;
Elliott Hughes85d15452011-09-16 17:33:01 -0700410 self->wait_mutex_->Unlock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700411 goto done;
412 }
413
414 /*
415 * Release the monitor lock and wait for a notification or
416 * a timeout to occur.
417 */
418 lock_.Unlock();
419
420 if (!timed) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700421 self->wait_cond_->Wait(*self->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700422 } else {
Elliott Hughes85d15452011-09-16 17:33:01 -0700423 self->wait_cond_->TimedWait(*self->wait_mutex_, ts);
Elliott Hughes5f791332011-09-15 17:45:30 -0700424 }
425 if (self->interrupted_) {
426 wasInterrupted = true;
427 }
428
429 self->interrupted_ = false;
430 self->wait_monitor_ = NULL;
Elliott Hughes85d15452011-09-16 17:33:01 -0700431 self->wait_mutex_->Unlock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700432
433 // Reacquire the monitor lock.
434 Lock(self);
435
436done:
437 /*
438 * We remove our thread from wait set after restoring the count
439 * and owner fields so the subroutine can check that the calling
440 * thread owns the monitor. Aside from that, the order of member
441 * updates is not order sensitive as we hold the pthread mutex.
442 */
443 owner_ = self;
444 lock_count_ = prevLockCount;
jeffhao33dc7712011-11-09 17:54:24 -0800445 locking_method_ = savedMethod;
446 locking_pc_ = savedPc;
Elliott Hughes5f791332011-09-15 17:45:30 -0700447 RemoveFromWaitSet(self);
448
449 /* set self->status back to Thread::kRunnable, and self-suspend if needed */
450 self->SetState(Thread::kRunnable);
451
452 if (wasInterrupted) {
453 /*
454 * We were interrupted while waiting, or somebody interrupted an
455 * un-interruptible thread earlier and we're bailing out immediately.
456 *
457 * The doc sayeth: "The interrupted status of the current thread is
458 * cleared when this exception is thrown."
459 */
460 self->interrupted_ = false;
461 if (interruptShouldThrow) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700462 Thread::Current()->ThrowNewException("Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700463 }
464 }
465}
466
467void Monitor::Notify(Thread* self) {
468 DCHECK(self != NULL);
469
470 // Make sure that we hold the lock.
471 if (owner_ != self) {
472 ThrowIllegalMonitorStateException("object not locked by thread before notify()");
473 return;
474 }
475 // Signal the first waiting thread in the wait set.
476 while (wait_set_ != NULL) {
477 Thread* thread = wait_set_;
478 wait_set_ = thread->wait_next_;
479 thread->wait_next_ = NULL;
480
481 // Check to see if the thread is still waiting.
Elliott Hughes85d15452011-09-16 17:33:01 -0700482 MutexLock mu(*thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700483 if (thread->wait_monitor_ != NULL) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700484 thread->wait_cond_->Signal();
Elliott Hughes5f791332011-09-15 17:45:30 -0700485 return;
486 }
487 }
488}
489
490void Monitor::NotifyAll(Thread* self) {
491 DCHECK(self != NULL);
492
493 // Make sure that we hold the lock.
494 if (owner_ != self) {
495 ThrowIllegalMonitorStateException("object not locked by thread before notifyAll()");
496 return;
497 }
498 // Signal all threads in the wait set.
499 while (wait_set_ != NULL) {
500 Thread* thread = wait_set_;
501 wait_set_ = thread->wait_next_;
502 thread->wait_next_ = NULL;
503 thread->Notify();
504 }
505}
506
507/*
508 * Changes the shape of a monitor from thin to fat, preserving the
509 * internal lock state. The calling thread must own the lock.
510 */
511void Monitor::Inflate(Thread* self, Object* obj) {
512 DCHECK(self != NULL);
513 DCHECK(obj != NULL);
514 DCHECK_EQ(LW_SHAPE(*obj->GetRawLockWordAddress()), LW_SHAPE_THIN);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700515 DCHECK_EQ(LW_LOCK_OWNER(*obj->GetRawLockWordAddress()), static_cast<int32_t>(self->GetThinLockId()));
Elliott Hughes5f791332011-09-15 17:45:30 -0700516
517 // Allocate and acquire a new monitor.
518 Monitor* m = new Monitor(obj);
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700519 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700520 LOG(INFO) << "monitor: thread " << self->GetThinLockId()
521 << " created monitor " << m << " for object " << obj;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700522 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700523 Runtime::Current()->GetMonitorList()->Add(m);
Elliott Hughes5f791332011-09-15 17:45:30 -0700524 m->Lock(self);
525 // Propagate the lock state.
526 uint32_t thin = *obj->GetRawLockWordAddress();
527 m->lock_count_ = LW_LOCK_COUNT(thin);
528 thin &= LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT;
529 thin |= reinterpret_cast<uint32_t>(m) | LW_SHAPE_FAT;
530 // Publish the updated lock word.
531 android_atomic_release_store(thin, obj->GetRawLockWordAddress());
532}
533
534void Monitor::MonitorEnter(Thread* self, Object* obj) {
535 volatile int32_t* thinp = obj->GetRawLockWordAddress();
536 struct timespec tm;
537 long sleepDelayNs;
538 long minSleepDelayNs = 1000000; /* 1 millisecond */
539 long maxSleepDelayNs = 1000000000; /* 1 second */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700540 uint32_t thin, newThin;
Elliott Hughes5f791332011-09-15 17:45:30 -0700541
Elliott Hughes4681c802011-09-25 18:04:37 -0700542 DCHECK(self != NULL);
543 DCHECK(obj != NULL);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700544 uint32_t threadId = self->GetThinLockId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700545retry:
546 thin = *thinp;
547 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
548 /*
549 * The lock is a thin lock. The owner field is used to
550 * determine the acquire method, ordered by cost.
551 */
552 if (LW_LOCK_OWNER(thin) == threadId) {
553 /*
554 * The calling thread owns the lock. Increment the
555 * value of the recursion count field.
556 */
557 *thinp += 1 << LW_LOCK_COUNT_SHIFT;
558 if (LW_LOCK_COUNT(*thinp) == LW_LOCK_COUNT_MASK) {
559 /*
560 * The reacquisition limit has been reached. Inflate
561 * the lock so the next acquire will not overflow the
562 * recursion count field.
563 */
564 Inflate(self, obj);
565 }
566 } else if (LW_LOCK_OWNER(thin) == 0) {
567 /*
568 * The lock is unowned. Install the thread id of the
569 * calling thread into the owner field. This is the
570 * common case. In performance critical code the JIT
571 * will have tried this before calling out to the VM.
572 */
573 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
574 if (android_atomic_acquire_cas(thin, newThin, thinp) != 0) {
575 // The acquire failed. Try again.
576 goto retry;
577 }
578 } else {
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700579 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700580 LOG(INFO) << StringPrintf("monitor: thread %d spin on lock %p (a %s) owned by %d",
581 threadId, thinp, PrettyTypeOf(obj).c_str(), LW_LOCK_OWNER(thin));
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700582 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700583 // The lock is owned by another thread. Notify the VM that we are about to wait.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700584 self->monitor_enter_object_ = obj;
Elliott Hughes5f791332011-09-15 17:45:30 -0700585 Thread::State oldStatus = self->SetState(Thread::kBlocked);
586 // Spin until the thin lock is released or inflated.
587 sleepDelayNs = 0;
588 for (;;) {
589 thin = *thinp;
590 // Check the shape of the lock word. Another thread
591 // may have inflated the lock while we were waiting.
592 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
593 if (LW_LOCK_OWNER(thin) == 0) {
594 // The lock has been released. Install the thread id of the
595 // calling thread into the owner field.
596 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
597 if (android_atomic_acquire_cas(thin, newThin, thinp) == 0) {
598 // The acquire succeed. Break out of the loop and proceed to inflate the lock.
599 break;
600 }
601 } else {
602 // The lock has not been released. Yield so the owning thread can run.
603 if (sleepDelayNs == 0) {
604 sched_yield();
605 sleepDelayNs = minSleepDelayNs;
606 } else {
607 tm.tv_sec = 0;
608 tm.tv_nsec = sleepDelayNs;
609 nanosleep(&tm, NULL);
610 // Prepare the next delay value. Wrap to avoid once a second polls for eternity.
611 if (sleepDelayNs < maxSleepDelayNs / 2) {
612 sleepDelayNs *= 2;
613 } else {
614 sleepDelayNs = minSleepDelayNs;
615 }
616 }
617 }
618 } else {
619 // The thin lock was inflated by another thread. Let the VM know we are no longer
620 // waiting and try again.
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700621 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700622 LOG(INFO) << "monitor: thread " << threadId
623 << " found lock " << (void*) thinp << " surprise-fattened by another thread";
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700624 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700625 self->monitor_enter_object_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700626 self->SetState(oldStatus);
627 goto retry;
628 }
629 }
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700630 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700631 LOG(INFO) << StringPrintf("monitor: thread %d spin on lock %p done", threadId, thinp);
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700632 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700633 // We have acquired the thin lock. Let the VM know that we are no longer waiting.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700634 self->monitor_enter_object_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700635 self->SetState(oldStatus);
636 // Fatten the lock.
637 Inflate(self, obj);
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700638 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700639 LOG(INFO) << StringPrintf("monitor: thread %d fattened lock %p", threadId, thinp);
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700640 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700641 }
642 } else {
643 // The lock is a fat lock.
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700644 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700645 LOG(INFO) << StringPrintf("monitor: thread %d locking fat lock %p (%p) %p on a %s",
646 threadId, thinp, LW_MONITOR(*thinp), (void*)*thinp, PrettyTypeOf(obj).c_str());
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700647 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700648 DCHECK(LW_MONITOR(*thinp) != NULL);
649 LW_MONITOR(*thinp)->Lock(self);
650 }
651}
652
653bool Monitor::MonitorExit(Thread* self, Object* obj) {
654 volatile int32_t* thinp = obj->GetRawLockWordAddress();
655
656 DCHECK(self != NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -0700657 //DCHECK_EQ(self->GetState(), Thread::kRunnable);
Elliott Hughes5f791332011-09-15 17:45:30 -0700658 DCHECK(obj != NULL);
659
660 /*
661 * Cache the lock word as its value can change while we are
662 * examining its state.
663 */
664 uint32_t thin = *thinp;
665 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
666 /*
667 * The lock is thin. We must ensure that the lock is owned
668 * by the given thread before unlocking it.
669 */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700670 if (LW_LOCK_OWNER(thin) == self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700671 /*
672 * We are the lock owner. It is safe to update the lock
673 * without CAS as lock ownership guards the lock itself.
674 */
675 if (LW_LOCK_COUNT(thin) == 0) {
676 /*
677 * The lock was not recursively acquired, the common
678 * case. Unlock by clearing all bits except for the
679 * hash state.
680 */
681 thin &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
682 android_atomic_release_store(thin, thinp);
683 } else {
684 /*
685 * The object was recursively acquired. Decrement the
686 * lock recursion count field.
687 */
688 *thinp -= 1 << LW_LOCK_COUNT_SHIFT;
689 }
690 } else {
691 /*
692 * We do not own the lock. The JVM spec requires that we
693 * throw an exception in this case.
694 */
695 ThrowIllegalMonitorStateException("unlock of unowned monitor");
696 return false;
697 }
698 } else {
699 /*
700 * The lock is fat. We must check to see if Unlock has
701 * raised any exceptions before continuing.
702 */
703 DCHECK(LW_MONITOR(*thinp) != NULL);
704 if (!LW_MONITOR(*thinp)->Unlock(self)) {
705 // An exception has been raised. Do not fall through.
706 return false;
707 }
708 }
709 return true;
710}
711
712/*
713 * Object.wait(). Also called for class init.
714 */
715void Monitor::Wait(Thread* self, Object *obj, int64_t ms, int32_t ns, bool interruptShouldThrow) {
716 volatile int32_t* thinp = obj->GetRawLockWordAddress();
717
718 // If the lock is still thin, we need to fatten it.
719 uint32_t thin = *thinp;
720 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
721 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700722 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700723 ThrowIllegalMonitorStateException("object not locked by thread before wait()");
724 return;
725 }
726
727 /* This thread holds the lock. We need to fatten the lock
728 * so 'self' can block on it. Don't update the object lock
729 * field yet, because 'self' needs to acquire the lock before
730 * any other thread gets a chance.
731 */
732 Inflate(self, obj);
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700733 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700734 LOG(INFO) << StringPrintf("monitor: thread %d fattened lock %p by wait()", self->GetThinLockId(), thinp);
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700735 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700736 }
737 LW_MONITOR(*thinp)->Wait(self, ms, ns, interruptShouldThrow);
738}
739
740void Monitor::Notify(Thread* self, Object *obj) {
741 uint32_t thin = *obj->GetRawLockWordAddress();
742
743 // If the lock is still thin, there aren't any waiters;
744 // waiting on an object forces lock fattening.
745 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
746 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700747 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700748 ThrowIllegalMonitorStateException("object not locked by thread before notify()");
749 return;
750 }
751 // no-op; there are no waiters to notify.
752 } else {
753 // It's a fat lock.
754 LW_MONITOR(thin)->Notify(self);
755 }
756}
757
758void Monitor::NotifyAll(Thread* self, Object *obj) {
759 uint32_t thin = *obj->GetRawLockWordAddress();
760
761 // If the lock is still thin, there aren't any waiters;
762 // waiting on an object forces lock fattening.
763 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
764 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700765 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700766 ThrowIllegalMonitorStateException("object not locked by thread before notifyAll()");
767 return;
768 }
769 // no-op; there are no waiters to notify.
770 } else {
771 // It's a fat lock.
772 LW_MONITOR(thin)->NotifyAll(self);
773 }
774}
775
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700776uint32_t Monitor::GetThinLockId(uint32_t raw_lock_word) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700777 if (LW_SHAPE(raw_lock_word) == LW_SHAPE_THIN) {
778 return LW_LOCK_OWNER(raw_lock_word);
779 } else {
780 Thread* owner = LW_MONITOR(raw_lock_word)->owner_;
781 return owner ? owner->GetThinLockId() : 0;
782 }
783}
784
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700785void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
786 Thread::State state = thread->GetState();
787
788 Object* object = NULL;
789 uint32_t lock_owner = ThreadList::kInvalidId;
790 if (state == Thread::kWaiting || state == Thread::kTimedWaiting) {
791 os << " - waiting on ";
792 Monitor* monitor = thread->wait_monitor_;
793 if (monitor != NULL) {
794 object = monitor->obj_;
795 }
796 lock_owner = Thread::LockOwnerFromThreadLock(object);
797 } else if (state == Thread::kBlocked) {
798 os << " - waiting to lock ";
799 object = thread->monitor_enter_object_;
800 if (object != NULL) {
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700801 lock_owner = object->GetThinLockId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700802 }
803 } else {
804 // We're not waiting on anything.
805 return;
806 }
807 os << "<" << object << ">";
808
809 // - waiting on <0x613f83d8> (a java.lang.ThreadLock) held by thread 5
810 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
811 os << " (a " << PrettyTypeOf(object) << ")";
812
813 if (lock_owner != ThreadList::kInvalidId) {
814 os << " held by thread " << lock_owner;
815 }
816
817 os << "\n";
818}
819
jeffhao33dc7712011-11-09 17:54:24 -0800820void Monitor::TranslateLocation(const Method* method, uint32_t pc,
821 const char*& source_file, uint32_t& line_number) const {
822 // If method is null, location is unknown
823 if (method == NULL) {
824 source_file = "unknown";
825 line_number = 0;
826 return;
827 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800828 MethodHelper mh(method);
829 source_file = mh.GetDeclaringClassSourceFile();
830 line_number = mh.GetLineNumFromNativePC(pc);
jeffhao33dc7712011-11-09 17:54:24 -0800831}
832
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700833MonitorList::MonitorList() : lock_("MonitorList lock") {
834}
835
836MonitorList::~MonitorList() {
837 MutexLock mu(lock_);
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700838
839 // In case there is a daemon thread with the monitor locked, clear
840 // the owner here so we can destroy the mutex, which will otherwise
841 // fail in pthread_mutex_destroy.
842 typedef std::list<Monitor*>::iterator It; // TODO: C++0x auto
843 for (It it = list_.begin(); it != list_.end(); it++) {
844 Monitor* monitor = *it;
845 Mutex& lock = monitor->lock_;
846 if (lock.GetOwner() != 0) {
847 DCHECK_EQ(lock.GetOwner(), monitor->owner_->GetTid());
848 lock.ClearOwner();
849 }
850 }
851
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700852 STLDeleteElements(&list_);
853}
854
855void MonitorList::Add(Monitor* m) {
856 MutexLock mu(lock_);
857 list_.push_front(m);
858}
859
860void MonitorList::SweepMonitorList(Heap::IsMarkedTester is_marked, void* arg) {
861 MutexLock mu(lock_);
862 typedef std::list<Monitor*>::iterator It; // TODO: C++0x auto
863 It it = list_.begin();
864 while (it != list_.end()) {
865 Monitor* m = *it;
866 if (!is_marked(m->GetObject(), arg)) {
867 if (Monitor::IsVerbose()) {
868 LOG(INFO) << "freeing monitor " << m << " belonging to unmarked object " << m->GetObject();
869 }
870 delete m;
871 it = list_.erase(it);
872 } else {
873 ++it;
874 }
875 }
876}
877
Elliott Hughes5f791332011-09-15 17:45:30 -0700878} // namespace art