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