nckernel  0.1
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
pthread_mutex.c
Go to the documentation of this file.
1 #include <sys/types.h>
2 #include <stdio.h>
3 #include <stddef.h>
4 #include <stdlib.h>
5 #include <errno.h>
6 #include <pthread.h>
7 
8 #include <interrupt.h>
9 
11 {
12  /* Release locked process(or thread) */
13  mutex->lock = 0;
14  return 0;
15 }
16 
18  const pthread_mutexattr_t *attr)
19 {
20  mutex->lock = 0;
21  mutex->owner = NULL;
22  mutex->refcnt = 0;
23  return 0;
24 }
25 
27 {
28  unsigned long flags;
29 
30  irq_local_save(&flags);
31  if (pthread_equal(mutex->owner, pthread_self())) {
32  mutex->refcnt++;
33  irq_local_restore(flags);
34  return 0;
35  }
36  irq_local_restore(flags);
37 
38  asm __volatile__ (
39  "1:"
40  "movl $0, %%eax;\n"
41  "movl $1, %%ecx;\n"
42  "lock; cmpxchgl %%ecx, %0;\n"
43  "jz 2f;\n"
44  "jmp 1b;\n"
45  "2:\n"
46  : "=m"(mutex->lock)
47  :
48  : "memory", "%ecx", "%eax"
49  );
50 
51  mutex->owner = pthread_self();
52  mutex->refcnt = 1;
53  return 0;
54 }
55 
57 {
58  int ret;
59  unsigned long flags;
60 
61  irq_local_save(&flags);
62  if (pthread_equal(mutex->owner, pthread_self())) {
63  mutex->refcnt++;
64  irq_local_restore(flags);
65  return 0;
66  }
67  irq_local_restore(flags);
68 
69  asm __volatile__ (
70  "movl $0, %%eax;\n"
71  "movl $1, %%ecx;\n"
72  "lock; cmpxchgl %%ecx, %0;\n"
73  "jz 2f;\n"
74  "movl $-1, %1;\n"
75  "jmp 3f\n"
76  "2:\n"
77  "movl $0, %1;\n"
78  "3:\n"
79  : "=m"(mutex->lock), "=m"(ret)
80  :
81  : "memory", "%ecx", "%eax"
82  );
83 
84  if (ret < 0) {
85  return ret;
86  }
87 
88  mutex->owner = pthread_self();
89  mutex->refcnt = 1;
90  return ret;
91 }
92 
94 {
95  unsigned long flags;
96 
97  irq_local_save(&flags);
98  if (!pthread_equal(mutex->owner, pthread_self())) {
99  irq_local_restore(flags);
100  return -EINVAL;
101  }
102 
103  mutex->refcnt--;
104  if (mutex->refcnt > 0) {
105  irq_local_restore(flags);
106  return 0;
107  }
108  irq_local_restore(flags);
109 
110  mutex->owner = NULL;
111  asm __volatile__ (
112  "movl $0, %%eax;\n"
113  "xchgl %%eax, %0;\n"
114  : "=m"(mutex->lock)
115  :
116  : "memory", "%eax"
117  );
118 
119  return 0;
120 }
121 
122 /* End of a file */