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