xref: /freebsd/lib/libc/gen/sem_new.c (revision 9199c09a159c4e3e98c212d4eec1edc5252d9e33)
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 
51 __weak_reference(_sem_close, sem_close);
52 __weak_reference(_sem_destroy, sem_destroy);
53 __weak_reference(_sem_getvalue, sem_getvalue);
54 __weak_reference(_sem_init, sem_init);
55 __weak_reference(_sem_open, sem_open);
56 __weak_reference(_sem_post, sem_post);
57 __weak_reference(_sem_timedwait, sem_timedwait);
58 __weak_reference(_sem_trywait, sem_trywait);
59 __weak_reference(_sem_unlink, sem_unlink);
60 __weak_reference(_sem_wait, sem_wait);
61 
62 #define SEM_PREFIX	"/tmp/SEMD"
63 #define SEM_MAGIC	((u_int32_t)0x73656d31)
64 
65 struct sem_nameinfo {
66 	int open_count;
67 	char *name;
68 	sem_t *sem;
69 	LIST_ENTRY(sem_nameinfo) next;
70 };
71 
72 static pthread_once_t once = PTHREAD_ONCE_INIT;
73 static pthread_mutex_t sem_llock;
74 static LIST_HEAD(,sem_nameinfo) sem_list = LIST_HEAD_INITIALIZER(sem_list);
75 
76 static void
77 sem_prefork()
78 {
79 
80 	_pthread_mutex_lock(&sem_llock);
81 }
82 
83 static void
84 sem_postfork()
85 {
86 	_pthread_mutex_unlock(&sem_llock);
87 }
88 
89 static void
90 sem_child_postfork()
91 {
92 	_pthread_mutex_unlock(&sem_llock);
93 }
94 
95 static void
96 sem_module_init(void)
97 {
98 	pthread_mutexattr_t ma;
99 
100 	_pthread_mutexattr_init(&ma);
101 	_pthread_mutexattr_settype(&ma,  PTHREAD_MUTEX_RECURSIVE);
102 	_pthread_mutex_init(&sem_llock, &ma);
103 	_pthread_mutexattr_destroy(&ma);
104 	_pthread_atfork(sem_prefork, sem_postfork, sem_child_postfork);
105 }
106 
107 static inline int
108 sem_check_validity(sem_t *sem)
109 {
110 
111 	if (sem->_magic == SEM_MAGIC)
112 		return (0);
113 	else {
114 		errno = EINVAL;
115 		return (-1);
116 	}
117 }
118 
119 int
120 _sem_init(sem_t *sem, int pshared, unsigned int value)
121 {
122 
123 	if (value > SEM_VALUE_MAX) {
124 		errno = EINVAL;
125 		return (-1);
126 	}
127 
128 	bzero(sem, sizeof(sem_t));
129 	sem->_magic = SEM_MAGIC;
130 	sem->_kern._count = (u_int32_t)value;
131 	sem->_kern._has_waiters = 0;
132 	sem->_kern._flags = pshared ? USYNC_PROCESS_SHARED : 0;
133 	return (0);
134 }
135 
136 sem_t *
137 _sem_open(const char *name, int flags, ...)
138 {
139 	char path[PATH_MAX];
140 
141 	struct stat sb;
142 	va_list ap;
143 	struct sem_nameinfo *ni = NULL;
144 	sem_t *sem = NULL;
145 	int fd = -1, mode, len;
146 
147 	if (name[0] != '/') {
148 		errno = EINVAL;
149 		return (NULL);
150 	}
151 	name++;
152 
153 	if (flags & ~(O_CREAT|O_EXCL)) {
154 		errno = EINVAL;
155 		return (NULL);
156 	}
157 
158 	_pthread_once(&once, sem_module_init);
159 
160 	_pthread_mutex_lock(&sem_llock);
161 	LIST_FOREACH(ni, &sem_list, next) {
162 		if (strcmp(name, ni->name) == 0) {
163 			ni->open_count++;
164 			sem = ni->sem;
165 			_pthread_mutex_unlock(&sem_llock);
166 			return (sem);
167 		}
168 	}
169 
170 	if (flags & O_CREAT) {
171 		va_start(ap, flags);
172 		mode = va_arg(ap, int);
173 		va_end(ap);
174 	}
175 
176 	len = sizeof(*ni) + strlen(name) + 1;
177 	ni = (struct sem_nameinfo *)malloc(len);
178 	if (ni == NULL) {
179 		errno = ENOSPC;
180 		goto error;
181 	}
182 
183 	ni->name = (char *)(ni+1);
184 	strcpy(ni->name, name);
185 
186 	strcpy(path, SEM_PREFIX);
187 	if (strlcat(path, name, sizeof(path)) >= sizeof(path)) {
188 		errno = ENAMETOOLONG;
189 		goto error;
190 	}
191 
192 	fd = _open(path, flags|O_RDWR, mode);
193 	if (fd == -1)
194 		goto error;
195 	if (flock(fd, LOCK_EX) == -1)
196 		goto error;
197 	if (_fstat(fd, &sb)) {
198 		flock(fd, LOCK_UN);
199 		goto error;
200 	}
201 	if (sb.st_size < sizeof(sem_t)) {
202 		sem_t tmp;
203 
204 		tmp._magic = SEM_MAGIC;
205 		tmp._kern._has_waiters = 0;
206 		tmp._kern._count = 0;
207 		tmp._kern._flags = USYNC_PROCESS_SHARED | SEM_NAMED;
208 		if (_write(fd, &tmp, sizeof(tmp)) != sizeof(tmp)) {
209 			flock(fd, LOCK_UN);
210 			goto error;
211 		}
212 	}
213 	flock(fd, LOCK_UN);
214 	sem = (sem_t *)mmap(NULL, sizeof(sem_t), PROT_READ|PROT_WRITE,
215 		MAP_SHARED|MAP_NOSYNC, fd, 0);
216 	if (sem == MAP_FAILED) {
217 		sem = NULL;
218 		if (errno == ENOMEM)
219 			errno = ENOSPC;
220 		goto error;
221 	}
222 	if (sem->_magic != SEM_MAGIC) {
223 		errno = EINVAL;
224 		goto error;
225 	}
226 	ni->open_count = 1;
227 	ni->sem = sem;
228 	LIST_INSERT_HEAD(&sem_list, ni, next);
229 	_pthread_mutex_unlock(&sem_llock);
230 	_close(fd);
231 	return (sem);
232 
233 error:
234 	_pthread_mutex_unlock(&sem_llock);
235 	if (fd != -1)
236 		_close(fd);
237 	if (sem != NULL)
238 		munmap(sem, sizeof(sem_t));
239 	free(ni);
240 	return (SEM_FAILED);
241 }
242 
243 int
244 _sem_close(sem_t *sem)
245 {
246 	struct sem_nameinfo *ni;
247 
248 	if (sem_check_validity(sem) != 0)
249 		return (-1);
250 
251 	if (!(sem->_kern._flags & SEM_NAMED)) {
252 		errno = EINVAL;
253 		return (-1);
254 	}
255 
256 	_pthread_mutex_lock(&sem_llock);
257 	LIST_FOREACH(ni, &sem_list, next) {
258 		if (sem == ni->sem) {
259 			if (--ni->open_count > 0) {
260 				_pthread_mutex_unlock(&sem_llock);
261 				return (0);
262 			}
263 			else
264 				break;
265 		}
266 	}
267 
268 	if (ni) {
269 		LIST_REMOVE(ni, next);
270 		_pthread_mutex_unlock(&sem_llock);
271 		munmap(sem, sizeof(*sem));
272 		free(ni);
273 		return (0);
274 	}
275 	_pthread_mutex_unlock(&sem_llock);
276 	return (-1);
277 }
278 
279 int
280 _sem_unlink(const char *name)
281 {
282 	char path[PATH_MAX];
283 
284 	if (name[0] != '/') {
285 		errno = ENOENT;
286 		return -1;
287 	}
288 	name++;
289 
290 	strcpy(path, SEM_PREFIX);
291 	if (strlcat(path, name, sizeof(path)) >= sizeof(path)) {
292 		errno = ENAMETOOLONG;
293 		return (-1);
294 	}
295 	return unlink(path);
296 }
297 
298 int
299 _sem_destroy(sem_t *sem)
300 {
301 
302 	if (sem_check_validity(sem) != 0)
303 		return (-1);
304 
305 	if (sem->_kern._flags & SEM_NAMED) {
306 		errno = EINVAL;
307 		return (-1);
308 	}
309 	sem->_magic = 0;
310 	return (0);
311 }
312 
313 int
314 _sem_getvalue(sem_t * __restrict sem, int * __restrict sval)
315 {
316 
317 	if (sem_check_validity(sem) != 0)
318 		return (-1);
319 
320 	*sval = (int)sem->_kern._count;
321 	return (0);
322 }
323 
324 static __inline int
325 usem_wake(struct _usem *sem)
326 {
327 	if (!sem->_has_waiters)
328 		return (0);
329 	return _umtx_op(sem, UMTX_OP_SEM_WAKE, 0, NULL, NULL);
330 }
331 
332 static __inline int
333 usem_wait(struct _usem *sem, const struct timespec *timeout)
334 {
335 	if (timeout && (timeout->tv_sec < 0 || (timeout->tv_sec == 0 &&
336 	    timeout->tv_nsec <= 0))) {
337 		errno = ETIMEDOUT;
338 		return (-1);
339 	}
340 	return _umtx_op(sem, UMTX_OP_SEM_WAIT, 0, NULL,
341 			__DECONST(void*, timeout));
342 }
343 
344 int
345 _sem_trywait(sem_t *sem)
346 {
347 	int val;
348 
349 	if (sem_check_validity(sem) != 0)
350 		return (-1);
351 
352 	while ((val = sem->_kern._count) > 0) {
353 		if (atomic_cmpset_acq_int(&sem->_kern._count, val, val - 1))
354 			return (0);
355 	}
356 	errno = EAGAIN;
357 	return (-1);
358 }
359 
360 static void
361 sem_cancel_handler(void *arg)
362 {
363 	sem_t *sem = arg;
364 
365 	if (sem->_kern._has_waiters && sem->_kern._count)
366 		usem_wake(&sem->_kern);
367 }
368 
369 #define TIMESPEC_SUB(dst, src, val)                             \
370         do {                                                    \
371                 (dst)->tv_sec = (src)->tv_sec - (val)->tv_sec;  \
372                 (dst)->tv_nsec = (src)->tv_nsec - (val)->tv_nsec; \
373                 if ((dst)->tv_nsec < 0) {                       \
374                         (dst)->tv_sec--;                        \
375                         (dst)->tv_nsec += 1000000000;           \
376                 }                                               \
377         } while (0)
378 
379 
380 static __inline int
381 enable_async_cancel(void)
382 {
383 	int old;
384 
385 	_pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old);
386 	return (old);
387 }
388 
389 static __inline void
390 restore_async_cancel(int val)
391 {
392 	_pthread_setcanceltype(val, NULL);
393 }
394 
395 int
396 _sem_timedwait(sem_t * __restrict sem,
397 	const struct timespec * __restrict abstime)
398 {
399 	struct timespec ts, ts2;
400 	int val, retval, saved_cancel;
401 
402 	if (sem_check_validity(sem) != 0)
403 		return (-1);
404 
405 	retval = 0;
406 	for (;;) {
407 		while ((val = sem->_kern._count) > 0) {
408 			if (atomic_cmpset_acq_int(&sem->_kern._count, val, val - 1))
409 				return (0);
410 		}
411 
412 		if (retval)
413 			break;
414 
415 		/*
416 		 * The timeout argument is only supposed to
417 		 * be checked if the thread would have blocked.
418 		 */
419 		if (abstime != NULL) {
420 			if (abstime->tv_nsec >= 1000000000 || abstime->tv_nsec < 0) {
421 				errno = EINVAL;
422 				return (-1);
423 			}
424 			clock_gettime(CLOCK_REALTIME, &ts);
425 			TIMESPEC_SUB(&ts2, abstime, &ts);
426 		}
427 		pthread_cleanup_push(sem_cancel_handler, sem);
428 		saved_cancel = enable_async_cancel();
429 		retval = usem_wait(&sem->_kern, abstime ? &ts2 : NULL);
430 		restore_async_cancel(saved_cancel);
431 		pthread_cleanup_pop(0);
432 	}
433 	return (retval);
434 }
435 
436 int
437 _sem_wait(sem_t *sem)
438 {
439 	return _sem_timedwait(sem, NULL);
440 }
441 
442 /*
443  * POSIX:
444  * The sem_post() interface is reentrant with respect to signals and may be
445  * invoked from a signal-catching function.
446  * The implementation does not use lock, so it should be safe.
447  */
448 int
449 _sem_post(sem_t *sem)
450 {
451 
452 	if (sem_check_validity(sem) != 0)
453 		return (-1);
454 
455 	atomic_add_rel_int(&sem->_kern._count, 1);
456 	return usem_wake(&sem->_kern);
457 }
458