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