Home | History | Annotate | Line # | Download | only in kern
sysv_shm.c revision 1.94
      1 /*	$NetBSD: sysv_shm.c,v 1.94 2007/02/07 18:45:36 rmind Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999 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.
     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  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *	This product includes software developed by the NetBSD
     22  *	Foundation, Inc. and its contributors.
     23  * 4. Neither the name of The NetBSD Foundation nor the names of its
     24  *    contributors may be used to endorse or promote products derived
     25  *    from this software without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     37  * POSSIBILITY OF SUCH DAMAGE.
     38  */
     39 
     40 /*
     41  * Copyright (c) 1994 Adam Glass and Charles M. Hannum.  All rights reserved.
     42  *
     43  * Redistribution and use in source and binary forms, with or without
     44  * modification, are permitted provided that the following conditions
     45  * are met:
     46  * 1. Redistributions of source code must retain the above copyright
     47  *    notice, this list of conditions and the following disclaimer.
     48  * 2. Redistributions in binary form must reproduce the above copyright
     49  *    notice, this list of conditions and the following disclaimer in the
     50  *    documentation and/or other materials provided with the distribution.
     51  * 3. All advertising materials mentioning features or use of this software
     52  *    must display the following acknowledgement:
     53  *	This product includes software developed by Adam Glass and Charles M.
     54  *	Hannum.
     55  * 4. The names of the authors may not be used to endorse or promote products
     56  *    derived from this software without specific prior written permission.
     57  *
     58  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
     59  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     60  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     61  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
     62  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     63  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     64  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     65  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     66  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     67  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     68  */
     69 
     70 #include <sys/cdefs.h>
     71 __KERNEL_RCSID(0, "$NetBSD: sysv_shm.c,v 1.94 2007/02/07 18:45:36 rmind Exp $");
     72 
     73 #define SYSVSHM
     74 
     75 #include <sys/param.h>
     76 #include <sys/kernel.h>
     77 #include <sys/shm.h>
     78 #include <sys/lock.h>
     79 #include <sys/malloc.h>
     80 #include <sys/mman.h>
     81 #include <sys/stat.h>
     82 #include <sys/sysctl.h>
     83 #include <sys/mount.h>		/* XXX for <sys/syscallargs.h> */
     84 #include <sys/sa.h>
     85 #include <sys/syscallargs.h>
     86 #include <sys/queue.h>
     87 #include <sys/pool.h>
     88 #include <sys/kauth.h>
     89 
     90 #include <uvm/uvm_extern.h>
     91 #include <uvm/uvm_object.h>
     92 
     93 static MALLOC_DEFINE(M_SHM, "shm", "SVID compatible shared memory segments");
     94 
     95 /*
     96  * Provides the following externally accessible functions:
     97  *
     98  * shminit(void);		                 initialization
     99  * shmexit(struct vmspace *)                     cleanup
    100  * shmfork(struct vmspace *, struct vmspace *)   fork handling
    101  *
    102  * Structures:
    103  * shmsegs (an array of 'struct shmid_ds')
    104  * per proc array of 'struct shmmap_state'
    105  */
    106 
    107 int shm_nused;
    108 struct	shmid_ds *shmsegs;
    109 
    110 struct shmmap_entry {
    111 	SLIST_ENTRY(shmmap_entry) next;
    112 	vaddr_t va;
    113 	int shmid;
    114 };
    115 
    116 struct lock	shm_lock;
    117 static int	shm_last_free, shm_committed, shm_use_phys;
    118 
    119 static POOL_INIT(shmmap_entry_pool, sizeof(struct shmmap_entry), 0, 0, 0,
    120     "shmmp", &pool_allocator_nointr);
    121 
    122 struct shmmap_state {
    123 	unsigned int nitems;
    124 	unsigned int nrefs;
    125 	SLIST_HEAD(, shmmap_entry) entries;
    126 };
    127 
    128 static int shm_find_segment_by_key(key_t);
    129 static void shm_deallocate_segment(struct shmid_ds *);
    130 static void shm_delete_mapping(struct vmspace *, struct shmmap_state *,
    131 			       struct shmmap_entry *);
    132 static int shmget_existing(struct lwp *, struct sys_shmget_args *,
    133 			   int, int, register_t *);
    134 static int shmget_allocate_segment(struct lwp *, struct sys_shmget_args *,
    135 				   int, register_t *);
    136 static struct shmmap_state *shmmap_getprivate(struct proc *);
    137 static struct shmmap_entry *shm_find_mapping(struct shmmap_state *, vaddr_t);
    138 static int shmrealloc(int);
    139 
    140 static int
    141 shm_find_segment_by_key(key_t key)
    142 {
    143 	int i;
    144 
    145 	for (i = 0; i < shminfo.shmmni; i++)
    146 		if ((shmsegs[i].shm_perm.mode & SHMSEG_ALLOCATED) &&
    147 		    shmsegs[i].shm_perm._key == key)
    148 			return i;
    149 	return -1;
    150 }
    151 
    152 static struct shmid_ds *
    153 shm_find_segment_by_shmid(int shmid)
    154 {
    155 	int segnum;
    156 	struct shmid_ds *shmseg;
    157 
    158 	segnum = IPCID_TO_IX(shmid);
    159 	if (segnum < 0 || segnum >= shminfo.shmmni)
    160 		return NULL;
    161 	shmseg = &shmsegs[segnum];
    162 	if ((shmseg->shm_perm.mode & SHMSEG_ALLOCATED) == 0)
    163 		return NULL;
    164 	if ((shmseg->shm_perm.mode & (SHMSEG_REMOVED|SHMSEG_RMLINGER)) == SHMSEG_REMOVED)
    165 		return NULL;
    166 	if (shmseg->shm_perm._seq != IPCID_TO_SEQ(shmid))
    167 		return NULL;
    168 	return shmseg;
    169 }
    170 
    171 static void
    172 shm_deallocate_segment(struct shmid_ds *shmseg)
    173 {
    174 	struct uvm_object *uobj = shmseg->_shm_internal;
    175 	size_t size = (shmseg->shm_segsz + PGOFSET) & ~PGOFSET;
    176 
    177 #ifdef SHMDEBUG
    178 	printf("shm freeing key 0x%lx seq 0x%x\n",
    179 	       shmseg->shm_perm._key, shmseg->shm_perm._seq);
    180 #endif
    181 
    182 	(*uobj->pgops->pgo_detach)(uobj);
    183 	shmseg->_shm_internal = NULL;
    184 	shm_committed -= btoc(size);
    185 	shmseg->shm_perm.mode = SHMSEG_FREE;
    186 	shm_nused--;
    187 }
    188 
    189 static void
    190 shm_delete_mapping(struct vmspace *vm, struct shmmap_state *shmmap_s,
    191     struct shmmap_entry *shmmap_se)
    192 {
    193 	struct shmid_ds *shmseg;
    194 	int segnum;
    195 	size_t size;
    196 
    197 	segnum = IPCID_TO_IX(shmmap_se->shmid);
    198 #ifdef DEBUG
    199 	if (segnum < 0 || segnum >= shminfo.shmmni)
    200 		panic("shm_delete_mapping: vmspace %p state %p entry %p - "
    201 		    "entry segment ID bad (%d)",
    202 		    vm, shmmap_s, shmmap_se, segnum);
    203 #endif
    204 	shmseg = &shmsegs[segnum];
    205 	size = (shmseg->shm_segsz + PGOFSET) & ~PGOFSET;
    206 	uvm_deallocate(&vm->vm_map, shmmap_se->va, size);
    207 	SLIST_REMOVE(&shmmap_s->entries, shmmap_se, shmmap_entry, next);
    208 	shmmap_s->nitems--;
    209 	pool_put(&shmmap_entry_pool, shmmap_se);
    210 	shmseg->shm_dtime = time_second;
    211 	if ((--shmseg->shm_nattch <= 0) &&
    212 	    (shmseg->shm_perm.mode & SHMSEG_REMOVED)) {
    213 		shm_deallocate_segment(shmseg);
    214 		shm_last_free = segnum;
    215 	}
    216 }
    217 
    218 /*
    219  * Get a non-shared shm map for that vmspace.
    220  * 3 cases:
    221  *   - no shm map present: create a fresh one
    222  *   - a shm map with refcount=1, just used by ourselves: fine
    223  *   - a shared shm map: copy to a fresh one and adjust refcounts
    224  */
    225 static struct shmmap_state *
    226 shmmap_getprivate(struct proc *p)
    227 {
    228 	struct shmmap_state *oshmmap_s, *shmmap_s;
    229 	struct shmmap_entry *oshmmap_se, *shmmap_se;
    230 
    231 	oshmmap_s = (struct shmmap_state *)p->p_vmspace->vm_shm;
    232 	if (oshmmap_s && oshmmap_s->nrefs == 1)
    233 		return (oshmmap_s);
    234 
    235 	shmmap_s = malloc(sizeof(struct shmmap_state), M_SHM, M_WAITOK);
    236 	memset(shmmap_s, 0, sizeof(struct shmmap_state));
    237 	shmmap_s->nrefs = 1;
    238 	SLIST_INIT(&shmmap_s->entries);
    239 	p->p_vmspace->vm_shm = (caddr_t)shmmap_s;
    240 
    241 	if (!oshmmap_s)
    242 		return (shmmap_s);
    243 
    244 #ifdef SHMDEBUG
    245 	printf("shmmap_getprivate: vm %p split (%d entries), was used by %d\n",
    246 	       p->p_vmspace, oshmmap_s->nitems, oshmmap_s->nrefs);
    247 #endif
    248 	SLIST_FOREACH(oshmmap_se, &oshmmap_s->entries, next) {
    249 		shmmap_se = pool_get(&shmmap_entry_pool, PR_WAITOK);
    250 		shmmap_se->va = oshmmap_se->va;
    251 		shmmap_se->shmid = oshmmap_se->shmid;
    252 		SLIST_INSERT_HEAD(&shmmap_s->entries, shmmap_se, next);
    253 	}
    254 	shmmap_s->nitems = oshmmap_s->nitems;
    255 	oshmmap_s->nrefs--;
    256 	return (shmmap_s);
    257 }
    258 
    259 static struct shmmap_entry *
    260 shm_find_mapping(struct shmmap_state *map, vaddr_t va)
    261 {
    262 	struct shmmap_entry *shmmap_se;
    263 
    264 	SLIST_FOREACH(shmmap_se, &map->entries, next) {
    265 		if (shmmap_se->va == va)
    266 			return shmmap_se;
    267 	}
    268 	return 0;
    269 }
    270 
    271 int
    272 sys_shmdt(struct lwp *l, void *v, register_t *retval)
    273 {
    274 	struct sys_shmdt_args /* {
    275 		syscallarg(const void *) shmaddr;
    276 	} */ *uap = v;
    277 	struct proc *p = l->l_proc;
    278 	struct shmmap_state *shmmap_s, *shmmap_s1;
    279 	struct shmmap_entry *shmmap_se;
    280 
    281 	shmmap_s = (struct shmmap_state *)p->p_vmspace->vm_shm;
    282 	if (shmmap_s == NULL)
    283 		return EINVAL;
    284 
    285 	shmmap_se = shm_find_mapping(shmmap_s, (vaddr_t)SCARG(uap, shmaddr));
    286 	if (!shmmap_se)
    287 		return EINVAL;
    288 
    289 	shmmap_s1 = shmmap_getprivate(p);
    290 	if (shmmap_s1 != shmmap_s) {
    291 		/* map has been copied, lookup entry in new map */
    292 		shmmap_se = shm_find_mapping(shmmap_s1,
    293 					     (vaddr_t)SCARG(uap, shmaddr));
    294 		KASSERT(shmmap_se != NULL);
    295 	}
    296 #ifdef SHMDEBUG
    297 	printf("shmdt: vm %p: remove %d @%lx\n",
    298 	       p->p_vmspace, shmmap_se->shmid, shmmap_se->va);
    299 #endif
    300 	shm_delete_mapping(p->p_vmspace, shmmap_s1, shmmap_se);
    301 	return 0;
    302 }
    303 
    304 int
    305 sys_shmat(struct lwp *l, void *v, register_t *retval)
    306 {
    307 	struct sys_shmat_args /* {
    308 		syscallarg(int) shmid;
    309 		syscallarg(const void *) shmaddr;
    310 		syscallarg(int) shmflg;
    311 	} */ *uap = v;
    312 	int error, flags = 0;
    313 	struct proc *p = l->l_proc;
    314 	kauth_cred_t cred = l->l_cred;
    315 	struct shmid_ds *shmseg;
    316 	struct shmmap_state *shmmap_s;
    317 	struct uvm_object *uobj;
    318 	vaddr_t attach_va;
    319 	vm_prot_t prot;
    320 	vsize_t size;
    321 	struct shmmap_entry *shmmap_se;
    322 
    323 	shmseg = shm_find_segment_by_shmid(SCARG(uap, shmid));
    324 	if (shmseg == NULL)
    325 		return EINVAL;
    326 	error = ipcperm(cred, &shmseg->shm_perm,
    327 		    (SCARG(uap, shmflg) & SHM_RDONLY) ? IPC_R : IPC_R|IPC_W);
    328 	if (error)
    329 		return error;
    330 
    331 	shmmap_s = (struct shmmap_state *)p->p_vmspace->vm_shm;
    332 	if (shmmap_s && shmmap_s->nitems >= shminfo.shmseg)
    333 		return EMFILE;
    334 
    335 	size = (shmseg->shm_segsz + PGOFSET) & ~PGOFSET;
    336 	prot = VM_PROT_READ;
    337 	if ((SCARG(uap, shmflg) & SHM_RDONLY) == 0)
    338 		prot |= VM_PROT_WRITE;
    339 	if (SCARG(uap, shmaddr)) {
    340 		flags |= UVM_FLAG_FIXED;
    341 		if (SCARG(uap, shmflg) & SHM_RND)
    342 			attach_va =
    343 			    (vaddr_t)SCARG(uap, shmaddr) & ~(SHMLBA-1);
    344 		else if (((vaddr_t)SCARG(uap, shmaddr) & (SHMLBA-1)) == 0)
    345 			attach_va = (vaddr_t)SCARG(uap, shmaddr);
    346 		else
    347 			return EINVAL;
    348 	} else {
    349 		/* This is just a hint to uvm_mmap() about where to put it. */
    350 		attach_va = p->p_emul->e_vm_default_addr(p,
    351 		    (vaddr_t)p->p_vmspace->vm_daddr, size);
    352 	}
    353 	uobj = shmseg->_shm_internal;
    354 	(*uobj->pgops->pgo_reference)(uobj);
    355 	error = uvm_map(&p->p_vmspace->vm_map, &attach_va, size,
    356 	    uobj, 0, 0,
    357 	    UVM_MAPFLAG(prot, prot, UVM_INH_SHARE, UVM_ADV_RANDOM, flags));
    358 	if (error)
    359 		goto out;
    360 	/* Lock the memory */
    361 	if (shm_use_phys || (shmseg->shm_perm.mode & SHMSEG_WIRED)) {
    362 		/* Wire the map */
    363 		error = uvm_map_pageable(&p->p_vmspace->vm_map, attach_va,
    364 		    attach_va + size, FALSE, 0);
    365 		if (error) {
    366 			if (error == EFAULT)
    367 				error = ENOMEM;
    368 			goto out;
    369 		}
    370 	}
    371 
    372 	shmmap_se = pool_get(&shmmap_entry_pool, PR_WAITOK);
    373 	shmmap_se->va = attach_va;
    374 	shmmap_se->shmid = SCARG(uap, shmid);
    375 	shmmap_s = shmmap_getprivate(p);
    376 #ifdef SHMDEBUG
    377 	printf("shmat: vm %p: add %d @%lx\n", p->p_vmspace, shmmap_se->shmid, attach_va);
    378 #endif
    379 	SLIST_INSERT_HEAD(&shmmap_s->entries, shmmap_se, next);
    380 	shmmap_s->nitems++;
    381 	shmseg->shm_lpid = p->p_pid;
    382 	shmseg->shm_atime = time_second;
    383 	shmseg->shm_nattch++;
    384 
    385 	retval[0] = attach_va;
    386 	return 0;
    387 out:
    388 	(*uobj->pgops->pgo_detach)(uobj);
    389 	return error;
    390 }
    391 
    392 int
    393 sys___shmctl13(struct lwp *l, void *v, register_t *retval)
    394 {
    395 	struct sys___shmctl13_args /* {
    396 		syscallarg(int) shmid;
    397 		syscallarg(int) cmd;
    398 		syscallarg(struct shmid_ds *) buf;
    399 	} */ *uap = v;
    400 	struct shmid_ds shmbuf;
    401 	int cmd, error;
    402 
    403 	cmd = SCARG(uap, cmd);
    404 
    405 	if (cmd == IPC_SET) {
    406 		error = copyin(SCARG(uap, buf), &shmbuf, sizeof(shmbuf));
    407 		if (error)
    408 			return (error);
    409 	}
    410 
    411 	error = shmctl1(l, SCARG(uap, shmid), cmd,
    412 	    (cmd == IPC_SET || cmd == IPC_STAT) ? &shmbuf : NULL);
    413 
    414 	if (error == 0 && cmd == IPC_STAT)
    415 		error = copyout(&shmbuf, SCARG(uap, buf), sizeof(shmbuf));
    416 
    417 	return (error);
    418 }
    419 
    420 int
    421 shmctl1(struct lwp *l, int shmid, int cmd, struct shmid_ds *shmbuf)
    422 {
    423 	kauth_cred_t cred = l->l_cred;
    424  	struct proc *p = l->l_proc;
    425 	struct shmid_ds *shmseg;
    426 	struct shmmap_entry *shmmap_se;
    427 	struct shmmap_state *shmmap_s;
    428 	int error = 0;
    429 	size_t size;
    430 
    431 	shmseg = shm_find_segment_by_shmid(shmid);
    432 	if (shmseg == NULL)
    433 		return EINVAL;
    434 
    435 	switch (cmd) {
    436 	case IPC_STAT:
    437 		if ((error = ipcperm(cred, &shmseg->shm_perm, IPC_R)) != 0)
    438 			return error;
    439 		memcpy(shmbuf, shmseg, sizeof(struct shmid_ds));
    440 		break;
    441 	case IPC_SET:
    442 		if ((error = ipcperm(cred, &shmseg->shm_perm, IPC_M)) != 0)
    443 			return error;
    444 		shmseg->shm_perm.uid = shmbuf->shm_perm.uid;
    445 		shmseg->shm_perm.gid = shmbuf->shm_perm.gid;
    446 		shmseg->shm_perm.mode =
    447 		    (shmseg->shm_perm.mode & ~ACCESSPERMS) |
    448 		    (shmbuf->shm_perm.mode & ACCESSPERMS);
    449 		shmseg->shm_ctime = time_second;
    450 		break;
    451 	case IPC_RMID:
    452 		if ((error = ipcperm(cred, &shmseg->shm_perm, IPC_M)) != 0)
    453 			return error;
    454 		shmseg->shm_perm._key = IPC_PRIVATE;
    455 		shmseg->shm_perm.mode |= SHMSEG_REMOVED;
    456 		if (shmseg->shm_nattch <= 0) {
    457 			shm_deallocate_segment(shmseg);
    458 			shm_last_free = IPCID_TO_IX(shmid);
    459 		}
    460 		break;
    461 	case SHM_LOCK:
    462 	case SHM_UNLOCK:
    463 		if ((error = kauth_authorize_generic(cred,
    464 		    KAUTH_GENERIC_ISSUSER, NULL)) != 0)
    465 			return error;
    466 		shmmap_s = shmmap_getprivate(p);
    467 		/* Find our shared memory address by shmid */
    468 		SLIST_FOREACH(shmmap_se, &shmmap_s->entries, next) {
    469 			if (shmmap_se->shmid != shmid)
    470 				continue;
    471 
    472 			size = (shmseg->shm_segsz + PGOFSET) & ~PGOFSET;
    473 
    474 			if (cmd == SHM_LOCK &&
    475 			    !(shmseg->shm_perm.mode & SHMSEG_WIRED)) {
    476 				/* Wire the entire object */
    477 				error = uobj_wirepages(shmseg->_shm_internal, 0,
    478 					round_page(shmseg->shm_segsz));
    479 				if (error)
    480 					return EIO;
    481 				/* Wire the map */
    482 				error = uvm_map_pageable(&p->p_vmspace->vm_map,
    483 				    shmmap_se->va, shmmap_se->va + size, FALSE,
    484 				    0);
    485 				if (error) {
    486 					uobj_unwirepages(shmseg->_shm_internal,
    487 					    0, round_page(shmseg->shm_segsz));
    488 					if (error == EFAULT)
    489 						error = ENOMEM;
    490 					return error;
    491 				}
    492 				/* Tag as wired */
    493 				shmseg->shm_perm.mode |= SHMSEG_WIRED;
    494 
    495 			} else if (cmd == SHM_UNLOCK &&
    496 			    (shmseg->shm_perm.mode & SHMSEG_WIRED)) {
    497 				/* Unwire the object */
    498 				uobj_unwirepages(shmseg->_shm_internal, 0,
    499 				    round_page(shmseg->shm_segsz));
    500 				error = uvm_map_pageable(&p->p_vmspace->vm_map,
    501 				    shmmap_se->va, shmmap_se->va + size, TRUE,
    502 				    0);
    503 				if (error) {
    504 					/*
    505 					 * In fact, uvm_map_pageable could fail
    506 					 * only if arguments are invalid,
    507 					 * otherwise it should allways return 0.
    508 					 */
    509 					return EIO;
    510 				}
    511 				/* Tag as unwired */
    512 				shmseg->shm_perm.mode &= ~SHMSEG_WIRED;
    513 			}
    514 		}
    515 		break;
    516 	default:
    517 		return EINVAL;
    518 	}
    519 	return 0;
    520 }
    521 
    522 static int
    523 shmget_existing(struct lwp *l, struct sys_shmget_args *uap, int mode,
    524     int segnum, register_t *retval)
    525 {
    526 	struct shmid_ds *shmseg;
    527 	kauth_cred_t cred = l->l_cred;
    528 	int error;
    529 
    530 	shmseg = &shmsegs[segnum];
    531 	if (shmseg->shm_perm.mode & SHMSEG_REMOVED) {
    532 		/*
    533 		 * This segment is in the process of being allocated.  Wait
    534 		 * until it's done, and look the key up again (in case the
    535 		 * allocation failed or it was freed).
    536 		 */
    537 		shmseg->shm_perm.mode |= SHMSEG_WANTED;
    538 		error = tsleep((caddr_t)shmseg, PLOCK | PCATCH, "shmget", 0);
    539 		if (error)
    540 			return error;
    541 		return EAGAIN;
    542 	}
    543 	if ((error = ipcperm(cred, &shmseg->shm_perm, mode)) != 0)
    544 		return error;
    545 	if (SCARG(uap, size) && SCARG(uap, size) > shmseg->shm_segsz)
    546 		return EINVAL;
    547 	if ((SCARG(uap, shmflg) & (IPC_CREAT | IPC_EXCL)) ==
    548 	    (IPC_CREAT | IPC_EXCL))
    549 		return EEXIST;
    550 	*retval = IXSEQ_TO_IPCID(segnum, shmseg->shm_perm);
    551 	return 0;
    552 }
    553 
    554 static int
    555 shmget_allocate_segment(struct lwp *l, struct sys_shmget_args *uap, int mode,
    556     register_t *retval)
    557 {
    558 	int i, segnum, shmid, size;
    559 	kauth_cred_t cred = l->l_cred;
    560 	struct shmid_ds *shmseg;
    561 	int error = 0;
    562 
    563 	if (SCARG(uap, size) < shminfo.shmmin ||
    564 	    SCARG(uap, size) > shminfo.shmmax)
    565 		return EINVAL;
    566 	if (shm_nused >= shminfo.shmmni) /* any shmids left? */
    567 		return ENOSPC;
    568 	size = (SCARG(uap, size) + PGOFSET) & ~PGOFSET;
    569 	if (shm_committed + btoc(size) > shminfo.shmall)
    570 		return ENOMEM;
    571 	if (shm_last_free < 0) {
    572 		for (i = 0; i < shminfo.shmmni; i++)
    573 			if (shmsegs[i].shm_perm.mode & SHMSEG_FREE)
    574 				break;
    575 		if (i == shminfo.shmmni)
    576 			panic("shmseg free count inconsistent");
    577 		segnum = i;
    578 	} else  {
    579 		segnum = shm_last_free;
    580 		shm_last_free = -1;
    581 	}
    582 	shmseg = &shmsegs[segnum];
    583 	/*
    584 	 * In case we sleep in malloc(), mark the segment present but deleted
    585 	 * so that noone else tries to create the same key.
    586 	 */
    587 	shmseg->shm_perm.mode = SHMSEG_ALLOCATED | SHMSEG_REMOVED;
    588 	shmseg->shm_perm._key = SCARG(uap, key);
    589 	shmseg->shm_perm._seq = (shmseg->shm_perm._seq + 1) & 0x7fff;
    590 	shmid = IXSEQ_TO_IPCID(segnum, shmseg->shm_perm);
    591 
    592 	shmseg->_shm_internal = uao_create(size, 0);
    593 
    594 	shmseg->shm_perm.cuid = shmseg->shm_perm.uid = kauth_cred_geteuid(cred);
    595 	shmseg->shm_perm.cgid = shmseg->shm_perm.gid = kauth_cred_getegid(cred);
    596 	shmseg->shm_perm.mode = (shmseg->shm_perm.mode & SHMSEG_WANTED) |
    597 	    (mode & (ACCESSPERMS|SHMSEG_RMLINGER)) | SHMSEG_ALLOCATED;
    598 	shmseg->shm_segsz = SCARG(uap, size);
    599 	shmseg->shm_cpid = l->l_proc->p_pid;
    600 	shmseg->shm_lpid = shmseg->shm_nattch = 0;
    601 	shmseg->shm_atime = shmseg->shm_dtime = 0;
    602 	shmseg->shm_ctime = time_second;
    603 	shm_committed += btoc(size);
    604 	shm_nused++;
    605 
    606 	*retval = shmid;
    607 	if (shmseg->shm_perm.mode & SHMSEG_WANTED) {
    608 		/*
    609 		 * Somebody else wanted this key while we were asleep.  Wake
    610 		 * them up now.
    611 		 */
    612 		shmseg->shm_perm.mode &= ~SHMSEG_WANTED;
    613 		wakeup((caddr_t)shmseg);
    614 	}
    615 
    616 	/* Lock the memory */
    617 	if (shm_use_phys) {
    618 		/* Wire the entire object */
    619 		error = uobj_wirepages(shmseg->_shm_internal, 0,
    620 		    round_page(shmseg->shm_segsz));
    621 		if (error) {
    622 			shm_deallocate_segment(shmseg);
    623 		} else {
    624 			/* Tag as wired */
    625 			shmseg->shm_perm.mode |= SHMSEG_WIRED;
    626 		}
    627 	}
    628 
    629 	return error;
    630 }
    631 
    632 int
    633 sys_shmget(struct lwp *l, void *v, register_t *retval)
    634 {
    635 	struct sys_shmget_args /* {
    636 		syscallarg(key_t) key;
    637 		syscallarg(int) size;
    638 		syscallarg(int) shmflg;
    639 	} */ *uap = v;
    640 	int segnum, mode, error;
    641 
    642 	mode = SCARG(uap, shmflg) & ACCESSPERMS;
    643 	if (SCARG(uap, shmflg) & _SHM_RMLINGER)
    644 		mode |= SHMSEG_RMLINGER;
    645 
    646 #ifdef SHMDEBUG
    647 	printf("shmget: key 0x%lx size 0x%x shmflg 0x%x mode 0x%x\n",
    648         	SCARG(uap, key), SCARG(uap, size), SCARG(uap, shmflg), mode);
    649 #endif
    650 
    651 	if (SCARG(uap, key) != IPC_PRIVATE) {
    652 again:
    653 		segnum = shm_find_segment_by_key(SCARG(uap, key));
    654 		if (segnum >= 0) {
    655 			error = shmget_existing(l, uap, mode, segnum, retval);
    656 			if (error == EAGAIN)
    657 				goto again;
    658 			return error;
    659 		}
    660 		if ((SCARG(uap, shmflg) & IPC_CREAT) == 0)
    661 			return ENOENT;
    662 	}
    663 	return shmget_allocate_segment(l, uap, mode, retval);
    664 }
    665 
    666 void
    667 shmfork(struct vmspace *vm1, struct vmspace *vm2)
    668 {
    669 	struct shmmap_state *shmmap_s;
    670 	struct shmmap_entry *shmmap_se;
    671 
    672 	vm2->vm_shm = vm1->vm_shm;
    673 
    674 	if (vm1->vm_shm == NULL)
    675 		return;
    676 
    677 #ifdef SHMDEBUG
    678 	printf("shmfork %p->%p\n", vm1, vm2);
    679 #endif
    680 
    681 	shmmap_s = (struct shmmap_state *)vm1->vm_shm;
    682 
    683 	SLIST_FOREACH(shmmap_se, &shmmap_s->entries, next)
    684 		shmsegs[IPCID_TO_IX(shmmap_se->shmid)].shm_nattch++;
    685 	shmmap_s->nrefs++;
    686 }
    687 
    688 void
    689 shmexit(struct vmspace *vm)
    690 {
    691 	struct shmmap_state *shmmap_s;
    692 	struct shmmap_entry *shmmap_se;
    693 
    694 	shmmap_s = (struct shmmap_state *)vm->vm_shm;
    695 	if (shmmap_s == NULL)
    696 		return;
    697 
    698 	vm->vm_shm = NULL;
    699 
    700 	if (--shmmap_s->nrefs > 0) {
    701 #ifdef SHMDEBUG
    702 		printf("shmexit: vm %p drop ref (%d entries), now used by %d\n",
    703 		       vm, shmmap_s->nitems, shmmap_s->nrefs);
    704 #endif
    705 		SLIST_FOREACH(shmmap_se, &shmmap_s->entries, next)
    706 			shmsegs[IPCID_TO_IX(shmmap_se->shmid)].shm_nattch--;
    707 		return;
    708 	}
    709 
    710 #ifdef SHMDEBUG
    711 	printf("shmexit: vm %p cleanup (%d entries)\n", vm, shmmap_s->nitems);
    712 #endif
    713 	while (!SLIST_EMPTY(&shmmap_s->entries)) {
    714 		shmmap_se = SLIST_FIRST(&shmmap_s->entries);
    715 		shm_delete_mapping(vm, shmmap_s, shmmap_se);
    716 	}
    717 	KASSERT(shmmap_s->nitems == 0);
    718 	free(shmmap_s, M_SHM);
    719 }
    720 
    721 static int
    722 shmrealloc(int newshmni)
    723 {
    724 	int i, sz;
    725 	vaddr_t v;
    726 	struct shmid_ds *newshmsegs;
    727 
    728 	/* XXX: Would be good to have a upper limit */
    729 	if (newshmni < 1)
    730 		return EINVAL;
    731 
    732 	/* We can't reallocate less memory than we use */
    733 	if (shm_nused > newshmni)
    734 		return EPERM;
    735 
    736 	/* Allocate new memory area */
    737 	sz = newshmni * sizeof(struct shmid_ds);
    738 	v = uvm_km_alloc(kernel_map, round_page(sz), 0, UVM_KMF_WIRED);
    739 	if (v == 0)
    740 		return ENOMEM;
    741 
    742 	newshmsegs = (void *)v;
    743 
    744 	/* Copy all memory to the new area */
    745 	for (i = 0; i < shm_nused; i++)
    746 		(void)memcpy(&newshmsegs[i], &shmsegs[i],
    747 		    sizeof(newshmsegs[0]));
    748 
    749 	/* Mark as free all new segments, if there is any */
    750 	for (; i < newshmni; i++) {
    751 		newshmsegs[i].shm_perm.mode = SHMSEG_FREE;
    752 		newshmsegs[i].shm_perm._seq = 0;
    753 	}
    754 
    755 	sz = shminfo.shmmni * sizeof(struct shmid_ds);
    756 	uvm_km_free(kernel_map, (vaddr_t)shmsegs, sz, UVM_KMF_WIRED);
    757 	shmsegs = newshmsegs;
    758 
    759 	return 0;
    760 }
    761 
    762 void
    763 shminit(void)
    764 {
    765 	int i, sz;
    766 	vaddr_t v;
    767 
    768 	lockinit(&shm_lock, PWAIT, "shmlk", 0, 0);
    769 
    770 	/* Allocate pageable memory for our structures */
    771 	sz = shminfo.shmmni * sizeof(struct shmid_ds);
    772 	v = uvm_km_alloc(kernel_map, round_page(sz), 0, UVM_KMF_WIRED);
    773 	if (v == 0)
    774 		panic("sysv_shm: cannot allocate memory");
    775 	shmsegs = (void *)v;
    776 
    777 	shminfo.shmmax *= PAGE_SIZE;
    778 
    779 	for (i = 0; i < shminfo.shmmni; i++) {
    780 		shmsegs[i].shm_perm.mode = SHMSEG_FREE;
    781 		shmsegs[i].shm_perm._seq = 0;
    782 	}
    783 	shm_last_free = 0;
    784 	shm_nused = 0;
    785 	shm_committed = 0;
    786 }
    787 
    788 static int
    789 sysctl_ipc_shmmni(SYSCTLFN_ARGS)
    790 {
    791 	int newsize, error;
    792 	struct sysctlnode node;
    793 	node = *rnode;
    794 	node.sysctl_data = &newsize;
    795 
    796 	newsize = shminfo.shmmni;
    797 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    798 	if (error || newp == NULL)
    799 		return error;
    800 
    801 	lockmgr(&shm_lock, LK_EXCLUSIVE, NULL);
    802 	error = shmrealloc(newsize);
    803 	if (error == 0)
    804 		shminfo.shmmni = newsize;
    805 	lockmgr(&shm_lock, LK_RELEASE, NULL);
    806 
    807 	return error;
    808 }
    809 
    810 static int
    811 sysctl_ipc_shmmaxpgs(SYSCTLFN_ARGS)
    812 {
    813 	int newsize, error;
    814 	struct sysctlnode node;
    815 	node = *rnode;
    816 	node.sysctl_data = &newsize;
    817 	newsize = shminfo.shmall;
    818 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    819 	if (error || newp == NULL)
    820 		return error;
    821 
    822 	/* XXX: Would be good to have a upper limit */
    823 	if (newsize < 1)
    824 		return EINVAL;
    825 
    826 	shminfo.shmall = newsize;
    827 	shminfo.shmmax = shminfo.shmall * PAGE_SIZE;
    828 
    829 	return 0;
    830 }
    831 
    832 SYSCTL_SETUP(sysctl_ipc_shm_setup, "sysctl kern.ipc subtree setup")
    833 {
    834 	sysctl_createv(clog, 0, NULL, NULL,
    835 		CTLFLAG_PERMANENT,
    836 		CTLTYPE_NODE, "kern", NULL,
    837 		NULL, 0, NULL, 0,
    838 		CTL_KERN, CTL_EOL);
    839 
    840 	sysctl_createv(clog, 0, NULL, NULL,
    841 		CTLFLAG_PERMANENT,
    842 		CTLTYPE_NODE, "ipc",
    843 		SYSCTL_DESCR("SysV IPC options"),
    844 		NULL, 0, NULL, 0,
    845 		CTL_KERN, KERN_SYSVIPC, CTL_EOL);
    846 
    847 	sysctl_createv(clog, 0, NULL, NULL,
    848 		CTLFLAG_PERMANENT | CTLFLAG_READONLY,
    849 		CTLTYPE_INT, "shmmax",
    850 		SYSCTL_DESCR("Max shared memory segment size in bytes"),
    851 		NULL, 0, &shminfo.shmmax, 0,
    852 		CTL_KERN, KERN_SYSVIPC, KERN_SYSVIPC_SHMMAX, CTL_EOL);
    853 
    854 	sysctl_createv(clog, 0, NULL, NULL,
    855 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
    856 		CTLTYPE_INT, "shmmni",
    857 		SYSCTL_DESCR("Max number of shared memory identifiers"),
    858 		sysctl_ipc_shmmni, 0, &shminfo.shmmni, 0,
    859 		CTL_KERN, KERN_SYSVIPC, KERN_SYSVIPC_SHMMNI, CTL_EOL);
    860 
    861 	sysctl_createv(clog, 0, NULL, NULL,
    862 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
    863 		CTLTYPE_INT, "shmseg",
    864 		SYSCTL_DESCR("Max shared memory segments per process"),
    865 		NULL, 0, &shminfo.shmseg, 0,
    866 		CTL_KERN, KERN_SYSVIPC, KERN_SYSVIPC_SHMSEG, CTL_EOL);
    867 
    868 	sysctl_createv(clog, 0, NULL, NULL,
    869 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
    870 		CTLTYPE_INT, "shmmaxpgs",
    871 		SYSCTL_DESCR("Max amount of shared memory in pages"),
    872 		sysctl_ipc_shmmaxpgs, 0, &shminfo.shmall, 0,
    873 		CTL_KERN, KERN_SYSVIPC, KERN_SYSVIPC_SHMMAXPGS, CTL_EOL);
    874 
    875 	sysctl_createv(clog, 0, NULL, NULL,
    876 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
    877 		CTLTYPE_INT, "shm_use_phys",
    878 		SYSCTL_DESCR("Enable/disable locking of shared memory in "
    879 		    "physical memory"), NULL, 0, &shm_use_phys, 0,
    880 		CTL_KERN, KERN_SYSVIPC, KERN_SYSVIPC_SHMUSEPHYS, CTL_EOL);
    881 }
    882