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