Home | History | Annotate | Line # | Download | only in kern
kern_resource.c revision 1.126.2.2
      1 /*	$NetBSD: kern_resource.c,v 1.126.2.2 2007/12/15 03:16:57 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1982, 1986, 1991, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  * (c) UNIX System Laboratories, Inc.
      7  * All or some portions of this file are derived from material licensed
      8  * to the University of California by American Telephone and Telegraph
      9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     10  * the permission of UNIX System Laboratories, Inc.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  *
     36  *	@(#)kern_resource.c	8.8 (Berkeley) 2/14/95
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 __KERNEL_RCSID(0, "$NetBSD: kern_resource.c,v 1.126.2.2 2007/12/15 03:16:57 ad Exp $");
     41 
     42 #include <sys/param.h>
     43 #include <sys/systm.h>
     44 #include <sys/kernel.h>
     45 #include <sys/file.h>
     46 #include <sys/resourcevar.h>
     47 #include <sys/malloc.h>
     48 #include <sys/namei.h>
     49 #include <sys/pool.h>
     50 #include <sys/proc.h>
     51 #include <sys/sysctl.h>
     52 #include <sys/kauth.h>
     53 #include <sys/atomic.h>
     54 #include <sys/mount.h>
     55 #include <sys/syscallargs.h>
     56 
     57 #include <uvm/uvm_extern.h>
     58 
     59 /*
     60  * Maximum process data and stack limits.
     61  * They are variables so they are patchable.
     62  */
     63 rlim_t maxdmap = MAXDSIZ;
     64 rlim_t maxsmap = MAXSSIZ;
     65 
     66 struct uihashhead *uihashtbl;
     67 u_long uihash;		/* size of hash table - 1 */
     68 kmutex_t uihashtbl_lock;
     69 
     70 static pool_cache_t plimit_cache;
     71 static pool_cache_t pstats_cache;
     72 
     73 void
     74 resource_init(void)
     75 {
     76 
     77 	plimit_cache = pool_cache_init(sizeof(struct plimit), 0, 0, 0,
     78 	    "plimitpl", NULL, IPL_NONE, NULL, NULL, NULL);
     79 	pstats_cache = pool_cache_init(sizeof(struct pstats), 0, 0, 0,
     80 	    "pstatspl", NULL, IPL_NONE, NULL, NULL, NULL);
     81 }
     82 
     83 /*
     84  * Resource controls and accounting.
     85  */
     86 
     87 int
     88 sys_getpriority(struct lwp *l, void *v, register_t *retval)
     89 {
     90 	struct sys_getpriority_args /* {
     91 		syscallarg(int) which;
     92 		syscallarg(id_t) who;
     93 	} */ *uap = v;
     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(&proclist_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 			mutex_enter(&p->p_mutex);
    128 			if (kauth_cred_geteuid(p->p_cred) ==
    129 			    (uid_t)who && p->p_nice < low)
    130 				low = p->p_nice;
    131 			mutex_exit(&p->p_mutex);
    132 		}
    133 		break;
    134 
    135 	default:
    136 		mutex_exit(&proclist_lock);
    137 		return (EINVAL);
    138 	}
    139 	mutex_exit(&proclist_lock);
    140 
    141 	if (low == NZERO + PRIO_MAX + 1)
    142 		return (ESRCH);
    143 	*retval = low - NZERO;
    144 	return (0);
    145 }
    146 
    147 /* ARGSUSED */
    148 int
    149 sys_setpriority(struct lwp *l, void *v, register_t *retval)
    150 {
    151 	struct sys_setpriority_args /* {
    152 		syscallarg(int) which;
    153 		syscallarg(id_t) who;
    154 		syscallarg(int) prio;
    155 	} */ *uap = v;
    156 	struct proc *curp = l->l_proc, *p;
    157 	int found = 0, error = 0;
    158 	int who = SCARG(uap, who);
    159 
    160 	mutex_enter(&proclist_lock);
    161 	switch (SCARG(uap, which)) {
    162 	case PRIO_PROCESS:
    163 		if (who == 0)
    164 			p = curp;
    165 		else
    166 			p = p_find(who, PFIND_LOCKED);
    167 		if (p != 0) {
    168 			mutex_enter(&p->p_mutex);
    169 			error = donice(l, p, SCARG(uap, prio));
    170 			mutex_exit(&p->p_mutex);
    171 		}
    172 		found++;
    173 		break;
    174 
    175 	case PRIO_PGRP: {
    176 		struct pgrp *pg;
    177 
    178 		if (who == 0)
    179 			pg = curp->p_pgrp;
    180 		else if ((pg = pg_find(who, PFIND_LOCKED)) == NULL)
    181 			break;
    182 		LIST_FOREACH(p, &pg->pg_members, p_pglist) {
    183 			mutex_enter(&p->p_mutex);
    184 			error = donice(l, p, SCARG(uap, prio));
    185 			mutex_exit(&p->p_mutex);
    186 			found++;
    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_mutex);
    196 			if (kauth_cred_geteuid(p->p_cred) ==
    197 			    (uid_t)SCARG(uap, who)) {
    198 				error = donice(l, p, SCARG(uap, prio));
    199 				found++;
    200 			}
    201 			mutex_exit(&p->p_mutex);
    202 		}
    203 		break;
    204 
    205 	default:
    206 		error = EINVAL;
    207 		break;
    208 	}
    209 	mutex_exit(&proclist_lock);
    210 	if (found == 0)
    211 		return (ESRCH);
    212 	return (error);
    213 }
    214 
    215 /*
    216  * Renice a process.
    217  *
    218  * Call with the target process' credentials locked.
    219  */
    220 int
    221 donice(struct lwp *l, struct proc *chgp, int n)
    222 {
    223 	kauth_cred_t cred = l->l_cred;
    224 	int onice;
    225 
    226 	KASSERT(mutex_owned(&chgp->p_mutex));
    227 
    228 	if (n > PRIO_MAX)
    229 		n = PRIO_MAX;
    230 	if (n < PRIO_MIN)
    231 		n = PRIO_MIN;
    232 	n += NZERO;
    233 	onice = chgp->p_nice;
    234 	onice = chgp->p_nice;
    235 
    236   again:
    237 	if (kauth_authorize_process(cred, KAUTH_PROCESS_NICE, chgp,
    238 	    KAUTH_ARG(n), NULL, NULL))
    239 		return (EACCES);
    240 	mutex_spin_enter(&chgp->p_smutex);
    241 	if (onice != chgp->p_nice) {
    242 		mutex_spin_exit(&chgp->p_smutex);
    243 		goto again;
    244 	}
    245 	sched_nice(chgp, n);
    246 	mutex_spin_exit(&chgp->p_smutex);
    247 	return (0);
    248 }
    249 
    250 /* ARGSUSED */
    251 int
    252 sys_setrlimit(struct lwp *l, void *v, register_t *retval)
    253 {
    254 	struct sys_setrlimit_args /* {
    255 		syscallarg(int) which;
    256 		syscallarg(const struct rlimit *) rlp;
    257 	} */ *uap = v;
    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 < 0 || limp->rlim_max < 0)
    278 		return (EINVAL);
    279 
    280 	if (limp->rlim_cur > limp->rlim_max) {
    281 		/*
    282 		 * This is programming error. According to SUSv2, we should
    283 		 * return error in this case.
    284 		 */
    285 		return (EINVAL);
    286 	}
    287 
    288 	alimp = &p->p_rlimit[which];
    289 	/* if we don't change the value, no need to limcopy() */
    290 	if (limp->rlim_cur == alimp->rlim_cur &&
    291 	    limp->rlim_max == alimp->rlim_max)
    292 		return 0;
    293 
    294 	error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_RLIMIT,
    295 	    p, limp, KAUTH_ARG(which), NULL);
    296 	if (error)
    297 		return (error);
    298 
    299 	lim_privatise(p, false);
    300 	/* p->p_limit is now unchangeable */
    301 	alimp = &p->p_rlimit[which];
    302 
    303 	switch (which) {
    304 
    305 	case RLIMIT_DATA:
    306 		if (limp->rlim_cur > maxdmap)
    307 			limp->rlim_cur = maxdmap;
    308 		if (limp->rlim_max > maxdmap)
    309 			limp->rlim_max = maxdmap;
    310 		break;
    311 
    312 	case RLIMIT_STACK:
    313 		if (limp->rlim_cur > maxsmap)
    314 			limp->rlim_cur = maxsmap;
    315 		if (limp->rlim_max > maxsmap)
    316 			limp->rlim_max = maxsmap;
    317 
    318 		/*
    319 		 * Return EINVAL if the new stack size limit is lower than
    320 		 * current usage. Otherwise, the process would get SIGSEGV the
    321 		 * moment it would try to access anything on it's current stack.
    322 		 * This conforms to SUSv2.
    323 		 */
    324 		if (limp->rlim_cur < p->p_vmspace->vm_ssize * PAGE_SIZE
    325 		    || limp->rlim_max < p->p_vmspace->vm_ssize * PAGE_SIZE) {
    326 			return (EINVAL);
    327 		}
    328 
    329 		/*
    330 		 * Stack is allocated to the max at exec time with
    331 		 * only "rlim_cur" bytes accessible (In other words,
    332 		 * allocates stack dividing two contiguous regions at
    333 		 * "rlim_cur" bytes boundary).
    334 		 *
    335 		 * Since allocation is done in terms of page, roundup
    336 		 * "rlim_cur" (otherwise, contiguous regions
    337 		 * overlap).  If stack limit is going up make more
    338 		 * accessible, if going down make inaccessible.
    339 		 */
    340 		limp->rlim_cur = round_page(limp->rlim_cur);
    341 		if (limp->rlim_cur != alimp->rlim_cur) {
    342 			vaddr_t addr;
    343 			vsize_t size;
    344 			vm_prot_t prot;
    345 
    346 			if (limp->rlim_cur > alimp->rlim_cur) {
    347 				prot = VM_PROT_READ | VM_PROT_WRITE;
    348 				size = limp->rlim_cur - alimp->rlim_cur;
    349 				addr = (vaddr_t)p->p_vmspace->vm_minsaddr -
    350 				    limp->rlim_cur;
    351 			} else {
    352 				prot = VM_PROT_NONE;
    353 				size = alimp->rlim_cur - limp->rlim_cur;
    354 				addr = (vaddr_t)p->p_vmspace->vm_minsaddr -
    355 				     alimp->rlim_cur;
    356 			}
    357 			(void) uvm_map_protect(&p->p_vmspace->vm_map,
    358 			    addr, addr+size, prot, false);
    359 		}
    360 		break;
    361 
    362 	case RLIMIT_NOFILE:
    363 		if (limp->rlim_cur > maxfiles)
    364 			limp->rlim_cur = maxfiles;
    365 		if (limp->rlim_max > maxfiles)
    366 			limp->rlim_max = maxfiles;
    367 		break;
    368 
    369 	case RLIMIT_NPROC:
    370 		if (limp->rlim_cur > maxproc)
    371 			limp->rlim_cur = maxproc;
    372 		if (limp->rlim_max > maxproc)
    373 			limp->rlim_max = maxproc;
    374 		break;
    375 	}
    376 
    377 	mutex_enter(&p->p_limit->pl_lock);
    378 	*alimp = *limp;
    379 	mutex_exit(&p->p_limit->pl_lock);
    380 	return (0);
    381 }
    382 
    383 /* ARGSUSED */
    384 int
    385 sys_getrlimit(struct lwp *l, void *v, register_t *retval)
    386 {
    387 	struct sys_getrlimit_args /* {
    388 		syscallarg(int) which;
    389 		syscallarg(struct rlimit *) rlp;
    390 	} */ *uap = v;
    391 	struct proc *p = l->l_proc;
    392 	int which = SCARG(uap, which);
    393 	struct rlimit rl;
    394 
    395 	if ((u_int)which >= RLIM_NLIMITS)
    396 		return (EINVAL);
    397 
    398 	mutex_enter(&p->p_mutex);
    399 	memcpy(&rl, &p->p_rlimit[which], sizeof(rl));
    400 	mutex_exit(&p->p_mutex);
    401 
    402 	return copyout(&rl, SCARG(uap, rlp), sizeof(rl));
    403 }
    404 
    405 /*
    406  * Transform the running time and tick information in proc p into user,
    407  * system, and interrupt time usage.
    408  *
    409  * Should be called with p->p_smutex held unless called from exit1().
    410  */
    411 void
    412 calcru(struct proc *p, struct timeval *up, struct timeval *sp,
    413     struct timeval *ip, struct timeval *rp)
    414 {
    415 	u_quad_t u, st, ut, it, tot;
    416 	unsigned long sec;
    417 	long usec;
    418  	struct timeval tv;
    419 	struct lwp *l;
    420 
    421 	mutex_spin_enter(&p->p_stmutex);
    422 	st = p->p_sticks;
    423 	ut = p->p_uticks;
    424 	it = p->p_iticks;
    425 	mutex_spin_exit(&p->p_stmutex);
    426 
    427 	sec = p->p_rtime.tv_sec;
    428 	usec = p->p_rtime.tv_usec;
    429 
    430 	LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    431 		lwp_lock(l);
    432 		sec += l->l_rtime.tv_sec;
    433 		if ((usec += l->l_rtime.tv_usec) >= 1000000) {
    434 			sec++;
    435 			usec -= 1000000;
    436 		}
    437 		if ((l->l_flag & LW_RUNNING) != 0) {
    438 			/*
    439 			 * Adjust for the current time slice.  This is
    440 			 * actually fairly important since the error
    441 			 * here is on the order of a time quantum,
    442 			 * which is much greater than the sampling
    443 			 * error.
    444 			 */
    445 			microtime(&tv);
    446 			sec += tv.tv_sec - l->l_stime.tv_sec;
    447 			usec += tv.tv_usec - l->l_stime.tv_usec;
    448 			if (usec >= 1000000) {
    449 				sec++;
    450 				usec -= 1000000;
    451 			}
    452 		}
    453 		lwp_unlock(l);
    454 	}
    455 
    456 	tot = st + ut + it;
    457 	u = sec * 1000000ull + usec;
    458 
    459 	if (tot == 0) {
    460 		/* No ticks, so can't use to share time out, split 50-50 */
    461 		st = ut = u / 2;
    462 	} else {
    463 		st = (u * st) / tot;
    464 		ut = (u * ut) / tot;
    465 	}
    466 	if (sp != NULL) {
    467 		sp->tv_sec = st / 1000000;
    468 		sp->tv_usec = st % 1000000;
    469 	}
    470 	if (up != NULL) {
    471 		up->tv_sec = ut / 1000000;
    472 		up->tv_usec = ut % 1000000;
    473 	}
    474 	if (ip != NULL) {
    475 		if (it != 0)
    476 			it = (u * it) / tot;
    477 		ip->tv_sec = it / 1000000;
    478 		ip->tv_usec = it % 1000000;
    479 	}
    480 	if (rp != NULL) {
    481 		rp->tv_sec = sec;
    482 		rp->tv_usec = usec;
    483 	}
    484 }
    485 
    486 /* ARGSUSED */
    487 int
    488 sys_getrusage(struct lwp *l, void *v, register_t *retval)
    489 {
    490 	struct sys_getrusage_args /* {
    491 		syscallarg(int) who;
    492 		syscallarg(struct rusage *) rusage;
    493 	} */ *uap = v;
    494 	struct rusage ru;
    495 	struct proc *p = l->l_proc;
    496 
    497 	switch (SCARG(uap, who)) {
    498 	case RUSAGE_SELF:
    499 		mutex_enter(&p->p_smutex);
    500 		memcpy(&ru, &p->p_stats->p_ru, sizeof(ru));
    501 		calcru(p, &ru.ru_utime, &ru.ru_stime, NULL, NULL);
    502 		mutex_exit(&p->p_smutex);
    503 		break;
    504 
    505 	case RUSAGE_CHILDREN:
    506 		mutex_enter(&p->p_smutex);
    507 		memcpy(&ru, &p->p_stats->p_cru, sizeof(ru));
    508 		mutex_exit(&p->p_smutex);
    509 		break;
    510 
    511 	default:
    512 		return EINVAL;
    513 	}
    514 
    515 	return copyout(&ru, SCARG(uap, rusage), sizeof(ru));
    516 }
    517 
    518 void
    519 ruadd(struct rusage *ru, struct rusage *ru2)
    520 {
    521 	long *ip, *ip2;
    522 	int i;
    523 
    524 	timeradd(&ru->ru_utime, &ru2->ru_utime, &ru->ru_utime);
    525 	timeradd(&ru->ru_stime, &ru2->ru_stime, &ru->ru_stime);
    526 	if (ru->ru_maxrss < ru2->ru_maxrss)
    527 		ru->ru_maxrss = ru2->ru_maxrss;
    528 	ip = &ru->ru_first; ip2 = &ru2->ru_first;
    529 	for (i = &ru->ru_last - &ru->ru_first; i >= 0; i--)
    530 		*ip++ += *ip2++;
    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_mutex);
    613 	if (p->p_limit->pl_flags & PL_WRITEABLE) {
    614 		/* Someone crept in while we were busy */
    615 		mutex_exit(&p->p_mutex);
    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_mutex);
    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 this should be in p_find() */
    731 	error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_CANSEE,
    732 	    ptmp, NULL, NULL, NULL);
    733 	if (error)
    734 		return (error);
    735 
    736 	/*
    737 	 * let them modify a temporary copy of the core name
    738 	 */
    739 	cname = PNBUF_GET();
    740 	lim = ptmp->p_limit;
    741 	mutex_enter(&lim->pl_lock);
    742 	strlcpy(cname, lim->pl_corename, MAXPATHLEN);
    743 	mutex_exit(&lim->pl_lock);
    744 
    745 	node = *rnode;
    746 	node.sysctl_data = cname;
    747 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    748 
    749 	/*
    750 	 * if that failed, or they have nothing new to say, or we've
    751 	 * heard it before...
    752 	 */
    753 	if (error || newp == NULL)
    754 		goto done;
    755 	lim = ptmp->p_limit;
    756 	mutex_enter(&lim->pl_lock);
    757 	error = strcmp(cname, lim->pl_corename);
    758 	mutex_exit(&lim->pl_lock);
    759 	if (error == 0)
    760 		/* Unchanged */
    761 		goto done;
    762 
    763 	error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_CORENAME,
    764 	    ptmp, cname, NULL, NULL);
    765 	if (error)
    766 		return (error);
    767 
    768 	/*
    769 	 * no error yet and cname now has the new core name in it.
    770 	 * let's see if it looks acceptable.  it must be either "core"
    771 	 * or end in ".core" or "/core".
    772 	 */
    773 	len = strlen(cname);
    774 	if (len < 4) {
    775 		error = EINVAL;
    776 	} else if (strcmp(cname + len - 4, "core") != 0) {
    777 		error = EINVAL;
    778 	} else if (len > 4 && cname[len - 5] != '/' && cname[len - 5] != '.') {
    779 		error = EINVAL;
    780 	}
    781 	if (error != 0) {
    782 		goto done;
    783 	}
    784 
    785 	/*
    786 	 * hmm...looks good.  now...where do we put it?
    787 	 */
    788 	tmp = malloc(len + 1, M_TEMP, M_WAITOK|M_CANFAIL);
    789 	if (tmp == NULL) {
    790 		error = ENOMEM;
    791 		goto done;
    792 	}
    793 	memcpy(tmp, cname, len + 1);
    794 
    795 	lim_privatise(ptmp, false);
    796 	lim = ptmp->p_limit;
    797 	mutex_enter(&lim->pl_lock);
    798 	ocore = lim->pl_corename;
    799 	lim->pl_corename = tmp;
    800 	mutex_exit(&lim->pl_lock);
    801 	if (ocore != defcorename)
    802 		free(ocore, M_TEMP);
    803 
    804 done:
    805 	PNBUF_PUT(cname);
    806 	return error;
    807 }
    808 
    809 /*
    810  * sysctl helper routine for checking/setting a process's stop flags,
    811  * one for fork and one for exec.
    812  */
    813 static int
    814 sysctl_proc_stop(SYSCTLFN_ARGS)
    815 {
    816 	struct proc *ptmp;
    817 	int i, f, error = 0;
    818 	struct sysctlnode node;
    819 
    820 	if (namelen != 0)
    821 		return (EINVAL);
    822 
    823 	error = sysctl_proc_findproc(l, &ptmp, (pid_t)name[-2]);
    824 	if (error)
    825 		return (error);
    826 
    827 	/* XXX this should be in p_find() */
    828 	error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_CANSEE,
    829 	    ptmp, NULL, NULL, NULL);
    830 	if (error)
    831 		return (error);
    832 
    833 	switch (rnode->sysctl_num) {
    834 	case PROC_PID_STOPFORK:
    835 		f = PS_STOPFORK;
    836 		break;
    837 	case PROC_PID_STOPEXEC:
    838 		f = PS_STOPEXEC;
    839 		break;
    840 	case PROC_PID_STOPEXIT:
    841 		f = PS_STOPEXIT;
    842 		break;
    843 	default:
    844 		return (EINVAL);
    845 	}
    846 
    847 	i = (ptmp->p_flag & f) ? 1 : 0;
    848 	node = *rnode;
    849 	node.sysctl_data = &i;
    850 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    851 	if (error || newp == NULL)
    852 		return (error);
    853 
    854 	mutex_enter(&ptmp->p_smutex);
    855 	error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_STOPFLAG,
    856 	    ptmp, KAUTH_ARG(f), NULL, NULL);
    857 	if (error)
    858 		return (error);
    859 	if (i)
    860 		ptmp->p_sflag |= f;
    861 	else
    862 		ptmp->p_sflag &= ~f;
    863 	mutex_exit(&ptmp->p_smutex);
    864 
    865 	return (0);
    866 }
    867 
    868 /*
    869  * sysctl helper routine for a process's rlimits as exposed by sysctl.
    870  */
    871 static int
    872 sysctl_proc_plimit(SYSCTLFN_ARGS)
    873 {
    874 	struct proc *ptmp;
    875 	u_int limitno;
    876 	int which, error = 0;
    877         struct rlimit alim;
    878 	struct sysctlnode node;
    879 
    880 	if (namelen != 0)
    881 		return (EINVAL);
    882 
    883 	which = name[-1];
    884 	if (which != PROC_PID_LIMIT_TYPE_SOFT &&
    885 	    which != PROC_PID_LIMIT_TYPE_HARD)
    886 		return (EINVAL);
    887 
    888 	limitno = name[-2] - 1;
    889 	if (limitno >= RLIM_NLIMITS)
    890 		return (EINVAL);
    891 
    892 	if (name[-3] != PROC_PID_LIMIT)
    893 		return (EINVAL);
    894 
    895 	error = sysctl_proc_findproc(l, &ptmp, (pid_t)name[-4]);
    896 	if (error)
    897 		return (error);
    898 
    899 	/* XXX this should be in p_find() */
    900 	error = kauth_authorize_process(l->l_cred, KAUTH_PROCESS_CANSEE,
    901 	    ptmp, NULL, NULL, NULL);
    902 	if (error)
    903 		return (error);
    904 
    905 	node = *rnode;
    906 	memcpy(&alim, &ptmp->p_rlimit[limitno], sizeof(alim));
    907 	if (which == PROC_PID_LIMIT_TYPE_HARD)
    908 		node.sysctl_data = &alim.rlim_max;
    909 	else
    910 		node.sysctl_data = &alim.rlim_cur;
    911 
    912 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    913 	if (error || newp == NULL)
    914 		return (error);
    915 
    916 	return (dosetrlimit(l, ptmp, limitno, &alim));
    917 }
    918 
    919 /*
    920  * and finally, the actually glue that sticks it to the tree
    921  */
    922 SYSCTL_SETUP(sysctl_proc_setup, "sysctl proc subtree setup")
    923 {
    924 
    925 	sysctl_createv(clog, 0, NULL, NULL,
    926 		       CTLFLAG_PERMANENT,
    927 		       CTLTYPE_NODE, "proc", NULL,
    928 		       NULL, 0, NULL, 0,
    929 		       CTL_PROC, CTL_EOL);
    930 	sysctl_createv(clog, 0, NULL, NULL,
    931 		       CTLFLAG_PERMANENT|CTLFLAG_ANYNUMBER,
    932 		       CTLTYPE_NODE, "curproc",
    933 		       SYSCTL_DESCR("Per-process settings"),
    934 		       NULL, 0, NULL, 0,
    935 		       CTL_PROC, PROC_CURPROC, CTL_EOL);
    936 
    937 	sysctl_createv(clog, 0, NULL, NULL,
    938 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE|CTLFLAG_ANYWRITE,
    939 		       CTLTYPE_STRING, "corename",
    940 		       SYSCTL_DESCR("Core file name"),
    941 		       sysctl_proc_corename, 0, NULL, MAXPATHLEN,
    942 		       CTL_PROC, PROC_CURPROC, PROC_PID_CORENAME, CTL_EOL);
    943 	sysctl_createv(clog, 0, NULL, NULL,
    944 		       CTLFLAG_PERMANENT,
    945 		       CTLTYPE_NODE, "rlimit",
    946 		       SYSCTL_DESCR("Process limits"),
    947 		       NULL, 0, NULL, 0,
    948 		       CTL_PROC, PROC_CURPROC, PROC_PID_LIMIT, CTL_EOL);
    949 
    950 #define create_proc_plimit(s, n) do {					\
    951 	sysctl_createv(clog, 0, NULL, NULL,				\
    952 		       CTLFLAG_PERMANENT,				\
    953 		       CTLTYPE_NODE, s,					\
    954 		       SYSCTL_DESCR("Process " s " limits"),		\
    955 		       NULL, 0, NULL, 0,				\
    956 		       CTL_PROC, PROC_CURPROC, PROC_PID_LIMIT, n,	\
    957 		       CTL_EOL);					\
    958 	sysctl_createv(clog, 0, NULL, NULL,				\
    959 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE|CTLFLAG_ANYWRITE, \
    960 		       CTLTYPE_QUAD, "soft",				\
    961 		       SYSCTL_DESCR("Process soft " s " limit"),	\
    962 		       sysctl_proc_plimit, 0, NULL, 0,			\
    963 		       CTL_PROC, PROC_CURPROC, PROC_PID_LIMIT, n,	\
    964 		       PROC_PID_LIMIT_TYPE_SOFT, CTL_EOL);		\
    965 	sysctl_createv(clog, 0, NULL, NULL,				\
    966 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE|CTLFLAG_ANYWRITE, \
    967 		       CTLTYPE_QUAD, "hard",				\
    968 		       SYSCTL_DESCR("Process hard " s " limit"),	\
    969 		       sysctl_proc_plimit, 0, NULL, 0,			\
    970 		       CTL_PROC, PROC_CURPROC, PROC_PID_LIMIT, n,	\
    971 		       PROC_PID_LIMIT_TYPE_HARD, CTL_EOL);		\
    972 	} while (0/*CONSTCOND*/)
    973 
    974 	create_proc_plimit("cputime",		PROC_PID_LIMIT_CPU);
    975 	create_proc_plimit("filesize",		PROC_PID_LIMIT_FSIZE);
    976 	create_proc_plimit("datasize",		PROC_PID_LIMIT_DATA);
    977 	create_proc_plimit("stacksize",		PROC_PID_LIMIT_STACK);
    978 	create_proc_plimit("coredumpsize",	PROC_PID_LIMIT_CORE);
    979 	create_proc_plimit("memoryuse",		PROC_PID_LIMIT_RSS);
    980 	create_proc_plimit("memorylocked",	PROC_PID_LIMIT_MEMLOCK);
    981 	create_proc_plimit("maxproc",		PROC_PID_LIMIT_NPROC);
    982 	create_proc_plimit("descriptors",	PROC_PID_LIMIT_NOFILE);
    983 	create_proc_plimit("sbsize",		PROC_PID_LIMIT_SBSIZE);
    984 
    985 #undef create_proc_plimit
    986 
    987 	sysctl_createv(clog, 0, NULL, NULL,
    988 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE|CTLFLAG_ANYWRITE,
    989 		       CTLTYPE_INT, "stopfork",
    990 		       SYSCTL_DESCR("Stop process at fork(2)"),
    991 		       sysctl_proc_stop, 0, NULL, 0,
    992 		       CTL_PROC, PROC_CURPROC, PROC_PID_STOPFORK, CTL_EOL);
    993 	sysctl_createv(clog, 0, NULL, NULL,
    994 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE|CTLFLAG_ANYWRITE,
    995 		       CTLTYPE_INT, "stopexec",
    996 		       SYSCTL_DESCR("Stop process at execve(2)"),
    997 		       sysctl_proc_stop, 0, NULL, 0,
    998 		       CTL_PROC, PROC_CURPROC, PROC_PID_STOPEXEC, CTL_EOL);
    999 	sysctl_createv(clog, 0, NULL, NULL,
   1000 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE|CTLFLAG_ANYWRITE,
   1001 		       CTLTYPE_INT, "stopexit",
   1002 		       SYSCTL_DESCR("Stop process before completing exit"),
   1003 		       sysctl_proc_stop, 0, NULL, 0,
   1004 		       CTL_PROC, PROC_CURPROC, PROC_PID_STOPEXIT, CTL_EOL);
   1005 }
   1006 
   1007 void
   1008 uid_init(void)
   1009 {
   1010 
   1011 	/*
   1012 	 * XXXSMP This could be at IPL_SOFTNET, but for now we want
   1013 	 * to to be deadlock free, so it must be at IPL_VM.
   1014 	 */
   1015 	mutex_init(&uihashtbl_lock, MUTEX_DEFAULT, IPL_VM);
   1016 
   1017 	/*
   1018 	 * Ensure that uid 0 is always in the user hash table, as
   1019 	 * sbreserve() expects it available from interrupt context.
   1020 	 */
   1021 	(void)uid_find(0);
   1022 }
   1023 
   1024 struct uidinfo *
   1025 uid_find(uid_t uid)
   1026 {
   1027 	struct uidinfo *uip;
   1028 	struct uidinfo *newuip = NULL;
   1029 	struct uihashhead *uipp;
   1030 
   1031 	uipp = UIHASH(uid);
   1032 
   1033 again:
   1034 	mutex_enter(&uihashtbl_lock);
   1035 	LIST_FOREACH(uip, uipp, ui_hash)
   1036 		if (uip->ui_uid == uid) {
   1037 			mutex_exit(&uihashtbl_lock);
   1038 			if (newuip) {
   1039 				mutex_destroy(&newuip->ui_lock);
   1040 				free(newuip, M_PROC);
   1041 			}
   1042 			return uip;
   1043 		}
   1044 	if (newuip == NULL) {
   1045 		mutex_exit(&uihashtbl_lock);
   1046 		/* Must not be called from interrupt context. */
   1047 		newuip = malloc(sizeof(*uip), M_PROC, M_WAITOK | M_ZERO);
   1048 		/* XXX this could be IPL_SOFTNET */
   1049 		mutex_init(&newuip->ui_lock, MUTEX_DEFAULT, IPL_VM);
   1050 		goto again;
   1051 	}
   1052 	uip = newuip;
   1053 
   1054 	LIST_INSERT_HEAD(uipp, uip, ui_hash);
   1055 	uip->ui_uid = uid;
   1056 	mutex_exit(&uihashtbl_lock);
   1057 
   1058 	return uip;
   1059 }
   1060 
   1061 /*
   1062  * Change the count associated with number of processes
   1063  * a given user is using.
   1064  */
   1065 int
   1066 chgproccnt(uid_t uid, int diff)
   1067 {
   1068 	struct uidinfo *uip;
   1069 
   1070 	if (diff == 0)
   1071 		return 0;
   1072 
   1073 	uip = uid_find(uid);
   1074 	mutex_enter(&uip->ui_lock);
   1075 	uip->ui_proccnt += diff;
   1076 	KASSERT(uip->ui_proccnt >= 0);
   1077 	mutex_exit(&uip->ui_lock);
   1078 	return uip->ui_proccnt;
   1079 }
   1080 
   1081 int
   1082 chgsbsize(struct uidinfo *uip, u_long *hiwat, u_long to, rlim_t xmax)
   1083 {
   1084 	rlim_t nsb;
   1085 
   1086 	mutex_enter(&uip->ui_lock);
   1087 	nsb = uip->ui_sbsize + to - *hiwat;
   1088 	if (to > *hiwat && nsb > xmax) {
   1089 		mutex_exit(&uip->ui_lock);
   1090 		return 0;
   1091 	}
   1092 	*hiwat = to;
   1093 	uip->ui_sbsize = nsb;
   1094 	KASSERT(uip->ui_sbsize >= 0);
   1095 	mutex_exit(&uip->ui_lock);
   1096 	return 1;
   1097 }
   1098