File: threadsync.cpp

package info (click to toggle)
dmtcp 2.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,496 kB
  • sloc: cpp: 33,592; ansic: 28,099; sh: 6,735; makefile: 1,950; perl: 1,690; python: 1,241; asm: 138; java: 13
file content (674 lines) | stat: -rw-r--r-- 23,769 bytes parent folder | download
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
/****************************************************************************
 *   Copyright (C) 2006-2013 by Jason Ansel, Kapil Arya, and Gene Cooperman *
 *   jansel@csail.mit.edu, kapil@ccs.neu.edu, gene@ccs.neu.edu              *
 *                                                                          *
 *  This file is part of DMTCP.                                             *
 *                                                                          *
 *  DMTCP is free software: you can redistribute it and/or                  *
 *  modify it under the terms of the GNU Lesser General Public License as   *
 *  published by the Free Software Foundation, either version 3 of the      *
 *  License, or (at your option) any later version.                         *
 *                                                                          *
 *  DMTCP is distributed in the hope that it will be useful,                *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of          *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           *
 *  GNU Lesser General Public License for more details.                     *
 *                                                                          *
 *  You should have received a copy of the GNU Lesser General Public        *
 *  License along with DMTCP:dmtcp/src.  If not, see                        *
 *  <http://www.gnu.org/licenses/>.                                         *
 ****************************************************************************/

#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>

#include "threadsync.h"
#include "dmtcpworker.h"
#include "syscallwrappers.h"
#include "workerstate.h"
#include "jassert.h"

using namespace dmtcp;

/*
 * _wrapperExecutionLock is used to make the checkpoint safe by making sure
 *   that no user-thread is executing any DMTCP wrapper code when it receives
 *   the checkpoint signal.
 * Working:
 *   On entering the wrapper in DMTCP, the user-thread acquires the read lock,
 *     and releases it before leaving the wrapper.
 *   When the Checkpoint-thread wants to send the SUSPEND signal to user
 *     threads, it must acquire the write lock. It is blocked until all the
 *     existing read-locks by user threads have been released. NOTE that this
 *     is a WRITER-PREFERRED lock.
 *
 * There is a corner case too -- the newly created thread that has not been
 *   initialized yet; we need to take some extra efforts for that.
 * Here are the steps to handle the newly created uninitialized thread:
 *   A counter (_uninitializedThreadCount) for the number of newly
 *     created uninitialized threads is kept.  The counter is made
 *     thread-safe by using a mutex.
 *   The calling thread (parent) increments the counter before calling clone.
 *   The newly created child thread decrements the counter at the end of
 *     initialization in MTCP/DMTCP.
 *   After acquiring the Write lock, the checkpoint thread waits until the
 *     number of uninitialized threads is zero. At that point, no thread is
 *     executing in the clone wrapper and it is safe to do a checkpoint.
 *
 * XXX: Currently this security is provided only for the clone wrapper; this
 * should be extended to other calls as well.           -- KAPIL
 */
// NOTE: PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP is not POSIX.
static pthread_rwlock_t
  _wrapperExecutionLock = PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP;
static pthread_rwlock_t
  _threadCreationLock = PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP;
static bool _wrapperExecutionLockAcquiredByCkptThread = false;
static bool _threadCreationLockAcquiredByCkptThread = false;

static pthread_mutex_t destroyDmtcpWorkerLock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t theCkptCanStart = PTHREAD_MUTEX_INITIALIZER;
static int ckptCanStartCount = 0;

static pthread_mutex_t libdlLock = PTHREAD_MUTEX_INITIALIZER;
static pid_t libdlLockOwner = 0;

static pthread_mutex_t uninitializedThreadCountLock = PTHREAD_MUTEX_INITIALIZER;
static int _uninitializedThreadCount = 0;
static bool _checkpointThreadInitialized = false;

#define INVALID_USER_THREAD_COUNT 0
static int preResumeThreadCount = INVALID_USER_THREAD_COUNT;
static pthread_mutex_t preResumeThreadCountLock = PTHREAD_MUTEX_INITIALIZER;

static __thread int _wrapperExecutionLockLockCount = 0;
static __thread int _threadCreationLockLockCount = 0;
#if TRACK_DLOPEN_DLSYM_FOR_LOCKS
static __thread bool _threadPerformingDlopenDlsym = false;
#endif
static __thread bool _sendCkptSignalOnFinalUnlock = false;
static __thread bool _isOkToGrabWrapperExecutionLock = true;
static __thread bool _hasThreadFinishedInitialization = false;


/* The following two functions dmtcp_libdlLock{Lock,Unlock} are used by dlopen
 * plugin.
 */
extern "C" int dmtcp_libdlLockLock() {
  return ThreadSync::libdlLockLock();
}

extern "C" void dmtcp_libdlLockUnlock() {
  ThreadSync::libdlLockUnlock();
}

void ThreadSync::initThread()
{
  // We initialize these thread-local variables here. If not done here,
  // there can be a race between checkpoint processing and this
  // thread trying to initialize some thread-local variable.
  // Here is a possible calltrace:
  //   pthread_start -> threadFinishedInitialization -> stopthisthread ->
  //   callbackHoldsAnyLocks -> JASSERT().
  _wrapperExecutionLockLockCount = 0;
  _threadCreationLockLockCount = 0;
#if TRACK_DLOPEN_DLSYM_FOR_LOCKS
  _threadPerformingDlopenDlsym = false;
#endif
  _sendCkptSignalOnFinalUnlock = false;
  _isOkToGrabWrapperExecutionLock = true;
  _hasThreadFinishedInitialization = false;
}

void ThreadSync::initMotherOfAll()
{
  initThread();
  _hasThreadFinishedInitialization = true;
}

void ThreadSync::acquireLocks()
{
  JASSERT(WorkerState::currentState() == WorkerState::RUNNING);
  /* TODO: We should introduce the notion of lock ranks/priorities for all
   * these locks to prevent future deadlocks due to rank violation.
   */

  JLOG(DMTCP)("waiting for dmtcp_lock():"
         " to get synchronized with _runCoordinatorCmd if we use DMTCP API");
  _dmtcp_lock();

  JLOG(DMTCP)("Waiting for lock(&theCkptCanStart)");
  JASSERT(_real_pthread_mutex_lock(&theCkptCanStart) == 0)(JASSERT_ERRNO);

  JLOG(DMTCP)("Waiting for libdlLock");
  JASSERT(_real_pthread_mutex_lock(&libdlLock) == 0) (JASSERT_ERRNO);

  JLOG(DMTCP)("Waiting for threads creation lock");
  JASSERT(_real_pthread_rwlock_wrlock(&_threadCreationLock) == 0)
    (JASSERT_ERRNO);
  _threadCreationLockAcquiredByCkptThread = true;

  JLOG(DMTCP)("Waiting for other threads to exit DMTCP-Wrappers");
  JASSERT(_real_pthread_rwlock_wrlock(&_wrapperExecutionLock) == 0)
    (JASSERT_ERRNO);
  _wrapperExecutionLockAcquiredByCkptThread = true;

  JLOG(DMTCP)("Waiting for newly created threads to finish initialization")
    (_uninitializedThreadCount);
  waitForThreadsToFinishInitialization();

  unsetOkToGrabLock();
  JLOG(DMTCP)("Done acquiring all locks");
}

void ThreadSync::releaseLocks()
{
  JASSERT(WorkerState::currentState() == WorkerState::SUSPENDED);

  JLOG(DMTCP)("Releasing ThreadSync locks");
  JASSERT(_real_pthread_rwlock_unlock(&_wrapperExecutionLock) == 0)
    (JASSERT_ERRNO);
  _wrapperExecutionLockAcquiredByCkptThread = false;
  JASSERT(_real_pthread_rwlock_unlock(&_threadCreationLock) == 0)
    (JASSERT_ERRNO);
  _threadCreationLockAcquiredByCkptThread = false;
  JASSERT(_real_pthread_mutex_unlock(&libdlLock) == 0) (JASSERT_ERRNO);
  JASSERT(_real_pthread_mutex_unlock(&theCkptCanStart) == 0) (JASSERT_ERRNO);

  _dmtcp_unlock();
  setOkToGrabLock();
}

void ThreadSync::resetLocks()
{
  pthread_rwlock_t newLock = PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP;
  _wrapperExecutionLock = newLock;
  _threadCreationLock = newLock;

  _wrapperExecutionLockLockCount = 0;
  _threadCreationLockLockCount = 0;
#if TRACK_DLOPEN_DLSYM_FOR_LOCKS
  _threadPerformingDlopenDlsym = false;
#endif
  _sendCkptSignalOnFinalUnlock = false;
  _isOkToGrabWrapperExecutionLock = true;
  _hasThreadFinishedInitialization = true;

  pthread_mutex_t newCountLock = PTHREAD_MUTEX_INITIALIZER;
  uninitializedThreadCountLock = newCountLock;
  pthread_mutex_t newPreResumeThreadCountLock = PTHREAD_MUTEX_INITIALIZER;
  preResumeThreadCountLock = newPreResumeThreadCountLock;
  preResumeThreadCount = 0; // Reset the thread count post fork

  pthread_mutex_t newDestroyDmtcpWorker = PTHREAD_MUTEX_INITIALIZER;
  destroyDmtcpWorkerLock = newDestroyDmtcpWorker;

  pthread_mutex_t newLibdlLock = PTHREAD_MUTEX_INITIALIZER;
  libdlLock = newLibdlLock;
  libdlLockOwner = 0;

  _checkpointThreadInitialized = false;
  _wrapperExecutionLockAcquiredByCkptThread = false;
  _threadCreationLockAcquiredByCkptThread = false;
}

bool ThreadSync::isThisThreadHoldingAnyLocks()
{
  // If the wrapperExec lock has been acquired by the ckpt thread, then we are
  // certainly not holding it :). It's possible for the count to be still '1',
  // as it may happen that the thread got suspended after releasing the lock
  // and before decrementing the lock-count.
  if (_hasThreadFinishedInitialization == false) {
    return true;
  }
  return (_wrapperExecutionLockAcquiredByCkptThread == false ||
          _threadCreationLockAcquiredByCkptThread == false) &&
         (_threadCreationLockLockCount > 0 ||
          _wrapperExecutionLockLockCount > 0);
}

bool ThreadSync::isOkToGrabLock()
{
  return _isOkToGrabWrapperExecutionLock;
}

void ThreadSync::setOkToGrabLock()
{
  _isOkToGrabWrapperExecutionLock = true;
}

void ThreadSync::unsetOkToGrabLock()
{
  _isOkToGrabWrapperExecutionLock = false;
}

void ThreadSync::setSendCkptSignalOnFinalUnlock()
{
  JASSERT(_sendCkptSignalOnFinalUnlock == false);
  _sendCkptSignalOnFinalUnlock = true;
}

void ThreadSync::sendCkptSignalOnFinalUnlock()
{
  if (_sendCkptSignalOnFinalUnlock && isThisThreadHoldingAnyLocks() == false) {
    _sendCkptSignalOnFinalUnlock = false;
    JASSERT(raise(DmtcpWorker::determineCkptSignal()) == 0)
      (getpid()) (dmtcp_gettid()) (JASSERT_ERRNO);
  }
}

#if TRACK_DLOPEN_DLSYM_FOR_LOCKS
extern "C" LIB_PRIVATE
void dmtcp_setThreadPerformingDlopenDlsym()
{
  ThreadSync::setThreadPerformingDlopenDlsym();
}

extern "C" LIB_PRIVATE
void dmtcp_unsetThreadPerformingDlopenDlsym()
{
  ThreadSync::unsetThreadPerformingDlopenDlsym();
}

bool ThreadSync::isThreadPerformingDlopenDlsym()
{
  return _threadPerformingDlopenDlsym;
}

void ThreadSync::setThreadPerformingDlopenDlsym()
{
  _threadPerformingDlopenDlsym = true;
}

void ThreadSync::unsetThreadPerformingDlopenDlsym()
{
  _threadPerformingDlopenDlsym = false;
}
#endif

void ThreadSync::destroyDmtcpWorkerLockLock()
{
  JASSERT(_real_pthread_mutex_lock(&destroyDmtcpWorkerLock) == 0)
    (JASSERT_ERRNO);
}

int ThreadSync::destroyDmtcpWorkerLockTryLock()
{
  return _real_pthread_mutex_trylock(&destroyDmtcpWorkerLock);
}

void ThreadSync::destroyDmtcpWorkerLockUnlock()
{
  JASSERT(_real_pthread_mutex_unlock(&destroyDmtcpWorkerLock) == 0)
    (JASSERT_ERRNO);
}

void ThreadSync::delayCheckpointsLock()
{
  if (ckptCanStartCount++ == 0) {
    JASSERT(_real_pthread_mutex_lock(&theCkptCanStart)==0)(JASSERT_ERRNO);
  }
}

void ThreadSync::delayCheckpointsUnlock() {
  if (--ckptCanStartCount == 0) {
    JASSERT(_real_pthread_mutex_unlock(&theCkptCanStart)==0)(JASSERT_ERRNO);
  }
}

static void incrementWrapperExecutionLockLockCount()
{
  _wrapperExecutionLockLockCount++;
}

static void decrementWrapperExecutionLockLockCount()
{
  if (_wrapperExecutionLockLockCount <= 0) {
    JASSERT(false) (_wrapperExecutionLockLockCount)
      .Text("wrapper-execution lock count can't be negative");
  }
  _wrapperExecutionLockLockCount--;
  ThreadSync::sendCkptSignalOnFinalUnlock();
}

static void incrementThreadCreationLockLockCount()
{
  _threadCreationLockLockCount++;
}

static void decrementThreadCreationLockLockCount()
{
  _threadCreationLockLockCount--;
  ThreadSync::sendCkptSignalOnFinalUnlock();
}

bool ThreadSync::libdlLockLock()
{
  int saved_errno = errno;
  bool lockAcquired = false;
  if (WorkerState::currentState() == WorkerState::RUNNING &&
      libdlLockOwner !=  dmtcp_gettid()) {
    JASSERT(_real_pthread_mutex_lock(&libdlLock) == 0);
    libdlLockOwner = dmtcp_gettid();
    lockAcquired = true;
  }
  errno = saved_errno;
  return lockAcquired;
}

void ThreadSync::libdlLockUnlock()
{
  int saved_errno = errno;
  JASSERT(libdlLockOwner == 0 || libdlLockOwner == dmtcp_gettid())
    (libdlLockOwner) (dmtcp_gettid());
  JASSERT (WorkerState::currentState() == WorkerState::RUNNING);
  libdlLockOwner = 0;
  JASSERT(_real_pthread_mutex_unlock(&libdlLock) == 0);
  errno = saved_errno;
}

// XXX: Handle deadlock error code
// NOTE: Don't do any fancy stuff in this wrapper which can cause the process
//       to go into DEADLOCK
bool ThreadSync::wrapperExecutionLockLock()
{
  int saved_errno = errno;
  bool lockAcquired = false;
  // Ignore locks if we are about to exit
  if (DmtcpWorker::exitInProgress()) {
    return false;
  }
  while (1) {
    if (WorkerState::currentState() == WorkerState::RUNNING &&
#if TRACK_DLOPEN_DLSYM_FOR_LOCKS
        isThreadPerformingDlopenDlsym() == false &&
#endif
        isOkToGrabLock() == true &&
        _wrapperExecutionLockLockCount == 0) {
      incrementWrapperExecutionLockLockCount();
      int retVal = _real_pthread_rwlock_tryrdlock(&_wrapperExecutionLock);
      if (retVal != 0 && retVal == EBUSY) {
        decrementWrapperExecutionLockLockCount();
        struct timespec sleepTime = {0, 100*1000*1000};
        nanosleep(&sleepTime, NULL);
        continue;
      }
      if (retVal != 0 && retVal != EDEADLK) {
        fprintf(stderr, "ERROR %d at %s:%d %s: Failed to acquire lock\n",
                errno, __FILE__, __LINE__, __PRETTY_FUNCTION__);
        _exit(DMTCP_FAIL_RC);
      }
      // retVal should always be 0 (success) here.
      lockAcquired = retVal == 0 ? true : false;
      if (!lockAcquired) {
        decrementWrapperExecutionLockLockCount();
      }
    }
    break;
  }
  errno = saved_errno;
  return lockAcquired;
}

/*
 * Execute fork() and exec() wrappers in exclusive mode
 *
 * fork() and exec() wrappers pass on the state/information about the current
 * process/program to the to-be-created process/program.
 *
 * There can be a potential race in the wrappers if this information gets
 * changed between the point where it was acquired and the point where the
 * process/program is created. An example of this situation would be a
 * different thread executing an open() call in parallel creating a
 * file-descriptor, which is not a part of the information/state gathered
 * earlier. This can result in unexpected behavior and can cause the
 * program/process to fail.
 *
 * This patch fixes this by acquiring the Wrapper-protection-lock in exclusive
 * mode (write-lock) when executing these wrappers. This guarantees that no
 * other thread would be executing inside a wrapper that can change the process
 * state/information.
 *
 * NOTE:
 * 1. Currently, we do not have WRAPPER_EXECUTION_LOCK/UNLOCK for socket()
 *    family of wrapper. That would be fixed in a later commit.
 * 2. We need to come up with a strategy for certain blocking system calls
 *    that can change the state of the process (e.g. accept).
 * 3. Using trywrlock() can result in starvation if multiple other threads are
 *    rapidly acquiring releasing the lock. For example thread A acquires the
 *    rdlock for 100 ms. Thread B executes and trywrlock and fails. Thread B
 *    sleeps goes to sleep for some time. While thread B is sleeping, thread A
 *    releases the rdlock and reacquires it or some other thread acquires the
 *    rdlock. This would cause the thread B to starve. This scenario can be
 *    easily observed if thread A calls
 *      epoll_wait(fd, events, max_events, -1).
 *    It is wrapped by the epoll_wait wrapper in IPC plugin, which then makes
 *    repeated calls to _real_epoll_wait with smaller timeout.
 */
bool ThreadSync::wrapperExecutionLockLockExcl()
{
  int saved_errno = errno;
  bool lockAcquired = false;
  // Ignore locks if we are about to exit
  if (DmtcpWorker::exitInProgress()) {
    return false;
  }
  if (WorkerState::currentState() == WorkerState::RUNNING) {
    incrementWrapperExecutionLockLockCount();
    int retVal = _real_pthread_rwlock_wrlock(&_wrapperExecutionLock);
    if (retVal != 0 && retVal != EDEADLK) {
      fprintf(stderr, "ERROR %s:%d %s: Failed to acquire lock\n",
              __FILE__, __LINE__, __PRETTY_FUNCTION__);
      _exit(DMTCP_FAIL_RC);
    }
    lockAcquired = retVal == 0 ? true : false;
    if (!lockAcquired) {
      decrementWrapperExecutionLockLockCount();
    }
  }
  errno = saved_errno;
  return lockAcquired;
}

// NOTE: Don't do any fancy stuff in this wrapper which can cause the process
// to go into DEADLOCK
void ThreadSync::wrapperExecutionLockUnlock()
{
  int saved_errno = errno;
  // Ignore locks if we are about to exit
  /*
   * NOTE: Ideally, this function should never be called from a wrapper if
   *       exitInProgress is set, but there are two cases when it gets
   *       called despite the flag being set:
   *       1) The exitInProgress flag is set, and then an incorrectly
   *          implemented wrapper calls this function even though the
   *          lock function returned false. See commit:
   *          f2d2a7c6feba38ab0b0cb8e09a4ad6cc37d9f330 for an example.
   *       2) A correctly implemented wrapper calls this but the exitInProgress
   *          is set after having acquired the wrapperExecution lock. This can
   *          occur if a user thread called exit while another was
   *          in the middle of the wrapper.
   *       The following if clause guards against both the scenarios.
   * TODO: Add a message that warns the user if any of the above
   *       two cases are seen.
   *
   */

  if (DmtcpWorker::exitInProgress()) {
    return;
  }
  if (_real_pthread_rwlock_unlock(&_wrapperExecutionLock) != 0) {
    fprintf(stderr, "ERROR %s:%d %s: Failed to release lock\n",
            __FILE__, __LINE__, __PRETTY_FUNCTION__);
    _exit(DMTCP_FAIL_RC);
  } else {
    decrementWrapperExecutionLockLockCount();
  }
  errno = saved_errno;
}

bool ThreadSync::threadCreationLockLock()
{
  int saved_errno = errno;
  bool lockAcquired = false;
  while (1) {
    if (WorkerState::currentState() == WorkerState::RUNNING) {
      incrementThreadCreationLockLockCount();
      int retVal = _real_pthread_rwlock_tryrdlock(&_threadCreationLock);
      if (retVal != 1 && retVal == EBUSY) {
        decrementThreadCreationLockLockCount();
        struct timespec sleepTime = {0, 100*1000*1000};
        nanosleep(&sleepTime, NULL);
        continue;
      }
      if (retVal != 0 && retVal != EDEADLK) {
        fprintf(stderr, "ERROR %s:%d %s: Failed to acquire lock\n",
                __FILE__, __LINE__, __PRETTY_FUNCTION__);
        _exit(DMTCP_FAIL_RC);
      }
      // retVal should always be 0 (success) here.
      lockAcquired = retVal == 0 ? true : false;

      // If for some reason, the lock was not acquired, decrement the count
      // that we incremented at the start of this block.
      if (!lockAcquired) {
        decrementThreadCreationLockLockCount();
      }
    }
    break;
  }
  errno = saved_errno;
  return lockAcquired;
}

void ThreadSync::threadCreationLockUnlock()
{
  int saved_errno = errno;
  if (WorkerState::currentState() != WorkerState::RUNNING) {
    fprintf(stderr, "DMTCP INTERNAL ERROR: %s:%d %s:\n"
            "       This process is not in RUNNING state and yet this thread\n"
            "       managed to acquire the threadCreationLock.\n"
            "       This should not be happening, something is wrong.",
            __FILE__, __LINE__, __PRETTY_FUNCTION__);
    _exit(DMTCP_FAIL_RC);
  }
  if (_real_pthread_rwlock_unlock(&_threadCreationLock) != 0) {
    fprintf(stderr, "ERROR %s:%d %s: Failed to release lock\n",
            __FILE__, __LINE__, __PRETTY_FUNCTION__);
    _exit(DMTCP_FAIL_RC);
  } else {
    decrementThreadCreationLockLockCount();
  }
  errno = saved_errno;
}

// GNU g++ uses __thread.  But the C++0x standard says to use thread_local.
//   If your compiler fails here, you can: change "__thread" to "thread_local";
//   or delete "__thread" (but if user code calls these routines from multiple
//   threads, it will not be thread-safe).
//   In GCC 4.3 and later, g++ supports -std=c++0x and -std=g++0x.
extern "C"
int dmtcp_plugin_disable_ckpt()
{
  return ThreadSync::wrapperExecutionLockLock();
}

extern "C"
void dmtcp_plugin_enable_ckpt()
{
  ThreadSync::wrapperExecutionLockUnlock();
}


void ThreadSync::waitForThreadsToFinishInitialization()
{
  while (_uninitializedThreadCount != 0) {
    struct timespec sleepTime = {0, 10*1000*1000};
    JLOG(DMTCP)("sleeping")(sleepTime.tv_nsec);
    nanosleep(&sleepTime, NULL);
  }
}

void ThreadSync::incrementUninitializedThreadCount()
{
  int saved_errno = errno;
  if (WorkerState::currentState() == WorkerState::RUNNING) {
    JASSERT(_real_pthread_mutex_lock(&uninitializedThreadCountLock) == 0)
      (JASSERT_ERRNO);
    _uninitializedThreadCount++;
    //JLOG(DMTCP)(":") (_uninitializedThreadCount);
    JASSERT(_real_pthread_mutex_unlock(&uninitializedThreadCountLock) == 0)
      (JASSERT_ERRNO);
  }
  errno = saved_errno;
}

void ThreadSync::decrementUninitializedThreadCount()
{
  int saved_errno = errno;
  if (WorkerState::currentState() == WorkerState::RUNNING) {
    JASSERT(_real_pthread_mutex_lock(&uninitializedThreadCountLock) == 0)
      (JASSERT_ERRNO);
    JASSERT(_uninitializedThreadCount > 0) (_uninitializedThreadCount);
    _uninitializedThreadCount--;
    //JLOG(DMTCP)(":") (_uninitializedThreadCount);
    JASSERT(_real_pthread_mutex_unlock(&uninitializedThreadCountLock) == 0)
      (JASSERT_ERRNO);
  }
  errno = saved_errno;
}

void ThreadSync::threadFinishedInitialization()
{
  // The following line is to make sure the thread-local data is initialized
  // before any wrapper call is made.
  _hasThreadFinishedInitialization = false;
  decrementUninitializedThreadCount();
  _hasThreadFinishedInitialization = true;
  ThreadSync::sendCkptSignalOnFinalUnlock();
}

void ThreadSync::incrNumUserThreads()
{
  // This routine is called from within stopthisthread so it is not safe to
  // call JNOTE/JLOG(DMTCP) etc.
  if (_real_pthread_mutex_lock(&preResumeThreadCountLock) != 0) {
    JASSERT(false) .Text("Failed to acquire preResumeThreadCountLock");
  }
  preResumeThreadCount++;
  if (_real_pthread_mutex_unlock(&preResumeThreadCountLock) != 0) {
    JASSERT(false) .Text("Failed to release preResumeThreadCountLock");
  }
}

void ThreadSync::processPreResumeCB()
{
  if (_real_pthread_mutex_lock(&preResumeThreadCountLock) != 0) {
    JASSERT(false) .Text("Failed to acquire preResumeThreadCountLock");
  }
  JASSERT(preResumeThreadCount > 0) (dmtcp_gettid()) (preResumeThreadCount);
  preResumeThreadCount--;
  if (_real_pthread_mutex_unlock(&preResumeThreadCountLock) != 0) {
    JASSERT(false) .Text("Failed to release preResumeThreadCountLock");
  }
}

void ThreadSync::waitForUserThreadsToFinishPreResumeCB()
{
  if (preResumeThreadCount != INVALID_USER_THREAD_COUNT) {
    while (preResumeThreadCount != 0) {
      struct timespec sleepTime = {0, 10*1000*1000};
      nanosleep(&sleepTime, NULL);
    }
  }
  // Now we wait for the lock to make sure that the user threads have released
  // it.
  if (_real_pthread_mutex_lock(&preResumeThreadCountLock) != 0) {
    JASSERT(false) .Text("Failed to acquire preResumeThreadCountLock");
  }
  if (_real_pthread_mutex_unlock(&preResumeThreadCountLock) != 0) {
    JASSERT(false) .Text("Failed to release preResumeThreadCountLock");
  }
}