Home | History | Annotate | Line # | Download | only in kern
kern_resource.c revision 1.116.2.5
      1 /*	$NetBSD: kern_resource.c,v 1.116.2.5 2007/08/20 21:27:32 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.5 2007/08/20 21:27:32 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 	sched_nice(chgp, n);
    233 	mutex_spin_exit(&chgp->p_stmutex);
    234 	return (0);
    235 }
    236 
    237 /* ARGSUSED */
    238 int
    239 sys_setrlimit(struct lwp *l, void *v, register_t *retval)
    240 {
    241 	struct sys_setrlimit_args /* {
    242 		syscallarg(int) which;
    243 		syscallarg(const struct rlimit *) rlp;
    244 	} */ *uap = v;
    245 	int which = SCARG(uap, which);
    246 	struct rlimit alim;
    247 	int error;
    248 
    249 	error = copyin(SCARG(uap, rlp), &alim, sizeof(struct rlimit));
    250 	if (error)
    251 		return (error);
    252 	return (dosetrlimit(l, l->l_proc, which, &alim));
    253 }
    254 
    255 int
    256 dosetrlimit(struct lwp *l, struct proc *p, int which, struct rlimit *limp)
    257 {
    258 	struct rlimit *alimp;
    259 	struct plimit *oldplim;
    260 	int error;
    261 
    262 	if ((u_int)which >= RLIM_NLIMITS)
    263 		return (EINVAL);
    264 
    265 	if (limp->rlim_cur < 0 || limp->rlim_max < 0)
    266 		return (EINVAL);
    267 
    268 	alimp = &p->p_rlimit[which];
    269 	/* if we don't change the value, no need to limcopy() */
    270 	if (limp->rlim_cur == alimp->rlim_cur &&
    271 	    limp->rlim_max == alimp->rlim_max)
    272 		return 0;
    273 
    274 	if (limp->rlim_cur > limp->rlim_max) {
    275 		/*
    276 		 * This is programming error. According to SUSv2, we should
    277 		 * return error in this case.
    278 		 */
    279 		return (EINVAL);
    280 	}
    281 	error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_RLIMIT,
    282 	    p, limp, KAUTH_ARG(which), NULL);
    283 	if (error)
    284 			return (error);
    285 
    286 	mutex_enter(&p->p_mutex);
    287 	if (p->p_limit->p_refcnt > 1 &&
    288 	    (p->p_limit->p_lflags & PL_SHAREMOD) == 0) {
    289 	    	oldplim = p->p_limit;
    290 		p->p_limit = limcopy(p);
    291 		limfree(oldplim);
    292 		alimp = &p->p_rlimit[which];
    293 	}
    294 
    295 	switch (which) {
    296 
    297 	case RLIMIT_DATA:
    298 		if (limp->rlim_cur > maxdmap)
    299 			limp->rlim_cur = maxdmap;
    300 		if (limp->rlim_max > maxdmap)
    301 			limp->rlim_max = maxdmap;
    302 		break;
    303 
    304 	case RLIMIT_STACK:
    305 		if (limp->rlim_cur > maxsmap)
    306 			limp->rlim_cur = maxsmap;
    307 		if (limp->rlim_max > maxsmap)
    308 			limp->rlim_max = maxsmap;
    309 
    310 		/*
    311 		 * Return EINVAL if the new stack size limit is lower than
    312 		 * current usage. Otherwise, the process would get SIGSEGV the
    313 		 * moment it would try to access anything on it's current stack.
    314 		 * This conforms to SUSv2.
    315 		 */
    316 		if (limp->rlim_cur < p->p_vmspace->vm_ssize * PAGE_SIZE
    317 		    || limp->rlim_max < p->p_vmspace->vm_ssize * PAGE_SIZE) {
    318 			mutex_exit(&p->p_mutex);
    319 			return (EINVAL);
    320 		}
    321 
    322 		/*
    323 		 * Stack is allocated to the max at exec time with
    324 		 * only "rlim_cur" bytes accessible (In other words,
    325 		 * allocates stack dividing two contiguous regions at
    326 		 * "rlim_cur" bytes boundary).
    327 		 *
    328 		 * Since allocation is done in terms of page, roundup
    329 		 * "rlim_cur" (otherwise, contiguous regions
    330 		 * overlap).  If stack limit is going up make more
    331 		 * accessible, if going down make inaccessible.
    332 		 */
    333 		limp->rlim_cur = round_page(limp->rlim_cur);
    334 		if (limp->rlim_cur != alimp->rlim_cur) {
    335 			vaddr_t addr;
    336 			vsize_t size;
    337 			vm_prot_t prot;
    338 
    339 			if (limp->rlim_cur > alimp->rlim_cur) {
    340 				prot = VM_PROT_READ | VM_PROT_WRITE;
    341 				size = limp->rlim_cur - alimp->rlim_cur;
    342 				addr = (vaddr_t)p->p_vmspace->vm_minsaddr -
    343 				    limp->rlim_cur;
    344 			} else {
    345 				prot = VM_PROT_NONE;
    346 				size = alimp->rlim_cur - limp->rlim_cur;
    347 				addr = (vaddr_t)p->p_vmspace->vm_minsaddr -
    348 				     alimp->rlim_cur;
    349 			}
    350 			(void) uvm_map_protect(&p->p_vmspace->vm_map,
    351 			    addr, addr+size, prot, false);
    352 		}
    353 		break;
    354 
    355 	case RLIMIT_NOFILE:
    356 		if (limp->rlim_cur > maxfiles)
    357 			limp->rlim_cur = maxfiles;
    358 		if (limp->rlim_max > maxfiles)
    359 			limp->rlim_max = maxfiles;
    360 		break;
    361 
    362 	case RLIMIT_NPROC:
    363 		if (limp->rlim_cur > maxproc)
    364 			limp->rlim_cur = maxproc;
    365 		if (limp->rlim_max > maxproc)
    366 			limp->rlim_max = maxproc;
    367 		break;
    368 	}
    369 	*alimp = *limp;
    370 	mutex_exit(&p->p_mutex);
    371 	return (0);
    372 }
    373 
    374 /* ARGSUSED */
    375 int
    376 sys_getrlimit(struct lwp *l, void *v, register_t *retval)
    377 {
    378 	struct sys_getrlimit_args /* {
    379 		syscallarg(int) which;
    380 		syscallarg(struct rlimit *) rlp;
    381 	} */ *uap = v;
    382 	struct proc *p = l->l_proc;
    383 	int which = SCARG(uap, which);
    384 	struct rlimit rl;
    385 
    386 	if ((u_int)which >= RLIM_NLIMITS)
    387 		return (EINVAL);
    388 
    389 	mutex_enter(&p->p_mutex);
    390 	memcpy(&rl, &p->p_rlimit[which], sizeof(rl));
    391 	mutex_exit(&p->p_mutex);
    392 
    393 	return copyout(&rl, SCARG(uap, rlp), sizeof(rl));
    394 }
    395 
    396 /*
    397  * Transform the running time and tick information in proc p into user,
    398  * system, and interrupt time usage.
    399  *
    400  * Should be called with p->p_smutex held unless called from exit1().
    401  */
    402 void
    403 calcru(struct proc *p, struct timeval *up, struct timeval *sp,
    404     struct timeval *ip, struct timeval *rp)
    405 {
    406 	u_quad_t u, st, ut, it, tot;
    407 	unsigned long sec;
    408 	long usec;
    409  	struct timeval tv;
    410 	struct lwp *l;
    411 
    412 	mutex_spin_enter(&p->p_stmutex);
    413 	st = p->p_sticks;
    414 	ut = p->p_uticks;
    415 	it = p->p_iticks;
    416 	mutex_spin_exit(&p->p_stmutex);
    417 
    418 	sec = p->p_rtime.tv_sec;
    419 	usec = p->p_rtime.tv_usec;
    420 
    421 	LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    422 		lwp_lock(l);
    423 		sec += l->l_rtime.tv_sec;
    424 		if ((usec += l->l_rtime.tv_usec) >= 1000000) {
    425 			sec++;
    426 			usec -= 1000000;
    427 		}
    428 		if ((l->l_flag & LW_RUNNING) != 0) {
    429 			/*
    430 			 * Adjust for the current time slice.  This is
    431 			 * actually fairly important since the error
    432 			 * here is on the order of a time quantum,
    433 			 * which is much greater than the sampling
    434 			 * error.
    435 			 */
    436 			microtime(&tv);
    437 			sec += tv.tv_sec - l->l_stime.tv_sec;
    438 			usec += tv.tv_usec - l->l_stime.tv_usec;
    439 			if (usec >= 1000000) {
    440 				sec++;
    441 				usec -= 1000000;
    442 			}
    443 		}
    444 		lwp_unlock(l);
    445 	}
    446 
    447 	tot = st + ut + it;
    448 	u = sec * 1000000ull + usec;
    449 
    450 	if (tot == 0) {
    451 		/* No ticks, so can't use to share time out, split 50-50 */
    452 		st = ut = u / 2;
    453 	} else {
    454 		st = (u * st) / tot;
    455 		ut = (u * ut) / tot;
    456 	}
    457 	if (sp != NULL) {
    458 		sp->tv_sec = st / 1000000;
    459 		sp->tv_usec = st % 1000000;
    460 	}
    461 	if (up != NULL) {
    462 		up->tv_sec = ut / 1000000;
    463 		up->tv_usec = ut % 1000000;
    464 	}
    465 	if (ip != NULL) {
    466 		if (it != 0)
    467 			it = (u * it) / tot;
    468 		ip->tv_sec = it / 1000000;
    469 		ip->tv_usec = it % 1000000;
    470 	}
    471 	if (rp != NULL) {
    472 		rp->tv_sec = sec;
    473 		rp->tv_usec = usec;
    474 	}
    475 }
    476 
    477 /* ARGSUSED */
    478 int
    479 sys_getrusage(struct lwp *l, void *v, register_t *retval)
    480 {
    481 	struct sys_getrusage_args /* {
    482 		syscallarg(int) who;
    483 		syscallarg(struct rusage *) rusage;
    484 	} */ *uap = v;
    485 	struct rusage ru;
    486 	struct proc *p = l->l_proc;
    487 
    488 	switch (SCARG(uap, who)) {
    489 	case RUSAGE_SELF:
    490 		mutex_enter(&p->p_smutex);
    491 		memcpy(&ru, &p->p_stats->p_ru, sizeof(ru));
    492 		calcru(p, &ru.ru_utime, &ru.ru_stime, NULL, NULL);
    493 		mutex_exit(&p->p_smutex);
    494 		break;
    495 
    496 	case RUSAGE_CHILDREN:
    497 		mutex_enter(&p->p_smutex);
    498 		memcpy(&ru, &p->p_stats->p_cru, sizeof(ru));
    499 		mutex_exit(&p->p_smutex);
    500 		break;
    501 
    502 	default:
    503 		return EINVAL;
    504 	}
    505 
    506 	return copyout(&ru, SCARG(uap, rusage), sizeof(ru));
    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 	KASSERT(mutex_owned(&p->p_mutex));
    539 
    540 	mutex_exit(&p->p_mutex);
    541 	newlim = pool_get(&plimit_pool, PR_WAITOK);
    542 	mutex_init(&newlim->p_lock, MUTEX_DEFAULT, IPL_NONE);
    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 		mutex_enter(&lim->p_lock);
    550 		if (lim->pl_corename != defcorename) {
    551 			l = strlen(lim->pl_corename) + 1;
    552 
    553 			mutex_exit(&lim->p_lock);
    554 			mutex_exit(&p->p_mutex);
    555 			corename = malloc(l, M_TEMP, M_WAITOK);
    556 			mutex_enter(&p->p_mutex);
    557 			mutex_enter(&lim->p_lock);
    558 
    559 			if (l != strlen(lim->pl_corename) + 1) {
    560 				mutex_exit(&lim->p_lock);
    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 		mutex_exit(&lim->p_lock);
    576 		break;
    577 	}
    578 
    579 	return (newlim);
    580 }
    581 
    582 void
    583 limfree(struct plimit *lim)
    584 {
    585 	int n;
    586 
    587 	mutex_enter(&lim->p_lock);
    588 	n = --lim->p_refcnt;
    589 	mutex_exit(&lim->p_lock);
    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 	mutex_destroy(&lim->p_lock);
    599 	pool_put(&plimit_pool, lim);
    600 }
    601 
    602 struct pstats *
    603 pstatscopy(struct pstats *ps)
    604 {
    605 
    606 	struct pstats *newps;
    607 
    608 	newps = pool_get(&pstats_pool, PR_WAITOK);
    609 
    610 	memset(&newps->pstat_startzero, 0,
    611 	(unsigned) ((char *)&newps->pstat_endzero -
    612 		    (char *)&newps->pstat_startzero));
    613 	memcpy(&newps->pstat_startcopy, &ps->pstat_startcopy,
    614 	((char *)&newps->pstat_endcopy -
    615 	 (char *)&newps->pstat_startcopy));
    616 
    617 	return (newps);
    618 
    619 }
    620 
    621 void
    622 pstatsfree(struct pstats *ps)
    623 {
    624 
    625 	pool_put(&pstats_pool, ps);
    626 }
    627 
    628 /*
    629  * sysctl interface in five parts
    630  */
    631 
    632 /*
    633  * a routine for sysctl proc subtree helpers that need to pick a valid
    634  * process by pid.
    635  */
    636 static int
    637 sysctl_proc_findproc(struct lwp *l, struct proc **p2, pid_t pid)
    638 {
    639 	struct proc *ptmp;
    640 	int error = 0;
    641 
    642 	if (pid == PROC_CURPROC)
    643 		ptmp = l->l_proc;
    644 	else if ((ptmp = pfind(pid)) == NULL)
    645 		error = ESRCH;
    646 
    647 	*p2 = ptmp;
    648 	return (error);
    649 }
    650 
    651 /*
    652  * sysctl helper routine for setting a process's specific corefile
    653  * name.  picks the process based on the given pid and checks the
    654  * correctness of the new value.
    655  */
    656 static int
    657 sysctl_proc_corename(SYSCTLFN_ARGS)
    658 {
    659 	struct proc *ptmp;
    660 	struct plimit *lim;
    661 	int error = 0, len;
    662 	char *cname;
    663 	char *tmp;
    664 	struct sysctlnode node;
    665 
    666 	/*
    667 	 * is this all correct?
    668 	 */
    669 	if (namelen != 0)
    670 		return (EINVAL);
    671 	if (name[-1] != PROC_PID_CORENAME)
    672 		return (EINVAL);
    673 
    674 	/*
    675 	 * whom are we tweaking?
    676 	 */
    677 	error = sysctl_proc_findproc(l, &ptmp, (pid_t)name[-2]);
    678 	if (error)
    679 		return (error);
    680 
    681 	/* XXX this should be in p_find() */
    682 	error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_CANSEE,
    683 	    ptmp, NULL, NULL, NULL);
    684 	if (error)
    685 		return (error);
    686 
    687 	cname = PNBUF_GET();
    688 	/*
    689 	 * let them modify a temporary copy of the core name
    690 	 */
    691 	node = *rnode;
    692 	strlcpy(cname, ptmp->p_limit->pl_corename, MAXPATHLEN);
    693 	node.sysctl_data = cname;
    694 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    695 
    696 	/*
    697 	 * if that failed, or they have nothing new to say, or we've
    698 	 * heard it before...
    699 	 */
    700 	if (error || newp == NULL ||
    701 	    strcmp(cname, ptmp->p_limit->pl_corename) == 0) {
    702 		goto done;
    703 	}
    704 
    705 	error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_CORENAME,
    706 	    ptmp, cname, NULL, NULL);
    707 	if (error)
    708 		return (error);
    709 
    710 	/*
    711 	 * no error yet and cname now has the new core name in it.
    712 	 * let's see if it looks acceptable.  it must be either "core"
    713 	 * or end in ".core" or "/core".
    714 	 */
    715 	len = strlen(cname);
    716 	if (len < 4) {
    717 		error = EINVAL;
    718 	} else if (strcmp(cname + len - 4, "core") != 0) {
    719 		error = EINVAL;
    720 	} else if (len > 4 && cname[len - 5] != '/' && cname[len - 5] != '.') {
    721 		error = EINVAL;
    722 	}
    723 	if (error != 0) {
    724 		goto done;
    725 	}
    726 
    727 	/*
    728 	 * hmm...looks good.  now...where do we put it?
    729 	 */
    730 	tmp = malloc(len + 1, M_TEMP, M_WAITOK|M_CANFAIL);
    731 	if (tmp == NULL) {
    732 		error = ENOMEM;
    733 		goto done;
    734 	}
    735 	strlcpy(tmp, cname, len + 1);
    736 
    737 	mutex_enter(&ptmp->p_mutex);
    738 	lim = ptmp->p_limit;
    739 	if (lim->p_refcnt > 1 && (lim->p_lflags & PL_SHAREMOD) == 0) {
    740 		ptmp->p_limit = limcopy(ptmp);
    741 		limfree(lim);
    742 		lim = ptmp->p_limit;
    743 	}
    744 	if (lim->pl_corename != defcorename)
    745 		free(lim->pl_corename, M_TEMP);
    746 	lim->pl_corename = tmp;
    747 	mutex_exit(&ptmp->p_mutex);
    748 done:
    749 	PNBUF_PUT(cname);
    750 	return error;
    751 }
    752 
    753 /*
    754  * sysctl helper routine for checking/setting a process's stop flags,
    755  * one for fork and one for exec.
    756  */
    757 static int
    758 sysctl_proc_stop(SYSCTLFN_ARGS)
    759 {
    760 	struct proc *ptmp;
    761 	int i, f, error = 0;
    762 	struct sysctlnode node;
    763 
    764 	if (namelen != 0)
    765 		return (EINVAL);
    766 
    767 	error = sysctl_proc_findproc(l, &ptmp, (pid_t)name[-2]);
    768 	if (error)
    769 		return (error);
    770 
    771 	/* XXX this should be in p_find() */
    772 	error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_CANSEE,
    773 	    ptmp, NULL, NULL, NULL);
    774 	if (error)
    775 		return (error);
    776 
    777 	switch (rnode->sysctl_num) {
    778 	case PROC_PID_STOPFORK:
    779 		f = PS_STOPFORK;
    780 		break;
    781 	case PROC_PID_STOPEXEC:
    782 		f = PS_STOPEXEC;
    783 		break;
    784 	case PROC_PID_STOPEXIT:
    785 		f = PS_STOPEXIT;
    786 		break;
    787 	default:
    788 		return (EINVAL);
    789 	}
    790 
    791 	i = (ptmp->p_flag & f) ? 1 : 0;
    792 	node = *rnode;
    793 	node.sysctl_data = &i;
    794 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    795 	if (error || newp == NULL)
    796 		return (error);
    797 
    798 	mutex_enter(&ptmp->p_smutex);
    799 	error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_STOPFLAG,
    800 	    ptmp, KAUTH_ARG(f), NULL, NULL);
    801 	if (error)
    802 		return (error);
    803 	if (i)
    804 		ptmp->p_sflag |= f;
    805 	else
    806 		ptmp->p_sflag &= ~f;
    807 	mutex_exit(&ptmp->p_smutex);
    808 
    809 	return (0);
    810 }
    811 
    812 /*
    813  * sysctl helper routine for a process's rlimits as exposed by sysctl.
    814  */
    815 static int
    816 sysctl_proc_plimit(SYSCTLFN_ARGS)
    817 {
    818 	struct proc *ptmp;
    819 	u_int limitno;
    820 	int which, error = 0;
    821         struct rlimit alim;
    822 	struct sysctlnode node;
    823 
    824 	if (namelen != 0)
    825 		return (EINVAL);
    826 
    827 	which = name[-1];
    828 	if (which != PROC_PID_LIMIT_TYPE_SOFT &&
    829 	    which != PROC_PID_LIMIT_TYPE_HARD)
    830 		return (EINVAL);
    831 
    832 	limitno = name[-2] - 1;
    833 	if (limitno >= RLIM_NLIMITS)
    834 		return (EINVAL);
    835 
    836 	if (name[-3] != PROC_PID_LIMIT)
    837 		return (EINVAL);
    838 
    839 	error = sysctl_proc_findproc(l, &ptmp, (pid_t)name[-4]);
    840 	if (error)
    841 		return (error);
    842 
    843 	/* XXX this should be in p_find() */
    844 	error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_CANSEE,
    845 	    ptmp, NULL, NULL, NULL);
    846 	if (error)
    847 		return (error);
    848 
    849 	node = *rnode;
    850 	memcpy(&alim, &ptmp->p_rlimit[limitno], sizeof(alim));
    851 	if (which == PROC_PID_LIMIT_TYPE_HARD)
    852 		node.sysctl_data = &alim.rlim_max;
    853 	else
    854 		node.sysctl_data = &alim.rlim_cur;
    855 
    856 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    857 	if (error || newp == NULL)
    858 		return (error);
    859 
    860 	return (dosetrlimit(l, ptmp, limitno, &alim));
    861 }
    862 
    863 /*
    864  * and finally, the actually glue that sticks it to the tree
    865  */
    866 SYSCTL_SETUP(sysctl_proc_setup, "sysctl proc subtree setup")
    867 {
    868 
    869 	sysctl_createv(clog, 0, NULL, NULL,
    870 		       CTLFLAG_PERMANENT,
    871 		       CTLTYPE_NODE, "proc", NULL,
    872 		       NULL, 0, NULL, 0,
    873 		       CTL_PROC, CTL_EOL);
    874 	sysctl_createv(clog, 0, NULL, NULL,
    875 		       CTLFLAG_PERMANENT|CTLFLAG_ANYNUMBER,
    876 		       CTLTYPE_NODE, "curproc",
    877 		       SYSCTL_DESCR("Per-process settings"),
    878 		       NULL, 0, NULL, 0,
    879 		       CTL_PROC, PROC_CURPROC, CTL_EOL);
    880 
    881 	sysctl_createv(clog, 0, NULL, NULL,
    882 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE|CTLFLAG_ANYWRITE,
    883 		       CTLTYPE_STRING, "corename",
    884 		       SYSCTL_DESCR("Core file name"),
    885 		       sysctl_proc_corename, 0, NULL, MAXPATHLEN,
    886 		       CTL_PROC, PROC_CURPROC, PROC_PID_CORENAME, CTL_EOL);
    887 	sysctl_createv(clog, 0, NULL, NULL,
    888 		       CTLFLAG_PERMANENT,
    889 		       CTLTYPE_NODE, "rlimit",
    890 		       SYSCTL_DESCR("Process limits"),
    891 		       NULL, 0, NULL, 0,
    892 		       CTL_PROC, PROC_CURPROC, PROC_PID_LIMIT, CTL_EOL);
    893 
    894 #define create_proc_plimit(s, n) do {					\
    895 	sysctl_createv(clog, 0, NULL, NULL,				\
    896 		       CTLFLAG_PERMANENT,				\
    897 		       CTLTYPE_NODE, s,					\
    898 		       SYSCTL_DESCR("Process " s " limits"),		\
    899 		       NULL, 0, NULL, 0,				\
    900 		       CTL_PROC, PROC_CURPROC, PROC_PID_LIMIT, n,	\
    901 		       CTL_EOL);					\
    902 	sysctl_createv(clog, 0, NULL, NULL,				\
    903 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE|CTLFLAG_ANYWRITE, \
    904 		       CTLTYPE_QUAD, "soft",				\
    905 		       SYSCTL_DESCR("Process soft " s " limit"),	\
    906 		       sysctl_proc_plimit, 0, NULL, 0,			\
    907 		       CTL_PROC, PROC_CURPROC, PROC_PID_LIMIT, n,	\
    908 		       PROC_PID_LIMIT_TYPE_SOFT, CTL_EOL);		\
    909 	sysctl_createv(clog, 0, NULL, NULL,				\
    910 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE|CTLFLAG_ANYWRITE, \
    911 		       CTLTYPE_QUAD, "hard",				\
    912 		       SYSCTL_DESCR("Process hard " s " limit"),	\
    913 		       sysctl_proc_plimit, 0, NULL, 0,			\
    914 		       CTL_PROC, PROC_CURPROC, PROC_PID_LIMIT, n,	\
    915 		       PROC_PID_LIMIT_TYPE_HARD, CTL_EOL);		\
    916 	} while (0/*CONSTCOND*/)
    917 
    918 	create_proc_plimit("cputime",		PROC_PID_LIMIT_CPU);
    919 	create_proc_plimit("filesize",		PROC_PID_LIMIT_FSIZE);
    920 	create_proc_plimit("datasize",		PROC_PID_LIMIT_DATA);
    921 	create_proc_plimit("stacksize",		PROC_PID_LIMIT_STACK);
    922 	create_proc_plimit("coredumpsize",	PROC_PID_LIMIT_CORE);
    923 	create_proc_plimit("memoryuse",		PROC_PID_LIMIT_RSS);
    924 	create_proc_plimit("memorylocked",	PROC_PID_LIMIT_MEMLOCK);
    925 	create_proc_plimit("maxproc",		PROC_PID_LIMIT_NPROC);
    926 	create_proc_plimit("descriptors",	PROC_PID_LIMIT_NOFILE);
    927 	create_proc_plimit("sbsize",		PROC_PID_LIMIT_SBSIZE);
    928 
    929 #undef create_proc_plimit
    930 
    931 	sysctl_createv(clog, 0, NULL, NULL,
    932 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE|CTLFLAG_ANYWRITE,
    933 		       CTLTYPE_INT, "stopfork",
    934 		       SYSCTL_DESCR("Stop process at fork(2)"),
    935 		       sysctl_proc_stop, 0, NULL, 0,
    936 		       CTL_PROC, PROC_CURPROC, PROC_PID_STOPFORK, CTL_EOL);
    937 	sysctl_createv(clog, 0, NULL, NULL,
    938 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE|CTLFLAG_ANYWRITE,
    939 		       CTLTYPE_INT, "stopexec",
    940 		       SYSCTL_DESCR("Stop process at execve(2)"),
    941 		       sysctl_proc_stop, 0, NULL, 0,
    942 		       CTL_PROC, PROC_CURPROC, PROC_PID_STOPEXEC, CTL_EOL);
    943 	sysctl_createv(clog, 0, NULL, NULL,
    944 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE|CTLFLAG_ANYWRITE,
    945 		       CTLTYPE_INT, "stopexit",
    946 		       SYSCTL_DESCR("Stop process before completing exit"),
    947 		       sysctl_proc_stop, 0, NULL, 0,
    948 		       CTL_PROC, PROC_CURPROC, PROC_PID_STOPEXIT, CTL_EOL);
    949 }
    950 
    951 void
    952 uid_init(void)
    953 {
    954 
    955 	/*
    956 	 * XXXSMP This could be at IPL_SOFTNET, but for now we want
    957 	 * to to be deadlock free, so it must be at IPL_VM.
    958 	 */
    959 	mutex_init(&uihashtbl_lock, MUTEX_DRIVER, IPL_VM);
    960 
    961 	/*
    962 	 * Ensure that uid 0 is always in the user hash table, as
    963 	 * sbreserve() expects it available from interrupt context.
    964 	 */
    965 	(void)uid_find(0);
    966 }
    967 
    968 struct uidinfo *
    969 uid_find(uid_t uid)
    970 {
    971 	struct uidinfo *uip;
    972 	struct uidinfo *newuip = NULL;
    973 	struct uihashhead *uipp;
    974 
    975 	uipp = UIHASH(uid);
    976 
    977 again:
    978 	mutex_enter(&uihashtbl_lock);
    979 	LIST_FOREACH(uip, uipp, ui_hash)
    980 		if (uip->ui_uid == uid) {
    981 			mutex_exit(&uihashtbl_lock);
    982 			if (newuip) {
    983 				free(newuip, M_PROC);
    984 				mutex_destroy(&newuip->ui_lock);
    985 			}
    986 			return uip;
    987 		}
    988 	if (newuip == NULL) {
    989 		mutex_exit(&uihashtbl_lock);
    990 		/* Must not be called from interrupt context. */
    991 		newuip = malloc(sizeof(*uip), M_PROC, M_WAITOK | M_ZERO);
    992 		mutex_init(&newuip->ui_lock, MUTEX_DRIVER, IPL_SOFTNET);
    993 		goto again;
    994 	}
    995 	uip = newuip;
    996 
    997 	LIST_INSERT_HEAD(uipp, uip, ui_hash);
    998 	uip->ui_uid = uid;
    999 	mutex_exit(&uihashtbl_lock);
   1000 
   1001 	return uip;
   1002 }
   1003 
   1004 /*
   1005  * Change the count associated with number of processes
   1006  * a given user is using.
   1007  */
   1008 int
   1009 chgproccnt(uid_t uid, int diff)
   1010 {
   1011 	struct uidinfo *uip;
   1012 
   1013 	if (diff == 0)
   1014 		return 0;
   1015 
   1016 	uip = uid_find(uid);
   1017 	mutex_enter(&uip->ui_lock);
   1018 	uip->ui_proccnt += diff;
   1019 	KASSERT(uip->ui_proccnt >= 0);
   1020 	mutex_exit(&uip->ui_lock);
   1021 	return uip->ui_proccnt;
   1022 }
   1023 
   1024 int
   1025 chgsbsize(struct uidinfo *uip, u_long *hiwat, u_long to, rlim_t xmax)
   1026 {
   1027 	rlim_t nsb;
   1028 
   1029 	mutex_enter(&uip->ui_lock);
   1030 	nsb = uip->ui_sbsize + to - *hiwat;
   1031 	if (to > *hiwat && nsb > xmax) {
   1032 		mutex_exit(&uip->ui_lock);
   1033 		return 0;
   1034 	}
   1035 	*hiwat = to;
   1036 	uip->ui_sbsize = nsb;
   1037 	KASSERT(uip->ui_sbsize >= 0);
   1038 	mutex_exit(&uip->ui_lock);
   1039 	return 1;
   1040 }
   1041