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