sysv_sem.c revision 1.104 1 /* $NetBSD: sysv_sem.c,v 1.104 2025/05/23 09:47:34 hannken Exp $ */
2
3 /*-
4 * Copyright (c) 1999, 2007 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9 * NASA Ames Research Center, and by Andrew Doran.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33 /*
34 * Implementation of SVID semaphores
35 *
36 * Author: Daniel Boulet
37 *
38 * This software is provided ``AS IS'' without any warranties of any kind.
39 */
40
41 #include <sys/cdefs.h>
42 __KERNEL_RCSID(0, "$NetBSD: sysv_sem.c,v 1.104 2025/05/23 09:47:34 hannken Exp $");
43
44 #ifdef _KERNEL_OPT
45 #include "opt_sysv.h"
46 #endif
47
48 #include <sys/param.h>
49 #include <sys/kernel.h>
50 #include <sys/sem.h>
51 #include <sys/sysctl.h>
52 #include <sys/kmem.h>
53 #include <sys/mount.h> /* XXX for <sys/syscallargs.h> */
54 #include <sys/syscallargs.h>
55 #include <sys/kauth.h>
56 #include <sys/once.h>
57
58 /*
59 * Memory areas:
60 * 1st: Pool of semaphore identifiers
61 * 2nd: Semaphores
62 * 3rd: Conditional variables
63 * 4th: Undo structures
64 */
65 struct semid_ds * sema __read_mostly;
66 static struct __sem * sem __read_mostly;
67 static kcondvar_t * semcv __read_mostly;
68 static int * semu __read_mostly;
69
70 static kmutex_t semlock __cacheline_aligned;
71 static bool sem_realloc_state __read_mostly;
72 static kcondvar_t sem_realloc_cv;
73
74 /*
75 * List of active undo structures, total number of semaphores,
76 * and total number of semop waiters.
77 */
78 static struct sem_undo *semu_list __read_mostly;
79 static u_int semtot __cacheline_aligned;
80 static u_int sem_waiters __cacheline_aligned;
81
82 /* Macro to find a particular sem_undo vector */
83 #define SEMU(s, ix) ((struct sem_undo *)(((long)s) + ix * seminfo.semusz))
84
85 #ifdef SEM_DEBUG
86 #define SEM_PRINTF(a) printf a
87 #else
88 #define SEM_PRINTF(a)
89 #endif
90
91 void *hook; /* cookie from exithook_establish() */
92
93 extern int kern_has_sysvsem;
94
95 SYSCTL_SETUP_PROTO(sysctl_ipc_sem_setup);
96
97 struct sem_undo *semu_alloc(struct proc *);
98 int semundo_adjust(struct proc *, struct sem_undo **, int, int, int);
99 void semundo_clear(int, int);
100
101 static ONCE_DECL(exithook_control);
102 static int seminit_exithook(void);
103
104 int
105 seminit(void)
106 {
107 int i, sz;
108 vaddr_t v;
109
110 mutex_init(&semlock, MUTEX_DEFAULT, IPL_NONE);
111 cv_init(&sem_realloc_cv, "semrealc");
112 sem_realloc_state = false;
113 semtot = 0;
114 sem_waiters = 0;
115
116 /* Allocate the wired memory for our structures */
117 sz = ALIGN(seminfo.semmni * sizeof(struct semid_ds)) +
118 ALIGN(seminfo.semmns * sizeof(struct __sem)) +
119 ALIGN(seminfo.semmni * sizeof(kcondvar_t)) +
120 ALIGN(seminfo.semmnu * seminfo.semusz);
121 sz = round_page(sz);
122 v = uvm_km_alloc(kernel_map, sz, 0, UVM_KMF_WIRED|UVM_KMF_ZERO);
123 if (v == 0) {
124 printf("sysv_sem: cannot allocate memory");
125 return ENOMEM;
126 }
127 sema = (void *)v;
128 sem = (void *)((uintptr_t)sema +
129 ALIGN(seminfo.semmni * sizeof(struct semid_ds)));
130 semcv = (void *)((uintptr_t)sem +
131 ALIGN(seminfo.semmns * sizeof(struct __sem)));
132 semu = (void *)((uintptr_t)semcv +
133 ALIGN(seminfo.semmni * sizeof(kcondvar_t)));
134
135 for (i = 0; i < seminfo.semmni; i++) {
136 sema[i]._sem_base = 0;
137 sema[i].sem_perm.mode = 0;
138 cv_init(&semcv[i], "semwait");
139 }
140 for (i = 0; i < seminfo.semmnu; i++) {
141 struct sem_undo *suptr = SEMU(semu, i);
142 suptr->un_proc = NULL;
143 }
144 semu_list = NULL;
145
146 kern_has_sysvsem = 1;
147
148 return 0;
149 }
150
151 static int
152 seminit_exithook(void)
153 {
154
155 hook = exithook_establish(semexit, NULL);
156 return 0;
157 }
158
159 int
160 semfini(void)
161 {
162 int i, sz;
163 vaddr_t v = (vaddr_t)sema;
164
165 /* Don't allow module unload if we're busy */
166 mutex_enter(&semlock);
167 if (semtot) {
168 mutex_exit(&semlock);
169 return 1;
170 }
171
172 /* Remove the exit hook */
173 if (hook)
174 exithook_disestablish(hook);
175
176 /* Destroy all our condvars */
177 for (i = 0; i < seminfo.semmni; i++) {
178 cv_destroy(&semcv[i]);
179 }
180
181 /* Free the wired memory that we allocated */
182 sz = ALIGN(seminfo.semmni * sizeof(struct semid_ds)) +
183 ALIGN(seminfo.semmns * sizeof(struct __sem)) +
184 ALIGN(seminfo.semmni * sizeof(kcondvar_t)) +
185 ALIGN(seminfo.semmnu * seminfo.semusz);
186 sz = round_page(sz);
187 uvm_km_free(kernel_map, v, sz, UVM_KMF_WIRED);
188
189 /* Destroy the last cv and mutex */
190 cv_destroy(&sem_realloc_cv);
191 mutex_exit(&semlock);
192 mutex_destroy(&semlock);
193
194 kern_has_sysvsem = 0;
195
196 return 0;
197 }
198
199 static int
200 semrealloc(int newsemmni, int newsemmns, int newsemmnu)
201 {
202 struct semid_ds *new_sema, *old_sema;
203 struct __sem *new_sem;
204 struct sem_undo *new_semu_list, *suptr, *nsuptr;
205 int *new_semu;
206 kcondvar_t *new_semcv;
207 vaddr_t v;
208 int i, j, lsemid, nmnus, sz;
209
210 if (newsemmni < 1 || newsemmns < 1 || newsemmnu < 1)
211 return EINVAL;
212
213 /* Allocate the wired memory for our structures */
214 sz = ALIGN(newsemmni * sizeof(struct semid_ds)) +
215 ALIGN(newsemmns * sizeof(struct __sem)) +
216 ALIGN(newsemmni * sizeof(kcondvar_t)) +
217 ALIGN(newsemmnu * seminfo.semusz);
218 sz = round_page(sz);
219 v = uvm_km_alloc(kernel_map, sz, 0, UVM_KMF_WIRED|UVM_KMF_ZERO);
220 if (v == 0)
221 return ENOMEM;
222
223 mutex_enter(&semlock);
224 if (sem_realloc_state) {
225 mutex_exit(&semlock);
226 uvm_km_free(kernel_map, v, sz, UVM_KMF_WIRED);
227 return EBUSY;
228 }
229 sem_realloc_state = true;
230 if (sem_waiters) {
231 /*
232 * Mark reallocation state, wake-up all waiters,
233 * and wait while they will all exit.
234 */
235 for (i = 0; i < seminfo.semmni; i++)
236 cv_broadcast(&semcv[i]);
237 while (sem_waiters)
238 cv_wait(&sem_realloc_cv, &semlock);
239 }
240 old_sema = sema;
241
242 /* Get the number of last slot */
243 lsemid = 0;
244 for (i = 0; i < seminfo.semmni; i++)
245 if (sema[i].sem_perm.mode & SEM_ALLOC)
246 lsemid = i;
247
248 /* Get the number of currently used undo structures */
249 nmnus = 0;
250 for (i = 0; i < seminfo.semmnu; i++) {
251 suptr = SEMU(semu, i);
252 if (suptr->un_proc == NULL)
253 continue;
254 nmnus++;
255 }
256
257 /* We cannot reallocate less memory than we use */
258 if (lsemid >= newsemmni || semtot > newsemmns || nmnus > newsemmnu) {
259 mutex_exit(&semlock);
260 uvm_km_free(kernel_map, v, sz, UVM_KMF_WIRED);
261 return EBUSY;
262 }
263
264 new_sema = (void *)v;
265 new_sem = (void *)((uintptr_t)new_sema +
266 ALIGN(newsemmni * sizeof(struct semid_ds)));
267 new_semcv = (void *)((uintptr_t)new_sem +
268 ALIGN(newsemmns * sizeof(struct __sem)));
269 new_semu = (void *)((uintptr_t)new_semcv +
270 ALIGN(newsemmni * sizeof(kcondvar_t)));
271
272 /* Initialize all semaphore identifiers and condvars */
273 for (i = 0; i < newsemmni; i++) {
274 new_sema[i]._sem_base = 0;
275 new_sema[i].sem_perm.mode = 0;
276 cv_init(&new_semcv[i], "semwait");
277 }
278 for (i = 0; i < newsemmnu; i++) {
279 nsuptr = SEMU(new_semu, i);
280 nsuptr->un_proc = NULL;
281 }
282
283 /*
284 * Copy all identifiers, semaphores and list of the
285 * undo structures to the new memory allocation.
286 */
287 j = 0;
288 for (i = 0; i <= lsemid; i++) {
289 if ((sema[i].sem_perm.mode & SEM_ALLOC) == 0)
290 continue;
291 memcpy(&new_sema[i], &sema[i], sizeof(struct semid_ds));
292 new_sema[i]._sem_base = &new_sem[j];
293 memcpy(new_sema[i]._sem_base, sema[i]._sem_base,
294 (sizeof(struct __sem) * sema[i].sem_nsems));
295 j += sema[i].sem_nsems;
296 }
297 KASSERT(j == semtot);
298
299 j = 0;
300 new_semu_list = NULL;
301 for (suptr = semu_list; suptr != NULL; suptr = suptr->un_next) {
302 KASSERT(j < newsemmnu);
303 nsuptr = SEMU(new_semu, j);
304 memcpy(nsuptr, suptr, SEMUSZ);
305 nsuptr->un_next = new_semu_list;
306 new_semu_list = nsuptr;
307 j++;
308 }
309
310 for (i = 0; i < seminfo.semmni; i++) {
311 KASSERT(cv_has_waiters(&semcv[i]) == false);
312 cv_destroy(&semcv[i]);
313 }
314
315 sz = ALIGN(seminfo.semmni * sizeof(struct semid_ds)) +
316 ALIGN(seminfo.semmns * sizeof(struct __sem)) +
317 ALIGN(seminfo.semmni * sizeof(kcondvar_t)) +
318 ALIGN(seminfo.semmnu * seminfo.semusz);
319 sz = round_page(sz);
320
321 /* Set the pointers and update the new values */
322 sema = new_sema;
323 sem = new_sem;
324 semcv = new_semcv;
325 semu = new_semu;
326 semu_list = new_semu_list;
327
328 seminfo.semmni = newsemmni;
329 seminfo.semmns = newsemmns;
330 seminfo.semmnu = newsemmnu;
331
332 /* Reallocation completed - notify all waiters, if any */
333 sem_realloc_state = false;
334 cv_broadcast(&sem_realloc_cv);
335 mutex_exit(&semlock);
336
337 uvm_km_free(kernel_map, (vaddr_t)old_sema, sz, UVM_KMF_WIRED);
338 return 0;
339 }
340
341 /*
342 * Placebo.
343 */
344
345 int
346 sys_semconfig(struct lwp *l, const struct sys_semconfig_args *uap,
347 register_t *retval)
348 {
349
350 RUN_ONCE(&exithook_control, seminit_exithook);
351
352 *retval = 0;
353 return 0;
354 }
355
356 /*
357 * Allocate a new sem_undo structure for a process.
358 * => Returns NULL on failure.
359 */
360 struct sem_undo *
361 semu_alloc(struct proc *p)
362 {
363 struct sem_undo *suptr, **supptr;
364 bool attempted = false;
365 int i;
366
367 KASSERT(mutex_owned(&semlock));
368 again:
369 /* Look for a free structure. */
370 for (i = 0; i < seminfo.semmnu; i++) {
371 suptr = SEMU(semu, i);
372 if (suptr->un_proc == NULL) {
373 /* Found. Fill it in and return. */
374 suptr->un_next = semu_list;
375 semu_list = suptr;
376 suptr->un_cnt = 0;
377 suptr->un_proc = p;
378 return suptr;
379 }
380 }
381
382 /* Not found. Attempt to free some structures. */
383 if (!attempted) {
384 bool freed = false;
385
386 attempted = true;
387 supptr = &semu_list;
388 while ((suptr = *supptr) != NULL) {
389 if (suptr->un_cnt == 0) {
390 suptr->un_proc = NULL;
391 *supptr = suptr->un_next;
392 freed = true;
393 } else {
394 supptr = &suptr->un_next;
395 }
396 }
397 if (freed) {
398 goto again;
399 }
400 }
401 return NULL;
402 }
403
404 /*
405 * Adjust a particular entry for a particular proc
406 */
407
408 int
409 semundo_adjust(struct proc *p, struct sem_undo **supptr, int semid, int semnum,
410 int adjval)
411 {
412 struct sem_undo *suptr;
413 struct sem_undo_entry *sunptr;
414 int i;
415
416 KASSERT(mutex_owned(&semlock));
417
418 /*
419 * Look for and remember the sem_undo if the caller doesn't
420 * provide it
421 */
422
423 suptr = *supptr;
424 if (suptr == NULL) {
425 for (suptr = semu_list; suptr != NULL; suptr = suptr->un_next)
426 if (suptr->un_proc == p)
427 break;
428
429 if (suptr == NULL) {
430 suptr = semu_alloc(p);
431 if (suptr == NULL)
432 return (ENOSPC);
433 }
434 *supptr = suptr;
435 }
436
437 /*
438 * Look for the requested entry and adjust it (delete if
439 * adjval becomes 0).
440 */
441 sunptr = &suptr->un_ent[0];
442 for (i = 0; i < suptr->un_cnt; i++, sunptr++) {
443 if (sunptr->un_id != semid || sunptr->un_num != semnum)
444 continue;
445 sunptr->un_adjval += adjval;
446 if (sunptr->un_adjval == 0) {
447 suptr->un_cnt--;
448 if (i < suptr->un_cnt)
449 suptr->un_ent[i] =
450 suptr->un_ent[suptr->un_cnt];
451 }
452 return (0);
453 }
454
455 /* Didn't find the right entry - create it */
456 if (suptr->un_cnt == SEMUME)
457 return (EINVAL);
458
459 sunptr = &suptr->un_ent[suptr->un_cnt];
460 suptr->un_cnt++;
461 sunptr->un_adjval = adjval;
462 sunptr->un_id = semid;
463 sunptr->un_num = semnum;
464 return (0);
465 }
466
467 void
468 semundo_clear(int semid, int semnum)
469 {
470 struct sem_undo *suptr;
471 struct sem_undo_entry *sunptr, *sunend;
472
473 KASSERT(mutex_owned(&semlock));
474
475 for (suptr = semu_list; suptr != NULL; suptr = suptr->un_next)
476 for (sunptr = &suptr->un_ent[0],
477 sunend = sunptr + suptr->un_cnt; sunptr < sunend;) {
478 if (sunptr->un_id == semid) {
479 if (semnum == -1 || sunptr->un_num == semnum) {
480 suptr->un_cnt--;
481 sunend--;
482 if (sunptr != sunend)
483 *sunptr = *sunend;
484 if (semnum != -1)
485 break;
486 else
487 continue;
488 }
489 }
490 sunptr++;
491 }
492 }
493
494 int
495 sys_____semctl50(struct lwp *l, const struct sys_____semctl50_args *uap,
496 register_t *retval)
497 {
498 /* {
499 syscallarg(int) semid;
500 syscallarg(int) semnum;
501 syscallarg(int) cmd;
502 syscallarg(union __semun *) arg;
503 } */
504 struct semid_ds sembuf;
505 int cmd, error;
506 void *pass_arg;
507 union __semun karg;
508
509 RUN_ONCE(&exithook_control, seminit_exithook);
510
511 cmd = SCARG(uap, cmd);
512
513 pass_arg = get_semctl_arg(cmd, &sembuf, &karg);
514
515 if (pass_arg) {
516 error = copyin(SCARG(uap, arg), &karg, sizeof(karg));
517 if (error)
518 return error;
519 if (cmd == IPC_SET) {
520 error = copyin(karg.buf, &sembuf, sizeof(sembuf));
521 if (error)
522 return (error);
523 }
524 }
525
526 error = semctl1(l, SCARG(uap, semid), SCARG(uap, semnum), cmd,
527 pass_arg, retval);
528
529 if (error == 0 && cmd == IPC_STAT)
530 error = copyout(&sembuf, karg.buf, sizeof(sembuf));
531
532 return (error);
533 }
534
535 int
536 semctl1(struct lwp *l, int semid, int semnum, int cmd, void *v,
537 register_t *retval)
538 {
539 kauth_cred_t cred = l->l_cred;
540 union __semun *arg = v;
541 struct semid_ds *sembuf = v, *semaptr;
542 int i, error, ix;
543
544 SEM_PRINTF(("call to semctl(%d, %d, %d, %p)\n",
545 semid, semnum, cmd, v));
546
547 mutex_enter(&semlock);
548
549 ix = IPCID_TO_IX(semid);
550 if (ix < 0 || ix >= seminfo.semmni) {
551 mutex_exit(&semlock);
552 return (EINVAL);
553 }
554
555 semaptr = &sema[ix];
556 if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0 ||
557 semaptr->sem_perm._seq != IPCID_TO_SEQ(semid)) {
558 mutex_exit(&semlock);
559 return (EINVAL);
560 }
561
562 switch (cmd) {
563 case IPC_RMID:
564 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_M)) != 0)
565 break;
566 semaptr->sem_perm.cuid = kauth_cred_geteuid(cred);
567 semaptr->sem_perm.uid = kauth_cred_geteuid(cred);
568 semtot -= semaptr->sem_nsems;
569 for (i = semaptr->_sem_base - sem; i < semtot; i++)
570 sem[i] = sem[i + semaptr->sem_nsems];
571 for (i = 0; i < seminfo.semmni; i++) {
572 if ((sema[i].sem_perm.mode & SEM_ALLOC) &&
573 sema[i]._sem_base > semaptr->_sem_base)
574 sema[i]._sem_base -= semaptr->sem_nsems;
575 }
576 semaptr->sem_perm.mode = 0;
577 semundo_clear(ix, -1);
578 cv_broadcast(&semcv[ix]);
579 break;
580
581 case IPC_SET:
582 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_M)))
583 break;
584 KASSERT(sembuf != NULL);
585 semaptr->sem_perm.uid = sembuf->sem_perm.uid;
586 semaptr->sem_perm.gid = sembuf->sem_perm.gid;
587 semaptr->sem_perm.mode = (semaptr->sem_perm.mode & ~0777) |
588 (sembuf->sem_perm.mode & 0777);
589 semaptr->sem_ctime = time_second;
590 break;
591
592 case IPC_STAT:
593 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_R)))
594 break;
595 KASSERT(sembuf != NULL);
596 memset(sembuf, 0, sizeof *sembuf);
597 sembuf->sem_perm = semaptr->sem_perm;
598 sembuf->sem_perm.mode &= 0777;
599 sembuf->sem_nsems = semaptr->sem_nsems;
600 sembuf->sem_otime = semaptr->sem_otime;
601 sembuf->sem_ctime = semaptr->sem_ctime;
602 break;
603
604 case GETNCNT:
605 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_R)))
606 break;
607 if (semnum < 0 || semnum >= semaptr->sem_nsems) {
608 error = EINVAL;
609 break;
610 }
611 *retval = semaptr->_sem_base[semnum].semncnt;
612 break;
613
614 case GETPID:
615 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_R)))
616 break;
617 if (semnum < 0 || semnum >= semaptr->sem_nsems) {
618 error = EINVAL;
619 break;
620 }
621 *retval = semaptr->_sem_base[semnum].sempid;
622 break;
623
624 case GETVAL:
625 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_R)))
626 break;
627 if (semnum < 0 || semnum >= semaptr->sem_nsems) {
628 error = EINVAL;
629 break;
630 }
631 *retval = semaptr->_sem_base[semnum].semval;
632 break;
633
634 case GETALL:
635 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_R)))
636 break;
637 KASSERT(arg != NULL);
638 for (i = 0; i < semaptr->sem_nsems; i++) {
639 error = copyout(&semaptr->_sem_base[i].semval,
640 &arg->array[i], sizeof(arg->array[i]));
641 if (error != 0)
642 break;
643 }
644 break;
645
646 case GETZCNT:
647 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_R)))
648 break;
649 if (semnum < 0 || semnum >= semaptr->sem_nsems) {
650 error = EINVAL;
651 break;
652 }
653 *retval = semaptr->_sem_base[semnum].semzcnt;
654 break;
655
656 case SETVAL:
657 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_W)))
658 break;
659 if (semnum < 0 || semnum >= semaptr->sem_nsems) {
660 error = EINVAL;
661 break;
662 }
663 KASSERT(arg != NULL);
664 if ((unsigned int)arg->val > seminfo.semvmx) {
665 error = ERANGE;
666 break;
667 }
668 semaptr->_sem_base[semnum].semval = arg->val;
669 semundo_clear(ix, semnum);
670 cv_broadcast(&semcv[ix]);
671 break;
672
673 case SETALL:
674 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_W)))
675 break;
676 KASSERT(arg != NULL);
677 for (i = 0; i < semaptr->sem_nsems; i++) {
678 unsigned short semval;
679 error = copyin(&arg->array[i], &semval,
680 sizeof(arg->array[i]));
681 if (error != 0)
682 break;
683 if ((unsigned int)semval > seminfo.semvmx) {
684 error = ERANGE;
685 break;
686 }
687 semaptr->_sem_base[i].semval = semval;
688 }
689 semundo_clear(ix, -1);
690 cv_broadcast(&semcv[ix]);
691 break;
692
693 default:
694 error = EINVAL;
695 break;
696 }
697
698 mutex_exit(&semlock);
699 return (error);
700 }
701
702 int
703 sys_semget(struct lwp *l, const struct sys_semget_args *uap,
704 register_t *retval)
705 {
706 /* {
707 syscallarg(key_t) key;
708 syscallarg(int) nsems;
709 syscallarg(int) semflg;
710 } */
711 int semid, error = 0;
712 int key = SCARG(uap, key);
713 int nsems = SCARG(uap, nsems);
714 int semflg = SCARG(uap, semflg);
715 kauth_cred_t cred = l->l_cred;
716
717 RUN_ONCE(&exithook_control, seminit_exithook);
718
719 SEM_PRINTF(("semget(0x%x, %d, 0%o)\n", key, nsems, semflg));
720
721 mutex_enter(&semlock);
722
723 if (key != IPC_PRIVATE) {
724 for (semid = 0; semid < seminfo.semmni; semid++) {
725 if ((sema[semid].sem_perm.mode & SEM_ALLOC) &&
726 sema[semid].sem_perm._key == key)
727 break;
728 }
729 if (semid < seminfo.semmni) {
730 SEM_PRINTF(("found public key\n"));
731 if ((error = ipcperm(cred, &sema[semid].sem_perm,
732 semflg & 0700)))
733 goto out;
734 if (nsems > 0 && sema[semid].sem_nsems < nsems) {
735 SEM_PRINTF(("too small\n"));
736 error = EINVAL;
737 goto out;
738 }
739 if ((semflg & IPC_CREAT) && (semflg & IPC_EXCL)) {
740 SEM_PRINTF(("not exclusive\n"));
741 error = EEXIST;
742 goto out;
743 }
744 goto found;
745 }
746 }
747
748 SEM_PRINTF(("need to allocate the semid_ds\n"));
749 if (key == IPC_PRIVATE || (semflg & IPC_CREAT)) {
750 if (nsems <= 0 || nsems > seminfo.semmsl) {
751 SEM_PRINTF(("nsems out of range (0<%d<=%d)\n", nsems,
752 seminfo.semmsl));
753 error = EINVAL;
754 goto out;
755 }
756 if (nsems > seminfo.semmns - semtot) {
757 SEM_PRINTF(("not enough semaphores left "
758 "(need %d, got %d)\n",
759 nsems, seminfo.semmns - semtot));
760 error = ENOSPC;
761 goto out;
762 }
763 for (semid = 0; semid < seminfo.semmni; semid++) {
764 if ((sema[semid].sem_perm.mode & SEM_ALLOC) == 0)
765 break;
766 }
767 if (semid == seminfo.semmni) {
768 SEM_PRINTF(("no more semid_ds's available\n"));
769 error = ENOSPC;
770 goto out;
771 }
772 SEM_PRINTF(("semid %d is available\n", semid));
773 sema[semid].sem_perm._key = key;
774 sema[semid].sem_perm.cuid = kauth_cred_geteuid(cred);
775 sema[semid].sem_perm.uid = kauth_cred_geteuid(cred);
776 sema[semid].sem_perm.cgid = kauth_cred_getegid(cred);
777 sema[semid].sem_perm.gid = kauth_cred_getegid(cred);
778 sema[semid].sem_perm.mode = (semflg & 0777) | SEM_ALLOC;
779 sema[semid].sem_perm._seq =
780 (sema[semid].sem_perm._seq + 1) & 0x7fff;
781 sema[semid].sem_nsems = nsems;
782 sema[semid].sem_otime = 0;
783 sema[semid].sem_ctime = time_second;
784 sema[semid]._sem_base = &sem[semtot];
785 semtot += nsems;
786 memset(sema[semid]._sem_base, 0,
787 sizeof(sema[semid]._sem_base[0]) * nsems);
788 SEM_PRINTF(("sembase = %p, next = %p\n", sema[semid]._sem_base,
789 &sem[semtot]));
790 } else {
791 SEM_PRINTF(("didn't find it and wasn't asked to create it\n"));
792 error = ENOENT;
793 goto out;
794 }
795
796 found:
797 *retval = IXSEQ_TO_IPCID(semid, sema[semid].sem_perm);
798 out:
799 mutex_exit(&semlock);
800 return (error);
801 }
802
803 #define SMALL_SOPS 8
804
805 void
806 do_semop_init(void)
807 {
808
809 RUN_ONCE(&exithook_control, seminit_exithook);
810 }
811
812 /* all pointers already in kernel space */
813 int
814 do_semop1(struct lwp *l, int usemid, struct sembuf *sops,
815 size_t nsops, struct timespec *timeout, register_t *retval)
816 {
817 struct proc *p = l->l_proc;
818 int semid, seq;
819 struct semid_ds *semaptr;
820 struct sembuf *sopptr = NULL;
821 struct __sem *semptr = NULL;
822 struct sem_undo *suptr = NULL;
823 kauth_cred_t cred = l->l_cred;
824 int timo = 0;
825 int i, error;
826 int do_wakeup, do_undos;
827
828 RUN_ONCE(&exithook_control, seminit_exithook);
829
830 SEM_PRINTF(("do_semop1(%d, %p, %zu)\n", usemid, sops, nsops));
831
832 if (__predict_false((p->p_flag & PK_SYSVSEM) == 0)) {
833 mutex_enter(p->p_lock);
834 p->p_flag |= PK_SYSVSEM;
835 mutex_exit(p->p_lock);
836 }
837
838 restart:
839 mutex_enter(&semlock);
840 /* In case of reallocation, we will wait for completion */
841 while (__predict_false(sem_realloc_state))
842 cv_wait(&sem_realloc_cv, &semlock);
843
844 semid = IPCID_TO_IX(usemid); /* Convert back to zero origin */
845 if (semid < 0 || semid >= seminfo.semmni) {
846 error = EINVAL;
847 goto out;
848 }
849
850 if (timeout) {
851 error = ts2timo(CLOCK_MONOTONIC, TIMER_RELTIME, timeout,
852 &timo, NULL);
853 if (error)
854 return error;
855 }
856
857 semaptr = &sema[semid];
858 seq = IPCID_TO_SEQ(usemid);
859 if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0 ||
860 semaptr->sem_perm._seq != seq) {
861 error = EINVAL;
862 goto out;
863 }
864
865 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_W))) {
866 SEM_PRINTF(("error = %d from ipaccess\n", error));
867 goto out;
868 }
869
870 for (i = 0; i < nsops; i++)
871 if (sops[i].sem_num >= semaptr->sem_nsems) {
872 error = EFBIG;
873 goto out;
874 }
875 /*
876 * Loop trying to satisfy the vector of requests.
877 * If we reach a point where we must wait, any requests already
878 * performed are rolled back and we go to sleep until some other
879 * process wakes us up. At this point, we start all over again.
880 *
881 * This ensures that from the perspective of other tasks, a set
882 * of requests is atomic (never partially satisfied).
883 */
884 do_undos = 0;
885
886 for (;;) {
887 do_wakeup = 0;
888
889 for (i = 0; i < nsops; i++) {
890 sopptr = &sops[i];
891 semptr = &semaptr->_sem_base[sopptr->sem_num];
892
893 SEM_PRINTF(("semop: semaptr=%p, sem_base=%p, "
894 "semptr=%p, sem[%d]=%d : op=%d, flag=%s\n",
895 semaptr, semaptr->_sem_base, semptr,
896 sopptr->sem_num, semptr->semval, sopptr->sem_op,
897 (sopptr->sem_flg & IPC_NOWAIT) ?
898 "nowait" : "wait"));
899
900 if (sopptr->sem_op < 0) {
901 if ((int)(semptr->semval +
902 sopptr->sem_op) < 0) {
903 SEM_PRINTF(("semop: "
904 "can't do it now\n"));
905 break;
906 } else {
907 semptr->semval += sopptr->sem_op;
908 if (semptr->semval == 0 &&
909 semptr->semzcnt > 0)
910 do_wakeup = 1;
911 }
912 if (sopptr->sem_flg & SEM_UNDO)
913 do_undos = 1;
914 } else if (sopptr->sem_op == 0) {
915 if (semptr->semval > 0) {
916 SEM_PRINTF(("semop: not zero now\n"));
917 break;
918 }
919 } else {
920 if (semptr->semncnt > 0)
921 do_wakeup = 1;
922 semptr->semval += sopptr->sem_op;
923 if (sopptr->sem_flg & SEM_UNDO)
924 do_undos = 1;
925 }
926 }
927
928 /*
929 * Did we get through the entire vector?
930 */
931 if (i >= nsops)
932 goto done;
933
934 /*
935 * No ... rollback anything that we've already done
936 */
937 SEM_PRINTF(("semop: rollback 0 through %d\n", i - 1));
938 while (i-- > 0)
939 semaptr->_sem_base[sops[i].sem_num].semval -=
940 sops[i].sem_op;
941
942 /*
943 * If the request that we couldn't satisfy has the
944 * NOWAIT flag set then return with EAGAIN.
945 */
946 if (sopptr->sem_flg & IPC_NOWAIT) {
947 error = EAGAIN;
948 goto out;
949 }
950
951 if (sopptr->sem_op == 0)
952 semptr->semzcnt++;
953 else
954 semptr->semncnt++;
955
956 sem_waiters++;
957 SEM_PRINTF(("semop: good night!\n"));
958 error = cv_timedwait_sig(&semcv[semid], &semlock, timo);
959 SEM_PRINTF(("semop: good morning (error=%d)!\n", error));
960 sem_waiters--;
961
962 /* Notify reallocator, if it is waiting */
963 cv_broadcast(&sem_realloc_cv);
964
965 /*
966 * Make sure that the semaphore still exists
967 */
968 if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0 ||
969 semaptr->sem_perm._seq != seq) {
970 error = EIDRM;
971 goto out;
972 }
973
974 /*
975 * The semaphore is still alive. Readjust the count of
976 * waiting processes.
977 */
978 semptr = &semaptr->_sem_base[sopptr->sem_num];
979 if (sopptr->sem_op == 0)
980 semptr->semzcnt--;
981 else
982 semptr->semncnt--;
983
984 /* In case of such state, restart the call */
985 if (sem_realloc_state) {
986 mutex_exit(&semlock);
987 goto restart;
988 }
989
990 /* Is it really morning, or was our sleep interrupted? */
991 if (error != 0) {
992 if (error == ERESTART)
993 error = EINTR; // Simplify to just EINTR
994 else if (error == EWOULDBLOCK)
995 error = EAGAIN; // Convert timeout to EAGAIN
996 goto out;
997 }
998 SEM_PRINTF(("semop: good morning!\n"));
999 }
1000 done:
1001 /*
1002 * Process any SEM_UNDO requests.
1003 */
1004 if (do_undos) {
1005 for (i = 0; i < nsops; i++) {
1006 /*
1007 * We only need to deal with SEM_UNDO's for non-zero
1008 * op's.
1009 */
1010 int adjval;
1011
1012 if ((sops[i].sem_flg & SEM_UNDO) == 0)
1013 continue;
1014 adjval = sops[i].sem_op;
1015 if (adjval == 0)
1016 continue;
1017 error = semundo_adjust(p, &suptr, semid,
1018 sops[i].sem_num, -adjval);
1019 if (error == 0)
1020 continue;
1021
1022 /*
1023 * Oh-Oh! We ran out of either sem_undo's or undo's.
1024 * Rollback the adjustments to this point and then
1025 * rollback the semaphore ups and down so we can return
1026 * with an error with all structures restored. We
1027 * rollback the undo's in the exact reverse order that
1028 * we applied them. This guarantees that we won't run
1029 * out of space as we roll things back out.
1030 */
1031 while (i-- > 0) {
1032 if ((sops[i].sem_flg & SEM_UNDO) == 0)
1033 continue;
1034 adjval = sops[i].sem_op;
1035 if (adjval == 0)
1036 continue;
1037 if (semundo_adjust(p, &suptr, semid,
1038 sops[i].sem_num, adjval) != 0)
1039 panic("semop - can't undo undos");
1040 }
1041
1042 for (i = 0; i < nsops; i++)
1043 semaptr->_sem_base[sops[i].sem_num].semval -=
1044 sops[i].sem_op;
1045
1046 SEM_PRINTF(("error = %d from semundo_adjust\n",
1047 error));
1048 goto out;
1049 } /* loop through the sops */
1050 } /* if (do_undos) */
1051
1052 /* We're definitely done - set the sempid's */
1053 for (i = 0; i < nsops; i++) {
1054 sopptr = &sops[i];
1055 semptr = &semaptr->_sem_base[sopptr->sem_num];
1056 semptr->sempid = p->p_pid;
1057 }
1058
1059 /* Update sem_otime */
1060 semaptr->sem_otime = time_second;
1061
1062 /* Do a wakeup if any semaphore was up'd. */
1063 if (do_wakeup) {
1064 SEM_PRINTF(("semop: doing wakeup\n"));
1065 cv_broadcast(&semcv[semid]);
1066 SEM_PRINTF(("semop: back from wakeup\n"));
1067 }
1068 SEM_PRINTF(("semop: done\n"));
1069 *retval = 0;
1070
1071 out:
1072 mutex_exit(&semlock);
1073 return error;
1074 }
1075
1076 static int
1077 do_semop(struct lwp *l, int usemid, struct sembuf *usops,
1078 size_t nsops, struct timespec *utimeout, register_t *retval)
1079 {
1080 struct sembuf small_sops[SMALL_SOPS];
1081 struct sembuf *sops;
1082 struct timespec timeout;
1083 int error;
1084
1085 do_semop_init();
1086
1087 SEM_PRINTF(("do_semop(%d, %p, %zu)\n", usemid, usops, nsops));
1088
1089 if (nsops <= SMALL_SOPS) {
1090 sops = small_sops;
1091 } else if (seminfo.semopm > 0 && nsops <= (size_t)seminfo.semopm) {
1092 sops = kmem_alloc(nsops * sizeof(*sops), KM_SLEEP);
1093 } else {
1094 SEM_PRINTF(("too many sops (max=%d, nsops=%zu)\n",
1095 seminfo.semopm, nsops));
1096 return (E2BIG);
1097 }
1098
1099 error = copyin(usops, sops, nsops * sizeof(sops[0]));
1100 if (error) {
1101 SEM_PRINTF(("error = %d from copyin(%p, %p, %zu)\n", error,
1102 usops, &sops, nsops * sizeof(sops[0])));
1103 if (sops != small_sops)
1104 kmem_free(sops, nsops * sizeof(*sops));
1105 return error;
1106 }
1107
1108 if (utimeout) {
1109 error = copyin(utimeout, &timeout, sizeof(timeout));
1110 if (error) {
1111 SEM_PRINTF(("error = %d from copyin(%p, %p, %zu)\n",
1112 error, utimeout, &timeout, sizeof(timeout)));
1113 return error;
1114 }
1115 }
1116
1117 error = do_semop1(l, usemid, sops, nsops, utimeout ? &timeout : NULL,
1118 retval);
1119
1120 if (sops != small_sops)
1121 kmem_free(sops, nsops * sizeof(*sops));
1122
1123 return error;
1124 }
1125
1126 int
1127 sys_semtimedop(struct lwp *l, const struct sys_semtimedop_args *uap,
1128 register_t *retval)
1129 {
1130 /* {
1131 syscallarg(int) semid;
1132 syscallarg(struct sembuf *) sops;
1133 syscallarg(size_t) nsops;
1134 syscallarg(struct timespec) timeout;
1135 } */
1136 int semid = SCARG(uap, semid);
1137 struct sembuf *sops = SCARG(uap, sops);
1138 size_t nsops = SCARG(uap, nsops);
1139 struct timespec *utimeout = SCARG(uap, timeout);
1140
1141 return do_semop(l, semid, sops, nsops, utimeout, retval);
1142 }
1143
1144 int
1145 sys_semop(struct lwp *l, const struct sys_semop_args *uap, register_t *retval)
1146 {
1147 /* {
1148 syscallarg(int) semid;
1149 syscallarg(struct sembuf *) sops;
1150 syscallarg(size_t) nsops;
1151 } */
1152 int semid = SCARG(uap, semid);
1153 struct sembuf *sops = SCARG(uap, sops);
1154 size_t nsops = SCARG(uap, nsops);
1155
1156 return do_semop(l, semid, sops, nsops, NULL, retval);
1157 }
1158
1159 /*
1160 * Go through the undo structures for this process and apply the
1161 * adjustments to semaphores.
1162 */
1163 /*ARGSUSED*/
1164 void
1165 semexit(struct proc *p, void *v)
1166 {
1167 struct sem_undo *suptr;
1168 struct sem_undo **supptr;
1169
1170 if ((p->p_flag & PK_SYSVSEM) == 0)
1171 return;
1172
1173 mutex_enter(&semlock);
1174
1175 /*
1176 * Go through the chain of undo vectors looking for one
1177 * associated with this process.
1178 */
1179
1180 for (supptr = &semu_list; (suptr = *supptr) != NULL;
1181 supptr = &suptr->un_next) {
1182 if (suptr->un_proc == p)
1183 break;
1184 }
1185
1186 /*
1187 * If there is no undo vector, skip to the end.
1188 */
1189
1190 if (suptr == NULL) {
1191 mutex_exit(&semlock);
1192 return;
1193 }
1194
1195 /*
1196 * We now have an undo vector for this process.
1197 */
1198
1199 SEM_PRINTF(("proc @%p has undo structure with %d entries\n", p,
1200 suptr->un_cnt));
1201
1202 /*
1203 * If there are any active undo elements then process them.
1204 */
1205 if (suptr->un_cnt > 0) {
1206 int ix;
1207
1208 for (ix = 0; ix < suptr->un_cnt; ix++) {
1209 int semid = suptr->un_ent[ix].un_id;
1210 int semnum = suptr->un_ent[ix].un_num;
1211 int adjval = suptr->un_ent[ix].un_adjval;
1212 struct semid_ds *semaptr;
1213
1214 semaptr = &sema[semid];
1215 if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0)
1216 if (semnum >= semaptr->sem_nsems)
1217 panic("semexit - semnum out of range");
1218
1219 SEM_PRINTF(("semexit: %p id=%d num=%d(adj=%d) ; "
1220 "sem=%d\n",
1221 suptr->un_proc, suptr->un_ent[ix].un_id,
1222 suptr->un_ent[ix].un_num,
1223 suptr->un_ent[ix].un_adjval,
1224 semaptr->_sem_base[semnum].semval));
1225
1226 if (adjval < 0 &&
1227 semaptr->_sem_base[semnum].semval < -adjval)
1228 semaptr->_sem_base[semnum].semval = 0;
1229 else
1230 semaptr->_sem_base[semnum].semval += adjval;
1231
1232 cv_broadcast(&semcv[semid]);
1233 SEM_PRINTF(("semexit: back from wakeup\n"));
1234 }
1235 }
1236
1237 /*
1238 * Deallocate the undo vector.
1239 */
1240 SEM_PRINTF(("removing vector\n"));
1241 suptr->un_proc = NULL;
1242 *supptr = suptr->un_next;
1243 mutex_exit(&semlock);
1244 }
1245
1246 /*
1247 * Sysctl initialization and nodes.
1248 */
1249
1250 static int
1251 sysctl_ipc_semmni(SYSCTLFN_ARGS)
1252 {
1253 int newsize, error;
1254 struct sysctlnode node;
1255 node = *rnode;
1256 node.sysctl_data = &newsize;
1257
1258 newsize = seminfo.semmni;
1259 error = sysctl_lookup(SYSCTLFN_CALL(&node));
1260 if (error || newp == NULL)
1261 return error;
1262
1263 return semrealloc(newsize, seminfo.semmns, seminfo.semmnu);
1264 }
1265
1266 static int
1267 sysctl_ipc_semmns(SYSCTLFN_ARGS)
1268 {
1269 int newsize, error;
1270 struct sysctlnode node;
1271 node = *rnode;
1272 node.sysctl_data = &newsize;
1273
1274 newsize = seminfo.semmns;
1275 error = sysctl_lookup(SYSCTLFN_CALL(&node));
1276 if (error || newp == NULL)
1277 return error;
1278
1279 return semrealloc(seminfo.semmni, newsize, seminfo.semmnu);
1280 }
1281
1282 static int
1283 sysctl_ipc_semmnu(SYSCTLFN_ARGS)
1284 {
1285 int newsize, error;
1286 struct sysctlnode node;
1287 node = *rnode;
1288 node.sysctl_data = &newsize;
1289
1290 newsize = seminfo.semmnu;
1291 error = sysctl_lookup(SYSCTLFN_CALL(&node));
1292 if (error || newp == NULL)
1293 return error;
1294
1295 return semrealloc(seminfo.semmni, seminfo.semmns, newsize);
1296 }
1297
1298 SYSCTL_SETUP(sysctl_ipc_sem_setup, "sysctl kern.ipc subtree setup")
1299 {
1300 const struct sysctlnode *node = NULL;
1301
1302 sysctl_createv(clog, 0, NULL, &node,
1303 CTLFLAG_PERMANENT,
1304 CTLTYPE_NODE, "ipc",
1305 SYSCTL_DESCR("SysV IPC options"),
1306 NULL, 0, NULL, 0,
1307 CTL_KERN, KERN_SYSVIPC, CTL_EOL);
1308
1309 if (node == NULL)
1310 return;
1311
1312 sysctl_createv(clog, 0, &node, NULL,
1313 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
1314 CTLTYPE_INT, "semmni",
1315 SYSCTL_DESCR("Max number of number of semaphore identifiers"),
1316 sysctl_ipc_semmni, 0, &seminfo.semmni, 0,
1317 CTL_CREATE, CTL_EOL);
1318 sysctl_createv(clog, 0, &node, NULL,
1319 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
1320 CTLTYPE_INT, "semmns",
1321 SYSCTL_DESCR("Max number of number of semaphores in system"),
1322 sysctl_ipc_semmns, 0, &seminfo.semmns, 0,
1323 CTL_CREATE, CTL_EOL);
1324 sysctl_createv(clog, 0, &node, NULL,
1325 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
1326 CTLTYPE_INT, "semmnu",
1327 SYSCTL_DESCR("Max number of undo structures in system"),
1328 sysctl_ipc_semmnu, 0, &seminfo.semmnu, 0,
1329 CTL_CREATE, CTL_EOL);
1330 }
1331