blob: 8d04e2dae374c27469919a869d911053a5ae0a11 [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) {
Elliott Hughesd07986f2011-12-06 18:27:45 -0800241 locking_method_ = self->GetCurrentMethod(&locking_pc_);
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 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800827 MethodHelper mh(method);
828 source_file = mh.GetDeclaringClassSourceFile();
829 line_number = mh.GetLineNumFromNativePC(pc);
jeffhao33dc7712011-11-09 17:54:24 -0800830}
831
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700832MonitorList::MonitorList() : lock_("MonitorList lock") {
833}
834
835MonitorList::~MonitorList() {
836 MutexLock mu(lock_);
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700837
838 // In case there is a daemon thread with the monitor locked, clear
839 // the owner here so we can destroy the mutex, which will otherwise
840 // fail in pthread_mutex_destroy.
841 typedef std::list<Monitor*>::iterator It; // TODO: C++0x auto
842 for (It it = list_.begin(); it != list_.end(); it++) {
843 Monitor* monitor = *it;
844 Mutex& lock = monitor->lock_;
845 if (lock.GetOwner() != 0) {
846 DCHECK_EQ(lock.GetOwner(), monitor->owner_->GetTid());
847 lock.ClearOwner();
848 }
849 }
850
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700851 STLDeleteElements(&list_);
852}
853
854void MonitorList::Add(Monitor* m) {
855 MutexLock mu(lock_);
856 list_.push_front(m);
857}
858
859void MonitorList::SweepMonitorList(Heap::IsMarkedTester is_marked, void* arg) {
860 MutexLock mu(lock_);
861 typedef std::list<Monitor*>::iterator It; // TODO: C++0x auto
862 It it = list_.begin();
863 while (it != list_.end()) {
864 Monitor* m = *it;
865 if (!is_marked(m->GetObject(), arg)) {
866 if (Monitor::IsVerbose()) {
867 LOG(INFO) << "freeing monitor " << m << " belonging to unmarked object " << m->GetObject();
868 }
869 delete m;
870 it = list_.erase(it);
871 } else {
872 ++it;
873 }
874 }
875}
876
Elliott Hughes5f791332011-09-15 17:45:30 -0700877} // namespace art