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