summaryrefslogtreecommitdiff
path: root/src/mutex.cc
blob: 18c94535c5fa894495dc0c16bcf327eac2ed926b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "mutex.h"

#include <errno.h>

#include "logging.h"
#include "runtime.h"
#include "thread.h"
#include "utils.h"

#if defined(__APPLE__)
#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
#endif

#define CHECK_MUTEX_CALL(call, args) CHECK_PTHREAD_CALL(call, args, name_)

extern int pthread_mutex_lock(pthread_mutex_t* mutex) EXCLUSIVE_LOCK_FUNCTION(mutex);
extern int pthread_mutex_unlock(pthread_mutex_t* mutex) UNLOCK_FUNCTION(1);
extern int pthread_mutex_trylock(pthread_mutex_t* mutex) EXCLUSIVE_TRYLOCK_FUNCTION(0, mutex);

namespace art {

// This works on Mac OS 10.7, but hasn't been tested on older releases.
struct __attribute__((__may_alias__)) darwin_pthread_mutex_t {
  uint32_t padding0[4];
  intptr_t padding1;
  uintptr_t owner_tid;
  // ...other stuff we don't care about.
};

struct __attribute__((__may_alias__)) darwin_pthread_rwlock_t {
  int32_t padding0[4];
  intptr_t padding1[2];
  uintptr_t rw_owner_tid;
  // ...other stuff we don't care about.
};

struct __attribute__((__may_alias__)) glibc_pthread_mutex_t {
  int32_t padding0[2];
  int owner;
  // ...other stuff we don't care about.
};

struct __attribute__((__may_alias__)) glibc_pthread_rwlock_t {
#ifdef __LP64__
  int32_t padding0[6];
#else
  int32_t padding0[7];
#endif
  int writer;
  // ...other stuff we don't care about.
};

ReaderWriterMutex* GlobalSynchronization::mutator_lock_ = NULL;
Mutex* GlobalSynchronization::thread_list_lock_ = NULL;
Mutex* GlobalSynchronization::classlinker_classes_lock_ = NULL;
ReaderWriterMutex* GlobalSynchronization::heap_bitmap_lock_ = NULL;
Mutex* GlobalSynchronization::abort_lock_ = NULL;
Mutex* GlobalSynchronization::logging_lock_ = NULL;
Mutex* GlobalSynchronization::unexpected_signal_lock_ = NULL;
Mutex* GlobalSynchronization::thread_suspend_count_lock_ = NULL;

void GlobalSynchronization::Init() {
  if (logging_lock_ != NULL) {
    // Already initialized.
    DCHECK(mutator_lock_ != NULL);
    DCHECK(thread_list_lock_ != NULL);
    DCHECK(classlinker_classes_lock_ != NULL);
    DCHECK(heap_bitmap_lock_ != NULL);
    DCHECK(abort_lock_ != NULL);
    DCHECK(logging_lock_ != NULL);
    DCHECK(unexpected_signal_lock_ != NULL);
    DCHECK(thread_suspend_count_lock_ != NULL);
  } else {
    logging_lock_ = new Mutex("logging lock", kLoggingLock, true);
    abort_lock_ = new Mutex("abort lock", kAbortLock, true);
    DCHECK(mutator_lock_ == NULL);
    mutator_lock_ = new ReaderWriterMutex("mutator lock", kMutatorLock);
    DCHECK(thread_list_lock_ == NULL);
    thread_list_lock_ = new Mutex("thread list lock", kThreadListLock);
    DCHECK(classlinker_classes_lock_ == NULL);
    classlinker_classes_lock_ = new Mutex("ClassLinker classes lock", kClassLinkerClassesLock);
    DCHECK(heap_bitmap_lock_ == NULL);
    heap_bitmap_lock_ = new ReaderWriterMutex("heap bitmap lock", kHeapBitmapLock);
    DCHECK(unexpected_signal_lock_ == NULL);
    unexpected_signal_lock_ = new Mutex("unexpected signal lock", kUnexpectedSignalLock, true);
    DCHECK(thread_suspend_count_lock_ == NULL);
    thread_suspend_count_lock_ = new Mutex("thread suspend count lock", kThreadSuspendCountLock);
  }
}

BaseMutex::BaseMutex(const char* name, MutexLevel level) : level_(level), name_(name) {}

static void CheckUnattachedThread(MutexLevel level) {
  // The check below enumerates the cases where we expect not to be able to sanity check locks
  // on a thread. TODO: tighten this check.
  Runtime* runtime = Runtime::Current();
  CHECK(runtime == NULL || !runtime->IsStarted() || runtime->IsShuttingDown() ||
        level == kDefaultMutexLevel  || level == kThreadListLock ||
        level == kLoggingLock || level == kAbortLock);
}

void BaseMutex::RegisterAsLockedWithCurrentThread() {
  Thread* self = Thread::Current();
  if (self == NULL) {
    CheckUnattachedThread(level_);
    return;
  }
  // Check if a bad Mutex of this level or lower is held.
  bool bad_mutexes_held = false;
  for (int i = level_; i >= 0; --i) {
    BaseMutex* held_mutex = self->GetHeldMutex(static_cast<MutexLevel>(i));
    if (UNLIKELY(held_mutex != NULL)) {
      LOG(ERROR) << "Lock level violation: holding \"" << held_mutex->name_ << "\" (level " << i
          << ") while locking \"" << name_ << "\" (level " << static_cast<int>(level_) << ")";
      if (i > kAbortLock) {
        // Only abort in the check below if this is more than abort level lock.
        bad_mutexes_held = true;
      }
    }
  }
  CHECK(!bad_mutexes_held);
  // Don't record monitors as they are outside the scope of analysis. They may be inspected off of
  // the monitor list.
  if (level_ != kMonitorLock) {
    self->SetHeldMutex(level_, this);
  }
}

void BaseMutex::RegisterAsUnlockedWithCurrentThread() {
  Thread* self = Thread::Current();
  if (self == NULL) {
    CheckUnattachedThread(level_);
    return;
  }
  if (level_ != kMonitorLock) {
    CHECK(self->GetHeldMutex(level_) == this) << "Unlocking on unacquired mutex: " << name_;
    self->SetHeldMutex(level_, NULL);
  }
}

void BaseMutex::CheckSafeToWait() {
  Thread* self = Thread::Current();
  if (self == NULL) {
    CheckUnattachedThread(level_);
    return;
  }
  CHECK(self->GetHeldMutex(level_) == this) << "Waiting on unacquired mutex: " << name_;
  bool bad_mutexes_held = false;
  for (int i = kMaxMutexLevel; i >= 0; --i) {
    if (i != level_) {
      BaseMutex* held_mutex = self->GetHeldMutex(static_cast<MutexLevel>(i));
      if (held_mutex != NULL) {
        LOG(ERROR) << "Holding " << held_mutex->name_ << " (level " << i
            << ") while performing wait on: "
            << name_ << " (level " << static_cast<int>(level_) << ")";
        bad_mutexes_held = true;
      }
    }
  }
  CHECK(!bad_mutexes_held);
}

Mutex::Mutex(const char* name, MutexLevel level, bool recursive)
    : BaseMutex(name, level), recursive_(recursive), recursion_count_(0) {
#if defined(__BIONIC__)
  // Use recursive mutexes as Bionic's non-recursive mutexes don't have TIDs to check lock
  // ownership of.
  pthread_mutexattr_t attributes;
  CHECK_MUTEX_CALL(pthread_mutexattr_init, (&attributes));
  CHECK_MUTEX_CALL(pthread_mutexattr_settype, (&attributes, PTHREAD_MUTEX_RECURSIVE));
  CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, &attributes));
  CHECK_MUTEX_CALL(pthread_mutexattr_destroy, (&attributes));
#else
  CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, NULL));
#endif
}

Mutex::~Mutex() {
  // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
  // may still be using locks.
  int rc = pthread_mutex_destroy(&mutex_);
  if (rc != 0) {
    errno = rc;
    // TODO: should we just not log at all if shutting down? this could be the logging mutex!
    bool shutting_down = Runtime::Current()->IsShuttingDown();
    PLOG(shutting_down ? WARNING : FATAL) << "pthread_mutex_destroy failed for " << name_;
  }
}

void Mutex::ExclusiveLock() {
  bool is_held = IsExclusiveHeld();
  CHECK(recursive_ || !is_held)
      << "Error attempt to recursively lock non-recursive lock \"" << name_ << "\"";
  if (!is_held) {
    CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
    RegisterAsLockedWithCurrentThread();
  }
  recursion_count_++;
  DCHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
      << name_ << " " << recursion_count_;
  AssertHeld();
}

bool Mutex::ExclusiveTryLock() {
  bool is_held = IsExclusiveHeld();
  CHECK(recursive_ || !is_held)
      << "Error attempt to recursively lock non-recursive lock \"" << name_ << "\"";
  if (!is_held) {
    int result = pthread_mutex_trylock(&mutex_);
    if (result == EBUSY) {
      return false;
    }
    if (result != 0) {
      errno = result;
      PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
    }
    RegisterAsLockedWithCurrentThread();
  }
  recursion_count_++;
  AssertHeld();
  return true;
}

void Mutex::ExclusiveUnlock() {
  AssertHeld();
  recursion_count_--;
  if (!recursive_ || recursion_count_ == 0) {
    DCHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
        << name_ << " " << recursion_count_;
    RegisterAsUnlockedWithCurrentThread();
    CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
  }
}

bool Mutex::IsExclusiveHeld() const {
  Thread* self = Thread::Current();
  bool result;
  if (self == NULL || level_ == kMonitorLock) {  // Handle unattached threads and monitors.
    result = (GetExclusiveOwnerTid() == static_cast<uint64_t>(GetTid()));
  } else {
    result = (self->GetHeldMutex(level_) == this);
    // Sanity debug check that if we think it is locked, so does the pthread.
    DCHECK(result == (GetExclusiveOwnerTid() == static_cast<uint64_t>(GetTid())));
  }
  return result;
}

uint64_t Mutex::GetExclusiveOwnerTid() const {
#if defined(__BIONIC__)
  return static_cast<uint64_t>((mutex_.value >> 16) & 0xffff);
#elif defined(__GLIBC__)
  return reinterpret_cast<const glibc_pthread_mutex_t*>(&mutex_)->owner;
#elif defined(__APPLE__)
  return reinterpret_cast<const darwin_pthread_mutex_t*>(&mutex_)->owner_tid;
#else
#error unsupported C library
#endif
}

ReaderWriterMutex::ReaderWriterMutex(const char* name, MutexLevel level) : BaseMutex(name, level) {
  CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, NULL));
}

ReaderWriterMutex::~ReaderWriterMutex() {
  // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
  // may still be using locks.
  int rc = pthread_rwlock_destroy(&rwlock_);
  if (rc != 0) {
    errno = rc;
    // TODO: should we just not log at all if shutting down? this could be the logging mutex!
    bool shutting_down = Runtime::Current()->IsShuttingDown();
    PLOG(shutting_down ? WARNING : FATAL) << "pthread_mutex_destroy failed for " << name_;
  }
}

void ReaderWriterMutex::ExclusiveLock() {
  AssertNotExclusiveHeld();
  CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
  RegisterAsLockedWithCurrentThread();
  AssertExclusiveHeld();
}

void ReaderWriterMutex::ExclusiveUnlock() {
  AssertExclusiveHeld();
  RegisterAsUnlockedWithCurrentThread();
  CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
}

#if HAVE_TIMED_RWLOCK
bool ReaderWriterMutex::ExclusiveLockWithTimeout(const timespec& abs_timeout) {
  int result = pthread_rwlock_timedwrlock(&rwlock_, &abs_timeout);
  if (result == ETIMEDOUT) {
    return false;
  }
  if (result != 0) {
    errno = result;
    PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
  }
  RegisterAsLockedWithCurrentThread();
  AssertSharedHeld();
  return true;
}
#endif

void ReaderWriterMutex::SharedLock() {
  CHECK_MUTEX_CALL(pthread_rwlock_rdlock, (&rwlock_));
  RegisterAsLockedWithCurrentThread();
  AssertSharedHeld();
}

bool ReaderWriterMutex::SharedTryLock() {
  int result = pthread_rwlock_tryrdlock(&rwlock_);
  if (result == EBUSY) {
    return false;
  }
  if (result != 0) {
    errno = result;
    PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
  }
  RegisterAsLockedWithCurrentThread();
  AssertSharedHeld();
  return true;
}

void ReaderWriterMutex::SharedUnlock() {
  AssertSharedHeld();
  RegisterAsUnlockedWithCurrentThread();
  CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
}

bool ReaderWriterMutex::IsExclusiveHeld() const {
  bool result = (GetExclusiveOwnerTid() == static_cast<uint64_t>(GetTid()));
  // Sanity that if the pthread thinks we own the lock the Thread agrees.
  Thread* self = Thread::Current();
  DCHECK((self == NULL) || !result || (self->GetHeldMutex(level_) == this));
  return result;
}

bool ReaderWriterMutex::IsSharedHeld() const {
  Thread* self = Thread::Current();
  bool result;
  if (UNLIKELY(self == NULL)) {  // Handle unattached threads.
    result = IsExclusiveHeld(); // TODO: a better best effort here.
  } else {
    result = (self->GetHeldMutex(level_) == this);
  }
  return result;
}

uint64_t ReaderWriterMutex::GetExclusiveOwnerTid() const {
#if defined(__BIONIC__)
  return rwlock_.writerThreadId;
#elif defined(__GLIBC__)
  return reinterpret_cast<const glibc_pthread_rwlock_t*>(&rwlock_)->writer;
#elif defined(__APPLE__)
  return reinterpret_cast<const darwin_pthread_rwlock_t*>(&rwlock_)->rw_owner_tid;
#else
#error unsupported C library
#endif
}

ConditionVariable::ConditionVariable(const std::string& name) : name_(name) {
  CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, NULL));
}

ConditionVariable::~ConditionVariable() {
  // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
  // may still be using condition variables.
  int rc = pthread_cond_destroy(&cond_);
  if (rc != 0) {
    errno = rc;
    bool shutting_down = Runtime::Current()->IsShuttingDown();
    PLOG(shutting_down ? WARNING : FATAL) << "pthread_cond_destroy failed for " << name_;
  }
}

void ConditionVariable::Broadcast() {
  CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
}

void ConditionVariable::Signal() {
  CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
}

void ConditionVariable::Wait(Mutex& mutex) {
  mutex.CheckSafeToWait();
  unsigned int old_recursion_count = mutex.recursion_count_;
  mutex.recursion_count_ = 0;
  CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &mutex.mutex_));
  mutex.recursion_count_ = old_recursion_count;
}

void ConditionVariable::TimedWait(Mutex& mutex, const timespec& ts) {
#ifdef HAVE_TIMEDWAIT_MONOTONIC
#define TIMEDWAIT pthread_cond_timedwait_monotonic
#else
#define TIMEDWAIT pthread_cond_timedwait
#endif
  mutex.CheckSafeToWait();
  unsigned int old_recursion_count = mutex.recursion_count_;
  mutex.recursion_count_ = 0;
  int rc = TIMEDWAIT(&cond_, &mutex.mutex_, &ts);
  mutex.recursion_count_ = old_recursion_count;
  if (rc != 0 && rc != ETIMEDOUT) {
    errno = rc;
    PLOG(FATAL) << "TimedWait failed for " << name_;
  }
}

}  // namespace art