Home | History | Annotate | Line # | Download | only in kern
kern_resource.c revision 1.130
      1 /*	$NetBSD: kern_resource.c,v 1.130 2007/12/26 16:01:36 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1982, 1986, 1991, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  * (c) UNIX System Laboratories, Inc.
      7  * All or some portions of this file are derived from material licensed
      8  * to the University of California by American Telephone and Telegraph
      9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     10  * the permission of UNIX System Laboratories, Inc.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  *
     36  *	@(#)kern_resource.c	8.8 (Berkeley) 2/14/95
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 __KERNEL_RCSID(0, "$NetBSD: kern_resource.c,v 1.130 2007/12/26 16:01:36 ad Exp $");
     41 
     42 #include <sys/param.h>
     43 #include <sys/systm.h>
     44 #include <sys/kernel.h>
     45 #include <sys/file.h>
     46 #include <sys/resourcevar.h>
     47 #include <sys/malloc.h>
     48 #include <sys/namei.h>
     49 #include <sys/pool.h>
     50 #include <sys/proc.h>
     51 #include <sys/sysctl.h>
     52 #include <sys/timevar.h>
     53 #include <sys/kauth.h>
     54 #include <sys/atomic.h>
     55 #include <sys/mount.h>
     56 #include <sys/syscallargs.h>
     57 
     58 #include <uvm/uvm_extern.h>
     59 
     60 /*
     61  * Maximum process data and stack limits.
     62  * They are variables so they are patchable.
     63  */
     64 rlim_t maxdmap = MAXDSIZ;
     65 rlim_t maxsmap = MAXSSIZ;
     66 
     67 struct uihashhead *uihashtbl;
     68 u_long uihash;		/* size of hash table - 1 */
     69 kmutex_t uihashtbl_lock;
     70 
     71 static pool_cache_t plimit_cache;
     72 static pool_cache_t pstats_cache;
     73 
     74 void
     75 resource_init(void)
     76 {
     77 
     78 	plimit_cache = pool_cache_init(sizeof(struct plimit), 0, 0, 0,
     79 	    "plimitpl", NULL, IPL_NONE, NULL, NULL, NULL);
     80 	pstats_cache = pool_cache_init(sizeof(struct pstats), 0, 0, 0,
     81 	    "pstatspl", NULL, IPL_NONE, NULL, NULL, NULL);
     82 }
     83 
     84 /*
     85  * Resource controls and accounting.
     86  */
     87 
     88 int
     89 sys_getpriority(struct lwp *l, const struct sys_getpriority_args *uap, register_t *retval)
     90 {
     91 	/* {
     92 		syscallarg(int) which;
     93 		syscallarg(id_t) who;
     94 	} */
     95 	struct proc *curp = l->l_proc, *p;
     96 	int low = NZERO + PRIO_MAX + 1;
     97 	int who = SCARG(uap, who);
     98 
     99 	mutex_enter(&proclist_lock);
    100 	switch (SCARG(uap, which)) {
    101 	case PRIO_PROCESS:
    102 		if (who == 0)
    103 			p = curp;
    104 		else
    105 			p = p_find(who, PFIND_LOCKED);
    106 		if (p != NULL)
    107 			low = p->p_nice;
    108 		break;
    109 
    110 	case PRIO_PGRP: {
    111 		struct pgrp *pg;
    112 
    113 		if (who == 0)
    114 			pg = curp->p_pgrp;
    115 		else if ((pg = pg_find(who, PFIND_LOCKED)) == NULL)
    116 			break;
    117 		LIST_FOREACH(p, &pg->pg_members, p_pglist) {
    118 			if (p->p_nice < low)
    119 				low = p->p_nice;
    120 		}
    121 		break;
    122 	}
    123 
    124 	case PRIO_USER:
    125 		if (who == 0)
    126 			who = (int)kauth_cred_geteuid(l->l_cred);
    127 		PROCLIST_FOREACH(p, &allproc) {
    128 			mutex_enter(&p->p_mutex);
    129 			if (kauth_cred_geteuid(p->p_cred) ==
    130 			    (uid_t)who && p->p_nice < low)
    131 				low = p->p_nice;
    132 			mutex_exit(&p->p_mutex);
    133 		}
    134 		break;
    135 
    136 	default:
    137 		mutex_exit(&proclist_lock);
    138 		return (EINVAL);
    139 	}
    140 	mutex_exit(&proclist_lock);
    141 
    142 	if (low == NZERO + PRIO_MAX + 1)
    143 		return (ESRCH);
    144 	*retval = low - NZERO;
    145 	return (0);
    146 }
    147 
    148 /* ARGSUSED */
    149 int
    150 sys_setpriority(struct lwp *l, const struct sys_setpriority_args *uap, register_t *retval)
    151 {
    152 	/* {
    153 		syscallarg(int) which;
    154 		syscallarg(id_t) who;
    155 		syscallarg(int) prio;
    156 	} */
    157 	struct proc *curp = l->l_proc, *p;
    158 	int found = 0, error = 0;
    159 	int who = SCARG(uap, who);
    160 
    161 	mutex_enter(&proclist_lock);
    162 	switch (SCARG(uap, which)) {
    163 	case PRIO_PROCESS:
    164 		if (who == 0)
    165 			p = curp;
    166 		else
    167 			p = p_find(who, PFIND_LOCKED);
    168 		if (p != 0) {
    169 			mutex_enter(&p->p_mutex);
    170 			error = donice(l, p, SCARG(uap, prio));
    171 			mutex_exit(&p->p_mutex);
    172 		}
    173 		found++;
    174 		break;
    175 
    176 	case PRIO_PGRP: {
    177 		struct pgrp *pg;
    178 
    179 		if (who == 0)
    180 			pg = curp->p_pgrp;
    181 		else if ((pg = pg_find(who, PFIND_LOCKED)) == NULL)
    182 			break;
    183 		LIST_FOREACH(p, &pg->pg_members, p_pglist) {
    184 			mutex_enter(&p->p_mutex);
    185 			error = donice(l, p, SCARG(uap, prio));
    186 			mutex_exit(&p->p_mutex);
    187 			found++;
    188 		}
    189 		break;
    190 	}
    191 
    192 	case PRIO_USER:
    193 		if (who == 0)
    194 			who = (int)kauth_cred_geteuid(l->l_cred);
    195 		PROCLIST_FOREACH(p, &allproc) {
    196 			mutex_enter(&p->p_mutex);
    197 			if (kauth_cred_geteuid(p->p_cred) ==
    198 			    (uid_t)SCARG(uap, who)) {
    199 				error = donice(l, p, SCARG(uap, prio));
    200 				found++;
    201 			}
    202 			mutex_exit(&p->p_mutex);
    203 		}
    204 		break;
    205 
    206 	default:
    207 		error = EINVAL;
    208 		break;
    209 	}
    210 	mutex_exit(&proclist_lock);
    211 	if (found == 0)
    212 		return (ESRCH);
    213 	return (error);
    214 }
    215 
    216 /*
    217  * Renice a process.
    218  *
    219  * Call with the target process' credentials locked.
    220  */
    221 int
    222 donice(struct lwp *l, struct proc *chgp, int n)
    223 {
    224 	kauth_cred_t cred = l->l_cred;
    225 	int onice;
    226 
    227 	KASSERT(mutex_owned(&chgp->p_mutex));
    228 
    229 	if (n > PRIO_MAX)
    230 		n = PRIO_MAX;
    231 	if (n < PRIO_MIN)
    232 		n = PRIO_MIN;
    233 	n += NZERO;
    234 	onice = chgp->p_nice;
    235 	onice = chgp->p_nice;
    236 
    237   again:
    238 	if (kauth_authorize_process(cred, KAUTH_PROCESS_NICE, chgp,
    239 	    KAUTH_ARG(n), NULL, NULL))
    240 		return (EACCES);
    241 	mutex_spin_enter(&chgp->p_smutex);
    242 	if (onice != chgp->p_nice) {
    243 		mutex_spin_exit(&chgp->p_smutex);
    244 		goto again;
    245 	}
    246 	sched_nice(chgp, n);
    247 	mutex_spin_exit(&chgp->p_smutex);
    248 	return (0);
    249 }
    250 
    251 /* ARGSUSED */
    252 int
    253 sys_setrlimit(struct lwp *l, const struct sys_setrlimit_args *uap, register_t *retval)
    254 {
    255 	/* {
    256 		syscallarg(int) which;
    257 		syscallarg(const struct rlimit *) rlp;
    258 	} */
    259 	int which = SCARG(uap, which);
    260 	struct rlimit alim;
    261 	int error;
    262 
    263 	error = copyin(SCARG(uap, rlp), &alim, sizeof(struct rlimit));
    264 	if (error)
    265 		return (error);
    266 	return (dosetrlimit(l, l->l_proc, which, &alim));
    267 }
    268 
    269 int
    270 dosetrlimit(struct lwp *l, struct proc *p, int which, struct rlimit *limp)
    271 {
    272 	struct rlimit *alimp;
    273 	int error;
    274 
    275 	if ((u_int)which >= RLIM_NLIMITS)
    276 		return (EINVAL);
    277 
    278 	if (limp->rlim_cur < 0 || limp->rlim_max < 0)
    279 		return (EINVAL);
    280 
    281 	if (limp->rlim_cur > limp->rlim_max) {
    282 		/*
    283 		 * This is programming error. According to SUSv2, we should
    284 		 * return error in this case.
    285 		 */
    286 		return (EINVAL);
    287 	}
    288 
    289 	alimp = &p->p_rlimit[which];
    290 	/* if we don't change the value, no need to limcopy() */
    291 	if (limp->rlim_cur == alimp->rlim_cur &&
    292 	    limp->rlim_max == alimp->rlim_max)
    293 		return 0;
    294 
    295 	error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_RLIMIT,
    296 	    p, limp, KAUTH_ARG(which), NULL);
    297 	if (error)
    298 		return (error);
    299 
    300 	lim_privatise(p, false);
    301 	/* p->p_limit is now unchangeable */
    302 	alimp = &p->p_rlimit[which];
    303 
    304 	switch (which) {
    305 
    306 	case RLIMIT_DATA:
    307 		if (limp->rlim_cur > maxdmap)
    308 			limp->rlim_cur = maxdmap;
    309 		if (limp->rlim_max > maxdmap)
    310 			limp->rlim_max = maxdmap;
    311 		break;
    312 
    313 	case RLIMIT_STACK:
    314 		if (limp->rlim_cur > maxsmap)
    315 			limp->rlim_cur = maxsmap;
    316 		if (limp->rlim_max > maxsmap)
    317 			limp->rlim_max = maxsmap;
    318 
    319 		/*
    320 		 * Return EINVAL if the new stack size limit is lower than
    321 		 * current usage. Otherwise, the process would get SIGSEGV the
    322 		 * moment it would try to access anything on it's current stack.
    323 		 * This conforms to SUSv2.
    324 		 */
    325 		if (limp->rlim_cur < p->p_vmspace->vm_ssize * PAGE_SIZE
    326 		    || limp->rlim_max < p->p_vmspace->vm_ssize * PAGE_SIZE) {
    327 			return (EINVAL);
    328 		}
    329 
    330 		/*
    331 		 * Stack is allocated to the max at exec time with
    332 		 * only "rlim_cur" bytes accessible (In other words,
    333 		 * allocates stack dividing two contiguous regions at
    334 		 * "rlim_cur" bytes boundary).
    335 		 *
    336 		 * Since allocation is done in terms of page, roundup
    337 		 * "rlim_cur" (otherwise, contiguous regions
    338 		 * overlap).  If stack limit is going up make more
    339 		 * accessible, if going down make inaccessible.
    340 		 */
    341 		limp->rlim_cur = round_page(limp->rlim_cur);
    342 		if (limp->rlim_cur != alimp->rlim_cur) {
    343 			vaddr_t addr;
    344 			vsize_t size;
    345 			vm_prot_t prot;
    346 
    347 			if (limp->rlim_cur > alimp->rlim_cur) {
    348 				prot = VM_PROT_READ | VM_PROT_WRITE;
    349 				size = limp->rlim_cur - alimp->rlim_cur;
    350 				addr = (vaddr_t)p->p_vmspace->vm_minsaddr -
    351 				    limp->rlim_cur;
    352 			} else {
    353 				prot = VM_PROT_NONE;
    354 				size = alimp->rlim_cur - limp->rlim_cur;
    355 				addr = (vaddr_t)p->p_vmspace->vm_minsaddr -
    356 				     alimp->rlim_cur;
    357 			}
    358 			(void) uvm_map_protect(&p->p_vmspace->vm_map,
    359 			    addr, addr+size, prot, false);
    360 		}
    361 		break;
    362 
    363 	case RLIMIT_NOFILE:
    364 		if (limp->rlim_cur > maxfiles)
    365 			limp->rlim_cur = maxfiles;
    366 		if (limp->rlim_max > maxfiles)
    367 			limp->rlim_max = maxfiles;
    368 		break;
    369 
    370 	case RLIMIT_NPROC:
    371 		if (limp->rlim_cur > maxproc)
    372 			limp->rlim_cur = maxproc;
    373 		if (limp->rlim_max > maxproc)
    374 			limp->rlim_max = maxproc;
    375 		break;
    376 	}
    377 
    378 	mutex_enter(&p->p_limit->pl_lock);
    379 	*alimp = *limp;
    380 	mutex_exit(&p->p_limit->pl_lock);
    381 	return (0);
    382 }
    383 
    384 /* ARGSUSED */
    385 int
    386 sys_getrlimit(struct lwp *l, const struct sys_getrlimit_args *uap, register_t *retval)
    387 {
    388 	/* {
    389 		syscallarg(int) which;
    390 		syscallarg(struct rlimit *) rlp;
    391 	} */
    392 	struct proc *p = l->l_proc;
    393 	int which = SCARG(uap, which);
    394 	struct rlimit rl;
    395 
    396 	if ((u_int)which >= RLIM_NLIMITS)
    397 		return (EINVAL);
    398 
    399 	mutex_enter(&p->p_mutex);
    400 	memcpy(&rl, &p->p_rlimit[which], sizeof(rl));
    401 	mutex_exit(&p->p_mutex);
    402 
    403 	return copyout(&rl, SCARG(uap, rlp), sizeof(rl));
    404 }
    405 
    406 /*
    407  * Transform the running time and tick information in proc p into user,
    408  * system, and interrupt time usage.
    409  *
    410  * Should be called with p->p_smutex held unless called from exit1().
    411  */
    412 void
    413 calcru(struct proc *p, struct timeval *up, struct timeval *sp,
    414     struct timeval *ip, struct timeval *rp)
    415 {
    416 	uint64_t u, st, ut, it, tot;
    417 	struct lwp *l;
    418 	struct bintime tm;
    419 	struct timeval tv;
    420 
    421 	mutex_spin_enter(&p->p_stmutex);
    422 	st = p->p_sticks;
    423 	ut = p->p_uticks;
    424 	it = p->p_iticks;
    425 	mutex_spin_exit(&p->p_stmutex);
    426 
    427 	tm = p->p_rtime;
    428 
    429 	LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    430 		lwp_lock(l);
    431 		bintime_add(&tm, &l->l_rtime);
    432 		if ((l->l_flag & LW_RUNNING) != 0) {
    433 			struct bintime diff;
    434 			/*
    435 			 * Adjust for the current time slice.  This is
    436 			 * actually fairly important since the error
    437 			 * here is on the order of a time quantum,
    438 			 * which is much greater than the sampling
    439 			 * error.
    440 			 */
    441 			binuptime(&diff);
    442 			bintime_sub(&diff, &l->l_stime);
    443 			bintime_add(&tm, &diff);
    444 		}
    445 		lwp_unlock(l);
    446 	}
    447 
    448 	tot = st + ut + it;
    449 	bintime2timeval(&tm, &tv);
    450 	u = (uint64_t)tv.tv_sec * 1000000ul + tv.tv_usec;
    451 
    452 	if (tot == 0) {
    453 		/* No ticks, so can't use to share time out, split 50-50 */
    454 		st = ut = u / 2;
    455 	} else {
    456 		st = (u * st) / tot;
    457 		ut = (u * ut) / tot;
    458 	}
    459 	if (sp != NULL) {
    460 		sp->tv_sec = st / 1000000;
    461 		sp->tv_usec = st % 1000000;
    462 	}
    463 	if (up != NULL) {
    464 		up->tv_sec = ut / 1000000;
    465 		up->tv_usec = ut % 1000000;
    466 	}
    467 	if (ip != NULL) {
    468 		if (it != 0)
    469 			it = (u * it) / tot;
    470 		ip->tv_sec = it / 1000000;
    471 		ip->tv_usec = it % 1000000;
    472 	}
    473 	if (rp != NULL) {
    474 		*rp = tv;
    475 	}
    476 }
    477 
    478 /* ARGSUSED */
    479 int
    480 sys_getrusage(struct lwp *l, const struct sys_getrusage_args *uap, register_t *retval)
    481 {
    482 	/* {
    483 		syscallarg(int) who;
    484 		syscallarg(struct rusage *) rusage;
    485 	} */
    486 	struct rusage ru;
    487 	struct proc *p = l->l_proc;
    488 
    489 	switch (SCARG(uap, who)) {
    490 	case RUSAGE_SELF:
    491 		mutex_enter(&p->p_smutex);
    492 		memcpy(&ru, &p->p_stats->p_ru, sizeof(ru));
    493 		calcru(p, &ru.ru_utime, &ru.ru_stime, NULL, NULL);
    494 		mutex_exit(&p->p_smutex);
    495 		break;
    496 
    497 	case RUSAGE_CHILDREN:
    498 		mutex_enter(&p->p_smutex);
    499 		memcpy(&ru, &p->p_stats->p_cru, sizeof(ru));
    500 		mutex_exit(&p->p_smutex);
    501 		break;
    502 
    503 	default:
    504 		return EINVAL;
    505 	}
    506 
    507 	return copyout(&ru, SCARG(uap, rusage), sizeof(ru));
    508 }
    509 
    510 void
    511 ruadd(struct rusage *ru, struct rusage *ru2)
    512 {
    513 	long *ip, *ip2;
    514 	int i;
    515 
    516 	timeradd(&ru->ru_utime, &ru2->ru_utime, &ru->ru_utime);
    517 	timeradd(&ru->ru_stime, &ru2->ru_stime, &ru->ru_stime);
    518 	if (ru->ru_maxrss < ru2->ru_maxrss)
    519 		ru->ru_maxrss = ru2->ru_maxrss;
    520 	ip = &ru->ru_first; ip2 = &ru2->ru_first;
    521 	for (i = &ru->ru_last - &ru->ru_first; i >= 0; i--)
    522 		*ip++ += *ip2++;
    523 }
    524 
    525 /*
    526  * Make a copy of the plimit structure.
    527  * We share these structures copy-on-write after fork,
    528  * and copy when a limit is changed.
    529  *
    530  * Unfortunately (due to PL_SHAREMOD) it is possibly for the structure
    531  * we are copying to change beneath our feet!
    532  */
    533 struct plimit *
    534 lim_copy(struct plimit *lim)
    535 {
    536 	struct plimit *newlim;
    537 	char *corename;
    538 	size_t alen, len;
    539 
    540 	newlim = pool_cache_get(plimit_cache, PR_WAITOK);
    541 	mutex_init(&newlim->pl_lock, MUTEX_DEFAULT, IPL_NONE);
    542 	newlim->pl_flags = 0;
    543 	newlim->pl_refcnt = 1;
    544 	newlim->pl_sv_limit = NULL;
    545 
    546 	mutex_enter(&lim->pl_lock);
    547 	memcpy(newlim->pl_rlimit, lim->pl_rlimit,
    548 	    sizeof(struct rlimit) * RLIM_NLIMITS);
    549 
    550 	alen = 0;
    551 	corename = NULL;
    552 	for (;;) {
    553 		if (lim->pl_corename == defcorename) {
    554 			newlim->pl_corename = defcorename;
    555 			break;
    556 		}
    557 		len = strlen(lim->pl_corename) + 1;
    558 		if (len <= alen) {
    559 			newlim->pl_corename = corename;
    560 			memcpy(corename, lim->pl_corename, len);
    561 			corename = NULL;
    562 			break;
    563 		}
    564 		mutex_exit(&lim->pl_lock);
    565 		if (corename != NULL)
    566 			free(corename, M_TEMP);
    567 		alen = len;
    568 		corename = malloc(alen, M_TEMP, M_WAITOK);
    569 		mutex_enter(&lim->pl_lock);
    570 	}
    571 	mutex_exit(&lim->pl_lock);
    572 	if (corename != NULL)
    573 		free(corename, M_TEMP);
    574 	return newlim;
    575 }
    576 
    577 void
    578 lim_addref(struct plimit *lim)
    579 {
    580 	atomic_inc_uint(&lim->pl_refcnt);
    581 }
    582 
    583 /*
    584  * Give a process it's own private plimit structure.
    585  * This will only be shared (in fork) if modifications are to be shared.
    586  */
    587 void
    588 lim_privatise(struct proc *p, bool set_shared)
    589 {
    590 	struct plimit *lim, *newlim;
    591 
    592 	lim = p->p_limit;
    593 	if (lim->pl_flags & PL_WRITEABLE) {
    594 		if (set_shared)
    595 			lim->pl_flags |= PL_SHAREMOD;
    596 		return;
    597 	}
    598 
    599 	if (set_shared && lim->pl_flags & PL_SHAREMOD)
    600 		return;
    601 
    602 	newlim = lim_copy(lim);
    603 
    604 	mutex_enter(&p->p_mutex);
    605 	if (p->p_limit->pl_flags & PL_WRITEABLE) {
    606 		/* Someone crept in while we were busy */
    607 		mutex_exit(&p->p_mutex);
    608 		limfree(newlim);
    609 		if (set_shared)
    610 			p->p_limit->pl_flags |= PL_SHAREMOD;
    611 		return;
    612 	}
    613 
    614 	/*
    615 	 * Since most accesses to p->p_limit aren't locked, we must not
    616 	 * delete the old limit structure yet.
    617 	 */
    618 	newlim->pl_sv_limit = p->p_limit;
    619 	newlim->pl_flags |= PL_WRITEABLE;
    620 	if (set_shared)
    621 		newlim->pl_flags |= PL_SHAREMOD;
    622 	p->p_limit = newlim;
    623 	mutex_exit(&p->p_mutex);
    624 }
    625 
    626 void
    627 limfree(struct plimit *lim)
    628 {
    629 	struct plimit *sv_lim;
    630 
    631 	do {
    632 		if (atomic_dec_uint_nv(&lim->pl_refcnt) > 0)
    633 			return;
    634 		if (lim->pl_corename != defcorename)
    635 			free(lim->pl_corename, M_TEMP);
    636 		sv_lim = lim->pl_sv_limit;
    637 		mutex_destroy(&lim->pl_lock);
    638 		pool_cache_put(plimit_cache, lim);
    639 	} while ((lim = sv_lim) != NULL);
    640 }
    641 
    642 struct pstats *
    643 pstatscopy(struct pstats *ps)
    644 {
    645 
    646 	struct pstats *newps;
    647 
    648 	newps = pool_cache_get(pstats_cache, PR_WAITOK);
    649 
    650 	memset(&newps->pstat_startzero, 0,
    651 	(unsigned) ((char *)&newps->pstat_endzero -
    652 		    (char *)&newps->pstat_startzero));
    653 	memcpy(&newps->pstat_startcopy, &ps->pstat_startcopy,
    654 	((char *)&newps->pstat_endcopy -
    655 	 (char *)&newps->pstat_startcopy));
    656 
    657 	return (newps);
    658 
    659 }
    660 
    661 void
    662 pstatsfree(struct pstats *ps)
    663 {
    664 
    665 	pool_cache_put(pstats_cache, ps);
    666 }
    667 
    668 /*
    669  * sysctl interface in five parts
    670  */
    671 
    672 /*
    673  * a routine for sysctl proc subtree helpers that need to pick a valid
    674  * process by pid.
    675  */
    676 static int
    677 sysctl_proc_findproc(struct lwp *l, struct proc **p2, pid_t pid)
    678 {
    679 	struct proc *ptmp;
    680 	int error = 0;
    681 
    682 	if (pid == PROC_CURPROC)
    683 		ptmp = l->l_proc;
    684 	else if ((ptmp = pfind(pid)) == NULL)
    685 		error = ESRCH;
    686 
    687 	*p2 = ptmp;
    688 	return (error);
    689 }
    690 
    691 /*
    692  * sysctl helper routine for setting a process's specific corefile
    693  * name.  picks the process based on the given pid and checks the
    694  * correctness of the new value.
    695  */
    696 static int
    697 sysctl_proc_corename(SYSCTLFN_ARGS)
    698 {
    699 	struct proc *ptmp;
    700 	struct plimit *lim;
    701 	int error = 0, len;
    702 	char *cname;
    703 	char *ocore;
    704 	char *tmp;
    705 	struct sysctlnode node;
    706 
    707 	/*
    708 	 * is this all correct?
    709 	 */
    710 	if (namelen != 0)
    711 		return (EINVAL);
    712 	if (name[-1] != PROC_PID_CORENAME)
    713 		return (EINVAL);
    714 
    715 	/*
    716 	 * whom are we tweaking?
    717 	 */
    718 	error = sysctl_proc_findproc(l, &ptmp, (pid_t)name[-2]);
    719 	if (error)
    720 		return (error);
    721 
    722 	/* XXX this should be in p_find() */
    723 	error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_CANSEE,
    724 	    ptmp, NULL, NULL, NULL);
    725 	if (error)
    726 		return (error);
    727 
    728 	/*
    729 	 * let them modify a temporary copy of the core name
    730 	 */
    731 	cname = PNBUF_GET();
    732 	lim = ptmp->p_limit;
    733 	mutex_enter(&lim->pl_lock);
    734 	strlcpy(cname, lim->pl_corename, MAXPATHLEN);
    735 	mutex_exit(&lim->pl_lock);
    736 
    737 	node = *rnode;
    738 	node.sysctl_data = cname;
    739 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    740 
    741 	/*
    742 	 * if that failed, or they have nothing new to say, or we've
    743 	 * heard it before...
    744 	 */
    745 	if (error || newp == NULL)
    746 		goto done;
    747 	lim = ptmp->p_limit;
    748 	mutex_enter(&lim->pl_lock);
    749 	error = strcmp(cname, lim->pl_corename);
    750 	mutex_exit(&lim->pl_lock);
    751 	if (error == 0)
    752 		/* Unchanged */
    753 		goto done;
    754 
    755 	error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_CORENAME,
    756 	    ptmp, cname, NULL, NULL);
    757 	if (error)
    758 		return (error);
    759 
    760 	/*
    761 	 * no error yet and cname now has the new core name in it.
    762 	 * let's see if it looks acceptable.  it must be either "core"
    763 	 * or end in ".core" or "/core".
    764 	 */
    765 	len = strlen(cname);
    766 	if (len < 4) {
    767 		error = EINVAL;
    768 	} else if (strcmp(cname + len - 4, "core") != 0) {
    769 		error = EINVAL;
    770 	} else if (len > 4 && cname[len - 5] != '/' && cname[len - 5] != '.') {
    771 		error = EINVAL;
    772 	}
    773 	if (error != 0) {
    774 		goto done;
    775 	}
    776 
    777 	/*
    778 	 * hmm...looks good.  now...where do we put it?
    779 	 */
    780 	tmp = malloc(len + 1, M_TEMP, M_WAITOK|M_CANFAIL);
    781 	if (tmp == NULL) {
    782 		error = ENOMEM;
    783 		goto done;
    784 	}
    785 	memcpy(tmp, cname, len + 1);
    786 
    787 	lim_privatise(ptmp, false);
    788 	lim = ptmp->p_limit;
    789 	mutex_enter(&lim->pl_lock);
    790 	ocore = lim->pl_corename;
    791 	lim->pl_corename = tmp;
    792 	mutex_exit(&lim->pl_lock);
    793 	if (ocore != defcorename)
    794 		free(ocore, M_TEMP);
    795 
    796 done:
    797 	PNBUF_PUT(cname);
    798 	return error;
    799 }
    800 
    801 /*
    802  * sysctl helper routine for checking/setting a process's stop flags,
    803  * one for fork and one for exec.
    804  */
    805 static int
    806 sysctl_proc_stop(SYSCTLFN_ARGS)
    807 {
    808 	struct proc *ptmp;
    809 	int i, f, error = 0;
    810 	struct sysctlnode node;
    811 
    812 	if (namelen != 0)
    813 		return (EINVAL);
    814 
    815 	error = sysctl_proc_findproc(l, &ptmp, (pid_t)name[-2]);
    816 	if (error)
    817 		return (error);
    818 
    819 	/* XXX this should be in p_find() */
    820 	error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_CANSEE,
    821 	    ptmp, NULL, NULL, NULL);
    822 	if (error)
    823 		return (error);
    824 
    825 	switch (rnode->sysctl_num) {
    826 	case PROC_PID_STOPFORK:
    827 		f = PS_STOPFORK;
    828 		break;
    829 	case PROC_PID_STOPEXEC:
    830 		f = PS_STOPEXEC;
    831 		break;
    832 	case PROC_PID_STOPEXIT:
    833 		f = PS_STOPEXIT;
    834 		break;
    835 	default:
    836 		return (EINVAL);
    837 	}
    838 
    839 	i = (ptmp->p_flag & f) ? 1 : 0;
    840 	node = *rnode;
    841 	node.sysctl_data = &i;
    842 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    843 	if (error || newp == NULL)
    844 		return (error);
    845 
    846 	mutex_enter(&ptmp->p_smutex);
    847 	error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_STOPFLAG,
    848 	    ptmp, KAUTH_ARG(f), NULL, NULL);
    849 	if (error)
    850 		return (error);
    851 	if (i)
    852 		ptmp->p_sflag |= f;
    853 	else
    854 		ptmp->p_sflag &= ~f;
    855 	mutex_exit(&ptmp->p_smutex);
    856 
    857 	return (0);
    858 }
    859 
    860 /*
    861  * sysctl helper routine for a process's rlimits as exposed by sysctl.
    862  */
    863 static int
    864 sysctl_proc_plimit(SYSCTLFN_ARGS)
    865 {
    866 	struct proc *ptmp;
    867 	u_int limitno;
    868 	int which, error = 0;
    869         struct rlimit alim;
    870 	struct sysctlnode node;
    871 
    872 	if (namelen != 0)
    873 		return (EINVAL);
    874 
    875 	which = name[-1];
    876 	if (which != PROC_PID_LIMIT_TYPE_SOFT &&
    877 	    which != PROC_PID_LIMIT_TYPE_HARD)
    878 		return (EINVAL);
    879 
    880 	limitno = name[-2] - 1;
    881 	if (limitno >= RLIM_NLIMITS)
    882 		return (EINVAL);
    883 
    884 	if (name[-3] != PROC_PID_LIMIT)
    885 		return (EINVAL);
    886 
    887 	error = sysctl_proc_findproc(l, &ptmp, (pid_t)name[-4]);
    888 	if (error)
    889 		return (error);
    890 
    891 	/* XXX this should be in p_find() */
    892 	error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_CANSEE,
    893 	    ptmp, NULL, NULL, NULL);
    894 	if (error)
    895 		return (error);
    896 
    897 	node = *rnode;
    898 	memcpy(&alim, &ptmp->p_rlimit[limitno], sizeof(alim));
    899 	if (which == PROC_PID_LIMIT_TYPE_HARD)
    900 		node.sysctl_data = &alim.rlim_max;
    901 	else
    902 		node.sysctl_data = &alim.rlim_cur;
    903 
    904 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    905 	if (error || newp == NULL)
    906 		return (error);
    907 
    908 	return (dosetrlimit(l, ptmp, limitno, &alim));
    909 }
    910 
    911 /*
    912  * and finally, the actually glue that sticks it to the tree
    913  */
    914 SYSCTL_SETUP(sysctl_proc_setup, "sysctl proc subtree setup")
    915 {
    916 
    917 	sysctl_createv(clog, 0, NULL, NULL,
    918 		       CTLFLAG_PERMANENT,
    919 		       CTLTYPE_NODE, "proc", NULL,
    920 		       NULL, 0, NULL, 0,
    921 		       CTL_PROC, CTL_EOL);
    922 	sysctl_createv(clog, 0, NULL, NULL,
    923 		       CTLFLAG_PERMANENT|CTLFLAG_ANYNUMBER,
    924 		       CTLTYPE_NODE, "curproc",
    925 		       SYSCTL_DESCR("Per-process settings"),
    926 		       NULL, 0, NULL, 0,
    927 		       CTL_PROC, PROC_CURPROC, CTL_EOL);
    928 
    929 	sysctl_createv(clog, 0, NULL, NULL,
    930 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE|CTLFLAG_ANYWRITE,
    931 		       CTLTYPE_STRING, "corename",
    932 		       SYSCTL_DESCR("Core file name"),
    933 		       sysctl_proc_corename, 0, NULL, MAXPATHLEN,
    934 		       CTL_PROC, PROC_CURPROC, PROC_PID_CORENAME, CTL_EOL);
    935 	sysctl_createv(clog, 0, NULL, NULL,
    936 		       CTLFLAG_PERMANENT,
    937 		       CTLTYPE_NODE, "rlimit",
    938 		       SYSCTL_DESCR("Process limits"),
    939 		       NULL, 0, NULL, 0,
    940 		       CTL_PROC, PROC_CURPROC, PROC_PID_LIMIT, CTL_EOL);
    941 
    942 #define create_proc_plimit(s, n) do {					\
    943 	sysctl_createv(clog, 0, NULL, NULL,				\
    944 		       CTLFLAG_PERMANENT,				\
    945 		       CTLTYPE_NODE, s,					\
    946 		       SYSCTL_DESCR("Process " s " limits"),		\
    947 		       NULL, 0, NULL, 0,				\
    948 		       CTL_PROC, PROC_CURPROC, PROC_PID_LIMIT, n,	\
    949 		       CTL_EOL);					\
    950 	sysctl_createv(clog, 0, NULL, NULL,				\
    951 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE|CTLFLAG_ANYWRITE, \
    952 		       CTLTYPE_QUAD, "soft",				\
    953 		       SYSCTL_DESCR("Process soft " s " limit"),	\
    954 		       sysctl_proc_plimit, 0, NULL, 0,			\
    955 		       CTL_PROC, PROC_CURPROC, PROC_PID_LIMIT, n,	\
    956 		       PROC_PID_LIMIT_TYPE_SOFT, CTL_EOL);		\
    957 	sysctl_createv(clog, 0, NULL, NULL,				\
    958 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE|CTLFLAG_ANYWRITE, \
    959 		       CTLTYPE_QUAD, "hard",				\
    960 		       SYSCTL_DESCR("Process hard " s " limit"),	\
    961 		       sysctl_proc_plimit, 0, NULL, 0,			\
    962 		       CTL_PROC, PROC_CURPROC, PROC_PID_LIMIT, n,	\
    963 		       PROC_PID_LIMIT_TYPE_HARD, CTL_EOL);		\
    964 	} while (0/*CONSTCOND*/)
    965 
    966 	create_proc_plimit("cputime",		PROC_PID_LIMIT_CPU);
    967 	create_proc_plimit("filesize",		PROC_PID_LIMIT_FSIZE);
    968 	create_proc_plimit("datasize",		PROC_PID_LIMIT_DATA);
    969 	create_proc_plimit("stacksize",		PROC_PID_LIMIT_STACK);
    970 	create_proc_plimit("coredumpsize",	PROC_PID_LIMIT_CORE);
    971 	create_proc_plimit("memoryuse",		PROC_PID_LIMIT_RSS);
    972 	create_proc_plimit("memorylocked",	PROC_PID_LIMIT_MEMLOCK);
    973 	create_proc_plimit("maxproc",		PROC_PID_LIMIT_NPROC);
    974 	create_proc_plimit("descriptors",	PROC_PID_LIMIT_NOFILE);
    975 	create_proc_plimit("sbsize",		PROC_PID_LIMIT_SBSIZE);
    976 
    977 #undef create_proc_plimit
    978 
    979 	sysctl_createv(clog, 0, NULL, NULL,
    980 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE|CTLFLAG_ANYWRITE,
    981 		       CTLTYPE_INT, "stopfork",
    982 		       SYSCTL_DESCR("Stop process at fork(2)"),
    983 		       sysctl_proc_stop, 0, NULL, 0,
    984 		       CTL_PROC, PROC_CURPROC, PROC_PID_STOPFORK, CTL_EOL);
    985 	sysctl_createv(clog, 0, NULL, NULL,
    986 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE|CTLFLAG_ANYWRITE,
    987 		       CTLTYPE_INT, "stopexec",
    988 		       SYSCTL_DESCR("Stop process at execve(2)"),
    989 		       sysctl_proc_stop, 0, NULL, 0,
    990 		       CTL_PROC, PROC_CURPROC, PROC_PID_STOPEXEC, CTL_EOL);
    991 	sysctl_createv(clog, 0, NULL, NULL,
    992 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE|CTLFLAG_ANYWRITE,
    993 		       CTLTYPE_INT, "stopexit",
    994 		       SYSCTL_DESCR("Stop process before completing exit"),
    995 		       sysctl_proc_stop, 0, NULL, 0,
    996 		       CTL_PROC, PROC_CURPROC, PROC_PID_STOPEXIT, CTL_EOL);
    997 }
    998 
    999 void
   1000 uid_init(void)
   1001 {
   1002 
   1003 	/*
   1004 	 * XXXSMP This could be at IPL_SOFTNET, but for now we want
   1005 	 * to to be deadlock free, so it must be at IPL_VM.
   1006 	 */
   1007 	mutex_init(&uihashtbl_lock, MUTEX_DEFAULT, IPL_VM);
   1008 
   1009 	/*
   1010 	 * Ensure that uid 0 is always in the user hash table, as
   1011 	 * sbreserve() expects it available from interrupt context.
   1012 	 */
   1013 	(void)uid_find(0);
   1014 }
   1015 
   1016 struct uidinfo *
   1017 uid_find(uid_t uid)
   1018 {
   1019 	struct uidinfo *uip;
   1020 	struct uidinfo *newuip = NULL;
   1021 	struct uihashhead *uipp;
   1022 
   1023 	uipp = UIHASH(uid);
   1024 
   1025 again:
   1026 	mutex_enter(&uihashtbl_lock);
   1027 	LIST_FOREACH(uip, uipp, ui_hash)
   1028 		if (uip->ui_uid == uid) {
   1029 			mutex_exit(&uihashtbl_lock);
   1030 			if (newuip) {
   1031 				mutex_destroy(&newuip->ui_lock);
   1032 				free(newuip, M_PROC);
   1033 			}
   1034 			return uip;
   1035 		}
   1036 	if (newuip == NULL) {
   1037 		mutex_exit(&uihashtbl_lock);
   1038 		/* Must not be called from interrupt context. */
   1039 		newuip = malloc(sizeof(*uip), M_PROC, M_WAITOK | M_ZERO);
   1040 		/* XXX this could be IPL_SOFTNET */
   1041 		mutex_init(&newuip->ui_lock, MUTEX_DEFAULT, IPL_VM);
   1042 		goto again;
   1043 	}
   1044 	uip = newuip;
   1045 
   1046 	LIST_INSERT_HEAD(uipp, uip, ui_hash);
   1047 	uip->ui_uid = uid;
   1048 	mutex_exit(&uihashtbl_lock);
   1049 
   1050 	return uip;
   1051 }
   1052 
   1053 /*
   1054  * Change the count associated with number of processes
   1055  * a given user is using.
   1056  */
   1057 int
   1058 chgproccnt(uid_t uid, int diff)
   1059 {
   1060 	struct uidinfo *uip;
   1061 
   1062 	if (diff == 0)
   1063 		return 0;
   1064 
   1065 	uip = uid_find(uid);
   1066 	mutex_enter(&uip->ui_lock);
   1067 	uip->ui_proccnt += diff;
   1068 	KASSERT(uip->ui_proccnt >= 0);
   1069 	mutex_exit(&uip->ui_lock);
   1070 	return uip->ui_proccnt;
   1071 }
   1072 
   1073 int
   1074 chgsbsize(struct uidinfo *uip, u_long *hiwat, u_long to, rlim_t xmax)
   1075 {
   1076 	rlim_t nsb;
   1077 
   1078 	mutex_enter(&uip->ui_lock);
   1079 	nsb = uip->ui_sbsize + to - *hiwat;
   1080 	if (to > *hiwat && nsb > xmax) {
   1081 		mutex_exit(&uip->ui_lock);
   1082 		return 0;
   1083 	}
   1084 	*hiwat = to;
   1085 	uip->ui_sbsize = nsb;
   1086 	KASSERT(uip->ui_sbsize >= 0);
   1087 	mutex_exit(&uip->ui_lock);
   1088 	return 1;
   1089 }
   1090