]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libc/gen/sem_new.c
MFC r317606:
[FreeBSD/FreeBSD.git] / lib / libc / gen / sem_new.c
1 /*
2  * Copyright (C) 2010 David Xu <davidxu@freebsd.org>.
3  * All rights reserved.
4  * 
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice(s), this list of conditions and the following disclaimer as
10  *    the first lines of this file unmodified other than the possible
11  *    addition of one or more copyright notices.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice(s), this list of conditions and the following disclaimer in
14  *    the documentation and/or other materials provided with the
15  *    distribution.
16  * 
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE
21  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
24  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
25  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
26  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
27  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  */
31
32 #include "namespace.h"
33 #include <sys/types.h>
34 #include <sys/queue.h>
35 #include <sys/mman.h>
36 #include <sys/stat.h>
37 #include <errno.h>
38 #include <machine/atomic.h>
39 #include <sys/umtx.h>
40 #include <limits.h>
41 #include <fcntl.h>
42 #include <pthread.h>
43 #include <stdarg.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <time.h>
47 #include <semaphore.h>
48 #include <unistd.h>
49 #include "un-namespace.h"
50 #include "libc_private.h"
51
52 __weak_reference(_sem_close, sem_close);
53 __weak_reference(_sem_destroy, sem_destroy);
54 __weak_reference(_sem_getvalue, sem_getvalue);
55 __weak_reference(_sem_init, sem_init);
56 __weak_reference(_sem_open, sem_open);
57 __weak_reference(_sem_post, sem_post);
58 __weak_reference(_sem_timedwait, sem_timedwait);
59 __weak_reference(_sem_clockwait_np, sem_clockwait_np);
60 __weak_reference(_sem_trywait, sem_trywait);
61 __weak_reference(_sem_unlink, sem_unlink);
62 __weak_reference(_sem_wait, sem_wait);
63
64 #define SEM_PREFIX      "/tmp/SEMD"
65 #define SEM_MAGIC       ((u_int32_t)0x73656d32)
66
67 _Static_assert(SEM_VALUE_MAX <= USEM_MAX_COUNT, "SEM_VALUE_MAX too large");
68
69 struct sem_nameinfo {
70         int open_count;
71         char *name;
72         dev_t dev;
73         ino_t ino;
74         sem_t *sem;
75         LIST_ENTRY(sem_nameinfo) next;
76 };
77
78 static pthread_once_t once = PTHREAD_ONCE_INIT;
79 static pthread_mutex_t sem_llock;
80 static LIST_HEAD(, sem_nameinfo) sem_list = LIST_HEAD_INITIALIZER(sem_list);
81
82 static void
83 sem_prefork(void)
84 {
85         
86         _pthread_mutex_lock(&sem_llock);
87 }
88
89 static void
90 sem_postfork(void)
91 {
92
93         _pthread_mutex_unlock(&sem_llock);
94 }
95
96 static void
97 sem_child_postfork(void)
98 {
99
100         _pthread_mutex_unlock(&sem_llock);
101 }
102
103 static void
104 sem_module_init(void)
105 {
106         pthread_mutexattr_t ma;
107
108         _pthread_mutexattr_init(&ma);
109         _pthread_mutexattr_settype(&ma,  PTHREAD_MUTEX_RECURSIVE);
110         _pthread_mutex_init(&sem_llock, &ma);
111         _pthread_mutexattr_destroy(&ma);
112         _pthread_atfork(sem_prefork, sem_postfork, sem_child_postfork);
113 }
114
115 static inline int
116 sem_check_validity(sem_t *sem)
117 {
118
119         if (sem->_magic == SEM_MAGIC)
120                 return (0);
121         errno = EINVAL;
122         return (-1);
123 }
124
125 int
126 _sem_init(sem_t *sem, int pshared, unsigned int value)
127 {
128
129         if (value > SEM_VALUE_MAX) {
130                 errno = EINVAL;
131                 return (-1);
132         }
133  
134         bzero(sem, sizeof(sem_t));
135         sem->_magic = SEM_MAGIC;
136         sem->_kern._count = (u_int32_t)value;
137         sem->_kern._flags = pshared ? USYNC_PROCESS_SHARED : 0;
138         return (0);
139 }
140
141 sem_t *
142 _sem_open(const char *name, int flags, ...)
143 {
144         char path[PATH_MAX];
145         struct stat sb;
146         va_list ap;
147         struct sem_nameinfo *ni;
148         sem_t *sem, tmp;
149         int errsave, fd, len, mode, value;
150
151         ni = NULL;
152         sem = NULL;
153         fd = -1;
154         value = 0;
155
156         if (name[0] != '/') {
157                 errno = EINVAL;
158                 return (SEM_FAILED);
159         }
160         name++;
161         strcpy(path, SEM_PREFIX);
162         if (strlcat(path, name, sizeof(path)) >= sizeof(path)) {
163                 errno = ENAMETOOLONG;
164                 return (SEM_FAILED);
165         }
166         if (flags & ~(O_CREAT|O_EXCL)) {
167                 errno = EINVAL;
168                 return (SEM_FAILED);
169         }
170         if ((flags & O_CREAT) != 0) {
171                 va_start(ap, flags);
172                 mode = va_arg(ap, int);
173                 value = va_arg(ap, int);
174                 va_end(ap);
175         }
176         fd = -1;
177         _pthread_once(&once, sem_module_init);
178
179         _pthread_mutex_lock(&sem_llock);
180         LIST_FOREACH(ni, &sem_list, next) {
181                 if (ni->name != NULL && strcmp(name, ni->name) == 0) {
182                         fd = _open(path, flags | O_RDWR | O_CLOEXEC |
183                             O_EXLOCK, mode);
184                         if (fd == -1 || _fstat(fd, &sb) == -1) {
185                                 ni = NULL;
186                                 goto error;
187                         }
188                         if ((flags & (O_CREAT | O_EXCL)) == (O_CREAT |
189                             O_EXCL) || ni->dev != sb.st_dev ||
190                             ni->ino != sb.st_ino) {
191                                 ni->name = NULL;
192                                 ni = NULL;
193                                 break;
194                         }
195                         ni->open_count++;
196                         sem = ni->sem;
197                         _pthread_mutex_unlock(&sem_llock);
198                         _close(fd);
199                         return (sem);
200                 }
201         }
202
203         len = sizeof(*ni) + strlen(name) + 1;
204         ni = (struct sem_nameinfo *)malloc(len);
205         if (ni == NULL) {
206                 errno = ENOSPC;
207                 goto error;
208         }
209
210         ni->name = (char *)(ni+1);
211         strcpy(ni->name, name);
212
213         if (fd == -1) {
214                 fd = _open(path, flags | O_RDWR | O_CLOEXEC | O_EXLOCK, mode);
215                 if (fd == -1 || _fstat(fd, &sb) == -1)
216                         goto error;
217         }
218         if (sb.st_size < sizeof(sem_t)) {
219                 tmp._magic = SEM_MAGIC;
220                 tmp._kern._count = value;
221                 tmp._kern._flags = USYNC_PROCESS_SHARED | SEM_NAMED;
222                 if (_write(fd, &tmp, sizeof(tmp)) != sizeof(tmp))
223                         goto error;
224         }
225         flock(fd, LOCK_UN);
226         sem = mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE,
227             MAP_SHARED | MAP_NOSYNC, fd, 0);
228         if (sem == MAP_FAILED) {
229                 sem = NULL;
230                 if (errno == ENOMEM)
231                         errno = ENOSPC;
232                 goto error;
233         }
234         if (sem->_magic != SEM_MAGIC) {
235                 errno = EINVAL;
236                 goto error;
237         }
238         ni->open_count = 1;
239         ni->sem = sem;
240         ni->dev = sb.st_dev;
241         ni->ino = sb.st_ino;
242         LIST_INSERT_HEAD(&sem_list, ni, next);
243         _close(fd);
244         _pthread_mutex_unlock(&sem_llock);
245         return (sem);
246
247 error:
248         errsave = errno;
249         if (fd != -1)
250                 _close(fd);
251         if (sem != NULL)
252                 munmap(sem, sizeof(sem_t));
253         free(ni);
254         _pthread_mutex_unlock(&sem_llock);
255         errno = errsave;
256         return (SEM_FAILED);
257 }
258
259 int
260 _sem_close(sem_t *sem)
261 {
262         struct sem_nameinfo *ni;
263
264         if (sem_check_validity(sem) != 0)
265                 return (-1);
266
267         if (!(sem->_kern._flags & SEM_NAMED)) {
268                 errno = EINVAL;
269                 return (-1);
270         }
271
272         _pthread_once(&once, sem_module_init);
273
274         _pthread_mutex_lock(&sem_llock);
275         LIST_FOREACH(ni, &sem_list, next) {
276                 if (sem == ni->sem) {
277                         if (--ni->open_count > 0) {
278                                 _pthread_mutex_unlock(&sem_llock);
279                                 return (0);
280                         }
281                         break;
282                 }
283         }
284
285         if (ni != NULL) {
286                 LIST_REMOVE(ni, next);
287                 _pthread_mutex_unlock(&sem_llock);
288                 munmap(sem, sizeof(*sem));
289                 free(ni);
290                 return (0);
291         }
292         _pthread_mutex_unlock(&sem_llock);
293         errno = EINVAL;
294         return (-1);
295 }
296
297 int
298 _sem_unlink(const char *name)
299 {
300         char path[PATH_MAX];
301
302         if (name[0] != '/') {
303                 errno = ENOENT;
304                 return -1;
305         }
306         name++;
307         strcpy(path, SEM_PREFIX);
308         if (strlcat(path, name, sizeof(path)) >= sizeof(path)) {
309                 errno = ENAMETOOLONG;
310                 return (-1);
311         }
312
313         return (unlink(path));
314 }
315
316 int
317 _sem_destroy(sem_t *sem)
318 {
319
320         if (sem_check_validity(sem) != 0)
321                 return (-1);
322
323         if (sem->_kern._flags & SEM_NAMED) {
324                 errno = EINVAL;
325                 return (-1);
326         }
327         sem->_magic = 0;
328         return (0);
329 }
330
331 int
332 _sem_getvalue(sem_t * __restrict sem, int * __restrict sval)
333 {
334
335         if (sem_check_validity(sem) != 0)
336                 return (-1);
337
338         *sval = (int)USEM_COUNT(sem->_kern._count);
339         return (0);
340 }
341
342 static __inline int
343 usem_wake(struct _usem2 *sem)
344 {
345
346         return (_umtx_op(sem, UMTX_OP_SEM2_WAKE, 0, NULL, NULL));
347 }
348
349 static __inline int
350 usem_wait(struct _usem2 *sem, clockid_t clock_id, int flags,
351     const struct timespec *rqtp, struct timespec *rmtp)
352 {
353         struct {
354                 struct _umtx_time timeout;
355                 struct timespec remain;
356         } tms;
357         void *tm_p;
358         size_t tm_size;
359         int retval;
360
361         if (rqtp == NULL) {
362                 tm_p = NULL;
363                 tm_size = 0;
364         } else {
365                 tms.timeout._clockid = clock_id;
366                 tms.timeout._flags = (flags & TIMER_ABSTIME) ? UMTX_ABSTIME : 0;
367                 tms.timeout._timeout = *rqtp;
368                 tm_p = &tms;
369                 tm_size = sizeof(tms);
370         }
371         retval = _umtx_op(sem, UMTX_OP_SEM2_WAIT, 0, (void *)tm_size, tm_p);
372         if (retval == -1 && errno == EINTR && (flags & TIMER_ABSTIME) == 0 &&
373             rqtp != NULL && rmtp != NULL) {
374                 *rmtp = tms.remain;
375         }
376
377         return (retval);
378 }
379
380 int
381 _sem_trywait(sem_t *sem)
382 {
383         int val;
384
385         if (sem_check_validity(sem) != 0)
386                 return (-1);
387
388         while (USEM_COUNT(val = sem->_kern._count) > 0) {
389                 if (atomic_cmpset_acq_int(&sem->_kern._count, val, val - 1))
390                         return (0);
391         }
392         errno = EAGAIN;
393         return (-1);
394 }
395
396 int
397 _sem_clockwait_np(sem_t * __restrict sem, clockid_t clock_id, int flags,
398         const struct timespec *rqtp, struct timespec *rmtp)
399 {
400         int val, retval;
401
402         if (sem_check_validity(sem) != 0)
403                 return (-1);
404
405         retval = 0;
406         _pthread_testcancel();
407         for (;;) {
408                 while (USEM_COUNT(val = sem->_kern._count) > 0) {
409                         if (atomic_cmpset_acq_int(&sem->_kern._count, val,
410                             val - 1))
411                                 return (0);
412                 }
413
414                 if (retval) {
415                         _pthread_testcancel();
416                         break;
417                 }
418
419                 /*
420                  * The timeout argument is only supposed to
421                  * be checked if the thread would have blocked.
422                  */
423                 if (rqtp != NULL) {
424                         if (rqtp->tv_nsec >= 1000000000 || rqtp->tv_nsec < 0) {
425                                 errno = EINVAL;
426                                 return (-1);
427                         }
428                 }
429                 _pthread_cancel_enter(1);
430                 retval = usem_wait(&sem->_kern, clock_id, flags, rqtp, rmtp);
431                 _pthread_cancel_leave(0);
432         }
433         return (retval);
434 }
435
436 int
437 _sem_timedwait(sem_t * __restrict sem,
438         const struct timespec * __restrict abstime)
439 {
440
441         return (_sem_clockwait_np(sem, CLOCK_REALTIME, TIMER_ABSTIME, abstime,
442             NULL));
443 };
444
445 int
446 _sem_wait(sem_t *sem)
447 {
448
449         return (_sem_timedwait(sem, NULL));
450 }
451
452 /*
453  * POSIX:
454  * The sem_post() interface is reentrant with respect to signals and may be
455  * invoked from a signal-catching function. 
456  * The implementation does not use lock, so it should be safe.
457  */
458 int
459 _sem_post(sem_t *sem)
460 {
461         unsigned int count;
462
463         if (sem_check_validity(sem) != 0)
464                 return (-1);
465
466         do {
467                 count = sem->_kern._count;
468                 if (USEM_COUNT(count) + 1 > SEM_VALUE_MAX) {
469                         errno = EOVERFLOW;
470                         return (-1);
471                 }
472         } while (!atomic_cmpset_rel_int(&sem->_kern._count, count, count + 1));
473         if (count & USEM_HAS_WAITERS)
474                 usem_wake(&sem->_kern);
475         return (0);
476 }