File: sched_winthread.c

package info (click to toggle)
virtuoso-opensource 6.1.6%2Bdfsg2-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 260,060 kB
  • ctags: 123,765
  • sloc: ansic: 652,532; sql: 458,419; xml: 282,834; java: 61,031; sh: 40,031; cpp: 36,890; cs: 25,240; php: 12,692; yacc: 9,523; lex: 7,018; makefile: 6,157; jsp: 4,484; awk: 1,643; perl: 1,013; ruby: 1,003; python: 326
file content (959 lines) | stat: -rw-r--r-- 19,492 bytes parent folder | download | duplicates (2)
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
/*
 *  sched_winthread.c
 *
 *  $Id$
 *
 *  Scheduler for Win32 threads
 *  
 *  This file is part of the OpenLink Software Virtuoso Open-Source (VOS)
 *  project.
 *  
 *  Copyright (C) 1998-2012 OpenLink Software
 *  
 *  This project is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU General Public License as published by the
 *  Free Software Foundation; only version 2 of the License, dated June 1991.
 *  
 *  This program 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
 *  General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 *  
 *  
*/

// TODO XXX INITIAL ATTRIBUTES, RESTART

#if !defined (WIN95COMPAT)
#define _WIN32_WINNT 0x400
#endif
#include "thread_int.h"

char *build_thread_model = "-threads";

/* Indicate preemptive scheduling for this model */
int _thread_sched_preempt = 1;

int _thread_num_total;		/* total threads in this model */
int _thread_num_runnable;	/* # threads that can be run */
int _thread_num_wait;		/* # threads waiting for something */
int _thread_num_dead;		/* # threads on free list */

#define Q_LOCK()		mutex_enter (_q_lock)
#define Q_UNLOCK()		mutex_leave (_q_lock)

static thread_t *_main_thread;
static DWORD tlsCurrentThread;
static thread_queue_t _deadq;
thread_queue_t _waitq;
static dk_mutex_t *_q_lock;

dk_mutex_t * all_mtxs_mtx;

static void
sched_init (void)
{
  _q_lock = mutex_allocate_typed (MUTEX_TYPE_LONG);

  thread_queue_init (&_waitq);
  thread_queue_init (&_deadq);

  _thread_num_wait = 0;
  _thread_num_dead = 0;
  _thread_num_runnable = -1;	/* not counted */
  _thread_num_total = 1;

#ifdef EXPIRIMENTAL
  io_init ();
#endif
#ifdef MTX_METER
  all_mtxs_mtx = mutex_allocate ();
#endif
}


/******************************************************************************
 *
 *  Threads
 *
 ******************************************************************************/

thread_t *
thread_current (void)
{
  return (thread_t *) TlsGetValue (tlsCurrentThread);
}


/*
 *  The main thread must call this function to convert itself into a thread.
 */
thread_t *
thread_initial (unsigned long stack_size)
{
  if (_main_thread)
    return _main_thread;
  else
    {
      NEW_VARZ (thread_t, thr);

      tlsCurrentThread = TlsAlloc ();
      if (tlsCurrentThread == (DWORD) -1)
	{
	  fprintf (stderr, "TlsAlloc() failed (%d)\n", GetLastError ());
	  return NULL;
	}

      assert (_main_thread == NULL);
      _main_thread = thr;

      sched_init ();

      if (stack_size == 0)
	stack_size = MAIN_STACK_SIZE;
#ifdef _DEBUG
	stack_size *= 2;
#endif
      thr->thr_stack_size = stack_size;
      thr->thr_status = RUNNING;
      thr->thr_sem = semaphore_allocate (0);
      thr->thr_schedule_sem = semaphore_allocate (0);
      thr->thr_cv = CreateEvent (NULL, TRUE, FALSE, NULL);
      thr->thr_handle = (void*) (ptrlong) GetCurrentThreadId ();
      if (thr->thr_cv == NULL)
	goto failed;
      _thread_init_attributes (thr);
      thread_set_priority (thr, NORMAL_PRIORITY);

      if (!TlsSetValue (tlsCurrentThread, thr))
	{
	  fprintf (stderr, "TlsSetValue() failed (%d)\n", GetLastError ());
	  goto failed;
	}

      return thr;

    failed:
      _thread_free_attributes (thr);
      dk_free (thr, sizeof (thread_t));
      return NULL;
    }
}


static unsigned int WINAPI
_thread_boot (void *arg)
{
  thread_t *thr = (thread_t *) arg;
  int rc;

  TlsSetValue (tlsCurrentThread, thr);

  /*thr->thr_handle = (void*) GetCurrentThreadId (); this is a identifier not a handle*/

  thr->thr_stack_base = (void*) &arg;
  /* Store the context so we can easily restart a dead fiber */
  setjmp (thr->thr_init_context);

  thr->thr_status = RUNNING;
  _thread_init_attributes (thr);

  rc = (*thr->thr_initial_function) (thr->thr_initial_argument);

  /* thread died, put it on the dead queue */
  thread_exit (rc);

  /* We should never come here */
  GPF_T;

  /* dummy */
  return 0;
}


static thread_t *
thread_alloc (void)
{
  thread_t *thr;
  thr = (thread_t *) dk_alloc ( sizeof (thread_t));
  memset (thr, 0, sizeof (thread_t));
  thr->thr_status = RUNNABLE;
  thr->thr_cv = CreateEvent (NULL, TRUE, FALSE, NULL);
  thr->thr_sem = semaphore_allocate (0);
  thr->thr_schedule_sem = semaphore_allocate (0);
  return thr;
}

#ifdef GC_THREADS
typedef HANDLE (WINAPI *CreateThreadPtr)(
  LPSECURITY_ATTRIBUTES lpThreadAttributes,
  SIZE_T dwStackSize,
  LPTHREAD_START_ROUTINE lpStartAddress,
  LPVOID lpParameter,
  DWORD dwCreationFlags,
  LPDWORD lpThreadId
);
CreateThreadPtr ptrCreateThread = CreateThread;

void
virtuoso_set_create_thread (CreateThreadPtr ptr)
{
  ptrCreateThread = ptr;
}
#else
void
virtuoso_set_create_thread (void * ptr)
{
}
#endif

thread_t *
thread_create (
    thread_init_func initial_function,
    unsigned long stack_size,
    void *initial_argument)
{
  thread_t *thr;
#ifdef GC_THREADS
  DWORD thr_id;
  HANDLE thdl;
#else
  unsigned int thr_id;
  uptrlong thdl;
#endif

  assert (_main_thread != NULL);

  if (stack_size == 0)
    stack_size = THREAD_STACK_SIZE;

#ifdef _DEBUG
  stack_size *= 2;
#endif
#ifdef _WIN64
  stack_size *= 4;
#endif

  /* Any free threads with the right stack size? */
  Q_LOCK ();
  for (thr = (thread_t *) _deadq.thq_head.thr_next;
       thr != (thread_t *) &_deadq.thq_head;
       thr = (thread_t *) thr->thr_hdr.thr_next)
    {
      if (thr->thr_stack_size >= stack_size)
	break;
    }
  Q_UNLOCK ();

  if (thr == (thread_t *) &_deadq.thq_head)
    {
      /* No free thread, create a new one */
      thr = thread_alloc ();
      thr->thr_stack_size = stack_size;
      thr->thr_initial_function = initial_function;
      thr->thr_initial_argument = initial_argument;
      if (thr->thr_cv == NULL)
	goto failed;
#ifdef GC_THREADS
      thdl = ptrCreateThread
#else
      thdl = _beginthreadex
#endif
	(
	  NULL,		// security
	  stack_size,	// stack size
	  _thread_boot,	// start address
	  thr,		// arglist
	  0,		// initflag
	  &thr_id);	// thrdaddr
      if (thdl == 0)
	{
	  log_error ("Can't create OS thread : %m");
	  goto failed;
	}
      thr->thr_handle = (void *) thdl;
      _thread_num_total++;
      thread_set_priority (thr, NORMAL_PRIORITY);
    }
  else
    {
      /* Set new context for the thread and resume it */
      Q_LOCK ();
      thread_queue_remove (&_deadq, thr);
      _thread_num_dead--;
      Q_UNLOCK ();
      assert (thr->thr_status == DEAD);
      /* Set new context for the thread and resume it */
      thr->thr_initial_function = initial_function;
      thr->thr_initial_argument = initial_argument;
      thr->thr_status = RUNNABLE;
      PulseEvent (thr->thr_cv);
    }

  return thr;

failed:
  if (thr->thr_status == RUNNABLE)
    {
      _thread_free_attributes (thr);
      dk_free (thr, sizeof (thread_t));
    }
  return NULL;
}


thread_t *
thread_attach (void)
{
  thread_t *thr;

  thr = thread_alloc ();
  thr->thr_stack_size = (unsigned long) -1;
  if (thr->thr_cv == NULL)
    goto failed;

  thr->thr_handle = GetCurrentThread ();
  thr->thr_attached = 1;

  TlsSetValue (tlsCurrentThread, thr);

  /*thr->thr_handle = (void*) GetCurrentThreadId (); this is a identifier not a handle*/

  thr->thr_stack_base = (void*) &thr;
  /* Store the context so we can easily restart a dead fiber */
  setjmp (thr->thr_init_context);

  thr->thr_status = RUNNING;
  _thread_init_attributes (thr);

  return thr;

failed:
  if (thr->thr_sem)
    semaphore_free (thr->thr_sem);
  if (thr->thr_schedule_sem)
    semaphore_free (thr->thr_schedule_sem);
  dk_free (thr, sizeof (thread_t));
  return NULL;
}


void
thread_allow_schedule (void)
{
}


void
thread_exit (int n)
{
  thread_t *thr = current_thread;
  int is_attached = thr->thr_attached;

  if (thr == _main_thread)
    call_exit (n);

  thr->thr_retcode = n;
  thr->thr_status = DEAD;

  ResetEvent (thr->thr_cv);

  if (is_attached)
    {
      thr->thr_status = TERMINATE;
      goto terminate;
    }
  Q_LOCK ();
  thread_queue_to (&_deadq, thr);
  _thread_num_dead++;

#ifdef WIN95COMPAT
  Q_UNLOCK ();
  if (WaitForSingleObject (thr->thr_cv, INFINITE) != WAIT_OBJECT_0)
#else
  if (SignalObjectAndWait (_q_lock->mtx_handle, thr->thr_cv,
      INFINITE, FALSE) != WAIT_OBJECT_0)
#endif
    {
      thread_queue_remove (&_deadq, thr);
      _thread_num_dead--;
      Q_UNLOCK ();
      _thread_num_total--;
      GPF_T1 ("SignalObjectAndWait() failed in thread_exit()\n");
      // _endthreadex ..
    }
  /* Woke up with a PulseEvent() */

#ifdef WIN95COMPAT
  Q_UNLOCK ();
#endif

  if (thr->thr_status == TERMINATE)
    goto terminate;

  /* Jumps back into _thread_boot */
  longjmp (thr->thr_init_context, 1);

terminate:
    {
      _thread_free_attributes (thr);
      semaphore_free (thr->thr_sem);
      semaphore_free (thr->thr_schedule_sem);
      CloseHandle (thr->thr_cv);
      CloseHandle (thr->thr_handle);
      thr_free_alloc_cache (thr);
      dk_free (thr, sizeof (thread_t));
    }
  if (!is_attached)
    {
      _thread_num_total--;
      _endthreadex (1);
    }
}

int
thread_release_dead_threads (int leave_count)
{
  thread_t *thr;
  thread_queue_t term;
  long thread_killed = 0;

  Q_LOCK ();
  /*fprintf (stderr, "Threads: total: %ld dead: %ld\n", _thread_num_total, _deadq.thq_count);*/
  if (_deadq.thq_count <= leave_count)
    {
      Q_UNLOCK ();
      return 0;
    }
  thread_queue_init (&term);
  while (_deadq.thq_count > leave_count)
    {
      thr = thread_queue_from (&_deadq);
      if (!thr)
	break;
      _thread_num_dead--;
      thread_queue_to (&term, thr);
    }
  Q_UNLOCK ();

  while (NULL != (thr = thread_queue_from (&term)))
    {
      thr->thr_status = TERMINATE;
      PulseEvent (thr->thr_cv);
#if 0
      WaitForSingleObject (thr->thr_handle, INFINITE);
	{
	  _thread_free_attributes (thr);
	  semaphore_free (thr->thr_sem);
	  CloseHandle (thr->thr_cv);
	  CloseHandle (thr->thr_handle);
	  dk_free (thr, sizeof (thread_t));
	}
#endif
      thread_killed++;
    }
#if 0
  if (thread_killed)
    log_info ("%ld OS threads released", thread_killed);
#endif
  return thread_killed;
}

int *
thread_errno (void)
{
  return &current_thread->thr_err;
}


int
thread_set_priority (thread_t *self, int prio)
{
  int old_prio = self->thr_priority;

  if (prio < 0 || prio >= MAX_PRIORITY)
    return old_prio;

  switch (prio)
    {
    case LOW_PRIORITY:
    case NORMAL_PRIORITY:
    case HIGH_PRIORITY:
      break;
    default:
      return old_prio;
    }


  self->thr_priority = prio;

  return old_prio;
}


int
thread_get_priority (thread_t *self)
{
  return self->thr_priority;
}


#ifdef EXPIRIMENTAL
/*
 *  Wait for an event to happen.
 *
 *  If holds != NULL, the caller holds the mutex, which will be released
 *  before going to sleep. The thread calling thread_signal_cond *must* hold
 *  the same mutex.
 *
 *  The holds mutex is reacquired after wakeup.
 */
int
thread_wait_cond (void *event, dk_mutex_t *holds, TVAL timeout)
{
  thread_t *thr = current_thread;
  HANDLE mtx;
  DWORD to;

  thr->thr_status = WAITEVENT;
  thr->thr_event = event;

  mtx = holds ? mtxt : _q_lock;

  Q_LOCK ();
  thread_queue_to (&_waitq, thr);
  _thread_num_wait++;

  if (holds)
    Q_UNLOCK ();

  to = timeout == TV_INFINITE ? INFINITE : timeout;

#ifdef WIN95COMPAT
  WaitForSingleObject (thr->thr_cv, to);
#else
  SignalObjectAndWait (mtx, thr->thr_cv, to, FALSE);
#endif

  mutex_enter (mtx);

  if (holds)
    Q_LOCK ();

  thread_queue_remove (&_waitq, thr);
  _thread_num_wait--;
  Q_UNLOCK ();

  thr->thr_status = RUNNING;
  return thr->thr_event == NULL ? 0 : -1;
}


int
thread_signal_cond (void *event)
{
  thread_t *thr;
  thread_t *next;
  int count;

  count = 0;
  Q_LOCK ();
  for (thr = (thread_t *) _waitq.thq_head.thr_next;
      thr != (thread_t *) &_waitq.thq_head;
      thr = next)
    {
      next = (thread_t *) thr->thr_hdr.thr_next;
      if (thr->thr_event == event)
	{
	  thr->thr_event = NULL;
	  PulseEvent (thr->thr_cv);
	  count++;
	}
    }
  Q_UNLOCK ();

  return count;
}


int
thread_select (int n, fd_set *rfds, fd_set *wfds, void *event, TVAL timeout)
{
  struct timeval *ptv, tv;

  if (timeout == TV_INFINITE)
    ptv = NULL;
  else
    {
      tv.tv_sec = timeout / 1000;
      tv.tv_usec = (timeout % 1000) * 1000;
      ptv = &tv;
    }

#error TODO - handle event

  return select (n, rfds, wfds, NULL, ptv);
}


void
thread_sleep (TVAL timeout)
{
  Sleep (timeout);
}
#endif


/******************************************************************************
 *
 *  Semaphores
 *
 ******************************************************************************/

semaphore_t *
semaphore_allocate (int entry_count)
{
  NEW_VARZ (semaphore_t, sem);
  sem->sem_handle = CreateSemaphore (NULL, entry_count, LONG_MAX, NULL);
  return sem;
}


void
semaphore_free (semaphore_t *self)
{
  CloseHandle (self->sem_handle);
  dk_free (self, sizeof (semaphore_t));
}


int
semaphore_enter (semaphore_t *self)
{
  _thread_num_wait++;
  WaitForSingleObject (self->sem_handle, INFINITE);
  _thread_num_wait--;
  return 0;
}


int
semaphore_try_enter (semaphore_t *self)
{
  if (WaitForSingleObject (self->sem_handle, 0) == WAIT_TIMEOUT)
    return 0;
  return 1;
}


#ifdef SEM_DEBUG
void
semaphore_leave_dbg (int ln, const char *file, semaphore_t *sem)
#else
void
semaphore_leave (semaphore_t *sem)
#endif
{
#ifdef SEM_DEBUG
    {
      int inx;
      for (inx = MAX_SEM_ENT - 1; inx > 0; inx--)
	{
	  sem->sem_last_left_line[inx] = sem->sem_last_left_line[inx - 1];
	  sem->sem_last_left_file[inx] = sem->sem_last_left_file[inx - 1];
	}
      sem->sem_last_left_line[0] = ln;
      sem->sem_last_left_file[0] = file;
    }
#endif
  ReleaseSemaphore (sem->sem_handle, 1, NULL);
}

/******************************************************************************
 *
 *  Mutexes
 *
 ******************************************************************************/


#ifdef MTX_METER
dk_set_t all_mtxs = NULL;
#endif

dk_mutex_t *
mutex_allocate_typed (int mutex_type)
{
  NEW_VARZ (dk_mutex_t, mtx);
  mtx->mtx_type = mutex_type;
#ifdef MTX_DEBUG
  mtx->mtx_owner = NULL;
#endif
  if (mutex_type == MUTEX_TYPE_LONG)
    {
      mtx->mtx_handle = CreateMutex (NULL, FALSE, NULL);
      return mtx;
    }
  else
    {
      NEW_VAR (CRITICAL_SECTION, cs);
      mtx->mtx_handle = cs;
      InitializeCriticalSection(mtx->mtx_handle);
#ifdef MTX_METER
      if (all_mtxs_mtx)
	mutex_enter (all_mtxs_mtx);
      dk_set_push (&all_mtxs, (void*) mtx);
      if (all_mtxs_mtx)
	mutex_leave (all_mtxs_mtx);
#endif
      return mtx;
    }
}

dk_mutex_t *
mutex_allocate (void)
{
  return mutex_allocate_typed(MUTEX_TYPE_SHORT);
}


#ifdef MTX_DEBUG
void
mutex_option (dk_mutex_t * mtx, char * name, mtx_entry_check_t ck, void * cd)
{
  dk_free_box (mtx->mtx_name);
  mtx->mtx_name = box_dv_short_string (name);
  mtx->mtx_entry_check = ck;
  mtx->mtx_entry_check_cd = cd;
}
#endif

void
dk_mutex_init (dk_mutex_t * mtx, int type)
{
  memset (mtx, 0, sizeof (dk_mutex_t));
  mtx->mtx_type = type;
#ifdef MTX_DEBUG
  mtx->mtx_owner = NULL;
#endif
  if (type == MUTEX_TYPE_LONG)
    {
      mtx->mtx_handle = CreateMutex (NULL, FALSE, NULL);
    }
  else
    {
      NEW_VAR (CRITICAL_SECTION, cs);
      mtx->mtx_handle = cs;
      InitializeCriticalSection(mtx->mtx_handle);
#ifdef MTX_METER
      if (all_mtxs_mtx)
	mutex_enter (all_mtxs_mtx);
      dk_set_push (&all_mtxs, (void*) mtx);
      if (all_mtxs_mtx)
	mutex_leave (all_mtxs_mtx);
#endif
    }
  return;
}

void
dk_mutex_destroy (dk_mutex_t *mtx)
{
#ifdef MTX_METER
  mutex_enter (all_mtxs_mtx);
  dk_set_delete (&all_mtxs, (void*) mtx);
  mutex_leave (all_mtxs_mtx);
#endif
  if (mtx->mtx_type == MUTEX_TYPE_LONG)
    {
      CloseHandle (mtx->mtx_handle);
    }
  else
    {
      DeleteCriticalSection(mtx->mtx_handle);
      dk_free(mtx->mtx_handle, sizeof(CRITICAL_SECTION));
    }
#ifdef MTX_DEBUG
  dk_free_box (mtx->mtx_name);
#endif
}

void
mutex_free (dk_mutex_t *self)
{
#ifdef MTX_METER
  mutex_enter (all_mtxs_mtx);
  dk_set_delete (&all_mtxs, (void*) self);
  mutex_leave (all_mtxs_mtx);
#endif
  if (self->mtx_type == MUTEX_TYPE_LONG)
    {
      CloseHandle (self->mtx_handle);
    }
  else
    {
      DeleteCriticalSection(self->mtx_handle);
      dk_free(self->mtx_handle, sizeof(CRITICAL_SECTION));
    }
#ifdef MTX_DEBUG
  dk_free_box (self->mtx_name);
#endif
  dk_free (self, sizeof (dk_mutex_t));
}


#ifdef MTX_DEBUG
int
mutex_enter_dbg (int line, char * file, dk_mutex_t *mtx)
#else
int
mutex_enter (dk_mutex_t *mtx)
#endif
{
#ifdef MTX_DEBUG
  thread_t* thr = thread_current();
#endif
  _thread_num_wait++;

#ifdef MTX_DEBUG
  assert (mtx->mtx_owner !=  mtx || !mtx);
  if (mtx->mtx_entry_check
      && !mtx->mtx_entry_check (mtx, thr, mtx->mtx_entry_check_cd))
    GPF_T1 ("Mtx entry check fail");
#endif

  if (mtx->mtx_type == MUTEX_TYPE_LONG)
    WaitForSingleObject (mtx->mtx_handle, INFINITE);
  else
    EnterCriticalSection(mtx->mtx_handle);
  _thread_num_wait--;
#ifdef MTX_DEBUG
  assert (mtx->mtx_owner == NULL);
  mtx->mtx_owner = thr;
  mtx->mtx_entry_file = file;
  mtx->mtx_entry_line = line;
#endif
  return 0;
}


int
mutex_try_enter (dk_mutex_t *mtx)
{
#ifdef MTX_DEBUG
  thread_t* thr = thread_current();
#endif
  if (mtx->mtx_type == MUTEX_TYPE_LONG)
    {
      if (WaitForSingleObject (mtx->mtx_handle, 0) == WAIT_TIMEOUT)
	return 0;
    }
  else
    {
      if (!TryEnterCriticalSection (mtx->mtx_handle))
	return 0;
    }

#ifdef MTX_DEBUG
  assert (mtx->mtx_owner == NULL);
  mtx->mtx_owner = thr;
  mtx->mtx_entry_file = __FILE__;
  mtx->mtx_entry_line = __LINE__;
#endif
  return 1;
}


#ifdef MTX_DEBUG
void mutex_leave_dbg (int line, char * file, dk_mutex_t *self)
#else
void mutex_leave (dk_mutex_t *self)
#endif
{
#ifdef MTX_DEBUG
  assert (self->mtx_owner == thread_current ());
  self->mtx_owner = NULL;
  self->mtx_leave_line = line;
  self->mtx_leave_file = file;
#endif
  if (self->mtx_type == MUTEX_TYPE_LONG)
    ReleaseMutex (self->mtx_handle);
  else
    LeaveCriticalSection(self->mtx_handle);
  return;
}


void
mutex_stat ()
{
  #ifdef MTX_METER
  DO_SET (dk_mutex_t *, mtx, &all_mtxs)
    {
      printf ("%s %lx E: %ld W %ld \n", mtx->mtx_name ? mtx->mtx_name : "<?>", (unsigned long) mtx,
	      mtx->mtx_enters, mtx->mtx_waits);
    }
  END_DO_SET();
  #else
  printf ("Mutex stats not enabled.}\n");
#endif
}

/******************************************************************************
 *
 *  Spinlocks
 *
 ******************************************************************************/

struct spinlock_s
  {
    CRITICAL_SECTION cs;
  };

spinlock_t *
spinlock_allocate (void)
{
  NEW_VAR (spinlock_t, sl);
  InitializeCriticalSection (&sl->cs);
  return sl;
}


void
spinlock_free (spinlock_t *self)
{
  dk_free (self, sizeof (spinlock_t));
}


void
spinlock_enter (spinlock_t *self)
{
  EnterCriticalSection (&self->cs);
}


void
spinlock_leave (spinlock_t *self)
{
  LeaveCriticalSection (&self->cs);
}


#ifdef MTX_DEBUG
#undef mutex_enter
int
mutex_enter (dk_mutex_t * mtx)
{
  return (mutex_enter_dbg (__LINE__, __FILE__, mtx));
}
#undef mutex_leave
void
mutex_leave (dk_mutex_t * mtx)
{
  mutex_leave_dbg (__LINE__, __FILE__, mtx);
}
#endif