sysv_sem.c revision 1.102 1 /* $NetBSD: sysv_sem.c,v 1.102 2025/05/09 10:22:55 martin 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.102 2025/05/09 10:22:55 martin 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, register_t *retval)
347 {
348
349 RUN_ONCE(&exithook_control, seminit_exithook);
350
351 *retval = 0;
352 return 0;
353 }
354
355 /*
356 * Allocate a new sem_undo structure for a process.
357 * => Returns NULL on failure.
358 */
359 struct sem_undo *
360 semu_alloc(struct proc *p)
361 {
362 struct sem_undo *suptr, **supptr;
363 bool attempted = false;
364 int i;
365
366 KASSERT(mutex_owned(&semlock));
367 again:
368 /* Look for a free structure. */
369 for (i = 0; i < seminfo.semmnu; i++) {
370 suptr = SEMU(semu, i);
371 if (suptr->un_proc == NULL) {
372 /* Found. Fill it in and return. */
373 suptr->un_next = semu_list;
374 semu_list = suptr;
375 suptr->un_cnt = 0;
376 suptr->un_proc = p;
377 return suptr;
378 }
379 }
380
381 /* Not found. Attempt to free some structures. */
382 if (!attempted) {
383 bool freed = false;
384
385 attempted = true;
386 supptr = &semu_list;
387 while ((suptr = *supptr) != NULL) {
388 if (suptr->un_cnt == 0) {
389 suptr->un_proc = NULL;
390 *supptr = suptr->un_next;
391 freed = true;
392 } else {
393 supptr = &suptr->un_next;
394 }
395 }
396 if (freed) {
397 goto again;
398 }
399 }
400 return NULL;
401 }
402
403 /*
404 * Adjust a particular entry for a particular proc
405 */
406
407 int
408 semundo_adjust(struct proc *p, struct sem_undo **supptr, int semid, int semnum,
409 int adjval)
410 {
411 struct sem_undo *suptr;
412 struct sem_undo_entry *sunptr;
413 int i;
414
415 KASSERT(mutex_owned(&semlock));
416
417 /*
418 * Look for and remember the sem_undo if the caller doesn't
419 * provide it
420 */
421
422 suptr = *supptr;
423 if (suptr == NULL) {
424 for (suptr = semu_list; suptr != NULL; suptr = suptr->un_next)
425 if (suptr->un_proc == p)
426 break;
427
428 if (suptr == NULL) {
429 suptr = semu_alloc(p);
430 if (suptr == NULL)
431 return (ENOSPC);
432 }
433 *supptr = suptr;
434 }
435
436 /*
437 * Look for the requested entry and adjust it (delete if
438 * adjval becomes 0).
439 */
440 sunptr = &suptr->un_ent[0];
441 for (i = 0; i < suptr->un_cnt; i++, sunptr++) {
442 if (sunptr->un_id != semid || sunptr->un_num != semnum)
443 continue;
444 sunptr->un_adjval += adjval;
445 if (sunptr->un_adjval == 0) {
446 suptr->un_cnt--;
447 if (i < suptr->un_cnt)
448 suptr->un_ent[i] =
449 suptr->un_ent[suptr->un_cnt];
450 }
451 return (0);
452 }
453
454 /* Didn't find the right entry - create it */
455 if (suptr->un_cnt == SEMUME)
456 return (EINVAL);
457
458 sunptr = &suptr->un_ent[suptr->un_cnt];
459 suptr->un_cnt++;
460 sunptr->un_adjval = adjval;
461 sunptr->un_id = semid;
462 sunptr->un_num = semnum;
463 return (0);
464 }
465
466 void
467 semundo_clear(int semid, int semnum)
468 {
469 struct sem_undo *suptr;
470 struct sem_undo_entry *sunptr, *sunend;
471
472 KASSERT(mutex_owned(&semlock));
473
474 for (suptr = semu_list; suptr != NULL; suptr = suptr->un_next)
475 for (sunptr = &suptr->un_ent[0],
476 sunend = sunptr + suptr->un_cnt; sunptr < sunend;) {
477 if (sunptr->un_id == semid) {
478 if (semnum == -1 || sunptr->un_num == semnum) {
479 suptr->un_cnt--;
480 sunend--;
481 if (sunptr != sunend)
482 *sunptr = *sunend;
483 if (semnum != -1)
484 break;
485 else
486 continue;
487 }
488 }
489 sunptr++;
490 }
491 }
492
493 int
494 sys_____semctl50(struct lwp *l, const struct sys_____semctl50_args *uap,
495 register_t *retval)
496 {
497 /* {
498 syscallarg(int) semid;
499 syscallarg(int) semnum;
500 syscallarg(int) cmd;
501 syscallarg(union __semun *) arg;
502 } */
503 struct semid_ds sembuf;
504 int cmd, error;
505 void *pass_arg;
506 union __semun karg;
507
508 RUN_ONCE(&exithook_control, seminit_exithook);
509
510 cmd = SCARG(uap, cmd);
511
512 pass_arg = get_semctl_arg(cmd, &sembuf, &karg);
513
514 if (pass_arg) {
515 error = copyin(SCARG(uap, arg), &karg, sizeof(karg));
516 if (error)
517 return error;
518 if (cmd == IPC_SET) {
519 error = copyin(karg.buf, &sembuf, sizeof(sembuf));
520 if (error)
521 return (error);
522 }
523 }
524
525 error = semctl1(l, SCARG(uap, semid), SCARG(uap, semnum), cmd,
526 pass_arg, retval);
527
528 if (error == 0 && cmd == IPC_STAT)
529 error = copyout(&sembuf, karg.buf, sizeof(sembuf));
530
531 return (error);
532 }
533
534 int
535 semctl1(struct lwp *l, int semid, int semnum, int cmd, void *v,
536 register_t *retval)
537 {
538 kauth_cred_t cred = l->l_cred;
539 union __semun *arg = v;
540 struct semid_ds *sembuf = v, *semaptr;
541 int i, error, ix;
542
543 SEM_PRINTF(("call to semctl(%d, %d, %d, %p)\n",
544 semid, semnum, cmd, v));
545
546 mutex_enter(&semlock);
547
548 ix = IPCID_TO_IX(semid);
549 if (ix < 0 || ix >= seminfo.semmni) {
550 mutex_exit(&semlock);
551 return (EINVAL);
552 }
553
554 semaptr = &sema[ix];
555 if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0 ||
556 semaptr->sem_perm._seq != IPCID_TO_SEQ(semid)) {
557 mutex_exit(&semlock);
558 return (EINVAL);
559 }
560
561 switch (cmd) {
562 case IPC_RMID:
563 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_M)) != 0)
564 break;
565 semaptr->sem_perm.cuid = kauth_cred_geteuid(cred);
566 semaptr->sem_perm.uid = kauth_cred_geteuid(cred);
567 semtot -= semaptr->sem_nsems;
568 for (i = semaptr->_sem_base - sem; i < semtot; i++)
569 sem[i] = sem[i + semaptr->sem_nsems];
570 for (i = 0; i < seminfo.semmni; i++) {
571 if ((sema[i].sem_perm.mode & SEM_ALLOC) &&
572 sema[i]._sem_base > semaptr->_sem_base)
573 sema[i]._sem_base -= semaptr->sem_nsems;
574 }
575 semaptr->sem_perm.mode = 0;
576 semundo_clear(ix, -1);
577 cv_broadcast(&semcv[ix]);
578 break;
579
580 case IPC_SET:
581 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_M)))
582 break;
583 KASSERT(sembuf != NULL);
584 semaptr->sem_perm.uid = sembuf->sem_perm.uid;
585 semaptr->sem_perm.gid = sembuf->sem_perm.gid;
586 semaptr->sem_perm.mode = (semaptr->sem_perm.mode & ~0777) |
587 (sembuf->sem_perm.mode & 0777);
588 semaptr->sem_ctime = time_second;
589 break;
590
591 case IPC_STAT:
592 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_R)))
593 break;
594 KASSERT(sembuf != NULL);
595 memset(sembuf, 0, sizeof *sembuf);
596 sembuf->sem_perm = semaptr->sem_perm;
597 sembuf->sem_perm.mode &= 0777;
598 sembuf->sem_nsems = semaptr->sem_nsems;
599 sembuf->sem_otime = semaptr->sem_otime;
600 sembuf->sem_ctime = semaptr->sem_ctime;
601 break;
602
603 case GETNCNT:
604 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_R)))
605 break;
606 if (semnum < 0 || semnum >= semaptr->sem_nsems) {
607 error = EINVAL;
608 break;
609 }
610 *retval = semaptr->_sem_base[semnum].semncnt;
611 break;
612
613 case GETPID:
614 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_R)))
615 break;
616 if (semnum < 0 || semnum >= semaptr->sem_nsems) {
617 error = EINVAL;
618 break;
619 }
620 *retval = semaptr->_sem_base[semnum].sempid;
621 break;
622
623 case GETVAL:
624 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_R)))
625 break;
626 if (semnum < 0 || semnum >= semaptr->sem_nsems) {
627 error = EINVAL;
628 break;
629 }
630 *retval = semaptr->_sem_base[semnum].semval;
631 break;
632
633 case GETALL:
634 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_R)))
635 break;
636 KASSERT(arg != NULL);
637 for (i = 0; i < semaptr->sem_nsems; i++) {
638 error = copyout(&semaptr->_sem_base[i].semval,
639 &arg->array[i], sizeof(arg->array[i]));
640 if (error != 0)
641 break;
642 }
643 break;
644
645 case GETZCNT:
646 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_R)))
647 break;
648 if (semnum < 0 || semnum >= semaptr->sem_nsems) {
649 error = EINVAL;
650 break;
651 }
652 *retval = semaptr->_sem_base[semnum].semzcnt;
653 break;
654
655 case SETVAL:
656 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_W)))
657 break;
658 if (semnum < 0 || semnum >= semaptr->sem_nsems) {
659 error = EINVAL;
660 break;
661 }
662 KASSERT(arg != NULL);
663 if ((unsigned int)arg->val > seminfo.semvmx) {
664 error = ERANGE;
665 break;
666 }
667 semaptr->_sem_base[semnum].semval = arg->val;
668 semundo_clear(ix, semnum);
669 cv_broadcast(&semcv[ix]);
670 break;
671
672 case SETALL:
673 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_W)))
674 break;
675 KASSERT(arg != NULL);
676 for (i = 0; i < semaptr->sem_nsems; i++) {
677 unsigned short semval;
678 error = copyin(&arg->array[i], &semval,
679 sizeof(arg->array[i]));
680 if (error != 0)
681 break;
682 if ((unsigned int)semval > seminfo.semvmx) {
683 error = ERANGE;
684 break;
685 }
686 semaptr->_sem_base[i].semval = semval;
687 }
688 semundo_clear(ix, -1);
689 cv_broadcast(&semcv[ix]);
690 break;
691
692 default:
693 error = EINVAL;
694 break;
695 }
696
697 mutex_exit(&semlock);
698 return (error);
699 }
700
701 int
702 sys_semget(struct lwp *l, const struct sys_semget_args *uap, register_t *retval)
703 {
704 /* {
705 syscallarg(key_t) key;
706 syscallarg(int) nsems;
707 syscallarg(int) semflg;
708 } */
709 int semid, error = 0;
710 int key = SCARG(uap, key);
711 int nsems = SCARG(uap, nsems);
712 int semflg = SCARG(uap, semflg);
713 kauth_cred_t cred = l->l_cred;
714
715 RUN_ONCE(&exithook_control, seminit_exithook);
716
717 SEM_PRINTF(("semget(0x%x, %d, 0%o)\n", key, nsems, semflg));
718
719 mutex_enter(&semlock);
720
721 if (key != IPC_PRIVATE) {
722 for (semid = 0; semid < seminfo.semmni; semid++) {
723 if ((sema[semid].sem_perm.mode & SEM_ALLOC) &&
724 sema[semid].sem_perm._key == key)
725 break;
726 }
727 if (semid < seminfo.semmni) {
728 SEM_PRINTF(("found public key\n"));
729 if ((error = ipcperm(cred, &sema[semid].sem_perm,
730 semflg & 0700)))
731 goto out;
732 if (nsems > 0 && sema[semid].sem_nsems < nsems) {
733 SEM_PRINTF(("too small\n"));
734 error = EINVAL;
735 goto out;
736 }
737 if ((semflg & IPC_CREAT) && (semflg & IPC_EXCL)) {
738 SEM_PRINTF(("not exclusive\n"));
739 error = EEXIST;
740 goto out;
741 }
742 goto found;
743 }
744 }
745
746 SEM_PRINTF(("need to allocate the semid_ds\n"));
747 if (key == IPC_PRIVATE || (semflg & IPC_CREAT)) {
748 if (nsems <= 0 || nsems > seminfo.semmsl) {
749 SEM_PRINTF(("nsems out of range (0<%d<=%d)\n", nsems,
750 seminfo.semmsl));
751 error = EINVAL;
752 goto out;
753 }
754 if (nsems > seminfo.semmns - semtot) {
755 SEM_PRINTF(("not enough semaphores left "
756 "(need %d, got %d)\n",
757 nsems, seminfo.semmns - semtot));
758 error = ENOSPC;
759 goto out;
760 }
761 for (semid = 0; semid < seminfo.semmni; semid++) {
762 if ((sema[semid].sem_perm.mode & SEM_ALLOC) == 0)
763 break;
764 }
765 if (semid == seminfo.semmni) {
766 SEM_PRINTF(("no more semid_ds's available\n"));
767 error = ENOSPC;
768 goto out;
769 }
770 SEM_PRINTF(("semid %d is available\n", semid));
771 sema[semid].sem_perm._key = key;
772 sema[semid].sem_perm.cuid = kauth_cred_geteuid(cred);
773 sema[semid].sem_perm.uid = kauth_cred_geteuid(cred);
774 sema[semid].sem_perm.cgid = kauth_cred_getegid(cred);
775 sema[semid].sem_perm.gid = kauth_cred_getegid(cred);
776 sema[semid].sem_perm.mode = (semflg & 0777) | SEM_ALLOC;
777 sema[semid].sem_perm._seq =
778 (sema[semid].sem_perm._seq + 1) & 0x7fff;
779 sema[semid].sem_nsems = nsems;
780 sema[semid].sem_otime = 0;
781 sema[semid].sem_ctime = time_second;
782 sema[semid]._sem_base = &sem[semtot];
783 semtot += nsems;
784 memset(sema[semid]._sem_base, 0,
785 sizeof(sema[semid]._sem_base[0]) * nsems);
786 SEM_PRINTF(("sembase = %p, next = %p\n", sema[semid]._sem_base,
787 &sem[semtot]));
788 } else {
789 SEM_PRINTF(("didn't find it and wasn't asked to create it\n"));
790 error = ENOENT;
791 goto out;
792 }
793
794 found:
795 *retval = IXSEQ_TO_IPCID(semid, sema[semid].sem_perm);
796 out:
797 mutex_exit(&semlock);
798 return (error);
799 }
800
801 #define SMALL_SOPS 8
802
803 void do_semop_init(void)
804 {
805 RUN_ONCE(&exithook_control, seminit_exithook);
806 }
807
808 /* all pointers already in kernel space */
809 int do_semop1(struct lwp *l, int usemid, struct sembuf *sops,
810 size_t nsops, struct timespec *timeout, register_t *retval)
811 {
812 struct proc *p = l->l_proc;
813 int semid, seq;
814 struct semid_ds *semaptr;
815 struct sembuf *sopptr = NULL;
816 struct __sem *semptr = NULL;
817 struct sem_undo *suptr = NULL;
818 kauth_cred_t cred = l->l_cred;
819 int timo = 0;
820 int i, error;
821 int do_wakeup, do_undos;
822
823 RUN_ONCE(&exithook_control, seminit_exithook);
824
825 SEM_PRINTF(("do_semop1(%d, %p, %zu)\n", usemid, usops, nsops));
826
827 if (__predict_false((p->p_flag & PK_SYSVSEM) == 0)) {
828 mutex_enter(p->p_lock);
829 p->p_flag |= PK_SYSVSEM;
830 mutex_exit(p->p_lock);
831 }
832
833 restart:
834 mutex_enter(&semlock);
835 /* In case of reallocation, we will wait for completion */
836 while (__predict_false(sem_realloc_state))
837 cv_wait(&sem_realloc_cv, &semlock);
838
839 semid = IPCID_TO_IX(usemid); /* Convert back to zero origin */
840 if (semid < 0 || semid >= seminfo.semmni) {
841 error = EINVAL;
842 goto out;
843 }
844
845 if (timeout) {
846 error = ts2timo(CLOCK_MONOTONIC, TIMER_RELTIME, timeout,
847 &timo, NULL);
848 if (error)
849 return error;
850 }
851
852 semaptr = &sema[semid];
853 seq = IPCID_TO_SEQ(usemid);
854 if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0 ||
855 semaptr->sem_perm._seq != seq) {
856 error = EINVAL;
857 goto out;
858 }
859
860 if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_W))) {
861 SEM_PRINTF(("error = %d from ipaccess\n", error));
862 goto out;
863 }
864
865 for (i = 0; i < nsops; i++)
866 if (sops[i].sem_num >= semaptr->sem_nsems) {
867 error = EFBIG;
868 goto out;
869 }
870 /*
871 * Loop trying to satisfy the vector of requests.
872 * If we reach a point where we must wait, any requests already
873 * performed are rolled back and we go to sleep until some other
874 * process wakes us up. At this point, we start all over again.
875 *
876 * This ensures that from the perspective of other tasks, a set
877 * of requests is atomic (never partially satisfied).
878 */
879 do_undos = 0;
880
881 for (;;) {
882 do_wakeup = 0;
883
884 for (i = 0; i < nsops; i++) {
885 sopptr = &sops[i];
886 semptr = &semaptr->_sem_base[sopptr->sem_num];
887
888 SEM_PRINTF(("semop: semaptr=%p, sem_base=%p, "
889 "semptr=%p, sem[%d]=%d : op=%d, flag=%s\n",
890 semaptr, semaptr->_sem_base, semptr,
891 sopptr->sem_num, semptr->semval, sopptr->sem_op,
892 (sopptr->sem_flg & IPC_NOWAIT) ?
893 "nowait" : "wait"));
894
895 if (sopptr->sem_op < 0) {
896 if ((int)(semptr->semval +
897 sopptr->sem_op) < 0) {
898 SEM_PRINTF(("semop: "
899 "can't do it now\n"));
900 break;
901 } else {
902 semptr->semval += sopptr->sem_op;
903 if (semptr->semval == 0 &&
904 semptr->semzcnt > 0)
905 do_wakeup = 1;
906 }
907 if (sopptr->sem_flg & SEM_UNDO)
908 do_undos = 1;
909 } else if (sopptr->sem_op == 0) {
910 if (semptr->semval > 0) {
911 SEM_PRINTF(("semop: not zero now\n"));
912 break;
913 }
914 } else {
915 if (semptr->semncnt > 0)
916 do_wakeup = 1;
917 semptr->semval += sopptr->sem_op;
918 if (sopptr->sem_flg & SEM_UNDO)
919 do_undos = 1;
920 }
921 }
922
923 /*
924 * Did we get through the entire vector?
925 */
926 if (i >= nsops)
927 goto done;
928
929 /*
930 * No ... rollback anything that we've already done
931 */
932 SEM_PRINTF(("semop: rollback 0 through %d\n", i - 1));
933 while (i-- > 0)
934 semaptr->_sem_base[sops[i].sem_num].semval -=
935 sops[i].sem_op;
936
937 /*
938 * If the request that we couldn't satisfy has the
939 * NOWAIT flag set then return with EAGAIN.
940 */
941 if (sopptr->sem_flg & IPC_NOWAIT) {
942 error = EAGAIN;
943 goto out;
944 }
945
946 if (sopptr->sem_op == 0)
947 semptr->semzcnt++;
948 else
949 semptr->semncnt++;
950
951 sem_waiters++;
952 SEM_PRINTF(("semop: good night!\n"));
953 error = cv_timedwait_sig(&semcv[semid], &semlock, timo);
954 SEM_PRINTF(("semop: good morning (error=%d)!\n", error));
955 sem_waiters--;
956
957 /* Notify reallocator, if it is waiting */
958 cv_broadcast(&sem_realloc_cv);
959
960 /*
961 * Make sure that the semaphore still exists
962 */
963 if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0 ||
964 semaptr->sem_perm._seq != seq) {
965 error = EIDRM;
966 goto out;
967 }
968
969 /*
970 * The semaphore is still alive. Readjust the count of
971 * waiting processes.
972 */
973 semptr = &semaptr->_sem_base[sopptr->sem_num];
974 if (sopptr->sem_op == 0)
975 semptr->semzcnt--;
976 else
977 semptr->semncnt--;
978
979 /* In case of such state, restart the call */
980 if (sem_realloc_state) {
981 mutex_exit(&semlock);
982 goto restart;
983 }
984
985 /* Is it really morning, or was our sleep interrupted? */
986 if (error != 0) {
987 if (error == ERESTART)
988 error = EINTR; // Simplify to just EINTR
989 else if (error == EWOULDBLOCK)
990 error = EAGAIN; // Convert timeout to EAGAIN
991 goto out;
992 }
993 SEM_PRINTF(("semop: good morning!\n"));
994 }
995 done:
996 /*
997 * Process any SEM_UNDO requests.
998 */
999 if (do_undos) {
1000 for (i = 0; i < nsops; i++) {
1001 /*
1002 * We only need to deal with SEM_UNDO's for non-zero
1003 * op's.
1004 */
1005 int adjval;
1006
1007 if ((sops[i].sem_flg & SEM_UNDO) == 0)
1008 continue;
1009 adjval = sops[i].sem_op;
1010 if (adjval == 0)
1011 continue;
1012 error = semundo_adjust(p, &suptr, semid,
1013 sops[i].sem_num, -adjval);
1014 if (error == 0)
1015 continue;
1016
1017 /*
1018 * Oh-Oh! We ran out of either sem_undo's or undo's.
1019 * Rollback the adjustments to this point and then
1020 * rollback the semaphore ups and down so we can return
1021 * with an error with all structures restored. We
1022 * rollback the undo's in the exact reverse order that
1023 * we applied them. This guarantees that we won't run
1024 * out of space as we roll things back out.
1025 */
1026 while (i-- > 0) {
1027 if ((sops[i].sem_flg & SEM_UNDO) == 0)
1028 continue;
1029 adjval = sops[i].sem_op;
1030 if (adjval == 0)
1031 continue;
1032 if (semundo_adjust(p, &suptr, semid,
1033 sops[i].sem_num, adjval) != 0)
1034 panic("semop - can't undo undos");
1035 }
1036
1037 for (i = 0; i < nsops; i++)
1038 semaptr->_sem_base[sops[i].sem_num].semval -=
1039 sops[i].sem_op;
1040
1041 SEM_PRINTF(("error = %d from semundo_adjust\n", error));
1042 goto out;
1043 } /* loop through the sops */
1044 } /* if (do_undos) */
1045
1046 /* We're definitely done - set the sempid's */
1047 for (i = 0; i < nsops; i++) {
1048 sopptr = &sops[i];
1049 semptr = &semaptr->_sem_base[sopptr->sem_num];
1050 semptr->sempid = p->p_pid;
1051 }
1052
1053 /* Update sem_otime */
1054 semaptr->sem_otime = time_second;
1055
1056 /* Do a wakeup if any semaphore was up'd. */
1057 if (do_wakeup) {
1058 SEM_PRINTF(("semop: doing wakeup\n"));
1059 cv_broadcast(&semcv[semid]);
1060 SEM_PRINTF(("semop: back from wakeup\n"));
1061 }
1062 SEM_PRINTF(("semop: done\n"));
1063 *retval = 0;
1064
1065 out:
1066 mutex_exit(&semlock);
1067 return error;
1068 }
1069
1070 static int
1071 do_semop(struct lwp *l, int usemid, struct sembuf *usops,
1072 size_t nsops, struct timespec *utimeout, register_t *retval)
1073 {
1074 struct sembuf small_sops[SMALL_SOPS];
1075 struct sembuf *sops;
1076 struct timespec timeout;
1077 int error;
1078
1079 do_semop_init();
1080
1081 SEM_PRINTF(("do_semop(%d, %p, %zu)\n", usemid, usops, nsops));
1082
1083 if (nsops <= SMALL_SOPS) {
1084 sops = small_sops;
1085 } else if (seminfo.semopm > 0 && nsops <= (size_t)seminfo.semopm) {
1086 sops = kmem_alloc(nsops * sizeof(*sops), KM_SLEEP);
1087 } else {
1088 SEM_PRINTF(("too many sops (max=%d, nsops=%zu)\n",
1089 seminfo.semopm, nsops));
1090 return (E2BIG);
1091 }
1092
1093 error = copyin(usops, sops, nsops * sizeof(sops[0]));
1094 if (error) {
1095 SEM_PRINTF(("error = %d from copyin(%p, %p, %zu)\n", error,
1096 usops, &sops, nsops * sizeof(sops[0])));
1097 if (sops != small_sops)
1098 kmem_free(sops, nsops * sizeof(*sops));
1099 return error;
1100 }
1101
1102 if (utimeout) {
1103 error = copyin(utimeout, &timeout, sizeof(timeout));
1104 if (error) {
1105 SEM_PRINTF(("error = %d from copyin(%p, %p, %zu)\n",
1106 error, utimeout, &timeout, sizeof(timeout)));
1107 return error;
1108 }
1109 }
1110
1111 error = do_semop1(l, usemid, sops, nsops, utimeout ? &timeout : NULL,
1112 retval);
1113
1114 if (sops != small_sops)
1115 kmem_free(sops, nsops * sizeof(*sops));
1116
1117 return error;
1118 }
1119
1120 int
1121 sys_semtimedop(struct lwp *l, const struct sys_semtimedop_args *uap,
1122 register_t *retval)
1123 {
1124 /* {
1125 syscallarg(int) semid;
1126 syscallarg(struct sembuf *) sops;
1127 syscallarg(size_t) nsops;
1128 syscallarg(struct timespec) timeout;
1129 } */
1130 int semid = SCARG(uap, semid);
1131 struct sembuf *sops = SCARG(uap, sops);
1132 size_t nsops = SCARG(uap, nsops);
1133 struct timespec *utimeout = SCARG(uap, timeout);
1134
1135 return do_semop(l, semid, sops, nsops, utimeout, retval);
1136 }
1137
1138 int
1139 sys_semop(struct lwp *l, const struct sys_semop_args *uap, register_t *retval)
1140 {
1141 /* {
1142 syscallarg(int) semid;
1143 syscallarg(struct sembuf *) sops;
1144 syscallarg(size_t) nsops;
1145 } */
1146 int semid = SCARG(uap, semid);
1147 struct sembuf *sops = SCARG(uap, sops);
1148 size_t nsops = SCARG(uap, nsops);
1149
1150 return do_semop(l, semid, sops, nsops, NULL, retval);
1151 }
1152
1153 /*
1154 * Go through the undo structures for this process and apply the
1155 * adjustments to semaphores.
1156 */
1157 /*ARGSUSED*/
1158 void
1159 semexit(struct proc *p, void *v)
1160 {
1161 struct sem_undo *suptr;
1162 struct sem_undo **supptr;
1163
1164 if ((p->p_flag & PK_SYSVSEM) == 0)
1165 return;
1166
1167 mutex_enter(&semlock);
1168
1169 /*
1170 * Go through the chain of undo vectors looking for one
1171 * associated with this process.
1172 */
1173
1174 for (supptr = &semu_list; (suptr = *supptr) != NULL;
1175 supptr = &suptr->un_next) {
1176 if (suptr->un_proc == p)
1177 break;
1178 }
1179
1180 /*
1181 * If there is no undo vector, skip to the end.
1182 */
1183
1184 if (suptr == NULL) {
1185 mutex_exit(&semlock);
1186 return;
1187 }
1188
1189 /*
1190 * We now have an undo vector for this process.
1191 */
1192
1193 SEM_PRINTF(("proc @%p has undo structure with %d entries\n", p,
1194 suptr->un_cnt));
1195
1196 /*
1197 * If there are any active undo elements then process them.
1198 */
1199 if (suptr->un_cnt > 0) {
1200 int ix;
1201
1202 for (ix = 0; ix < suptr->un_cnt; ix++) {
1203 int semid = suptr->un_ent[ix].un_id;
1204 int semnum = suptr->un_ent[ix].un_num;
1205 int adjval = suptr->un_ent[ix].un_adjval;
1206 struct semid_ds *semaptr;
1207
1208 semaptr = &sema[semid];
1209 if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0)
1210 if (semnum >= semaptr->sem_nsems)
1211 panic("semexit - semnum out of range");
1212
1213 SEM_PRINTF(("semexit: %p id=%d num=%d(adj=%d) ; "
1214 "sem=%d\n",
1215 suptr->un_proc, suptr->un_ent[ix].un_id,
1216 suptr->un_ent[ix].un_num,
1217 suptr->un_ent[ix].un_adjval,
1218 semaptr->_sem_base[semnum].semval));
1219
1220 if (adjval < 0 &&
1221 semaptr->_sem_base[semnum].semval < -adjval)
1222 semaptr->_sem_base[semnum].semval = 0;
1223 else
1224 semaptr->_sem_base[semnum].semval += adjval;
1225
1226 cv_broadcast(&semcv[semid]);
1227 SEM_PRINTF(("semexit: back from wakeup\n"));
1228 }
1229 }
1230
1231 /*
1232 * Deallocate the undo vector.
1233 */
1234 SEM_PRINTF(("removing vector\n"));
1235 suptr->un_proc = NULL;
1236 *supptr = suptr->un_next;
1237 mutex_exit(&semlock);
1238 }
1239
1240 /*
1241 * Sysctl initialization and nodes.
1242 */
1243
1244 static int
1245 sysctl_ipc_semmni(SYSCTLFN_ARGS)
1246 {
1247 int newsize, error;
1248 struct sysctlnode node;
1249 node = *rnode;
1250 node.sysctl_data = &newsize;
1251
1252 newsize = seminfo.semmni;
1253 error = sysctl_lookup(SYSCTLFN_CALL(&node));
1254 if (error || newp == NULL)
1255 return error;
1256
1257 return semrealloc(newsize, seminfo.semmns, seminfo.semmnu);
1258 }
1259
1260 static int
1261 sysctl_ipc_semmns(SYSCTLFN_ARGS)
1262 {
1263 int newsize, error;
1264 struct sysctlnode node;
1265 node = *rnode;
1266 node.sysctl_data = &newsize;
1267
1268 newsize = seminfo.semmns;
1269 error = sysctl_lookup(SYSCTLFN_CALL(&node));
1270 if (error || newp == NULL)
1271 return error;
1272
1273 return semrealloc(seminfo.semmni, newsize, seminfo.semmnu);
1274 }
1275
1276 static int
1277 sysctl_ipc_semmnu(SYSCTLFN_ARGS)
1278 {
1279 int newsize, error;
1280 struct sysctlnode node;
1281 node = *rnode;
1282 node.sysctl_data = &newsize;
1283
1284 newsize = seminfo.semmnu;
1285 error = sysctl_lookup(SYSCTLFN_CALL(&node));
1286 if (error || newp == NULL)
1287 return error;
1288
1289 return semrealloc(seminfo.semmni, seminfo.semmns, newsize);
1290 }
1291
1292 SYSCTL_SETUP(sysctl_ipc_sem_setup, "sysctl kern.ipc subtree setup")
1293 {
1294 const struct sysctlnode *node = NULL;
1295
1296 sysctl_createv(clog, 0, NULL, &node,
1297 CTLFLAG_PERMANENT,
1298 CTLTYPE_NODE, "ipc",
1299 SYSCTL_DESCR("SysV IPC options"),
1300 NULL, 0, NULL, 0,
1301 CTL_KERN, KERN_SYSVIPC, CTL_EOL);
1302
1303 if (node == NULL)
1304 return;
1305
1306 sysctl_createv(clog, 0, &node, NULL,
1307 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
1308 CTLTYPE_INT, "semmni",
1309 SYSCTL_DESCR("Max number of number of semaphore identifiers"),
1310 sysctl_ipc_semmni, 0, &seminfo.semmni, 0,
1311 CTL_CREATE, CTL_EOL);
1312 sysctl_createv(clog, 0, &node, NULL,
1313 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
1314 CTLTYPE_INT, "semmns",
1315 SYSCTL_DESCR("Max number of number of semaphores in system"),
1316 sysctl_ipc_semmns, 0, &seminfo.semmns, 0,
1317 CTL_CREATE, CTL_EOL);
1318 sysctl_createv(clog, 0, &node, NULL,
1319 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
1320 CTLTYPE_INT, "semmnu",
1321 SYSCTL_DESCR("Max number of undo structures in system"),
1322 sysctl_ipc_semmnu, 0, &seminfo.semmnu, 0,
1323 CTL_CREATE, CTL_EOL);
1324 }
1325