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