xref: /freebsd/sys/kern/sysv_shm.c (revision 908e960ea6343acd9515d89d5d5696f9d8bf090c)
1 /*	$NetBSD: sysv_shm.c,v 1.23 1994/07/04 23:25:12 glass Exp $	*/
2 /*-
3  * Copyright (c) 1994 Adam Glass and Charles Hannum.  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, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by Adam Glass and Charles
16  *	Hannum.
17  * 4. The names of the authors may not be used to endorse or promote products
18  *    derived from this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
21  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31 /*-
32  * Copyright (c) 2003-2005 McAfee, Inc.
33  * All rights reserved.
34  *
35  * This software was developed for the FreeBSD Project in part by McAfee
36  * Research, the Security Research Division of McAfee, Inc under DARPA/SPAWAR
37  * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS research
38  * program.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59  * SUCH DAMAGE.
60  */
61 
62 #include <sys/cdefs.h>
63 __FBSDID("$FreeBSD$");
64 
65 #include "opt_compat.h"
66 #include "opt_sysvipc.h"
67 
68 #include <sys/param.h>
69 #include <sys/systm.h>
70 #include <sys/kernel.h>
71 #include <sys/lock.h>
72 #include <sys/sysctl.h>
73 #include <sys/shm.h>
74 #include <sys/proc.h>
75 #include <sys/malloc.h>
76 #include <sys/mman.h>
77 #include <sys/module.h>
78 #include <sys/mutex.h>
79 #include <sys/resourcevar.h>
80 #include <sys/stat.h>
81 #include <sys/syscall.h>
82 #include <sys/syscallsubr.h>
83 #include <sys/sysent.h>
84 #include <sys/sysproto.h>
85 #include <sys/jail.h>
86 
87 #include <security/mac/mac_framework.h>
88 
89 #include <vm/vm.h>
90 #include <vm/vm_param.h>
91 #include <vm/pmap.h>
92 #include <vm/vm_object.h>
93 #include <vm/vm_map.h>
94 #include <vm/vm_page.h>
95 #include <vm/vm_pager.h>
96 
97 static MALLOC_DEFINE(M_SHM, "shm", "SVID compatible shared memory segments");
98 
99 #if defined(__i386__) && (defined(COMPAT_FREEBSD4) || defined(COMPAT_43))
100 struct oshmctl_args;
101 static int oshmctl(struct thread *td, struct oshmctl_args *uap);
102 #endif
103 
104 static int shmget_allocate_segment(struct thread *td,
105     struct shmget_args *uap, int mode);
106 static int shmget_existing(struct thread *td, struct shmget_args *uap,
107     int mode, int segnum);
108 
109 #if defined(__i386__) && (defined(COMPAT_FREEBSD4) || defined(COMPAT_43))
110 /* XXX casting to (sy_call_t *) is bogus, as usual. */
111 static sy_call_t *shmcalls[] = {
112 	(sy_call_t *)shmat, (sy_call_t *)oshmctl,
113 	(sy_call_t *)shmdt, (sy_call_t *)shmget,
114 	(sy_call_t *)shmctl
115 };
116 #endif
117 
118 #define	SHMSEG_FREE     	0x0200
119 #define	SHMSEG_REMOVED  	0x0400
120 #define	SHMSEG_ALLOCATED	0x0800
121 #define	SHMSEG_WANTED		0x1000
122 
123 static int shm_last_free, shm_nused, shmalloced;
124 vm_size_t shm_committed;
125 static struct shmid_kernel	*shmsegs;
126 
127 struct shmmap_state {
128 	vm_offset_t va;
129 	int shmid;
130 };
131 
132 static void shm_deallocate_segment(struct shmid_kernel *);
133 static int shm_find_segment_by_key(key_t);
134 static struct shmid_kernel *shm_find_segment_by_shmid(int);
135 static struct shmid_kernel *shm_find_segment_by_shmidx(int);
136 static int shm_delete_mapping(struct vmspace *vm, struct shmmap_state *);
137 static void shmrealloc(void);
138 static void shminit(void);
139 static int sysvshm_modload(struct module *, int, void *);
140 static int shmunload(void);
141 static void shmexit_myhook(struct vmspace *vm);
142 static void shmfork_myhook(struct proc *p1, struct proc *p2);
143 static int sysctl_shmsegs(SYSCTL_HANDLER_ARGS);
144 
145 /*
146  * Tuneable values.
147  */
148 #ifndef SHMMAXPGS
149 #define	SHMMAXPGS	8192	/* Note: sysv shared memory is swap backed. */
150 #endif
151 #ifndef SHMMAX
152 #define	SHMMAX	(SHMMAXPGS*PAGE_SIZE)
153 #endif
154 #ifndef SHMMIN
155 #define	SHMMIN	1
156 #endif
157 #ifndef SHMMNI
158 #define	SHMMNI	192
159 #endif
160 #ifndef SHMSEG
161 #define	SHMSEG	128
162 #endif
163 #ifndef SHMALL
164 #define	SHMALL	(SHMMAXPGS)
165 #endif
166 
167 struct	shminfo shminfo = {
168 	SHMMAX,
169 	SHMMIN,
170 	SHMMNI,
171 	SHMSEG,
172 	SHMALL
173 };
174 
175 static int shm_use_phys;
176 static int shm_allow_removed;
177 
178 SYSCTL_ULONG(_kern_ipc, OID_AUTO, shmmax, CTLFLAG_RW, &shminfo.shmmax, 0,
179     "Maximum shared memory segment size");
180 SYSCTL_ULONG(_kern_ipc, OID_AUTO, shmmin, CTLFLAG_RW, &shminfo.shmmin, 0,
181     "Minimum shared memory segment size");
182 SYSCTL_ULONG(_kern_ipc, OID_AUTO, shmmni, CTLFLAG_RDTUN, &shminfo.shmmni, 0,
183     "Number of shared memory identifiers");
184 SYSCTL_ULONG(_kern_ipc, OID_AUTO, shmseg, CTLFLAG_RDTUN, &shminfo.shmseg, 0,
185     "Number of segments per process");
186 SYSCTL_ULONG(_kern_ipc, OID_AUTO, shmall, CTLFLAG_RW, &shminfo.shmall, 0,
187     "Maximum number of pages available for shared memory");
188 SYSCTL_INT(_kern_ipc, OID_AUTO, shm_use_phys, CTLFLAG_RW,
189     &shm_use_phys, 0, "Enable/Disable locking of shared memory pages in core");
190 SYSCTL_INT(_kern_ipc, OID_AUTO, shm_allow_removed, CTLFLAG_RW,
191     &shm_allow_removed, 0,
192     "Enable/Disable attachment to attached segments marked for removal");
193 SYSCTL_PROC(_kern_ipc, OID_AUTO, shmsegs, CTLFLAG_RD,
194     NULL, 0, sysctl_shmsegs, "",
195     "Current number of shared memory segments allocated");
196 
197 static int
198 shm_find_segment_by_key(key)
199 	key_t key;
200 {
201 	int i;
202 
203 	for (i = 0; i < shmalloced; i++)
204 		if ((shmsegs[i].u.shm_perm.mode & SHMSEG_ALLOCATED) &&
205 		    shmsegs[i].u.shm_perm.key == key)
206 			return (i);
207 	return (-1);
208 }
209 
210 static struct shmid_kernel *
211 shm_find_segment_by_shmid(int shmid)
212 {
213 	int segnum;
214 	struct shmid_kernel *shmseg;
215 
216 	segnum = IPCID_TO_IX(shmid);
217 	if (segnum < 0 || segnum >= shmalloced)
218 		return (NULL);
219 	shmseg = &shmsegs[segnum];
220 	if ((shmseg->u.shm_perm.mode & SHMSEG_ALLOCATED) == 0 ||
221 	    (!shm_allow_removed &&
222 	     (shmseg->u.shm_perm.mode & SHMSEG_REMOVED) != 0) ||
223 	    shmseg->u.shm_perm.seq != IPCID_TO_SEQ(shmid))
224 		return (NULL);
225 	return (shmseg);
226 }
227 
228 static struct shmid_kernel *
229 shm_find_segment_by_shmidx(int segnum)
230 {
231 	struct shmid_kernel *shmseg;
232 
233 	if (segnum < 0 || segnum >= shmalloced)
234 		return (NULL);
235 	shmseg = &shmsegs[segnum];
236 	if ((shmseg->u.shm_perm.mode & SHMSEG_ALLOCATED) == 0 ||
237 	    (!shm_allow_removed &&
238 	     (shmseg->u.shm_perm.mode & SHMSEG_REMOVED) != 0))
239 		return (NULL);
240 	return (shmseg);
241 }
242 
243 static void
244 shm_deallocate_segment(shmseg)
245 	struct shmid_kernel *shmseg;
246 {
247 	vm_size_t size;
248 
249 	GIANT_REQUIRED;
250 
251 	vm_object_deallocate(shmseg->u.shm_internal);
252 	shmseg->u.shm_internal = NULL;
253 	size = round_page(shmseg->shm_bsegsz);
254 	shm_committed -= btoc(size);
255 	shm_nused--;
256 	shmseg->u.shm_perm.mode = SHMSEG_FREE;
257 #ifdef MAC
258 	mac_sysvshm_cleanup(shmseg);
259 #endif
260 }
261 
262 static int
263 shm_delete_mapping(struct vmspace *vm, struct shmmap_state *shmmap_s)
264 {
265 	struct shmid_kernel *shmseg;
266 	int segnum, result;
267 	vm_size_t size;
268 
269 	GIANT_REQUIRED;
270 
271 	segnum = IPCID_TO_IX(shmmap_s->shmid);
272 	shmseg = &shmsegs[segnum];
273 	size = round_page(shmseg->shm_bsegsz);
274 	result = vm_map_remove(&vm->vm_map, shmmap_s->va, shmmap_s->va + size);
275 	if (result != KERN_SUCCESS)
276 		return (EINVAL);
277 	shmmap_s->shmid = -1;
278 	shmseg->u.shm_dtime = time_second;
279 	if ((--shmseg->u.shm_nattch <= 0) &&
280 	    (shmseg->u.shm_perm.mode & SHMSEG_REMOVED)) {
281 		shm_deallocate_segment(shmseg);
282 		shm_last_free = segnum;
283 	}
284 	return (0);
285 }
286 
287 #ifndef _SYS_SYSPROTO_H_
288 struct shmdt_args {
289 	const void *shmaddr;
290 };
291 #endif
292 int
293 shmdt(td, uap)
294 	struct thread *td;
295 	struct shmdt_args *uap;
296 {
297 	struct proc *p = td->td_proc;
298 	struct shmmap_state *shmmap_s;
299 #ifdef MAC
300 	struct shmid_kernel *shmsegptr;
301 #endif
302 	int i;
303 	int error = 0;
304 
305 	if (!prison_allow(td->td_ucred, PR_ALLOW_SYSVIPC))
306 		return (ENOSYS);
307 	mtx_lock(&Giant);
308 	shmmap_s = p->p_vmspace->vm_shm;
309  	if (shmmap_s == NULL) {
310 		error = EINVAL;
311 		goto done2;
312 	}
313 	for (i = 0; i < shminfo.shmseg; i++, shmmap_s++) {
314 		if (shmmap_s->shmid != -1 &&
315 		    shmmap_s->va == (vm_offset_t)uap->shmaddr) {
316 			break;
317 		}
318 	}
319 	if (i == shminfo.shmseg) {
320 		error = EINVAL;
321 		goto done2;
322 	}
323 #ifdef MAC
324 	shmsegptr = &shmsegs[IPCID_TO_IX(shmmap_s->shmid)];
325 	error = mac_sysvshm_check_shmdt(td->td_ucred, shmsegptr);
326 	if (error != 0)
327 		goto done2;
328 #endif
329 	error = shm_delete_mapping(p->p_vmspace, shmmap_s);
330 done2:
331 	mtx_unlock(&Giant);
332 	return (error);
333 }
334 
335 #ifndef _SYS_SYSPROTO_H_
336 struct shmat_args {
337 	int shmid;
338 	const void *shmaddr;
339 	int shmflg;
340 };
341 #endif
342 int
343 kern_shmat(td, shmid, shmaddr, shmflg)
344 	struct thread *td;
345 	int shmid;
346 	const void *shmaddr;
347 	int shmflg;
348 {
349 	struct proc *p = td->td_proc;
350 	int i, flags;
351 	struct shmid_kernel *shmseg;
352 	struct shmmap_state *shmmap_s = NULL;
353 	vm_offset_t attach_va;
354 	vm_prot_t prot;
355 	vm_size_t size;
356 	int rv;
357 	int error = 0;
358 
359 	if (!prison_allow(td->td_ucred, PR_ALLOW_SYSVIPC))
360 		return (ENOSYS);
361 	mtx_lock(&Giant);
362 	shmmap_s = p->p_vmspace->vm_shm;
363 	if (shmmap_s == NULL) {
364 		shmmap_s = malloc(shminfo.shmseg * sizeof(struct shmmap_state),
365 		    M_SHM, M_WAITOK);
366 		for (i = 0; i < shminfo.shmseg; i++)
367 			shmmap_s[i].shmid = -1;
368 		p->p_vmspace->vm_shm = shmmap_s;
369 	}
370 	shmseg = shm_find_segment_by_shmid(shmid);
371 	if (shmseg == NULL) {
372 		error = EINVAL;
373 		goto done2;
374 	}
375 	error = ipcperm(td, &shmseg->u.shm_perm,
376 	    (shmflg & SHM_RDONLY) ? IPC_R : IPC_R|IPC_W);
377 	if (error)
378 		goto done2;
379 #ifdef MAC
380 	error = mac_sysvshm_check_shmat(td->td_ucred, shmseg, shmflg);
381 	if (error != 0)
382 		goto done2;
383 #endif
384 	for (i = 0; i < shminfo.shmseg; i++) {
385 		if (shmmap_s->shmid == -1)
386 			break;
387 		shmmap_s++;
388 	}
389 	if (i >= shminfo.shmseg) {
390 		error = EMFILE;
391 		goto done2;
392 	}
393 	size = round_page(shmseg->shm_bsegsz);
394 #ifdef VM_PROT_READ_IS_EXEC
395 	prot = VM_PROT_READ | VM_PROT_EXECUTE;
396 #else
397 	prot = VM_PROT_READ;
398 #endif
399 	if ((shmflg & SHM_RDONLY) == 0)
400 		prot |= VM_PROT_WRITE;
401 	flags = MAP_ANON | MAP_SHARED;
402 	if (shmaddr) {
403 		flags |= MAP_FIXED;
404 		if (shmflg & SHM_RND) {
405 			attach_va = (vm_offset_t)shmaddr & ~(SHMLBA-1);
406 		} else if (((vm_offset_t)shmaddr & (SHMLBA-1)) == 0) {
407 			attach_va = (vm_offset_t)shmaddr;
408 		} else {
409 			error = EINVAL;
410 			goto done2;
411 		}
412 	} else {
413 		/*
414 		 * This is just a hint to vm_map_find() about where to
415 		 * put it.
416 		 */
417 		PROC_LOCK(p);
418 		attach_va = round_page((vm_offset_t)p->p_vmspace->vm_daddr +
419 		    lim_max(p, RLIMIT_DATA));
420 		PROC_UNLOCK(p);
421 	}
422 
423 	vm_object_reference(shmseg->u.shm_internal);
424 	rv = vm_map_find(&p->p_vmspace->vm_map, shmseg->u.shm_internal,
425 	    0, &attach_va, size, (flags & MAP_FIXED) ? VMFS_NO_SPACE :
426 	    VMFS_ANY_SPACE, prot, prot, 0);
427 	if (rv != KERN_SUCCESS) {
428 		vm_object_deallocate(shmseg->u.shm_internal);
429 		error = ENOMEM;
430 		goto done2;
431 	}
432 	vm_map_inherit(&p->p_vmspace->vm_map,
433 		attach_va, attach_va + size, VM_INHERIT_SHARE);
434 
435 	shmmap_s->va = attach_va;
436 	shmmap_s->shmid = shmid;
437 	shmseg->u.shm_lpid = p->p_pid;
438 	shmseg->u.shm_atime = time_second;
439 	shmseg->u.shm_nattch++;
440 	td->td_retval[0] = attach_va;
441 done2:
442 	mtx_unlock(&Giant);
443 	return (error);
444 }
445 
446 int
447 shmat(td, uap)
448 	struct thread *td;
449 	struct shmat_args *uap;
450 {
451 	return kern_shmat(td, uap->shmid, uap->shmaddr, uap->shmflg);
452 }
453 
454 #if defined(__i386__) && (defined(COMPAT_FREEBSD4) || defined(COMPAT_43))
455 struct oshmid_ds {
456 	struct	ipc_perm shm_perm;	/* operation perms */
457 	int	shm_segsz;		/* size of segment (bytes) */
458 	u_short	shm_cpid;		/* pid, creator */
459 	u_short	shm_lpid;		/* pid, last operation */
460 	short	shm_nattch;		/* no. of current attaches */
461 	time_t	shm_atime;		/* last attach time */
462 	time_t	shm_dtime;		/* last detach time */
463 	time_t	shm_ctime;		/* last change time */
464 	void	*shm_handle;		/* internal handle for shm segment */
465 };
466 
467 struct oshmctl_args {
468 	int shmid;
469 	int cmd;
470 	struct oshmid_ds *ubuf;
471 };
472 static int
473 oshmctl(td, uap)
474 	struct thread *td;
475 	struct oshmctl_args *uap;
476 {
477 #ifdef COMPAT_43
478 	int error = 0;
479 	struct shmid_kernel *shmseg;
480 	struct oshmid_ds outbuf;
481 
482 	if (!prison_allow(td->td_ucred, PR_ALLOW_SYSVIPC))
483 		return (ENOSYS);
484 	mtx_lock(&Giant);
485 	shmseg = shm_find_segment_by_shmid(uap->shmid);
486 	if (shmseg == NULL) {
487 		error = EINVAL;
488 		goto done2;
489 	}
490 	switch (uap->cmd) {
491 	case IPC_STAT:
492 		error = ipcperm(td, &shmseg->u.shm_perm, IPC_R);
493 		if (error)
494 			goto done2;
495 #ifdef MAC
496 		error = mac_sysvshm_check_shmctl(td->td_ucred, shmseg, uap->cmd);
497 		if (error != 0)
498 			goto done2;
499 #endif
500 		outbuf.shm_perm = shmseg->u.shm_perm;
501 		outbuf.shm_segsz = shmseg->u.shm_segsz;
502 		outbuf.shm_cpid = shmseg->u.shm_cpid;
503 		outbuf.shm_lpid = shmseg->u.shm_lpid;
504 		outbuf.shm_nattch = shmseg->u.shm_nattch;
505 		outbuf.shm_atime = shmseg->u.shm_atime;
506 		outbuf.shm_dtime = shmseg->u.shm_dtime;
507 		outbuf.shm_ctime = shmseg->u.shm_ctime;
508 		outbuf.shm_handle = shmseg->u.shm_internal;
509 		error = copyout(&outbuf, uap->ubuf, sizeof(outbuf));
510 		if (error)
511 			goto done2;
512 		break;
513 	default:
514 		error = shmctl(td, (struct shmctl_args *)uap);
515 		break;
516 	}
517 done2:
518 	mtx_unlock(&Giant);
519 	return (error);
520 #else
521 	return (EINVAL);
522 #endif
523 }
524 #endif
525 
526 #ifndef _SYS_SYSPROTO_H_
527 struct shmctl_args {
528 	int shmid;
529 	int cmd;
530 	struct shmid_ds *buf;
531 };
532 #endif
533 int
534 kern_shmctl(td, shmid, cmd, buf, bufsz)
535 	struct thread *td;
536 	int shmid;
537 	int cmd;
538 	void *buf;
539 	size_t *bufsz;
540 {
541 	int error = 0;
542 	struct shmid_kernel *shmseg;
543 
544 	if (!prison_allow(td->td_ucred, PR_ALLOW_SYSVIPC))
545 		return (ENOSYS);
546 
547 	mtx_lock(&Giant);
548 	switch (cmd) {
549 	/*
550 	 * It is possible that kern_shmctl is being called from the Linux ABI
551 	 * layer, in which case, we will need to implement IPC_INFO.  It should
552 	 * be noted that other shmctl calls will be funneled through here for
553 	 * Linix binaries as well.
554 	 *
555 	 * NB: The Linux ABI layer will convert this data to structure(s) more
556 	 * consistent with the Linux ABI.
557 	 */
558 	case IPC_INFO:
559 		memcpy(buf, &shminfo, sizeof(shminfo));
560 		if (bufsz)
561 			*bufsz = sizeof(shminfo);
562 		td->td_retval[0] = shmalloced;
563 		goto done2;
564 	case SHM_INFO: {
565 		struct shm_info shm_info;
566 		shm_info.used_ids = shm_nused;
567 		shm_info.shm_rss = 0;	/*XXX where to get from ? */
568 		shm_info.shm_tot = 0;	/*XXX where to get from ? */
569 		shm_info.shm_swp = 0;	/*XXX where to get from ? */
570 		shm_info.swap_attempts = 0;	/*XXX where to get from ? */
571 		shm_info.swap_successes = 0;	/*XXX where to get from ? */
572 		memcpy(buf, &shm_info, sizeof(shm_info));
573 		if (bufsz)
574 			*bufsz = sizeof(shm_info);
575 		td->td_retval[0] = shmalloced;
576 		goto done2;
577 	}
578 	}
579 	if (cmd == SHM_STAT)
580 		shmseg = shm_find_segment_by_shmidx(shmid);
581 	else
582 		shmseg = shm_find_segment_by_shmid(shmid);
583 	if (shmseg == NULL) {
584 		error = EINVAL;
585 		goto done2;
586 	}
587 #ifdef MAC
588 	error = mac_sysvshm_check_shmctl(td->td_ucred, shmseg, cmd);
589 	if (error != 0)
590 		goto done2;
591 #endif
592 	switch (cmd) {
593 	case SHM_STAT:
594 	case IPC_STAT:
595 		error = ipcperm(td, &shmseg->u.shm_perm, IPC_R);
596 		if (error)
597 			goto done2;
598 		memcpy(buf, &shmseg->u, sizeof(struct shmid_ds));
599 		if (bufsz)
600 			*bufsz = sizeof(struct shmid_ds);
601 		if (cmd == SHM_STAT)
602 			td->td_retval[0] = IXSEQ_TO_IPCID(shmid, shmseg->u.shm_perm);
603 		break;
604 	case IPC_SET: {
605 		struct shmid_ds *shmid;
606 
607 		shmid = (struct shmid_ds *)buf;
608 		error = ipcperm(td, &shmseg->u.shm_perm, IPC_M);
609 		if (error)
610 			goto done2;
611 		shmseg->u.shm_perm.uid = shmid->shm_perm.uid;
612 		shmseg->u.shm_perm.gid = shmid->shm_perm.gid;
613 		shmseg->u.shm_perm.mode =
614 		    (shmseg->u.shm_perm.mode & ~ACCESSPERMS) |
615 		    (shmid->shm_perm.mode & ACCESSPERMS);
616 		shmseg->u.shm_ctime = time_second;
617 		break;
618 	}
619 	case IPC_RMID:
620 		error = ipcperm(td, &shmseg->u.shm_perm, IPC_M);
621 		if (error)
622 			goto done2;
623 		shmseg->u.shm_perm.key = IPC_PRIVATE;
624 		shmseg->u.shm_perm.mode |= SHMSEG_REMOVED;
625 		if (shmseg->u.shm_nattch <= 0) {
626 			shm_deallocate_segment(shmseg);
627 			shm_last_free = IPCID_TO_IX(shmid);
628 		}
629 		break;
630 #if 0
631 	case SHM_LOCK:
632 	case SHM_UNLOCK:
633 #endif
634 	default:
635 		error = EINVAL;
636 		break;
637 	}
638 done2:
639 	mtx_unlock(&Giant);
640 	return (error);
641 }
642 
643 int
644 shmctl(td, uap)
645 	struct thread *td;
646 	struct shmctl_args *uap;
647 {
648 	int error = 0;
649 	struct shmid_ds buf;
650 	size_t bufsz;
651 
652 	/*
653 	 * The only reason IPC_INFO, SHM_INFO, SHM_STAT exists is to support
654 	 * Linux binaries.  If we see the call come through the FreeBSD ABI,
655 	 * return an error back to the user since we do not to support this.
656 	 */
657 	if (uap->cmd == IPC_INFO || uap->cmd == SHM_INFO ||
658 	    uap->cmd == SHM_STAT)
659 		return (EINVAL);
660 
661 	/* IPC_SET needs to copyin the buffer before calling kern_shmctl */
662 	if (uap->cmd == IPC_SET) {
663 		if ((error = copyin(uap->buf, &buf, sizeof(struct shmid_ds))))
664 			goto done;
665 	}
666 
667 	error = kern_shmctl(td, uap->shmid, uap->cmd, (void *)&buf, &bufsz);
668 	if (error)
669 		goto done;
670 
671 	/* Cases in which we need to copyout */
672 	switch (uap->cmd) {
673 	case IPC_STAT:
674 		error = copyout(&buf, uap->buf, bufsz);
675 		break;
676 	}
677 
678 done:
679 	if (error) {
680 		/* Invalidate the return value */
681 		td->td_retval[0] = -1;
682 	}
683 	return (error);
684 }
685 
686 
687 #ifndef _SYS_SYSPROTO_H_
688 struct shmget_args {
689 	key_t key;
690 	size_t size;
691 	int shmflg;
692 };
693 #endif
694 static int
695 shmget_existing(td, uap, mode, segnum)
696 	struct thread *td;
697 	struct shmget_args *uap;
698 	int mode;
699 	int segnum;
700 {
701 	struct shmid_kernel *shmseg;
702 	int error;
703 
704 	shmseg = &shmsegs[segnum];
705 	if (shmseg->u.shm_perm.mode & SHMSEG_REMOVED) {
706 		/*
707 		 * This segment is in the process of being allocated.  Wait
708 		 * until it's done, and look the key up again (in case the
709 		 * allocation failed or it was freed).
710 		 */
711 		shmseg->u.shm_perm.mode |= SHMSEG_WANTED;
712 		error = tsleep(shmseg, PLOCK | PCATCH, "shmget", 0);
713 		if (error)
714 			return (error);
715 		return (EAGAIN);
716 	}
717 	if ((uap->shmflg & (IPC_CREAT | IPC_EXCL)) == (IPC_CREAT | IPC_EXCL))
718 		return (EEXIST);
719 #ifdef MAC
720 	error = mac_sysvshm_check_shmget(td->td_ucred, shmseg, uap->shmflg);
721 	if (error != 0)
722 		return (error);
723 #endif
724 	if (uap->size != 0 && uap->size > shmseg->shm_bsegsz)
725 		return (EINVAL);
726 	td->td_retval[0] = IXSEQ_TO_IPCID(segnum, shmseg->u.shm_perm);
727 	return (0);
728 }
729 
730 static int
731 shmget_allocate_segment(td, uap, mode)
732 	struct thread *td;
733 	struct shmget_args *uap;
734 	int mode;
735 {
736 	int i, segnum, shmid;
737 	size_t size;
738 	struct ucred *cred = td->td_ucred;
739 	struct shmid_kernel *shmseg;
740 	vm_object_t shm_object;
741 
742 	GIANT_REQUIRED;
743 
744 	if (uap->size < shminfo.shmmin || uap->size > shminfo.shmmax)
745 		return (EINVAL);
746 	if (shm_nused >= shminfo.shmmni) /* Any shmids left? */
747 		return (ENOSPC);
748 	size = round_page(uap->size);
749 	if (shm_committed + btoc(size) > shminfo.shmall)
750 		return (ENOMEM);
751 	if (shm_last_free < 0) {
752 		shmrealloc();	/* Maybe expand the shmsegs[] array. */
753 		for (i = 0; i < shmalloced; i++)
754 			if (shmsegs[i].u.shm_perm.mode & SHMSEG_FREE)
755 				break;
756 		if (i == shmalloced)
757 			return (ENOSPC);
758 		segnum = i;
759 	} else  {
760 		segnum = shm_last_free;
761 		shm_last_free = -1;
762 	}
763 	shmseg = &shmsegs[segnum];
764 	/*
765 	 * In case we sleep in malloc(), mark the segment present but deleted
766 	 * so that noone else tries to create the same key.
767 	 */
768 	shmseg->u.shm_perm.mode = SHMSEG_ALLOCATED | SHMSEG_REMOVED;
769 	shmseg->u.shm_perm.key = uap->key;
770 	shmseg->u.shm_perm.seq = (shmseg->u.shm_perm.seq + 1) & 0x7fff;
771 	shmid = IXSEQ_TO_IPCID(segnum, shmseg->u.shm_perm);
772 
773 	/*
774 	 * We make sure that we have allocated a pager before we need
775 	 * to.
776 	 */
777 	if (shm_use_phys) {
778 		shm_object =
779 		    vm_pager_allocate(OBJT_PHYS, 0, size, VM_PROT_DEFAULT, 0);
780 	} else {
781 		shm_object =
782 		    vm_pager_allocate(OBJT_SWAP, 0, size, VM_PROT_DEFAULT, 0);
783 	}
784 	VM_OBJECT_LOCK(shm_object);
785 	vm_object_clear_flag(shm_object, OBJ_ONEMAPPING);
786 	vm_object_set_flag(shm_object, OBJ_NOSPLIT);
787 	VM_OBJECT_UNLOCK(shm_object);
788 
789 	shmseg->u.shm_internal = shm_object;
790 	shmseg->u.shm_perm.cuid = shmseg->u.shm_perm.uid = cred->cr_uid;
791 	shmseg->u.shm_perm.cgid = shmseg->u.shm_perm.gid = cred->cr_gid;
792 	shmseg->u.shm_perm.mode = (shmseg->u.shm_perm.mode & SHMSEG_WANTED) |
793 	    (mode & ACCESSPERMS) | SHMSEG_ALLOCATED;
794 	shmseg->u.shm_segsz = uap->size;
795 	shmseg->shm_bsegsz = uap->size;
796 	shmseg->u.shm_cpid = td->td_proc->p_pid;
797 	shmseg->u.shm_lpid = shmseg->u.shm_nattch = 0;
798 	shmseg->u.shm_atime = shmseg->u.shm_dtime = 0;
799 #ifdef MAC
800 	mac_sysvshm_create(cred, shmseg);
801 #endif
802 	shmseg->u.shm_ctime = time_second;
803 	shm_committed += btoc(size);
804 	shm_nused++;
805 	if (shmseg->u.shm_perm.mode & SHMSEG_WANTED) {
806 		/*
807 		 * Somebody else wanted this key while we were asleep.  Wake
808 		 * them up now.
809 		 */
810 		shmseg->u.shm_perm.mode &= ~SHMSEG_WANTED;
811 		wakeup(shmseg);
812 	}
813 	td->td_retval[0] = shmid;
814 	return (0);
815 }
816 
817 int
818 shmget(td, uap)
819 	struct thread *td;
820 	struct shmget_args *uap;
821 {
822 	int segnum, mode;
823 	int error;
824 
825 	if (!prison_allow(td->td_ucred, PR_ALLOW_SYSVIPC))
826 		return (ENOSYS);
827 	mtx_lock(&Giant);
828 	mode = uap->shmflg & ACCESSPERMS;
829 	if (uap->key != IPC_PRIVATE) {
830 	again:
831 		segnum = shm_find_segment_by_key(uap->key);
832 		if (segnum >= 0) {
833 			error = shmget_existing(td, uap, mode, segnum);
834 			if (error == EAGAIN)
835 				goto again;
836 			goto done2;
837 		}
838 		if ((uap->shmflg & IPC_CREAT) == 0) {
839 			error = ENOENT;
840 			goto done2;
841 		}
842 	}
843 	error = shmget_allocate_segment(td, uap, mode);
844 done2:
845 	mtx_unlock(&Giant);
846 	return (error);
847 }
848 
849 int
850 shmsys(td, uap)
851 	struct thread *td;
852 	/* XXX actually varargs. */
853 	struct shmsys_args /* {
854 		int	which;
855 		int	a2;
856 		int	a3;
857 		int	a4;
858 	} */ *uap;
859 {
860 #if defined(__i386__) && (defined(COMPAT_FREEBSD4) || defined(COMPAT_43))
861 	int error;
862 
863 	if (!prison_allow(td->td_ucred, PR_ALLOW_SYSVIPC))
864 		return (ENOSYS);
865 	if (uap->which < 0 ||
866 	    uap->which >= sizeof(shmcalls)/sizeof(shmcalls[0]))
867 		return (EINVAL);
868 	mtx_lock(&Giant);
869 	error = (*shmcalls[uap->which])(td, &uap->a2);
870 	mtx_unlock(&Giant);
871 	return (error);
872 #else
873 	return (nosys(td, NULL));
874 #endif
875 }
876 
877 static void
878 shmfork_myhook(p1, p2)
879 	struct proc *p1, *p2;
880 {
881 	struct shmmap_state *shmmap_s;
882 	size_t size;
883 	int i;
884 
885 	mtx_lock(&Giant);
886 	size = shminfo.shmseg * sizeof(struct shmmap_state);
887 	shmmap_s = malloc(size, M_SHM, M_WAITOK);
888 	bcopy(p1->p_vmspace->vm_shm, shmmap_s, size);
889 	p2->p_vmspace->vm_shm = shmmap_s;
890 	for (i = 0; i < shminfo.shmseg; i++, shmmap_s++)
891 		if (shmmap_s->shmid != -1)
892 			shmsegs[IPCID_TO_IX(shmmap_s->shmid)].u.shm_nattch++;
893 	mtx_unlock(&Giant);
894 }
895 
896 static void
897 shmexit_myhook(struct vmspace *vm)
898 {
899 	struct shmmap_state *base, *shm;
900 	int i;
901 
902 	if ((base = vm->vm_shm) != NULL) {
903 		vm->vm_shm = NULL;
904 		mtx_lock(&Giant);
905 		for (i = 0, shm = base; i < shminfo.shmseg; i++, shm++) {
906 			if (shm->shmid != -1)
907 				shm_delete_mapping(vm, shm);
908 		}
909 		mtx_unlock(&Giant);
910 		free(base, M_SHM);
911 	}
912 }
913 
914 static void
915 shmrealloc(void)
916 {
917 	int i;
918 	struct shmid_kernel *newsegs;
919 
920 	if (shmalloced >= shminfo.shmmni)
921 		return;
922 
923 	newsegs = malloc(shminfo.shmmni * sizeof(*newsegs), M_SHM, M_WAITOK);
924 	if (newsegs == NULL)
925 		return;
926 	for (i = 0; i < shmalloced; i++)
927 		bcopy(&shmsegs[i], &newsegs[i], sizeof(newsegs[0]));
928 	for (; i < shminfo.shmmni; i++) {
929 		shmsegs[i].u.shm_perm.mode = SHMSEG_FREE;
930 		shmsegs[i].u.shm_perm.seq = 0;
931 #ifdef MAC
932 		mac_sysvshm_init(&shmsegs[i]);
933 #endif
934 	}
935 	free(shmsegs, M_SHM);
936 	shmsegs = newsegs;
937 	shmalloced = shminfo.shmmni;
938 }
939 
940 static void
941 shminit()
942 {
943 	int i;
944 
945 	TUNABLE_ULONG_FETCH("kern.ipc.shmmaxpgs", &shminfo.shmall);
946 	for (i = PAGE_SIZE; i > 0; i--) {
947 		shminfo.shmmax = shminfo.shmall * i;
948 		if (shminfo.shmmax >= shminfo.shmall)
949 			break;
950 	}
951 	TUNABLE_ULONG_FETCH("kern.ipc.shmmin", &shminfo.shmmin);
952 	TUNABLE_ULONG_FETCH("kern.ipc.shmmni", &shminfo.shmmni);
953 	TUNABLE_ULONG_FETCH("kern.ipc.shmseg", &shminfo.shmseg);
954 	TUNABLE_INT_FETCH("kern.ipc.shm_use_phys", &shm_use_phys);
955 
956 	shmalloced = shminfo.shmmni;
957 	shmsegs = malloc(shmalloced * sizeof(shmsegs[0]), M_SHM, M_WAITOK);
958 	if (shmsegs == NULL)
959 		panic("cannot allocate initial memory for sysvshm");
960 	for (i = 0; i < shmalloced; i++) {
961 		shmsegs[i].u.shm_perm.mode = SHMSEG_FREE;
962 		shmsegs[i].u.shm_perm.seq = 0;
963 #ifdef MAC
964 		mac_sysvshm_init(&shmsegs[i]);
965 #endif
966 	}
967 	shm_last_free = 0;
968 	shm_nused = 0;
969 	shm_committed = 0;
970 	shmexit_hook = &shmexit_myhook;
971 	shmfork_hook = &shmfork_myhook;
972 }
973 
974 static int
975 shmunload()
976 {
977 #ifdef MAC
978 	int i;
979 #endif
980 
981 	if (shm_nused > 0)
982 		return (EBUSY);
983 
984 #ifdef MAC
985 	for (i = 0; i < shmalloced; i++)
986 		mac_sysvshm_destroy(&shmsegs[i]);
987 #endif
988 	free(shmsegs, M_SHM);
989 	shmexit_hook = NULL;
990 	shmfork_hook = NULL;
991 	return (0);
992 }
993 
994 static int
995 sysctl_shmsegs(SYSCTL_HANDLER_ARGS)
996 {
997 
998 	return (SYSCTL_OUT(req, shmsegs, shmalloced * sizeof(shmsegs[0])));
999 }
1000 
1001 static int
1002 sysvshm_modload(struct module *module, int cmd, void *arg)
1003 {
1004 	int error = 0;
1005 
1006 	switch (cmd) {
1007 	case MOD_LOAD:
1008 		shminit();
1009 		break;
1010 	case MOD_UNLOAD:
1011 		error = shmunload();
1012 		break;
1013 	case MOD_SHUTDOWN:
1014 		break;
1015 	default:
1016 		error = EINVAL;
1017 		break;
1018 	}
1019 	return (error);
1020 }
1021 
1022 static moduledata_t sysvshm_mod = {
1023 	"sysvshm",
1024 	&sysvshm_modload,
1025 	NULL
1026 };
1027 
1028 SYSCALL_MODULE_HELPER(shmsys);
1029 SYSCALL_MODULE_HELPER(shmat);
1030 SYSCALL_MODULE_HELPER(shmctl);
1031 SYSCALL_MODULE_HELPER(shmdt);
1032 SYSCALL_MODULE_HELPER(shmget);
1033 
1034 DECLARE_MODULE(sysvshm, sysvshm_mod,
1035 	SI_SUB_SYSV_SHM, SI_ORDER_FIRST);
1036 MODULE_VERSION(sysvshm, 1);
1037