Home | History | Annotate | Line # | Download | only in kern
kern_resource.c revision 1.116.2.2
      1 /*	$NetBSD: kern_resource.c,v 1.116.2.2 2007/05/13 17:36:35 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.116.2.2 2007/05/13 17:36:35 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/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 kmutex_t uihashtbl_lock;
     69 
     70 /*
     71  * Resource controls and accounting.
     72  */
     73 
     74 int
     75 sys_getpriority(struct lwp *l, void *v, register_t *retval)
     76 {
     77 	struct sys_getpriority_args /* {
     78 		syscallarg(int) which;
     79 		syscallarg(id_t) who;
     80 	} */ *uap = v;
     81 	struct proc *curp = l->l_proc, *p;
     82 	int low = NZERO + PRIO_MAX + 1;
     83 	int who = SCARG(uap, who);
     84 
     85 	mutex_enter(&proclist_lock);
     86 	switch (SCARG(uap, which)) {
     87 	case PRIO_PROCESS:
     88 		if (who == 0)
     89 			p = curp;
     90 		else
     91 			p = p_find(who, PFIND_LOCKED);
     92 		if (p != NULL)
     93 			low = p->p_nice;
     94 		break;
     95 
     96 	case PRIO_PGRP: {
     97 		struct pgrp *pg;
     98 
     99 		if (who == 0)
    100 			pg = curp->p_pgrp;
    101 		else if ((pg = pg_find(who, PFIND_LOCKED)) == NULL)
    102 			break;
    103 		LIST_FOREACH(p, &pg->pg_members, p_pglist) {
    104 			if (p->p_nice < low)
    105 				low = p->p_nice;
    106 		}
    107 		break;
    108 	}
    109 
    110 	case PRIO_USER:
    111 		if (who == 0)
    112 			who = (int)kauth_cred_geteuid(l->l_cred);
    113 		PROCLIST_FOREACH(p, &allproc) {
    114 			mutex_enter(&p->p_mutex);
    115 			if (kauth_cred_geteuid(p->p_cred) ==
    116 			    (uid_t)who && p->p_nice < low)
    117 				low = p->p_nice;
    118 			mutex_exit(&p->p_mutex);
    119 		}
    120 		break;
    121 
    122 	default:
    123 		mutex_exit(&proclist_lock);
    124 		return (EINVAL);
    125 	}
    126 	mutex_exit(&proclist_lock);
    127 
    128 	if (low == NZERO + PRIO_MAX + 1)
    129 		return (ESRCH);
    130 	*retval = low - NZERO;
    131 	return (0);
    132 }
    133 
    134 /* ARGSUSED */
    135 int
    136 sys_setpriority(struct lwp *l, void *v, register_t *retval)
    137 {
    138 	struct sys_setpriority_args /* {
    139 		syscallarg(int) which;
    140 		syscallarg(id_t) who;
    141 		syscallarg(int) prio;
    142 	} */ *uap = v;
    143 	struct proc *curp = l->l_proc, *p;
    144 	int found = 0, error = 0;
    145 	int who = SCARG(uap, who);
    146 
    147 	mutex_enter(&proclist_lock);
    148 	switch (SCARG(uap, which)) {
    149 	case PRIO_PROCESS:
    150 		if (who == 0)
    151 			p = curp;
    152 		else
    153 			p = p_find(who, PFIND_LOCKED);
    154 		if (p != 0) {
    155 			mutex_enter(&p->p_mutex);
    156 			error = donice(l, p, SCARG(uap, prio));
    157 			mutex_exit(&p->p_mutex);
    158 		}
    159 		found++;
    160 		break;
    161 
    162 	case PRIO_PGRP: {
    163 		struct pgrp *pg;
    164 
    165 		if (who == 0)
    166 			pg = curp->p_pgrp;
    167 		else if ((pg = pg_find(who, PFIND_LOCKED)) == NULL)
    168 			break;
    169 		LIST_FOREACH(p, &pg->pg_members, p_pglist) {
    170 			mutex_enter(&p->p_mutex);
    171 			error = donice(l, p, SCARG(uap, prio));
    172 			mutex_exit(&p->p_mutex);
    173 			found++;
    174 		}
    175 		break;
    176 	}
    177 
    178 	case PRIO_USER:
    179 		if (who == 0)
    180 			who = (int)kauth_cred_geteuid(l->l_cred);
    181 		PROCLIST_FOREACH(p, &allproc) {
    182 			mutex_enter(&p->p_mutex);
    183 			if (kauth_cred_geteuid(p->p_cred) ==
    184 			    (uid_t)SCARG(uap, who)) {
    185 				error = donice(l, p, SCARG(uap, prio));
    186 				found++;
    187 			}
    188 			mutex_exit(&p->p_mutex);
    189 		}
    190 		break;
    191 
    192 	default:
    193 		error = EINVAL;
    194 		break;
    195 	}
    196 	mutex_exit(&proclist_lock);
    197 	if (found == 0)
    198 		return (ESRCH);
    199 	return (error);
    200 }
    201 
    202 /*
    203  * Renice a process.
    204  *
    205  * Call with the target process' credentials locked.
    206  */
    207 int
    208 donice(struct lwp *l, struct proc *chgp, int n)
    209 {
    210 	kauth_cred_t cred = l->l_cred;
    211 	int onice;
    212 
    213 	KASSERT(mutex_owned(&chgp->p_mutex));
    214 
    215 	if (n > PRIO_MAX)
    216 		n = PRIO_MAX;
    217 	if (n < PRIO_MIN)
    218 		n = PRIO_MIN;
    219 	n += NZERO;
    220 	onice = chgp->p_nice;
    221 	onice = chgp->p_nice;
    222 
    223   again:
    224 	if (kauth_authorize_process(cred, KAUTH_PROCESS_NICE, chgp,
    225 	    KAUTH_ARG(n), NULL, NULL))
    226 		return (EACCES);
    227 	mutex_spin_enter(&chgp->p_stmutex);
    228 	if (onice != chgp->p_nice) {
    229 		mutex_spin_exit(&chgp->p_stmutex);
    230 		goto again;
    231 	}
    232 	chgp->p_nice = n;
    233 	(void)resetprocpriority(chgp);
    234 	mutex_spin_exit(&chgp->p_stmutex);
    235 	return (0);
    236 }
    237 
    238 /* ARGSUSED */
    239 int
    240 sys_setrlimit(struct lwp *l, void *v, register_t *retval)
    241 {
    242 	struct sys_setrlimit_args /* {
    243 		syscallarg(int) which;
    244 		syscallarg(const struct rlimit *) rlp;
    245 	} */ *uap = v;
    246 	int which = SCARG(uap, which);
    247 	struct rlimit alim;
    248 	int error;
    249 
    250 	error = copyin(SCARG(uap, rlp), &alim, sizeof(struct rlimit));
    251 	if (error)
    252 		return (error);
    253 	return (dosetrlimit(l, l->l_proc, which, &alim));
    254 }
    255 
    256 int
    257 dosetrlimit(struct lwp *l, struct proc *p, int which, struct rlimit *limp)
    258 {
    259 	struct rlimit *alimp;
    260 	struct plimit *oldplim;
    261 	int error;
    262 
    263 	if ((u_int)which >= RLIM_NLIMITS)
    264 		return (EINVAL);
    265 
    266 	if (limp->rlim_cur < 0 || limp->rlim_max < 0)
    267 		return (EINVAL);
    268 
    269 	alimp = &p->p_rlimit[which];
    270 	/* if we don't change the value, no need to limcopy() */
    271 	if (limp->rlim_cur == alimp->rlim_cur &&
    272 	    limp->rlim_max == alimp->rlim_max)
    273 		return 0;
    274 
    275 	if (limp->rlim_cur > limp->rlim_max) {
    276 		/*
    277 		 * This is programming error. According to SUSv2, we should
    278 		 * return error in this case.
    279 		 */
    280 		return (EINVAL);
    281 	}
    282 	error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_RLIMIT,
    283 	    p, limp, KAUTH_ARG(which), NULL);
    284 	if (error)
    285 			return (error);
    286 
    287 	mutex_enter(&p->p_mutex);
    288 	if (p->p_limit->p_refcnt > 1 &&
    289 	    (p->p_limit->p_lflags & PL_SHAREMOD) == 0) {
    290 	    	oldplim = p->p_limit;
    291 		p->p_limit = limcopy(p);
    292 		limfree(oldplim);
    293 		alimp = &p->p_rlimit[which];
    294 	}
    295 
    296 	switch (which) {
    297 
    298 	case RLIMIT_DATA:
    299 		if (limp->rlim_cur > maxdmap)
    300 			limp->rlim_cur = maxdmap;
    301 		if (limp->rlim_max > maxdmap)
    302 			limp->rlim_max = maxdmap;
    303 		break;
    304 
    305 	case RLIMIT_STACK:
    306 		if (limp->rlim_cur > maxsmap)
    307 			limp->rlim_cur = maxsmap;
    308 		if (limp->rlim_max > maxsmap)
    309 			limp->rlim_max = maxsmap;
    310 
    311 		/*
    312 		 * Return EINVAL if the new stack size limit is lower than
    313 		 * current usage. Otherwise, the process would get SIGSEGV the
    314 		 * moment it would try to access anything on it's current stack.
    315 		 * This conforms to SUSv2.
    316 		 */
    317 		if (limp->rlim_cur < p->p_vmspace->vm_ssize * PAGE_SIZE
    318 		    || limp->rlim_max < p->p_vmspace->vm_ssize * PAGE_SIZE) {
    319 			mutex_exit(&p->p_mutex);
    320 			return (EINVAL);
    321 		}
    322 
    323 		/*
    324 		 * Stack is allocated to the max at exec time with
    325 		 * only "rlim_cur" bytes accessible (In other words,
    326 		 * allocates stack dividing two contiguous regions at
    327 		 * "rlim_cur" bytes boundary).
    328 		 *
    329 		 * Since allocation is done in terms of page, roundup
    330 		 * "rlim_cur" (otherwise, contiguous regions
    331 		 * overlap).  If stack limit is going up make more
    332 		 * accessible, if going down make inaccessible.
    333 		 */
    334 		limp->rlim_cur = round_page(limp->rlim_cur);
    335 		if (limp->rlim_cur != alimp->rlim_cur) {
    336 			vaddr_t addr;
    337 			vsize_t size;
    338 			vm_prot_t prot;
    339 
    340 			if (limp->rlim_cur > alimp->rlim_cur) {
    341 				prot = VM_PROT_READ | VM_PROT_WRITE;
    342 				size = limp->rlim_cur - alimp->rlim_cur;
    343 				addr = (vaddr_t)p->p_vmspace->vm_minsaddr -
    344 				    limp->rlim_cur;
    345 			} else {
    346 				prot = VM_PROT_NONE;
    347 				size = alimp->rlim_cur - limp->rlim_cur;
    348 				addr = (vaddr_t)p->p_vmspace->vm_minsaddr -
    349 				     alimp->rlim_cur;
    350 			}
    351 			(void) uvm_map_protect(&p->p_vmspace->vm_map,
    352 			    addr, addr+size, prot, false);
    353 		}
    354 		break;
    355 
    356 	case RLIMIT_NOFILE:
    357 		if (limp->rlim_cur > maxfiles)
    358 			limp->rlim_cur = maxfiles;
    359 		if (limp->rlim_max > maxfiles)
    360 			limp->rlim_max = maxfiles;
    361 		break;
    362 
    363 	case RLIMIT_NPROC:
    364 		if (limp->rlim_cur > maxproc)
    365 			limp->rlim_cur = maxproc;
    366 		if (limp->rlim_max > maxproc)
    367 			limp->rlim_max = maxproc;
    368 		break;
    369 	}
    370 	*alimp = *limp;
    371 	mutex_exit(&p->p_mutex);
    372 	return (0);
    373 }
    374 
    375 /* ARGSUSED */
    376 int
    377 sys_getrlimit(struct lwp *l, void *v, register_t *retval)
    378 {
    379 	struct sys_getrlimit_args /* {
    380 		syscallarg(int) which;
    381 		syscallarg(struct rlimit *) rlp;
    382 	} */ *uap = v;
    383 	struct proc *p = l->l_proc;
    384 	int which = SCARG(uap, which);
    385 
    386 	if ((u_int)which >= RLIM_NLIMITS)
    387 		return (EINVAL);
    388 	return (copyout(&p->p_rlimit[which], SCARG(uap, rlp),
    389 	    sizeof(struct rlimit)));
    390 }
    391 
    392 /*
    393  * Transform the running time and tick information in proc p into user,
    394  * system, and interrupt time usage.
    395  *
    396  * Should be called with p->p_smutex held unless called from exit1().
    397  */
    398 void
    399 calcru(struct proc *p, struct timeval *up, struct timeval *sp,
    400     struct timeval *ip, struct timeval *rp)
    401 {
    402 	u_quad_t u, st, ut, it, tot;
    403 	unsigned long sec;
    404 	long usec;
    405  	struct timeval tv;
    406 	struct lwp *l;
    407 
    408 	mutex_spin_enter(&p->p_stmutex);
    409 	st = p->p_sticks;
    410 	ut = p->p_uticks;
    411 	it = p->p_iticks;
    412 	mutex_spin_exit(&p->p_stmutex);
    413 
    414 	sec = p->p_rtime.tv_sec;
    415 	usec = p->p_rtime.tv_usec;
    416 
    417 	LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    418 		lwp_lock(l);
    419 		sec += l->l_rtime.tv_sec;
    420 		if ((usec += l->l_rtime.tv_usec) >= 1000000) {
    421 			sec++;
    422 			usec -= 1000000;
    423 		}
    424 		if (l->l_cpu == curcpu()) {
    425 			struct schedstate_percpu *spc;
    426 
    427 			KDASSERT(l->l_cpu != NULL);
    428 			spc = &l->l_cpu->ci_schedstate;
    429 
    430 			/*
    431 			 * Adjust for the current time slice.  This is
    432 			 * actually fairly important since the error
    433 			 * here is on the order of a time quantum,
    434 			 * which is much greater than the sampling
    435 			 * error.
    436 			 */
    437 			microtime(&tv);
    438 			sec += tv.tv_sec - spc->spc_runtime.tv_sec;
    439 			usec += tv.tv_usec - spc->spc_runtime.tv_usec;
    440 			if (usec >= 1000000) {
    441 				sec++;
    442 				usec -= 1000000;
    443 			}
    444 		}
    445 		lwp_unlock(l);
    446 	}
    447 
    448 	tot = st + ut + it;
    449 	u = sec * 1000000ull + usec;
    450 
    451 	if (tot == 0) {
    452 		/* No ticks, so can't use to share time out, split 50-50 */
    453 		st = ut = u / 2;
    454 	} else {
    455 		st = (u * st) / tot;
    456 		ut = (u * ut) / tot;
    457 	}
    458 	if (sp != NULL) {
    459 		sp->tv_sec = st / 1000000;
    460 		sp->tv_usec = st % 1000000;
    461 	}
    462 	if (up != NULL) {
    463 		up->tv_sec = ut / 1000000;
    464 		up->tv_usec = ut % 1000000;
    465 	}
    466 	if (ip != NULL) {
    467 		if (it != 0)
    468 			it = (u * it) / tot;
    469 		ip->tv_sec = it / 1000000;
    470 		ip->tv_usec = it % 1000000;
    471 	}
    472 	if (rp != NULL) {
    473 		rp->tv_sec = sec;
    474 		rp->tv_usec = usec;
    475 	}
    476 }
    477 
    478 /* ARGSUSED */
    479 int
    480 sys_getrusage(struct lwp *l, void *v, register_t *retval)
    481 {
    482 	struct sys_getrusage_args /* {
    483 		syscallarg(int) who;
    484 		syscallarg(struct rusage *) rusage;
    485 	} */ *uap = v;
    486 	struct rusage *rup;
    487 	struct proc *p = l->l_proc;
    488 
    489 	switch (SCARG(uap, who)) {
    490 
    491 	case RUSAGE_SELF:
    492 		rup = &p->p_stats->p_ru;
    493 		mutex_enter(&p->p_smutex);
    494 		calcru(p, &rup->ru_utime, &rup->ru_stime, NULL, NULL);
    495 		mutex_exit(&p->p_smutex);
    496 		break;
    497 
    498 	case RUSAGE_CHILDREN:
    499 		rup = &p->p_stats->p_cru;
    500 		break;
    501 
    502 	default:
    503 		return (EINVAL);
    504 	}
    505 	return (copyout(rup, SCARG(uap, rusage), sizeof(struct rusage)));
    506 }
    507 
    508 void
    509 ruadd(struct rusage *ru, struct rusage *ru2)
    510 {
    511 	long *ip, *ip2;
    512 	int i;
    513 
    514 	timeradd(&ru->ru_utime, &ru2->ru_utime, &ru->ru_utime);
    515 	timeradd(&ru->ru_stime, &ru2->ru_stime, &ru->ru_stime);
    516 	if (ru->ru_maxrss < ru2->ru_maxrss)
    517 		ru->ru_maxrss = ru2->ru_maxrss;
    518 	ip = &ru->ru_first; ip2 = &ru2->ru_first;
    519 	for (i = &ru->ru_last - &ru->ru_first; i >= 0; i--)
    520 		*ip++ += *ip2++;
    521 }
    522 
    523 /*
    524  * Make a copy of the plimit structure.
    525  * We share these structures copy-on-write after fork,
    526  * and copy when a limit is changed.
    527  *
    528  * XXXSMP This is atrocious, need to simplify.
    529  */
    530 struct plimit *
    531 limcopy(struct proc *p)
    532 {
    533 	struct plimit *lim, *newlim;
    534 	char *corename;
    535 	size_t l;
    536 
    537 	KASSERT(mutex_owned(&p->p_mutex));
    538 
    539 	mutex_exit(&p->p_mutex);
    540 	newlim = pool_get(&plimit_pool, PR_WAITOK);
    541 	mutex_init(&newlim->p_lock, MUTEX_DEFAULT, IPL_NONE);
    542 	newlim->p_lflags = 0;
    543 	newlim->p_refcnt = 1;
    544 	mutex_enter(&p->p_mutex);
    545 
    546 	for (;;) {
    547 		lim = p->p_limit;
    548 		mutex_enter(&lim->p_lock);
    549 		if (lim->pl_corename != defcorename) {
    550 			l = strlen(lim->pl_corename) + 1;
    551 
    552 			mutex_exit(&lim->p_lock);
    553 			mutex_exit(&p->p_mutex);
    554 			corename = malloc(l, M_TEMP, M_WAITOK);
    555 			mutex_enter(&p->p_mutex);
    556 			mutex_enter(&lim->p_lock);
    557 
    558 			if (l != strlen(lim->pl_corename) + 1) {
    559 				mutex_exit(&lim->p_lock);
    560 				mutex_exit(&p->p_mutex);
    561 				free(corename, M_TEMP);
    562 				mutex_enter(&p->p_mutex);
    563 				continue;
    564 			}
    565 		} else
    566 			l = 0;
    567 
    568 		memcpy(newlim->pl_rlimit, lim->pl_rlimit,
    569 		    sizeof(struct rlimit) * RLIM_NLIMITS);
    570 		if (l != 0)
    571 			strlcpy(newlim->pl_corename, lim->pl_corename, l);
    572 		else
    573 			newlim->pl_corename = defcorename;
    574 		mutex_exit(&lim->p_lock);
    575 		break;
    576 	}
    577 
    578 	return (newlim);
    579 }
    580 
    581 void
    582 limfree(struct plimit *lim)
    583 {
    584 	int n;
    585 
    586 	mutex_enter(&lim->p_lock);
    587 	n = --lim->p_refcnt;
    588 	mutex_exit(&lim->p_lock);
    589 	if (n > 0)
    590 		return;
    591 #ifdef DIAGNOSTIC
    592 	if (n < 0)
    593 		panic("limfree");
    594 #endif
    595 	if (lim->pl_corename != defcorename)
    596 		free(lim->pl_corename, M_TEMP);
    597 	mutex_destroy(&lim->p_lock);
    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 void
    951 uid_init(void)
    952 {
    953 
    954 	/*
    955 	 * XXXSMP This could be at IPL_SOFTNET, but for now we want
    956 	 * to to be deadlock free, so it must be at IPL_VM.
    957 	 */
    958 	mutex_init(&uihashtbl_lock, MUTEX_DRIVER, IPL_VM);
    959 
    960 	/*
    961 	 * Ensure that uid 0 is always in the user hash table, as
    962 	 * sbreserve() expects it available from interrupt context.
    963 	 */
    964 	(void)uid_find(0);
    965 }
    966 
    967 struct uidinfo *
    968 uid_find(uid_t uid)
    969 {
    970 	struct uidinfo *uip;
    971 	struct uidinfo *newuip = NULL;
    972 	struct uihashhead *uipp;
    973 
    974 	uipp = UIHASH(uid);
    975 
    976 again:
    977 	mutex_enter(&uihashtbl_lock);
    978 	LIST_FOREACH(uip, uipp, ui_hash)
    979 		if (uip->ui_uid == uid) {
    980 			mutex_exit(&uihashtbl_lock);
    981 			if (newuip) {
    982 				free(newuip, M_PROC);
    983 				mutex_destroy(&newuip->ui_lock);
    984 			}
    985 			return uip;
    986 		}
    987 	if (newuip == NULL) {
    988 		mutex_exit(&uihashtbl_lock);
    989 		/* Must not be called from interrupt context. */
    990 		newuip = malloc(sizeof(*uip), M_PROC, M_WAITOK | M_ZERO);
    991 		mutex_init(&newuip->ui_lock, MUTEX_DRIVER, IPL_SOFTNET);
    992 		goto again;
    993 	}
    994 	uip = newuip;
    995 
    996 	LIST_INSERT_HEAD(uipp, uip, ui_hash);
    997 	uip->ui_uid = uid;
    998 	mutex_exit(&uihashtbl_lock);
    999 
   1000 	return uip;
   1001 }
   1002 
   1003 /*
   1004  * Change the count associated with number of processes
   1005  * a given user is using.
   1006  */
   1007 int
   1008 chgproccnt(uid_t uid, int diff)
   1009 {
   1010 	struct uidinfo *uip;
   1011 
   1012 	if (diff == 0)
   1013 		return 0;
   1014 
   1015 	uip = uid_find(uid);
   1016 	mutex_enter(&uip->ui_lock);
   1017 	uip->ui_proccnt += diff;
   1018 	KASSERT(uip->ui_proccnt >= 0);
   1019 	mutex_exit(&uip->ui_lock);
   1020 	return uip->ui_proccnt;
   1021 }
   1022 
   1023 int
   1024 chgsbsize(struct uidinfo *uip, u_long *hiwat, u_long to, rlim_t xmax)
   1025 {
   1026 	rlim_t nsb;
   1027 
   1028 	mutex_enter(&uip->ui_lock);
   1029 	nsb = uip->ui_sbsize + to - *hiwat;
   1030 	if (to > *hiwat && nsb > xmax) {
   1031 		mutex_exit(&uip->ui_lock);
   1032 		return 0;
   1033 	}
   1034 	*hiwat = to;
   1035 	uip->ui_sbsize = nsb;
   1036 	KASSERT(uip->ui_sbsize >= 0);
   1037 	mutex_exit(&uip->ui_lock);
   1038 	return 1;
   1039 }
   1040