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