blob: 16298aed8654a73b5264f8bf019e641356f2ef29 [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
27#include "mutex.h"
28#include "object.h"
Elliott Hughesc33a32b2011-10-11 18:18:07 -070029#include "stl_util.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070030#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070031#include "thread_list.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070032
33namespace art {
34
35/*
36 * Every Object has a monitor associated with it, but not every Object is
37 * actually locked. Even the ones that are locked do not need a
38 * full-fledged monitor until a) there is actual contention or b) wait()
39 * is called on the Object.
40 *
41 * For Android, we have implemented a scheme similar to the one described
42 * in Bacon et al.'s "Thin locks: featherweight synchronization for Java"
43 * (ACM 1998). Things are even easier for us, though, because we have
44 * a full 32 bits to work with.
45 *
46 * The two states of an Object's lock are referred to as "thin" and
47 * "fat". A lock may transition from the "thin" state to the "fat"
48 * state and this transition is referred to as inflation. Once a lock
49 * has been inflated it remains in the "fat" state indefinitely.
50 *
51 * The lock value itself is stored in Object.lock. The LSB of the
52 * lock encodes its state. When cleared, the lock is in the "thin"
53 * state and its bits are formatted as follows:
54 *
55 * [31 ---- 19] [18 ---- 3] [2 ---- 1] [0]
56 * lock count thread id hash state 0
57 *
58 * When set, the lock is in the "fat" state and its bits are formatted
59 * as follows:
60 *
61 * [31 ---- 3] [2 ---- 1] [0]
62 * pointer hash state 1
63 *
64 * For an in-depth description of the mechanics of thin-vs-fat locking,
65 * read the paper referred to above.
Elliott Hughes54e7df12011-09-16 11:47:04 -070066 *
Elliott Hughes5f791332011-09-15 17:45:30 -070067 * Monitors provide:
68 * - mutually exclusive access to resources
69 * - a way for multiple threads to wait for notification
70 *
71 * In effect, they fill the role of both mutexes and condition variables.
72 *
73 * Only one thread can own the monitor at any time. There may be several
74 * threads waiting on it (the wait call unlocks it). One or more waiting
75 * threads may be getting interrupted or notified at any given time.
76 *
77 * TODO: the various members of monitor are not SMP-safe.
78 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070079
80
81/*
82 * Monitor accessor. Extracts a monitor structure pointer from a fat
83 * lock. Performs no error checking.
84 */
85#define LW_MONITOR(x) \
86 ((Monitor*)((x) & ~((LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT) | LW_SHAPE_MASK)))
87
88/*
89 * Lock recursion count field. Contains a count of the number of times
90 * a lock has been recursively acquired.
91 */
92#define LW_LOCK_COUNT_MASK 0x1fff
93#define LW_LOCK_COUNT_SHIFT 19
94#define LW_LOCK_COUNT(x) (((x) >> LW_LOCK_COUNT_SHIFT) & LW_LOCK_COUNT_MASK)
95
Elliott Hughesfc861622011-10-17 17:57:47 -070096bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070097bool Monitor::is_verbose_ = false;
Elliott Hughesfc861622011-10-17 17:57:47 -070098uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070099
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700100bool Monitor::IsVerbose() {
101 return is_verbose_;
102}
103
Elliott Hughesfc861622011-10-17 17:57:47 -0700104bool Monitor::IsSensitiveThread() {
105 if (is_sensitive_thread_hook_ != NULL) {
106 return (*is_sensitive_thread_hook_)();
107 }
108 return false;
109}
110
111void Monitor::Init(bool is_verbose, uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700112 is_verbose_ = is_verbose;
Elliott Hughesfc861622011-10-17 17:57:47 -0700113 lock_profiling_threshold_ = lock_profiling_threshold;
114 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700115}
116
Elliott Hughes5f791332011-09-15 17:45:30 -0700117Monitor::Monitor(Object* obj)
118 : owner_(NULL),
119 lock_count_(0),
120 obj_(obj),
121 wait_set_(NULL),
122 lock_("a monitor lock"),
Elliott Hughes5f791332011-09-15 17:45:30 -0700123 owner_filename_(NULL),
124 owner_line_number_(0) {
125}
126
127Monitor::~Monitor() {
128 DCHECK(obj_ != NULL);
129 DCHECK_EQ(LW_SHAPE(*obj_->GetRawLockWordAddress()), LW_SHAPE_FAT);
130
131#ifndef NDEBUG
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700132 // This lock is associated with an object that's being swept.
133 bool locked = lock_.TryLock();
134 DCHECK(locked) << obj_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700135 lock_.Unlock();
136#endif
137}
138
139/*
140 * Links a thread into a monitor's wait set. The monitor lock must be
141 * held by the caller of this routine.
142 */
143void Monitor::AppendToWaitSet(Thread* thread) {
144 DCHECK(owner_ == Thread::Current());
145 DCHECK(thread != NULL);
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700146 DCHECK(thread->wait_next_ == NULL) << thread->wait_next_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700147 if (wait_set_ == NULL) {
148 wait_set_ = thread;
149 return;
150 }
151
152 // push_back.
153 Thread* t = wait_set_;
154 while (t->wait_next_ != NULL) {
155 t = t->wait_next_;
156 }
157 t->wait_next_ = thread;
158}
159
160/*
161 * Unlinks a thread from a monitor's wait set. The monitor lock must
162 * be held by the caller of this routine.
163 */
164void Monitor::RemoveFromWaitSet(Thread *thread) {
165 DCHECK(owner_ == Thread::Current());
166 DCHECK(thread != NULL);
167 if (wait_set_ == NULL) {
168 return;
169 }
170 if (wait_set_ == thread) {
171 wait_set_ = thread->wait_next_;
172 thread->wait_next_ = NULL;
173 return;
174 }
175
176 Thread* t = wait_set_;
177 while (t->wait_next_ != NULL) {
178 if (t->wait_next_ == thread) {
179 t->wait_next_ = thread->wait_next_;
180 thread->wait_next_ = NULL;
181 return;
182 }
183 t = t->wait_next_;
184 }
185}
186
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700187Object* Monitor::GetObject() {
188 return obj_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700189}
190
Elliott Hughes5f791332011-09-15 17:45:30 -0700191void Monitor::Lock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700192 if (owner_ == self) {
193 lock_count_++;
194 return;
195 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700196
197 uint64_t waitStart, waitEnd;
Elliott Hughes5f791332011-09-15 17:45:30 -0700198 if (!lock_.TryLock()) {
Elliott Hughesfc861622011-10-17 17:57:47 -0700199 uint32_t wait_threshold = lock_profiling_threshold_;
200 const char* current_owner_filename = NULL;
201 uint32_t current_owner_line_number = -1;
Elliott Hughes5f791332011-09-15 17:45:30 -0700202 {
203 ScopedThreadStateChange tsc(self, Thread::kBlocked);
Elliott Hughesfc861622011-10-17 17:57:47 -0700204 if (wait_threshold != 0) {
205 waitStart = NanoTime() / 1000;
206 }
207 current_owner_filename = owner_filename_;
208 current_owner_line_number = owner_line_number_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700209
210 lock_.Lock();
Elliott Hughesfc861622011-10-17 17:57:47 -0700211 if (wait_threshold != 0) {
212 waitEnd = NanoTime() / 1000;
213 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700214 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700215
216 if (wait_threshold != 0) {
217 uint64_t wait_ms = (waitEnd - waitStart) / 1000;
218 uint32_t sample_percent;
219 if (wait_ms >= wait_threshold) {
220 sample_percent = 100;
221 } else {
222 sample_percent = 100 * wait_ms / wait_threshold;
223 }
224 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
225 LogContentionEvent(self, wait_ms, sample_percent, current_owner_filename, current_owner_line_number);
226 }
227 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700228 }
229 owner_ = self;
230 DCHECK_EQ(lock_count_, 0);
231
232 // When debugging, save the current monitor holder for future
233 // acquisition failures to use in sampled logging.
Elliott Hughesfc861622011-10-17 17:57:47 -0700234 if (lock_profiling_threshold_ != 0) {
235 self->GetCurrentLocation(owner_filename_, owner_line_number_);
236 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700237}
238
239void ThrowIllegalMonitorStateException(const char* msg) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700240 Thread::Current()->ThrowNewException("Ljava/lang/IllegalMonitorStateException;", msg);
Elliott Hughes5f791332011-09-15 17:45:30 -0700241}
242
243bool Monitor::Unlock(Thread* self) {
244 DCHECK(self != NULL);
245 if (owner_ == self) {
246 // We own the monitor, so nobody else can be in here.
247 if (lock_count_ == 0) {
248 owner_ = NULL;
249 owner_filename_ = "unlocked";
250 owner_line_number_ = 0;
251 lock_.Unlock();
252 } else {
253 --lock_count_;
254 }
255 } else {
256 // We don't own this, so we're not allowed to unlock it.
257 // The JNI spec says that we should throw IllegalMonitorStateException
258 // in this case.
259 ThrowIllegalMonitorStateException("unlock of unowned monitor");
260 return false;
261 }
262 return true;
263}
264
265/*
266 * Converts the given relative waiting time into an absolute time.
267 */
268void ToAbsoluteTime(int64_t ms, int32_t ns, struct timespec *ts) {
269 int64_t endSec;
270
271#ifdef HAVE_TIMEDWAIT_MONOTONIC
272 clock_gettime(CLOCK_MONOTONIC, ts);
273#else
274 {
275 struct timeval tv;
276 gettimeofday(&tv, NULL);
277 ts->tv_sec = tv.tv_sec;
278 ts->tv_nsec = tv.tv_usec * 1000;
279 }
280#endif
281 endSec = ts->tv_sec + ms / 1000;
282 if (endSec >= 0x7fffffff) {
283 LOG(INFO) << "Note: end time exceeds epoch";
284 endSec = 0x7ffffffe;
285 }
286 ts->tv_sec = endSec;
287 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
288
289 // Catch rollover.
290 if (ts->tv_nsec >= 1000000000L) {
291 ts->tv_sec++;
292 ts->tv_nsec -= 1000000000L;
293 }
294}
295
296int dvmRelativeCondWait(pthread_cond_t* cond, pthread_mutex_t* mutex, int64_t ms, int32_t ns) {
297 struct timespec ts;
298 ToAbsoluteTime(ms, ns, &ts);
299#if defined(HAVE_TIMEDWAIT_MONOTONIC)
300 int rc = pthread_cond_timedwait_monotonic(cond, mutex, &ts);
301#else
302 int rc = pthread_cond_timedwait(cond, mutex, &ts);
303#endif
304 DCHECK(rc == 0 || rc == ETIMEDOUT);
305 return rc;
306}
307
308/*
309 * Wait on a monitor until timeout, interrupt, or notification. Used for
310 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
311 *
312 * If another thread calls Thread.interrupt(), we throw InterruptedException
313 * and return immediately if one of the following are true:
314 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
315 * - blocked in join(), join(long), or join(long, int) methods of Thread
316 * - blocked in sleep(long), or sleep(long, int) methods of Thread
317 * Otherwise, we set the "interrupted" flag.
318 *
319 * Checks to make sure that "ns" is in the range 0-999999
320 * (i.e. fractions of a millisecond) and throws the appropriate
321 * exception if it isn't.
322 *
323 * The spec allows "spurious wakeups", and recommends that all code using
324 * Object.wait() do so in a loop. This appears to derive from concerns
325 * about pthread_cond_wait() on multiprocessor systems. Some commentary
326 * on the web casts doubt on whether these can/should occur.
327 *
328 * Since we're allowed to wake up "early", we clamp extremely long durations
329 * to return at the end of the 32-bit time epoch.
330 */
331void Monitor::Wait(Thread* self, int64_t ms, int32_t ns, bool interruptShouldThrow) {
332 DCHECK(self != NULL);
333
334 // Make sure that we hold the lock.
335 if (owner_ != self) {
336 ThrowIllegalMonitorStateException("object not locked by thread before wait()");
337 return;
338 }
339
340 // Enforce the timeout range.
341 if (ms < 0 || ns < 0 || ns > 999999) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700342 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Elliott Hughes5f791332011-09-15 17:45:30 -0700343 "timeout arguments out of range: ms=%lld ns=%d", ms, ns);
344 return;
345 }
346
347 // Compute absolute wakeup time, if necessary.
348 struct timespec ts;
349 bool timed = false;
350 if (ms != 0 || ns != 0) {
351 ToAbsoluteTime(ms, ns, &ts);
352 timed = true;
353 }
354
355 /*
356 * Add ourselves to the set of threads waiting on this monitor, and
357 * release our hold. We need to let it go even if we're a few levels
358 * deep in a recursive lock, and we need to restore that later.
359 *
360 * We append to the wait set ahead of clearing the count and owner
361 * fields so the subroutine can check that the calling thread owns
362 * the monitor. Aside from that, the order of member updates is
363 * not order sensitive as we hold the pthread mutex.
364 */
365 AppendToWaitSet(self);
366 int prevLockCount = lock_count_;
367 lock_count_ = 0;
368 owner_ = NULL;
369 const char* savedFileName = owner_filename_;
370 owner_filename_ = NULL;
371 uint32_t savedLineNumber = owner_line_number_;
372 owner_line_number_ = 0;
373
374 /*
375 * Update thread status. If the GC wakes up, it'll ignore us, knowing
376 * that we won't touch any references in this state, and we'll check
377 * our suspend mode before we transition out.
378 */
379 if (timed) {
380 self->SetState(Thread::kTimedWaiting);
381 } else {
382 self->SetState(Thread::kWaiting);
383 }
384
Elliott Hughes85d15452011-09-16 17:33:01 -0700385 self->wait_mutex_->Lock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700386
387 /*
388 * Set wait_monitor_ to the monitor object we will be waiting on.
389 * When wait_monitor_ is non-NULL a notifying or interrupting thread
390 * must signal the thread's wait_cond_ to wake it up.
391 */
392 DCHECK(self->wait_monitor_ == NULL);
393 self->wait_monitor_ = this;
394
395 /*
396 * Handle the case where the thread was interrupted before we called
397 * wait().
398 */
399 bool wasInterrupted = false;
400 if (self->interrupted_) {
401 wasInterrupted = true;
402 self->wait_monitor_ = NULL;
Elliott Hughes85d15452011-09-16 17:33:01 -0700403 self->wait_mutex_->Unlock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700404 goto done;
405 }
406
407 /*
408 * Release the monitor lock and wait for a notification or
409 * a timeout to occur.
410 */
411 lock_.Unlock();
412
413 if (!timed) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700414 self->wait_cond_->Wait(*self->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700415 } else {
Elliott Hughes85d15452011-09-16 17:33:01 -0700416 self->wait_cond_->TimedWait(*self->wait_mutex_, ts);
Elliott Hughes5f791332011-09-15 17:45:30 -0700417 }
418 if (self->interrupted_) {
419 wasInterrupted = true;
420 }
421
422 self->interrupted_ = false;
423 self->wait_monitor_ = NULL;
Elliott Hughes85d15452011-09-16 17:33:01 -0700424 self->wait_mutex_->Unlock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700425
426 // Reacquire the monitor lock.
427 Lock(self);
428
429done:
430 /*
431 * We remove our thread from wait set after restoring the count
432 * and owner fields so the subroutine can check that the calling
433 * thread owns the monitor. Aside from that, the order of member
434 * updates is not order sensitive as we hold the pthread mutex.
435 */
436 owner_ = self;
437 lock_count_ = prevLockCount;
438 owner_filename_ = savedFileName;
439 owner_line_number_ = savedLineNumber;
440 RemoveFromWaitSet(self);
441
442 /* set self->status back to Thread::kRunnable, and self-suspend if needed */
443 self->SetState(Thread::kRunnable);
444
445 if (wasInterrupted) {
446 /*
447 * We were interrupted while waiting, or somebody interrupted an
448 * un-interruptible thread earlier and we're bailing out immediately.
449 *
450 * The doc sayeth: "The interrupted status of the current thread is
451 * cleared when this exception is thrown."
452 */
453 self->interrupted_ = false;
454 if (interruptShouldThrow) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700455 Thread::Current()->ThrowNewException("Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700456 }
457 }
458}
459
460void Monitor::Notify(Thread* self) {
461 DCHECK(self != NULL);
462
463 // Make sure that we hold the lock.
464 if (owner_ != self) {
465 ThrowIllegalMonitorStateException("object not locked by thread before notify()");
466 return;
467 }
468 // Signal the first waiting thread in the wait set.
469 while (wait_set_ != NULL) {
470 Thread* thread = wait_set_;
471 wait_set_ = thread->wait_next_;
472 thread->wait_next_ = NULL;
473
474 // Check to see if the thread is still waiting.
Elliott Hughes85d15452011-09-16 17:33:01 -0700475 MutexLock mu(*thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700476 if (thread->wait_monitor_ != NULL) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700477 thread->wait_cond_->Signal();
Elliott Hughes5f791332011-09-15 17:45:30 -0700478 return;
479 }
480 }
481}
482
483void Monitor::NotifyAll(Thread* self) {
484 DCHECK(self != NULL);
485
486 // Make sure that we hold the lock.
487 if (owner_ != self) {
488 ThrowIllegalMonitorStateException("object not locked by thread before notifyAll()");
489 return;
490 }
491 // Signal all threads in the wait set.
492 while (wait_set_ != NULL) {
493 Thread* thread = wait_set_;
494 wait_set_ = thread->wait_next_;
495 thread->wait_next_ = NULL;
496 thread->Notify();
497 }
498}
499
500/*
501 * Changes the shape of a monitor from thin to fat, preserving the
502 * internal lock state. The calling thread must own the lock.
503 */
504void Monitor::Inflate(Thread* self, Object* obj) {
505 DCHECK(self != NULL);
506 DCHECK(obj != NULL);
507 DCHECK_EQ(LW_SHAPE(*obj->GetRawLockWordAddress()), LW_SHAPE_THIN);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700508 DCHECK_EQ(LW_LOCK_OWNER(*obj->GetRawLockWordAddress()), static_cast<int32_t>(self->GetThinLockId()));
Elliott Hughes5f791332011-09-15 17:45:30 -0700509
510 // Allocate and acquire a new monitor.
511 Monitor* m = new Monitor(obj);
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700512 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700513 LOG(INFO) << "monitor: thread " << self->GetThinLockId()
514 << " created monitor " << m << " for object " << obj;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700515 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700516 Runtime::Current()->GetMonitorList()->Add(m);
Elliott Hughes5f791332011-09-15 17:45:30 -0700517 m->Lock(self);
518 // Propagate the lock state.
519 uint32_t thin = *obj->GetRawLockWordAddress();
520 m->lock_count_ = LW_LOCK_COUNT(thin);
521 thin &= LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT;
522 thin |= reinterpret_cast<uint32_t>(m) | LW_SHAPE_FAT;
523 // Publish the updated lock word.
524 android_atomic_release_store(thin, obj->GetRawLockWordAddress());
525}
526
527void Monitor::MonitorEnter(Thread* self, Object* obj) {
528 volatile int32_t* thinp = obj->GetRawLockWordAddress();
529 struct timespec tm;
530 long sleepDelayNs;
531 long minSleepDelayNs = 1000000; /* 1 millisecond */
532 long maxSleepDelayNs = 1000000000; /* 1 second */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700533 uint32_t thin, newThin;
Elliott Hughes5f791332011-09-15 17:45:30 -0700534
Elliott Hughes4681c802011-09-25 18:04:37 -0700535 DCHECK(self != NULL);
536 DCHECK(obj != NULL);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700537 uint32_t threadId = self->GetThinLockId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700538retry:
539 thin = *thinp;
540 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
541 /*
542 * The lock is a thin lock. The owner field is used to
543 * determine the acquire method, ordered by cost.
544 */
545 if (LW_LOCK_OWNER(thin) == threadId) {
546 /*
547 * The calling thread owns the lock. Increment the
548 * value of the recursion count field.
549 */
550 *thinp += 1 << LW_LOCK_COUNT_SHIFT;
551 if (LW_LOCK_COUNT(*thinp) == LW_LOCK_COUNT_MASK) {
552 /*
553 * The reacquisition limit has been reached. Inflate
554 * the lock so the next acquire will not overflow the
555 * recursion count field.
556 */
557 Inflate(self, obj);
558 }
559 } else if (LW_LOCK_OWNER(thin) == 0) {
560 /*
561 * The lock is unowned. Install the thread id of the
562 * calling thread into the owner field. This is the
563 * common case. In performance critical code the JIT
564 * will have tried this before calling out to the VM.
565 */
566 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
567 if (android_atomic_acquire_cas(thin, newThin, thinp) != 0) {
568 // The acquire failed. Try again.
569 goto retry;
570 }
571 } else {
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700572 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700573 LOG(INFO) << StringPrintf("monitor: thread %d spin on lock %p (a %s) owned by %d",
574 threadId, thinp, PrettyTypeOf(obj).c_str(), LW_LOCK_OWNER(thin));
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700575 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700576 // The lock is owned by another thread. Notify the VM that we are about to wait.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700577 self->monitor_enter_object_ = obj;
Elliott Hughes5f791332011-09-15 17:45:30 -0700578 Thread::State oldStatus = self->SetState(Thread::kBlocked);
579 // Spin until the thin lock is released or inflated.
580 sleepDelayNs = 0;
581 for (;;) {
582 thin = *thinp;
583 // Check the shape of the lock word. Another thread
584 // may have inflated the lock while we were waiting.
585 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
586 if (LW_LOCK_OWNER(thin) == 0) {
587 // The lock has been released. Install the thread id of the
588 // calling thread into the owner field.
589 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
590 if (android_atomic_acquire_cas(thin, newThin, thinp) == 0) {
591 // The acquire succeed. Break out of the loop and proceed to inflate the lock.
592 break;
593 }
594 } else {
595 // The lock has not been released. Yield so the owning thread can run.
596 if (sleepDelayNs == 0) {
597 sched_yield();
598 sleepDelayNs = minSleepDelayNs;
599 } else {
600 tm.tv_sec = 0;
601 tm.tv_nsec = sleepDelayNs;
602 nanosleep(&tm, NULL);
603 // Prepare the next delay value. Wrap to avoid once a second polls for eternity.
604 if (sleepDelayNs < maxSleepDelayNs / 2) {
605 sleepDelayNs *= 2;
606 } else {
607 sleepDelayNs = minSleepDelayNs;
608 }
609 }
610 }
611 } else {
612 // The thin lock was inflated by another thread. Let the VM know we are no longer
613 // waiting and try again.
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700614 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700615 LOG(INFO) << "monitor: thread " << threadId
616 << " found lock " << (void*) thinp << " surprise-fattened by another thread";
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700617 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700618 self->monitor_enter_object_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700619 self->SetState(oldStatus);
620 goto retry;
621 }
622 }
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700623 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700624 LOG(INFO) << StringPrintf("monitor: thread %d spin on lock %p done", threadId, thinp);
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700625 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700626 // We have acquired the thin lock. Let the VM know that we are no longer waiting.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700627 self->monitor_enter_object_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700628 self->SetState(oldStatus);
629 // Fatten the lock.
630 Inflate(self, obj);
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700631 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700632 LOG(INFO) << StringPrintf("monitor: thread %d fattened lock %p", threadId, thinp);
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700633 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700634 }
635 } else {
636 // The lock is a fat lock.
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 locking fat lock %p (%p) %p on a %s",
639 threadId, thinp, LW_MONITOR(*thinp), (void*)*thinp, PrettyTypeOf(obj).c_str());
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700640 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700641 DCHECK(LW_MONITOR(*thinp) != NULL);
642 LW_MONITOR(*thinp)->Lock(self);
643 }
644}
645
646bool Monitor::MonitorExit(Thread* self, Object* obj) {
647 volatile int32_t* thinp = obj->GetRawLockWordAddress();
648
649 DCHECK(self != NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -0700650 //DCHECK_EQ(self->GetState(), Thread::kRunnable);
Elliott Hughes5f791332011-09-15 17:45:30 -0700651 DCHECK(obj != NULL);
652
653 /*
654 * Cache the lock word as its value can change while we are
655 * examining its state.
656 */
657 uint32_t thin = *thinp;
658 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
659 /*
660 * The lock is thin. We must ensure that the lock is owned
661 * by the given thread before unlocking it.
662 */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700663 if (LW_LOCK_OWNER(thin) == self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700664 /*
665 * We are the lock owner. It is safe to update the lock
666 * without CAS as lock ownership guards the lock itself.
667 */
668 if (LW_LOCK_COUNT(thin) == 0) {
669 /*
670 * The lock was not recursively acquired, the common
671 * case. Unlock by clearing all bits except for the
672 * hash state.
673 */
674 thin &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
675 android_atomic_release_store(thin, thinp);
676 } else {
677 /*
678 * The object was recursively acquired. Decrement the
679 * lock recursion count field.
680 */
681 *thinp -= 1 << LW_LOCK_COUNT_SHIFT;
682 }
683 } else {
684 /*
685 * We do not own the lock. The JVM spec requires that we
686 * throw an exception in this case.
687 */
688 ThrowIllegalMonitorStateException("unlock of unowned monitor");
689 return false;
690 }
691 } else {
692 /*
693 * The lock is fat. We must check to see if Unlock has
694 * raised any exceptions before continuing.
695 */
696 DCHECK(LW_MONITOR(*thinp) != NULL);
697 if (!LW_MONITOR(*thinp)->Unlock(self)) {
698 // An exception has been raised. Do not fall through.
699 return false;
700 }
701 }
702 return true;
703}
704
705/*
706 * Object.wait(). Also called for class init.
707 */
708void Monitor::Wait(Thread* self, Object *obj, int64_t ms, int32_t ns, bool interruptShouldThrow) {
709 volatile int32_t* thinp = obj->GetRawLockWordAddress();
710
711 // If the lock is still thin, we need to fatten it.
712 uint32_t thin = *thinp;
713 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
714 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700715 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700716 ThrowIllegalMonitorStateException("object not locked by thread before wait()");
717 return;
718 }
719
720 /* This thread holds the lock. We need to fatten the lock
721 * so 'self' can block on it. Don't update the object lock
722 * field yet, because 'self' needs to acquire the lock before
723 * any other thread gets a chance.
724 */
725 Inflate(self, obj);
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700726 if (is_verbose_) {
Elliott Hughesf8e01272011-10-17 11:29:05 -0700727 LOG(INFO) << StringPrintf("monitor: thread %d fattened lock %p by wait()", self->GetThinLockId(), thinp);
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700728 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700729 }
730 LW_MONITOR(*thinp)->Wait(self, ms, ns, interruptShouldThrow);
731}
732
733void Monitor::Notify(Thread* self, Object *obj) {
734 uint32_t thin = *obj->GetRawLockWordAddress();
735
736 // If the lock is still thin, there aren't any waiters;
737 // waiting on an object forces lock fattening.
738 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
739 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700740 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700741 ThrowIllegalMonitorStateException("object not locked by thread before notify()");
742 return;
743 }
744 // no-op; there are no waiters to notify.
745 } else {
746 // It's a fat lock.
747 LW_MONITOR(thin)->Notify(self);
748 }
749}
750
751void Monitor::NotifyAll(Thread* self, Object *obj) {
752 uint32_t thin = *obj->GetRawLockWordAddress();
753
754 // If the lock is still thin, there aren't any waiters;
755 // waiting on an object forces lock fattening.
756 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
757 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700758 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700759 ThrowIllegalMonitorStateException("object not locked by thread before notifyAll()");
760 return;
761 }
762 // no-op; there are no waiters to notify.
763 } else {
764 // It's a fat lock.
765 LW_MONITOR(thin)->NotifyAll(self);
766 }
767}
768
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700769uint32_t Monitor::GetThinLockId(uint32_t raw_lock_word) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700770 if (LW_SHAPE(raw_lock_word) == LW_SHAPE_THIN) {
771 return LW_LOCK_OWNER(raw_lock_word);
772 } else {
773 Thread* owner = LW_MONITOR(raw_lock_word)->owner_;
774 return owner ? owner->GetThinLockId() : 0;
775 }
776}
777
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700778void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
779 Thread::State state = thread->GetState();
780
781 Object* object = NULL;
782 uint32_t lock_owner = ThreadList::kInvalidId;
783 if (state == Thread::kWaiting || state == Thread::kTimedWaiting) {
784 os << " - waiting on ";
785 Monitor* monitor = thread->wait_monitor_;
786 if (monitor != NULL) {
787 object = monitor->obj_;
788 }
789 lock_owner = Thread::LockOwnerFromThreadLock(object);
790 } else if (state == Thread::kBlocked) {
791 os << " - waiting to lock ";
792 object = thread->monitor_enter_object_;
793 if (object != NULL) {
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700794 lock_owner = object->GetThinLockId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700795 }
796 } else {
797 // We're not waiting on anything.
798 return;
799 }
800 os << "<" << object << ">";
801
802 // - waiting on <0x613f83d8> (a java.lang.ThreadLock) held by thread 5
803 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
804 os << " (a " << PrettyTypeOf(object) << ")";
805
806 if (lock_owner != ThreadList::kInvalidId) {
807 os << " held by thread " << lock_owner;
808 }
809
810 os << "\n";
811}
812
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700813MonitorList::MonitorList() : lock_("MonitorList lock") {
814}
815
816MonitorList::~MonitorList() {
817 MutexLock mu(lock_);
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700818
819 // In case there is a daemon thread with the monitor locked, clear
820 // the owner here so we can destroy the mutex, which will otherwise
821 // fail in pthread_mutex_destroy.
822 typedef std::list<Monitor*>::iterator It; // TODO: C++0x auto
823 for (It it = list_.begin(); it != list_.end(); it++) {
824 Monitor* monitor = *it;
825 Mutex& lock = monitor->lock_;
826 if (lock.GetOwner() != 0) {
827 DCHECK_EQ(lock.GetOwner(), monitor->owner_->GetTid());
828 lock.ClearOwner();
829 }
830 }
831
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700832 STLDeleteElements(&list_);
833}
834
835void MonitorList::Add(Monitor* m) {
836 MutexLock mu(lock_);
837 list_.push_front(m);
838}
839
840void MonitorList::SweepMonitorList(Heap::IsMarkedTester is_marked, void* arg) {
841 MutexLock mu(lock_);
842 typedef std::list<Monitor*>::iterator It; // TODO: C++0x auto
843 It it = list_.begin();
844 while (it != list_.end()) {
845 Monitor* m = *it;
846 if (!is_marked(m->GetObject(), arg)) {
847 if (Monitor::IsVerbose()) {
848 LOG(INFO) << "freeing monitor " << m << " belonging to unmarked object " << m->GetObject();
849 }
850 delete m;
851 it = list_.erase(it);
852 } else {
853 ++it;
854 }
855 }
856}
857
Elliott Hughes5f791332011-09-15 17:45:30 -0700858} // namespace art