xref: /freebsd/sys/kern/kern_resource.c (revision 35ccfc58d8065d58df2469c13fce9d3a60d53845)
1 /*-
2  * Copyright (c) 1982, 1986, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)kern_resource.c	8.5 (Berkeley) 1/21/94
39  * $FreeBSD$
40  */
41 
42 #include "opt_compat.h"
43 #include "opt_rlimit.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/sysproto.h>
48 #include <sys/file.h>
49 #include <sys/kernel.h>
50 #include <sys/resourcevar.h>
51 #include <sys/malloc.h>
52 #include <sys/proc.h>
53 #include <sys/time.h>
54 #include <sys/mutex.h>
55 
56 #include <vm/vm.h>
57 #include <vm/vm_param.h>
58 #include <sys/lock.h>
59 #include <vm/pmap.h>
60 #include <vm/vm_map.h>
61 
62 static int donice __P((struct proc *curp, struct proc *chgp, int n));
63 /* dosetrlimit non-static:  Needed by SysVR4 emulator */
64 int dosetrlimit __P((struct proc *p, u_int which, struct rlimit *limp));
65 
66 static MALLOC_DEFINE(M_UIDINFO, "uidinfo", "uidinfo structures");
67 #define	UIHASH(uid)	(&uihashtbl[(uid) & uihash])
68 static struct mtx uihashtbl_mtx;
69 static LIST_HEAD(uihashhead, uidinfo) *uihashtbl;
70 static u_long uihash;		/* size of hash table - 1 */
71 
72 static struct uidinfo	*uicreate __P((uid_t uid));
73 static struct uidinfo	*uilookup __P((uid_t uid));
74 
75 /*
76  * Resource controls and accounting.
77  */
78 
79 #ifndef _SYS_SYSPROTO_H_
80 struct getpriority_args {
81 	int	which;
82 	int	who;
83 };
84 #endif
85 int
86 getpriority(curp, uap)
87 	struct proc *curp;
88 	register struct getpriority_args *uap;
89 {
90 	register struct proc *p;
91 	register int low = PRIO_MAX + 1;
92 
93 	switch (uap->which) {
94 
95 	case PRIO_PROCESS:
96 		if (uap->who == 0)
97 			p = curp;
98 		else
99 			p = pfind(uap->who);
100 		if (p == 0)
101 			break;
102 		if (p_can(curp, p, P_CAN_SEE, NULL))
103 			break;
104 		low = p->p_nice;
105 		break;
106 
107 	case PRIO_PGRP: {
108 		register struct pgrp *pg;
109 
110 		if (uap->who == 0)
111 			pg = curp->p_pgrp;
112 		else if ((pg = pgfind(uap->who)) == NULL)
113 			break;
114 		LIST_FOREACH(p, &pg->pg_members, p_pglist) {
115 			if (!p_can(curp, p, P_CAN_SEE, NULL) && p->p_nice < low)
116 				low = p->p_nice;
117 		}
118 		break;
119 	}
120 
121 	case PRIO_USER:
122 		if (uap->who == 0)
123 			uap->who = curp->p_ucred->cr_uid;
124 		lockmgr(&allproc_lock, LK_SHARED, NULL, CURPROC);
125 		LIST_FOREACH(p, &allproc, p_list)
126 			if (!p_can(curp, p, P_CAN_SEE, NULL) &&
127 			    p->p_ucred->cr_uid == uap->who &&
128 			    p->p_nice < low)
129 				low = p->p_nice;
130 		lockmgr(&allproc_lock, LK_RELEASE, NULL, CURPROC);
131 		break;
132 
133 	default:
134 		return (EINVAL);
135 	}
136 	if (low == PRIO_MAX + 1)
137 		return (ESRCH);
138 	curp->p_retval[0] = low;
139 	return (0);
140 }
141 
142 #ifndef _SYS_SYSPROTO_H_
143 struct setpriority_args {
144 	int	which;
145 	int	who;
146 	int	prio;
147 };
148 #endif
149 /* ARGSUSED */
150 int
151 setpriority(curp, uap)
152 	struct proc *curp;
153 	register struct setpriority_args *uap;
154 {
155 	register struct proc *p;
156 	int found = 0, error = 0;
157 
158 	switch (uap->which) {
159 
160 	case PRIO_PROCESS:
161 		if (uap->who == 0)
162 			p = curp;
163 		else
164 			p = pfind(uap->who);
165 		if (p == 0)
166 			break;
167 		if (p_can(curp, p, P_CAN_SEE, NULL))
168 			break;
169 		error = donice(curp, p, uap->prio);
170 		found++;
171 		break;
172 
173 	case PRIO_PGRP: {
174 		register struct pgrp *pg;
175 
176 		if (uap->who == 0)
177 			pg = curp->p_pgrp;
178 		else if ((pg = pgfind(uap->who)) == NULL)
179 			break;
180 		LIST_FOREACH(p, &pg->pg_members, p_pglist) {
181 			if (!p_can(curp, p, P_CAN_SEE, NULL)) {
182 				error = donice(curp, p, uap->prio);
183 				found++;
184 			}
185 		}
186 		break;
187 	}
188 
189 	case PRIO_USER:
190 		if (uap->who == 0)
191 			uap->who = curp->p_ucred->cr_uid;
192 		lockmgr(&allproc_lock, LK_SHARED, NULL, CURPROC);
193 		LIST_FOREACH(p, &allproc, p_list)
194 			if (p->p_ucred->cr_uid == uap->who &&
195 			    !p_can(curp, p, P_CAN_SEE, NULL)) {
196 				error = donice(curp, p, uap->prio);
197 				found++;
198 			}
199 		lockmgr(&allproc_lock, LK_RELEASE, NULL, CURPROC);
200 		break;
201 
202 	default:
203 		return (EINVAL);
204 	}
205 	if (found == 0)
206 		return (ESRCH);
207 	return (error);
208 }
209 
210 static int
211 donice(curp, chgp, n)
212 	register struct proc *curp, *chgp;
213 	register int n;
214 {
215 	int	error;
216 
217 	if ((error = p_can(curp, chgp, P_CAN_SCHED, NULL)))
218 		return (error);
219 	if (n > PRIO_MAX)
220 		n = PRIO_MAX;
221 	if (n < PRIO_MIN)
222 		n = PRIO_MIN;
223 	if (n < chgp->p_nice && suser(curp))
224 		return (EACCES);
225 	chgp->p_nice = n;
226 	(void)resetpriority(chgp);
227 	return (0);
228 }
229 
230 /* rtprio system call */
231 #ifndef _SYS_SYSPROTO_H_
232 struct rtprio_args {
233 	int		function;
234 	pid_t		pid;
235 	struct rtprio	*rtp;
236 };
237 #endif
238 
239 /*
240  * Set realtime priority
241  */
242 
243 /* ARGSUSED */
244 int
245 rtprio(curp, uap)
246 	struct proc *curp;
247 	register struct rtprio_args *uap;
248 {
249 	register struct proc *p;
250 	struct rtprio rtp;
251 	int error;
252 
253 	error = copyin(uap->rtp, &rtp, sizeof(struct rtprio));
254 	if (error)
255 		return (error);
256 
257 	if (uap->pid == 0)
258 		p = curp;
259 	else
260 		p = pfind(uap->pid);
261 
262 	if (p == 0)
263 		return (ESRCH);
264 
265 	switch (uap->function) {
266 	case RTP_LOOKUP:
267 		return (copyout(&p->p_rtprio, uap->rtp, sizeof(struct rtprio)));
268 	case RTP_SET:
269 		if ((error = p_can(curp, p, P_CAN_SCHED, NULL)))
270 		        return (error);
271 		/* disallow setting rtprio in most cases if not superuser */
272 		if (suser(curp) != 0) {
273 			/* can't set someone else's */
274 			if (uap->pid)
275 				return (EPERM);
276 			/* can't set realtime priority */
277 /*
278  * Realtime priority has to be restricted for reasons which should be
279  * obvious. However, for idle priority, there is a potential for
280  * system deadlock if an idleprio process gains a lock on a resource
281  * that other processes need (and the idleprio process can't run
282  * due to a CPU-bound normal process). Fix me! XXX
283  */
284 #if 0
285  			if (RTP_PRIO_IS_REALTIME(rtp.type))
286 #endif
287 			if (rtp.type != RTP_PRIO_NORMAL)
288 				return (EPERM);
289 		}
290 		switch (rtp.type) {
291 #ifdef RTP_PRIO_FIFO
292 		case RTP_PRIO_FIFO:
293 #endif
294 		case RTP_PRIO_REALTIME:
295 		case RTP_PRIO_NORMAL:
296 		case RTP_PRIO_IDLE:
297 			if (rtp.prio > RTP_PRIO_MAX)
298 				return (EINVAL);
299 			p->p_rtprio = rtp;
300 			return (0);
301 		default:
302 			return (EINVAL);
303 		}
304 
305 	default:
306 		return (EINVAL);
307 	}
308 }
309 
310 #if defined(COMPAT_43) || defined(COMPAT_SUNOS)
311 #ifndef _SYS_SYSPROTO_H_
312 struct osetrlimit_args {
313 	u_int	which;
314 	struct	orlimit *rlp;
315 };
316 #endif
317 /* ARGSUSED */
318 int
319 osetrlimit(p, uap)
320 	struct proc *p;
321 	register struct osetrlimit_args *uap;
322 {
323 	struct orlimit olim;
324 	struct rlimit lim;
325 	int error;
326 
327 	if ((error =
328 	    copyin((caddr_t)uap->rlp, (caddr_t)&olim, sizeof(struct orlimit))))
329 		return (error);
330 	lim.rlim_cur = olim.rlim_cur;
331 	lim.rlim_max = olim.rlim_max;
332 	return (dosetrlimit(p, uap->which, &lim));
333 }
334 
335 #ifndef _SYS_SYSPROTO_H_
336 struct ogetrlimit_args {
337 	u_int	which;
338 	struct	orlimit *rlp;
339 };
340 #endif
341 /* ARGSUSED */
342 int
343 ogetrlimit(p, uap)
344 	struct proc *p;
345 	register struct ogetrlimit_args *uap;
346 {
347 	struct orlimit olim;
348 
349 	if (uap->which >= RLIM_NLIMITS)
350 		return (EINVAL);
351 	olim.rlim_cur = p->p_rlimit[uap->which].rlim_cur;
352 	if (olim.rlim_cur == -1)
353 		olim.rlim_cur = 0x7fffffff;
354 	olim.rlim_max = p->p_rlimit[uap->which].rlim_max;
355 	if (olim.rlim_max == -1)
356 		olim.rlim_max = 0x7fffffff;
357 	return (copyout((caddr_t)&olim, (caddr_t)uap->rlp, sizeof(olim)));
358 }
359 #endif /* COMPAT_43 || COMPAT_SUNOS */
360 
361 #ifndef _SYS_SYSPROTO_H_
362 struct __setrlimit_args {
363 	u_int	which;
364 	struct	rlimit *rlp;
365 };
366 #endif
367 /* ARGSUSED */
368 int
369 setrlimit(p, uap)
370 	struct proc *p;
371 	register struct __setrlimit_args *uap;
372 {
373 	struct rlimit alim;
374 	int error;
375 
376 	if ((error =
377 	    copyin((caddr_t)uap->rlp, (caddr_t)&alim, sizeof (struct rlimit))))
378 		return (error);
379 	return (dosetrlimit(p, uap->which, &alim));
380 }
381 
382 int
383 dosetrlimit(p, which, limp)
384 	struct proc *p;
385 	u_int which;
386 	struct rlimit *limp;
387 {
388 	register struct rlimit *alimp;
389 	int error;
390 
391 	if (which >= RLIM_NLIMITS)
392 		return (EINVAL);
393 	alimp = &p->p_rlimit[which];
394 
395 	/*
396 	 * Preserve historical bugs by treating negative limits as unsigned.
397 	 */
398 	if (limp->rlim_cur < 0)
399 		limp->rlim_cur = RLIM_INFINITY;
400 	if (limp->rlim_max < 0)
401 		limp->rlim_max = RLIM_INFINITY;
402 
403 	if (limp->rlim_cur > alimp->rlim_max ||
404 	    limp->rlim_max > alimp->rlim_max)
405 		if ((error = suser_xxx(0, p, PRISON_ROOT)))
406 			return (error);
407 	if (limp->rlim_cur > limp->rlim_max)
408 		limp->rlim_cur = limp->rlim_max;
409 	if (p->p_limit->p_refcnt > 1 &&
410 	    (p->p_limit->p_lflags & PL_SHAREMOD) == 0) {
411 		p->p_limit->p_refcnt--;
412 		p->p_limit = limcopy(p->p_limit);
413 		alimp = &p->p_rlimit[which];
414 	}
415 
416 	switch (which) {
417 
418 	case RLIMIT_CPU:
419 		if (limp->rlim_cur > RLIM_INFINITY / (rlim_t)1000000)
420 			p->p_limit->p_cpulimit = RLIM_INFINITY;
421 		else
422 			p->p_limit->p_cpulimit =
423 			    (rlim_t)1000000 * limp->rlim_cur;
424 		break;
425 	case RLIMIT_DATA:
426 		if (limp->rlim_cur > MAXDSIZ)
427 			limp->rlim_cur = MAXDSIZ;
428 		if (limp->rlim_max > MAXDSIZ)
429 			limp->rlim_max = MAXDSIZ;
430 		break;
431 
432 	case RLIMIT_STACK:
433 		if (limp->rlim_cur > MAXSSIZ)
434 			limp->rlim_cur = MAXSSIZ;
435 		if (limp->rlim_max > MAXSSIZ)
436 			limp->rlim_max = MAXSSIZ;
437 		/*
438 		 * Stack is allocated to the max at exec time with only
439 		 * "rlim_cur" bytes accessible.  If stack limit is going
440 		 * up make more accessible, if going down make inaccessible.
441 		 */
442 		if (limp->rlim_cur != alimp->rlim_cur) {
443 			vm_offset_t addr;
444 			vm_size_t size;
445 			vm_prot_t prot;
446 
447 			if (limp->rlim_cur > alimp->rlim_cur) {
448 				prot = VM_PROT_ALL;
449 				size = limp->rlim_cur - alimp->rlim_cur;
450 				addr = USRSTACK - limp->rlim_cur;
451 			} else {
452 				prot = VM_PROT_NONE;
453 				size = alimp->rlim_cur - limp->rlim_cur;
454 				addr = USRSTACK - alimp->rlim_cur;
455 			}
456 			addr = trunc_page(addr);
457 			size = round_page(size);
458 			(void) vm_map_protect(&p->p_vmspace->vm_map,
459 					      addr, addr+size, prot, FALSE);
460 		}
461 		break;
462 
463 	case RLIMIT_NOFILE:
464 		if (limp->rlim_cur > maxfilesperproc)
465 			limp->rlim_cur = maxfilesperproc;
466 		if (limp->rlim_max > maxfilesperproc)
467 			limp->rlim_max = maxfilesperproc;
468 		break;
469 
470 	case RLIMIT_NPROC:
471 		if (limp->rlim_cur > maxprocperuid)
472 			limp->rlim_cur = maxprocperuid;
473 		if (limp->rlim_max > maxprocperuid)
474 			limp->rlim_max = maxprocperuid;
475 		break;
476 	}
477 	*alimp = *limp;
478 	return (0);
479 }
480 
481 #ifndef _SYS_SYSPROTO_H_
482 struct __getrlimit_args {
483 	u_int	which;
484 	struct	rlimit *rlp;
485 };
486 #endif
487 /* ARGSUSED */
488 int
489 getrlimit(p, uap)
490 	struct proc *p;
491 	register struct __getrlimit_args *uap;
492 {
493 
494 	if (uap->which >= RLIM_NLIMITS)
495 		return (EINVAL);
496 	return (copyout((caddr_t)&p->p_rlimit[uap->which], (caddr_t)uap->rlp,
497 	    sizeof (struct rlimit)));
498 }
499 
500 /*
501  * Transform the running time and tick information in proc p into user,
502  * system, and interrupt time usage.
503  */
504 void
505 calcru(p, up, sp, ip)
506 	struct proc *p;
507 	struct timeval *up;
508 	struct timeval *sp;
509 	struct timeval *ip;
510 {
511 	/* {user, system, interrupt, total} {ticks, usec}; previous tu: */
512 	u_int64_t ut, uu, st, su, it, iu, tt, tu, ptu;
513 	int s;
514 	struct timeval tv;
515 
516 	/* XXX: why spl-protect ?  worst case is an off-by-one report */
517 	s = splstatclock();
518 	ut = p->p_uticks;
519 	st = p->p_sticks;
520 	it = p->p_iticks;
521 	splx(s);
522 
523 	tt = ut + st + it;
524 	if (tt == 0) {
525 		st = 1;
526 		tt = 1;
527 	}
528 
529 	tu = p->p_runtime;
530 	if (p == curproc) {
531 		/*
532 		 * Adjust for the current time slice.  This is actually fairly
533 		 * important since the error here is on the order of a time
534 		 * quantum, which is much greater than the sampling error.
535 		 */
536 		microuptime(&tv);
537 		if (timevalcmp(&tv, &switchtime, <))
538 			printf("microuptime() went backwards (%ld.%06ld -> %ld.%06ld)\n",
539 			    switchtime.tv_sec, switchtime.tv_usec,
540 			    tv.tv_sec, tv.tv_usec);
541 		else
542 			tu += (tv.tv_usec - switchtime.tv_usec) +
543 			    (tv.tv_sec - switchtime.tv_sec) * (int64_t)1000000;
544 	}
545 	ptu = p->p_uu + p->p_su + p->p_iu;
546 	if (tu < ptu || (int64_t)tu < 0) {
547 		/* XXX no %qd in kernel.  Truncate. */
548 		printf("calcru: negative time of %ld usec for pid %d (%s)\n",
549 		       (long)tu, p->p_pid, p->p_comm);
550 		tu = ptu;
551 	}
552 
553 	/* Subdivide tu. */
554 	uu = (tu * ut) / tt;
555 	su = (tu * st) / tt;
556 	iu = tu - uu - su;
557 
558 	/* Enforce monotonicity. */
559 	if (uu < p->p_uu || su < p->p_su || iu < p->p_iu) {
560 		if (uu < p->p_uu)
561 			uu = p->p_uu;
562 		else if (uu + p->p_su + p->p_iu > tu)
563 			uu = tu - p->p_su - p->p_iu;
564 		if (st == 0)
565 			su = p->p_su;
566 		else {
567 			su = ((tu - uu) * st) / (st + it);
568 			if (su < p->p_su)
569 				su = p->p_su;
570 			else if (uu + su + p->p_iu > tu)
571 				su = tu - uu - p->p_iu;
572 		}
573 		KASSERT(uu + su + p->p_iu <= tu,
574 		    ("calcru: monotonisation botch 1"));
575 		iu = tu - uu - su;
576 		KASSERT(iu >= p->p_iu,
577 		    ("calcru: monotonisation botch 2"));
578 	}
579 	p->p_uu = uu;
580 	p->p_su = su;
581 	p->p_iu = iu;
582 
583 	up->tv_sec = uu / 1000000;
584 	up->tv_usec = uu % 1000000;
585 	sp->tv_sec = su / 1000000;
586 	sp->tv_usec = su % 1000000;
587 	if (ip != NULL) {
588 		ip->tv_sec = iu / 1000000;
589 		ip->tv_usec = iu % 1000000;
590 	}
591 }
592 
593 #ifndef _SYS_SYSPROTO_H_
594 struct getrusage_args {
595 	int	who;
596 	struct	rusage *rusage;
597 };
598 #endif
599 /* ARGSUSED */
600 int
601 getrusage(p, uap)
602 	register struct proc *p;
603 	register struct getrusage_args *uap;
604 {
605 	register struct rusage *rup;
606 
607 	switch (uap->who) {
608 
609 	case RUSAGE_SELF:
610 		rup = &p->p_stats->p_ru;
611 		calcru(p, &rup->ru_utime, &rup->ru_stime, NULL);
612 		break;
613 
614 	case RUSAGE_CHILDREN:
615 		rup = &p->p_stats->p_cru;
616 		break;
617 
618 	default:
619 		return (EINVAL);
620 	}
621 	return (copyout((caddr_t)rup, (caddr_t)uap->rusage,
622 	    sizeof (struct rusage)));
623 }
624 
625 void
626 ruadd(ru, ru2)
627 	register struct rusage *ru, *ru2;
628 {
629 	register long *ip, *ip2;
630 	register int i;
631 
632 	timevaladd(&ru->ru_utime, &ru2->ru_utime);
633 	timevaladd(&ru->ru_stime, &ru2->ru_stime);
634 	if (ru->ru_maxrss < ru2->ru_maxrss)
635 		ru->ru_maxrss = ru2->ru_maxrss;
636 	ip = &ru->ru_first; ip2 = &ru2->ru_first;
637 	for (i = &ru->ru_last - &ru->ru_first; i >= 0; i--)
638 		*ip++ += *ip2++;
639 }
640 
641 /*
642  * Make a copy of the plimit structure.
643  * We share these structures copy-on-write after fork,
644  * and copy when a limit is changed.
645  */
646 struct plimit *
647 limcopy(lim)
648 	struct plimit *lim;
649 {
650 	register struct plimit *copy;
651 
652 	MALLOC(copy, struct plimit *, sizeof(struct plimit),
653 	    M_SUBPROC, M_WAITOK);
654 	bcopy(lim->pl_rlimit, copy->pl_rlimit, sizeof(struct plimit));
655 	copy->p_lflags = 0;
656 	copy->p_refcnt = 1;
657 	return (copy);
658 }
659 
660 /*
661  * Find the uidinfo structure for a uid.  This structure is used to
662  * track the total resource consumption (process count, socket buffer
663  * size, etc.) for the uid and impose limits.
664  */
665 void
666 uihashinit()
667 {
668 
669 	uihashtbl = hashinit(maxproc / 16, M_UIDINFO, &uihash);
670 	mtx_init(&uihashtbl_mtx, "uidinfo hash", MTX_DEF);
671 }
672 
673 /*
674  * lookup a uidinfo struct for the parameter uid.
675  * uihashtbl_mtx must be locked.
676  */
677 static struct uidinfo *
678 uilookup(uid)
679 	uid_t uid;
680 {
681 	struct	uihashhead *uipp;
682 	struct	uidinfo *uip;
683 
684 	mtx_assert(&uihashtbl_mtx, MA_OWNED);
685 	uipp = UIHASH(uid);
686 	LIST_FOREACH(uip, uipp, ui_hash)
687 		if (uip->ui_uid == uid)
688 			break;
689 
690 	return (uip);
691 }
692 
693 /*
694  * Create a uidinfo struct for the parameter uid.
695  * uihashtbl_mtx must be locked.
696  */
697 static struct uidinfo *
698 uicreate(uid)
699 	uid_t uid;
700 {
701 	struct	uidinfo *uip;
702 
703 	mtx_assert(&uihashtbl_mtx, MA_OWNED);
704 	MALLOC(uip, struct uidinfo *, sizeof(*uip), M_UIDINFO, M_WAITOK|M_ZERO);
705 	LIST_INSERT_HEAD(UIHASH(uid), uip, ui_hash);
706 	uip->ui_uid = uid;
707 	mtx_init(&uip->ui_mtx, "uidinfo struct", MTX_DEF);
708 	return (uip);
709 }
710 
711 /*
712  * find or allocate a struct uidinfo for a particular uid
713  * increases refcount on uidinfo struct returned.
714  * uifree() should be called on a struct uidinfo when released.
715  */
716 struct uidinfo *
717 uifind(uid)
718 	uid_t uid;
719 {
720 	struct	uidinfo *uip;
721 
722 	mtx_enter(&uihashtbl_mtx, MTX_DEF);
723 	uip = uilookup(uid);
724 	if (uip == NULL)
725 		uip = uicreate(uid);
726 	uihold(uip);
727 	mtx_exit(&uihashtbl_mtx, MTX_DEF);
728 	return (uip);
729 }
730 
731 /*
732  * place another refcount on a uidinfo struct
733  */
734 void
735 uihold(uip)
736 struct uidinfo *uip;
737 {
738 
739 	mtx_enter(&uip->ui_mtx, MTX_DEF);
740 	uip->ui_ref++;
741 	mtx_exit(&uip->ui_mtx, MTX_DEF);
742 }
743 
744 /*
745  * subtract one from the refcount in the struct uidinfo, if 0 free it
746  * since uidinfo structs have a long lifetime we use a
747  * opportunistic refcounting scheme to avoid locking the lookup hash
748  * for each release.
749  *
750  * if the refcount hits 0 we need to free the structure
751  * which means we need to lock the hash.
752  * optimal case:
753  *   After locking the struct and lowering the refcount, we find
754  *   that we don't need to free, simply unlock and return
755  * suboptimal case:
756  *   refcount lowering results in need to free, bump the count
757  *   back up, loose the lock and aquire the locks in the proper
758  *	 order to try again.
759  */
760 void
761 uifree(uip)
762 	struct	uidinfo *uip;
763 {
764 
765 	/*
766 	 * try for optimal, recucing the refcount doesn't make us free it.
767 	 */
768 	mtx_enter(&uip->ui_mtx, MTX_DEF);
769 	if (--uip->ui_ref != 0) {
770 		mtx_exit(&uip->ui_mtx, MTX_DEF);
771 		return;
772 	}
773 	/*
774 	 * ok, we need to free, before we release the mutex to get
775 	 * the lock ordering correct we need to
776 	 * backout our change to the refcount so that no one else
777 	 * races to free it.
778 	 */
779 	uip->ui_ref++;
780 	mtx_exit(&uip->ui_mtx, MTX_DEF);
781 
782 	/* get the locks in order */
783 	mtx_enter(&uihashtbl_mtx, MTX_DEF);
784 	mtx_enter(&uip->ui_mtx, MTX_DEF);
785 	/*
786 	 * it's possible that someone has referenced it after we dropped the
787 	 * initial lock, if so it's thier responsiblity to free it, but
788 	 * we still must remove one from the count because we backed out
789 	 * our change above.
790 	 */
791 	if (--uip->ui_ref == 0) {
792 		LIST_REMOVE(uip, ui_hash);
793 		mtx_exit(&uihashtbl_mtx, MTX_DEF);
794 		if (uip->ui_sbsize != 0)
795 			/* XXX no %qd in kernel.  Truncate. */
796 			printf("freeing uidinfo: uid = %d, sbsize = %ld\n",
797 			    uip->ui_uid, (long)uip->ui_sbsize);
798 		if (uip->ui_proccnt != 0)
799 			printf("freeing uidinfo: uid = %d, proccnt = %ld\n",
800 			    uip->ui_uid, uip->ui_proccnt);
801 		mtx_destroy(&uip->ui_mtx);
802 		FREE(uip, M_UIDINFO);
803 		return;
804 	}
805 	mtx_exit(&uihashtbl_mtx, MTX_DEF);
806 	mtx_exit(&uip->ui_mtx, MTX_DEF);
807 	return;
808 }
809 
810 /*
811  * Change the count associated with number of processes
812  * a given user is using.  When 'max' is 0, don't enforce a limit
813  */
814 int
815 chgproccnt(uip, diff, max)
816 	struct	uidinfo	*uip;
817 	int	diff;
818 	int	max;
819 {
820 
821 	mtx_enter(&uip->ui_mtx, MTX_DEF);
822 	/* don't allow them to exceed max, but allow subtraction */
823 	if (diff > 0 && uip->ui_proccnt + diff > max && max != 0) {
824 		mtx_exit(&uip->ui_mtx, MTX_DEF);
825 		return (0);
826 	}
827 	uip->ui_proccnt += diff;
828 	if (uip->ui_proccnt < 0)
829 		printf("negative proccnt for uid = %d\n", uip->ui_uid);
830 	mtx_exit(&uip->ui_mtx, MTX_DEF);
831 	return (1);
832 }
833 
834 /*
835  * Change the total socket buffer size a user has used.
836  */
837 int
838 chgsbsize(uip, hiwat, to, max)
839 	struct	uidinfo	*uip;
840 	u_long *hiwat;
841 	u_long	to;
842 	rlim_t	max;
843 {
844 	rlim_t new;
845 	int s;
846 
847 	s = splnet();
848 	mtx_enter(&uip->ui_mtx, MTX_DEF);
849 	new = uip->ui_sbsize + to - *hiwat;
850 	/* don't allow them to exceed max, but allow subtraction */
851 	if (to > *hiwat && new > max) {
852 		splx(s);
853 		mtx_exit(&uip->ui_mtx, MTX_DEF);
854 		return (0);
855 	}
856 	uip->ui_sbsize = new;
857 	*hiwat = to;
858 	if (uip->ui_sbsize < 0)
859 		printf("negative sbsize for uid = %d\n", uip->ui_uid);
860 	splx(s);
861 	mtx_exit(&uip->ui_mtx, MTX_DEF);
862 	return (1);
863 }
864