]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_resource.c
Merge release 1.14 of bsnmp.
[FreeBSD/FreeBSD.git] / sys / kern / kern_resource.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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.5 (Berkeley) 1/21/94
37  */
38
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/sysproto.h>
45 #include <sys/file.h>
46 #include <sys/kernel.h>
47 #include <sys/lock.h>
48 #include <sys/malloc.h>
49 #include <sys/mutex.h>
50 #include <sys/priv.h>
51 #include <sys/proc.h>
52 #include <sys/refcount.h>
53 #include <sys/racct.h>
54 #include <sys/resourcevar.h>
55 #include <sys/rwlock.h>
56 #include <sys/sched.h>
57 #include <sys/sx.h>
58 #include <sys/syscallsubr.h>
59 #include <sys/sysctl.h>
60 #include <sys/sysent.h>
61 #include <sys/time.h>
62 #include <sys/umtx.h>
63
64 #include <vm/vm.h>
65 #include <vm/vm_param.h>
66 #include <vm/pmap.h>
67 #include <vm/vm_map.h>
68
69 static MALLOC_DEFINE(M_PLIMIT, "plimit", "plimit structures");
70 static MALLOC_DEFINE(M_UIDINFO, "uidinfo", "uidinfo structures");
71 #define UIHASH(uid)     (&uihashtbl[(uid) & uihash])
72 static struct rwlock uihashtbl_lock;
73 static LIST_HEAD(uihashhead, uidinfo) *uihashtbl;
74 static u_long uihash;           /* size of hash table - 1 */
75
76 static void     calcru1(struct proc *p, struct rusage_ext *ruxp,
77                     struct timeval *up, struct timeval *sp);
78 static int      donice(struct thread *td, struct proc *chgp, int n);
79 static struct uidinfo *uilookup(uid_t uid);
80 static void     ruxagg_ext_locked(struct rusage_ext *rux, struct thread *td);
81
82 /*
83  * Resource controls and accounting.
84  */
85 #ifndef _SYS_SYSPROTO_H_
86 struct getpriority_args {
87         int     which;
88         int     who;
89 };
90 #endif
91 int
92 sys_getpriority(struct thread *td, struct getpriority_args *uap)
93 {
94
95         return (kern_getpriority(td, uap->which, uap->who));
96 }
97
98 int
99 kern_getpriority(struct thread *td, int which, int who)
100 {
101         struct proc *p;
102         struct pgrp *pg;
103         int error, low;
104
105         error = 0;
106         low = PRIO_MAX + 1;
107         switch (which) {
108
109         case PRIO_PROCESS:
110                 if (who == 0)
111                         low = td->td_proc->p_nice;
112                 else {
113                         p = pfind(who);
114                         if (p == NULL)
115                                 break;
116                         if (p_cansee(td, p) == 0)
117                                 low = p->p_nice;
118                         PROC_UNLOCK(p);
119                 }
120                 break;
121
122         case PRIO_PGRP:
123                 sx_slock(&proctree_lock);
124                 if (who == 0) {
125                         pg = td->td_proc->p_pgrp;
126                         PGRP_LOCK(pg);
127                 } else {
128                         pg = pgfind(who);
129                         if (pg == NULL) {
130                                 sx_sunlock(&proctree_lock);
131                                 break;
132                         }
133                 }
134                 sx_sunlock(&proctree_lock);
135                 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
136                         PROC_LOCK(p);
137                         if (p->p_state == PRS_NORMAL &&
138                             p_cansee(td, p) == 0) {
139                                 if (p->p_nice < low)
140                                         low = p->p_nice;
141                         }
142                         PROC_UNLOCK(p);
143                 }
144                 PGRP_UNLOCK(pg);
145                 break;
146
147         case PRIO_USER:
148                 if (who == 0)
149                         who = td->td_ucred->cr_uid;
150                 sx_slock(&allproc_lock);
151                 FOREACH_PROC_IN_SYSTEM(p) {
152                         PROC_LOCK(p);
153                         if (p->p_state == PRS_NORMAL &&
154                             p_cansee(td, p) == 0 &&
155                             p->p_ucred->cr_uid == who) {
156                                 if (p->p_nice < low)
157                                         low = p->p_nice;
158                         }
159                         PROC_UNLOCK(p);
160                 }
161                 sx_sunlock(&allproc_lock);
162                 break;
163
164         default:
165                 error = EINVAL;
166                 break;
167         }
168         if (low == PRIO_MAX + 1 && error == 0)
169                 error = ESRCH;
170         td->td_retval[0] = low;
171         return (error);
172 }
173
174 #ifndef _SYS_SYSPROTO_H_
175 struct setpriority_args {
176         int     which;
177         int     who;
178         int     prio;
179 };
180 #endif
181 int
182 sys_setpriority(struct thread *td, struct setpriority_args *uap)
183 {
184
185         return (kern_setpriority(td, uap->which, uap->who, uap->prio));
186 }
187
188 int
189 kern_setpriority(struct thread *td, int which, int who, int prio)
190 {
191         struct proc *curp, *p;
192         struct pgrp *pg;
193         int found = 0, error = 0;
194
195         curp = td->td_proc;
196         switch (which) {
197         case PRIO_PROCESS:
198                 if (who == 0) {
199                         PROC_LOCK(curp);
200                         error = donice(td, curp, prio);
201                         PROC_UNLOCK(curp);
202                 } else {
203                         p = pfind(who);
204                         if (p == NULL)
205                                 break;
206                         error = p_cansee(td, p);
207                         if (error == 0)
208                                 error = donice(td, p, prio);
209                         PROC_UNLOCK(p);
210                 }
211                 found++;
212                 break;
213
214         case PRIO_PGRP:
215                 sx_slock(&proctree_lock);
216                 if (who == 0) {
217                         pg = curp->p_pgrp;
218                         PGRP_LOCK(pg);
219                 } else {
220                         pg = pgfind(who);
221                         if (pg == NULL) {
222                                 sx_sunlock(&proctree_lock);
223                                 break;
224                         }
225                 }
226                 sx_sunlock(&proctree_lock);
227                 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
228                         PROC_LOCK(p);
229                         if (p->p_state == PRS_NORMAL &&
230                             p_cansee(td, p) == 0) {
231                                 error = donice(td, p, prio);
232                                 found++;
233                         }
234                         PROC_UNLOCK(p);
235                 }
236                 PGRP_UNLOCK(pg);
237                 break;
238
239         case PRIO_USER:
240                 if (who == 0)
241                         who = td->td_ucred->cr_uid;
242                 sx_slock(&allproc_lock);
243                 FOREACH_PROC_IN_SYSTEM(p) {
244                         PROC_LOCK(p);
245                         if (p->p_state == PRS_NORMAL &&
246                             p->p_ucred->cr_uid == who &&
247                             p_cansee(td, p) == 0) {
248                                 error = donice(td, p, prio);
249                                 found++;
250                         }
251                         PROC_UNLOCK(p);
252                 }
253                 sx_sunlock(&allproc_lock);
254                 break;
255
256         default:
257                 error = EINVAL;
258                 break;
259         }
260         if (found == 0 && error == 0)
261                 error = ESRCH;
262         return (error);
263 }
264
265 /*
266  * Set "nice" for a (whole) process.
267  */
268 static int
269 donice(struct thread *td, struct proc *p, int n)
270 {
271         int error;
272
273         PROC_LOCK_ASSERT(p, MA_OWNED);
274         if ((error = p_cansched(td, p)))
275                 return (error);
276         if (n > PRIO_MAX)
277                 n = PRIO_MAX;
278         if (n < PRIO_MIN)
279                 n = PRIO_MIN;
280         if (n < p->p_nice && priv_check(td, PRIV_SCHED_SETPRIORITY) != 0)
281                 return (EACCES);
282         sched_nice(p, n);
283         return (0);
284 }
285
286 static int unprivileged_idprio;
287 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_idprio, CTLFLAG_RW,
288     &unprivileged_idprio, 0, "Allow non-root users to set an idle priority");
289
290 /*
291  * Set realtime priority for LWP.
292  */
293 #ifndef _SYS_SYSPROTO_H_
294 struct rtprio_thread_args {
295         int             function;
296         lwpid_t         lwpid;
297         struct rtprio   *rtp;
298 };
299 #endif
300 int
301 sys_rtprio_thread(struct thread *td, struct rtprio_thread_args *uap)
302 {
303         struct proc *p;
304         struct rtprio rtp;
305         struct thread *td1;
306         int cierror, error;
307
308         /* Perform copyin before acquiring locks if needed. */
309         if (uap->function == RTP_SET)
310                 cierror = copyin(uap->rtp, &rtp, sizeof(struct rtprio));
311         else
312                 cierror = 0;
313
314         if (uap->lwpid == 0 || uap->lwpid == td->td_tid) {
315                 p = td->td_proc;
316                 td1 = td;
317                 PROC_LOCK(p);
318         } else {
319                 /* Only look up thread in current process */
320                 td1 = tdfind(uap->lwpid, curproc->p_pid);
321                 if (td1 == NULL)
322                         return (ESRCH);
323                 p = td1->td_proc;
324         }
325
326         switch (uap->function) {
327         case RTP_LOOKUP:
328                 if ((error = p_cansee(td, p)))
329                         break;
330                 pri_to_rtp(td1, &rtp);
331                 PROC_UNLOCK(p);
332                 return (copyout(&rtp, uap->rtp, sizeof(struct rtprio)));
333         case RTP_SET:
334                 if ((error = p_cansched(td, p)) || (error = cierror))
335                         break;
336
337                 /* Disallow setting rtprio in most cases if not superuser. */
338
339                 /*
340                  * Realtime priority has to be restricted for reasons which
341                  * should be obvious.  However, for idleprio processes, there is
342                  * a potential for system deadlock if an idleprio process gains
343                  * a lock on a resource that other processes need (and the
344                  * idleprio process can't run due to a CPU-bound normal
345                  * process).  Fix me!  XXX
346                  *
347                  * This problem is not only related to idleprio process.
348                  * A user level program can obtain a file lock and hold it
349                  * indefinitely.  Additionally, without idleprio processes it is
350                  * still conceivable that a program with low priority will never
351                  * get to run.  In short, allowing this feature might make it
352                  * easier to lock a resource indefinitely, but it is not the
353                  * only thing that makes it possible.
354                  */
355                 if (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_REALTIME ||
356                     (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_IDLE &&
357                     unprivileged_idprio == 0)) {
358                         error = priv_check(td, PRIV_SCHED_RTPRIO);
359                         if (error)
360                                 break;
361                 }
362                 error = rtp_to_pri(&rtp, td1);
363                 break;
364         default:
365                 error = EINVAL;
366                 break;
367         }
368         PROC_UNLOCK(p);
369         return (error);
370 }
371
372 /*
373  * Set realtime priority.
374  */
375 #ifndef _SYS_SYSPROTO_H_
376 struct rtprio_args {
377         int             function;
378         pid_t           pid;
379         struct rtprio   *rtp;
380 };
381 #endif
382 int
383 sys_rtprio(struct thread *td, struct rtprio_args *uap)
384 {
385         struct proc *p;
386         struct thread *tdp;
387         struct rtprio rtp;
388         int cierror, error;
389
390         /* Perform copyin before acquiring locks if needed. */
391         if (uap->function == RTP_SET)
392                 cierror = copyin(uap->rtp, &rtp, sizeof(struct rtprio));
393         else
394                 cierror = 0;
395
396         if (uap->pid == 0) {
397                 p = td->td_proc;
398                 PROC_LOCK(p);
399         } else {
400                 p = pfind(uap->pid);
401                 if (p == NULL)
402                         return (ESRCH);
403         }
404
405         switch (uap->function) {
406         case RTP_LOOKUP:
407                 if ((error = p_cansee(td, p)))
408                         break;
409                 /*
410                  * Return OUR priority if no pid specified,
411                  * or if one is, report the highest priority
412                  * in the process.  There isn't much more you can do as
413                  * there is only room to return a single priority.
414                  * Note: specifying our own pid is not the same
415                  * as leaving it zero.
416                  */
417                 if (uap->pid == 0) {
418                         pri_to_rtp(td, &rtp);
419                 } else {
420                         struct rtprio rtp2;
421
422                         rtp.type = RTP_PRIO_IDLE;
423                         rtp.prio = RTP_PRIO_MAX;
424                         FOREACH_THREAD_IN_PROC(p, tdp) {
425                                 pri_to_rtp(tdp, &rtp2);
426                                 if (rtp2.type <  rtp.type ||
427                                     (rtp2.type == rtp.type &&
428                                     rtp2.prio < rtp.prio)) {
429                                         rtp.type = rtp2.type;
430                                         rtp.prio = rtp2.prio;
431                                 }
432                         }
433                 }
434                 PROC_UNLOCK(p);
435                 return (copyout(&rtp, uap->rtp, sizeof(struct rtprio)));
436         case RTP_SET:
437                 if ((error = p_cansched(td, p)) || (error = cierror))
438                         break;
439
440                 /*
441                  * Disallow setting rtprio in most cases if not superuser.
442                  * See the comment in sys_rtprio_thread about idprio
443                  * threads holding a lock.
444                  */
445                 if (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_REALTIME ||
446                     (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_IDLE &&
447                     !unprivileged_idprio)) {
448                         error = priv_check(td, PRIV_SCHED_RTPRIO);
449                         if (error)
450                                 break;
451                 }
452
453                 /*
454                  * If we are setting our own priority, set just our
455                  * thread but if we are doing another process,
456                  * do all the threads on that process. If we
457                  * specify our own pid we do the latter.
458                  */
459                 if (uap->pid == 0) {
460                         error = rtp_to_pri(&rtp, td);
461                 } else {
462                         FOREACH_THREAD_IN_PROC(p, td) {
463                                 if ((error = rtp_to_pri(&rtp, td)) != 0)
464                                         break;
465                         }
466                 }
467                 break;
468         default:
469                 error = EINVAL;
470                 break;
471         }
472         PROC_UNLOCK(p);
473         return (error);
474 }
475
476 int
477 rtp_to_pri(struct rtprio *rtp, struct thread *td)
478 {
479         u_char  newpri, oldclass, oldpri;
480
481         switch (RTP_PRIO_BASE(rtp->type)) {
482         case RTP_PRIO_REALTIME:
483                 if (rtp->prio > RTP_PRIO_MAX)
484                         return (EINVAL);
485                 newpri = PRI_MIN_REALTIME + rtp->prio;
486                 break;
487         case RTP_PRIO_NORMAL:
488                 if (rtp->prio > (PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE))
489                         return (EINVAL);
490                 newpri = PRI_MIN_TIMESHARE + rtp->prio;
491                 break;
492         case RTP_PRIO_IDLE:
493                 if (rtp->prio > RTP_PRIO_MAX)
494                         return (EINVAL);
495                 newpri = PRI_MIN_IDLE + rtp->prio;
496                 break;
497         default:
498                 return (EINVAL);
499         }
500
501         thread_lock(td);
502         oldclass = td->td_pri_class;
503         sched_class(td, rtp->type);     /* XXX fix */
504         oldpri = td->td_user_pri;
505         sched_user_prio(td, newpri);
506         if (td->td_user_pri != oldpri && (oldclass != RTP_PRIO_NORMAL ||
507             td->td_pri_class != RTP_PRIO_NORMAL))
508                 sched_prio(td, td->td_user_pri);
509         if (TD_ON_UPILOCK(td) && oldpri != newpri) {
510                 critical_enter();
511                 thread_unlock(td);
512                 umtx_pi_adjust(td, oldpri);
513                 critical_exit();
514         } else
515                 thread_unlock(td);
516         return (0);
517 }
518
519 void
520 pri_to_rtp(struct thread *td, struct rtprio *rtp)
521 {
522
523         thread_lock(td);
524         switch (PRI_BASE(td->td_pri_class)) {
525         case PRI_REALTIME:
526                 rtp->prio = td->td_base_user_pri - PRI_MIN_REALTIME;
527                 break;
528         case PRI_TIMESHARE:
529                 rtp->prio = td->td_base_user_pri - PRI_MIN_TIMESHARE;
530                 break;
531         case PRI_IDLE:
532                 rtp->prio = td->td_base_user_pri - PRI_MIN_IDLE;
533                 break;
534         default:
535                 break;
536         }
537         rtp->type = td->td_pri_class;
538         thread_unlock(td);
539 }
540
541 #if defined(COMPAT_43)
542 #ifndef _SYS_SYSPROTO_H_
543 struct osetrlimit_args {
544         u_int   which;
545         struct  orlimit *rlp;
546 };
547 #endif
548 int
549 osetrlimit(struct thread *td, struct osetrlimit_args *uap)
550 {
551         struct orlimit olim;
552         struct rlimit lim;
553         int error;
554
555         if ((error = copyin(uap->rlp, &olim, sizeof(struct orlimit))))
556                 return (error);
557         lim.rlim_cur = olim.rlim_cur;
558         lim.rlim_max = olim.rlim_max;
559         error = kern_setrlimit(td, uap->which, &lim);
560         return (error);
561 }
562
563 #ifndef _SYS_SYSPROTO_H_
564 struct ogetrlimit_args {
565         u_int   which;
566         struct  orlimit *rlp;
567 };
568 #endif
569 int
570 ogetrlimit(struct thread *td, struct ogetrlimit_args *uap)
571 {
572         struct orlimit olim;
573         struct rlimit rl;
574         int error;
575
576         if (uap->which >= RLIM_NLIMITS)
577                 return (EINVAL);
578         lim_rlimit(td, uap->which, &rl);
579
580         /*
581          * XXX would be more correct to convert only RLIM_INFINITY to the
582          * old RLIM_INFINITY and fail with EOVERFLOW for other larger
583          * values.  Most 64->32 and 32->16 conversions, including not
584          * unimportant ones of uids are even more broken than what we
585          * do here (they blindly truncate).  We don't do this correctly
586          * here since we have little experience with EOVERFLOW yet.
587          * Elsewhere, getuid() can't fail...
588          */
589         olim.rlim_cur = rl.rlim_cur > 0x7fffffff ? 0x7fffffff : rl.rlim_cur;
590         olim.rlim_max = rl.rlim_max > 0x7fffffff ? 0x7fffffff : rl.rlim_max;
591         error = copyout(&olim, uap->rlp, sizeof(olim));
592         return (error);
593 }
594 #endif /* COMPAT_43 */
595
596 #ifndef _SYS_SYSPROTO_H_
597 struct __setrlimit_args {
598         u_int   which;
599         struct  rlimit *rlp;
600 };
601 #endif
602 int
603 sys_setrlimit(struct thread *td, struct __setrlimit_args *uap)
604 {
605         struct rlimit alim;
606         int error;
607
608         if ((error = copyin(uap->rlp, &alim, sizeof(struct rlimit))))
609                 return (error);
610         error = kern_setrlimit(td, uap->which, &alim);
611         return (error);
612 }
613
614 static void
615 lim_cb(void *arg)
616 {
617         struct rlimit rlim;
618         struct thread *td;
619         struct proc *p;
620
621         p = arg;
622         PROC_LOCK_ASSERT(p, MA_OWNED);
623         /*
624          * Check if the process exceeds its cpu resource allocation.  If
625          * it reaches the max, arrange to kill the process in ast().
626          */
627         if (p->p_cpulimit == RLIM_INFINITY)
628                 return;
629         PROC_STATLOCK(p);
630         FOREACH_THREAD_IN_PROC(p, td) {
631                 ruxagg(p, td);
632         }
633         PROC_STATUNLOCK(p);
634         if (p->p_rux.rux_runtime > p->p_cpulimit * cpu_tickrate()) {
635                 lim_rlimit_proc(p, RLIMIT_CPU, &rlim);
636                 if (p->p_rux.rux_runtime >= rlim.rlim_max * cpu_tickrate()) {
637                         killproc(p, "exceeded maximum CPU limit");
638                 } else {
639                         if (p->p_cpulimit < rlim.rlim_max)
640                                 p->p_cpulimit += 5;
641                         kern_psignal(p, SIGXCPU);
642                 }
643         }
644         if ((p->p_flag & P_WEXIT) == 0)
645                 callout_reset_sbt(&p->p_limco, SBT_1S, 0,
646                     lim_cb, p, C_PREL(1));
647 }
648
649 int
650 kern_setrlimit(struct thread *td, u_int which, struct rlimit *limp)
651 {
652
653         return (kern_proc_setrlimit(td, td->td_proc, which, limp));
654 }
655
656 int
657 kern_proc_setrlimit(struct thread *td, struct proc *p, u_int which,
658     struct rlimit *limp)
659 {
660         struct plimit *newlim, *oldlim;
661         struct rlimit *alimp;
662         struct rlimit oldssiz;
663         int error;
664
665         if (which >= RLIM_NLIMITS)
666                 return (EINVAL);
667
668         /*
669          * Preserve historical bugs by treating negative limits as unsigned.
670          */
671         if (limp->rlim_cur < 0)
672                 limp->rlim_cur = RLIM_INFINITY;
673         if (limp->rlim_max < 0)
674                 limp->rlim_max = RLIM_INFINITY;
675
676         oldssiz.rlim_cur = 0;
677         newlim = lim_alloc();
678         PROC_LOCK(p);
679         oldlim = p->p_limit;
680         alimp = &oldlim->pl_rlimit[which];
681         if (limp->rlim_cur > alimp->rlim_max ||
682             limp->rlim_max > alimp->rlim_max)
683                 if ((error = priv_check(td, PRIV_PROC_SETRLIMIT))) {
684                         PROC_UNLOCK(p);
685                         lim_free(newlim);
686                         return (error);
687                 }
688         if (limp->rlim_cur > limp->rlim_max)
689                 limp->rlim_cur = limp->rlim_max;
690         lim_copy(newlim, oldlim);
691         alimp = &newlim->pl_rlimit[which];
692
693         switch (which) {
694
695         case RLIMIT_CPU:
696                 if (limp->rlim_cur != RLIM_INFINITY &&
697                     p->p_cpulimit == RLIM_INFINITY)
698                         callout_reset_sbt(&p->p_limco, SBT_1S, 0,
699                             lim_cb, p, C_PREL(1));
700                 p->p_cpulimit = limp->rlim_cur;
701                 break;
702         case RLIMIT_DATA:
703                 if (limp->rlim_cur > maxdsiz)
704                         limp->rlim_cur = maxdsiz;
705                 if (limp->rlim_max > maxdsiz)
706                         limp->rlim_max = maxdsiz;
707                 break;
708
709         case RLIMIT_STACK:
710                 if (limp->rlim_cur > maxssiz)
711                         limp->rlim_cur = maxssiz;
712                 if (limp->rlim_max > maxssiz)
713                         limp->rlim_max = maxssiz;
714                 oldssiz = *alimp;
715                 if (p->p_sysent->sv_fixlimit != NULL)
716                         p->p_sysent->sv_fixlimit(&oldssiz,
717                             RLIMIT_STACK);
718                 break;
719
720         case RLIMIT_NOFILE:
721                 if (limp->rlim_cur > maxfilesperproc)
722                         limp->rlim_cur = maxfilesperproc;
723                 if (limp->rlim_max > maxfilesperproc)
724                         limp->rlim_max = maxfilesperproc;
725                 break;
726
727         case RLIMIT_NPROC:
728                 if (limp->rlim_cur > maxprocperuid)
729                         limp->rlim_cur = maxprocperuid;
730                 if (limp->rlim_max > maxprocperuid)
731                         limp->rlim_max = maxprocperuid;
732                 if (limp->rlim_cur < 1)
733                         limp->rlim_cur = 1;
734                 if (limp->rlim_max < 1)
735                         limp->rlim_max = 1;
736                 break;
737         }
738         if (p->p_sysent->sv_fixlimit != NULL)
739                 p->p_sysent->sv_fixlimit(limp, which);
740         *alimp = *limp;
741         p->p_limit = newlim;
742         PROC_UPDATE_COW(p);
743         PROC_UNLOCK(p);
744         lim_free(oldlim);
745
746         if (which == RLIMIT_STACK &&
747             /*
748              * Skip calls from exec_new_vmspace(), done when stack is
749              * not mapped yet.
750              */
751             (td != curthread || (p->p_flag & P_INEXEC) == 0)) {
752                 /*
753                  * Stack is allocated to the max at exec time with only
754                  * "rlim_cur" bytes accessible.  If stack limit is going
755                  * up make more accessible, if going down make inaccessible.
756                  */
757                 if (limp->rlim_cur != oldssiz.rlim_cur) {
758                         vm_offset_t addr;
759                         vm_size_t size;
760                         vm_prot_t prot;
761
762                         if (limp->rlim_cur > oldssiz.rlim_cur) {
763                                 prot = p->p_sysent->sv_stackprot;
764                                 size = limp->rlim_cur - oldssiz.rlim_cur;
765                                 addr = p->p_sysent->sv_usrstack -
766                                     limp->rlim_cur;
767                         } else {
768                                 prot = VM_PROT_NONE;
769                                 size = oldssiz.rlim_cur - limp->rlim_cur;
770                                 addr = p->p_sysent->sv_usrstack -
771                                     oldssiz.rlim_cur;
772                         }
773                         addr = trunc_page(addr);
774                         size = round_page(size);
775                         (void)vm_map_protect(&p->p_vmspace->vm_map,
776                             addr, addr + size, prot, FALSE);
777                 }
778         }
779
780         return (0);
781 }
782
783 #ifndef _SYS_SYSPROTO_H_
784 struct __getrlimit_args {
785         u_int   which;
786         struct  rlimit *rlp;
787 };
788 #endif
789 /* ARGSUSED */
790 int
791 sys_getrlimit(struct thread *td, struct __getrlimit_args *uap)
792 {
793         struct rlimit rlim;
794         int error;
795
796         if (uap->which >= RLIM_NLIMITS)
797                 return (EINVAL);
798         lim_rlimit(td, uap->which, &rlim);
799         error = copyout(&rlim, uap->rlp, sizeof(struct rlimit));
800         return (error);
801 }
802
803 /*
804  * Transform the running time and tick information for children of proc p
805  * into user and system time usage.
806  */
807 void
808 calccru(struct proc *p, struct timeval *up, struct timeval *sp)
809 {
810
811         PROC_LOCK_ASSERT(p, MA_OWNED);
812         calcru1(p, &p->p_crux, up, sp);
813 }
814
815 /*
816  * Transform the running time and tick information in proc p into user
817  * and system time usage.  If appropriate, include the current time slice
818  * on this CPU.
819  */
820 void
821 calcru(struct proc *p, struct timeval *up, struct timeval *sp)
822 {
823         struct thread *td;
824         uint64_t runtime, u;
825
826         PROC_LOCK_ASSERT(p, MA_OWNED);
827         PROC_STATLOCK_ASSERT(p, MA_OWNED);
828         /*
829          * If we are getting stats for the current process, then add in the
830          * stats that this thread has accumulated in its current time slice.
831          * We reset the thread and CPU state as if we had performed a context
832          * switch right here.
833          */
834         td = curthread;
835         if (td->td_proc == p) {
836                 u = cpu_ticks();
837                 runtime = u - PCPU_GET(switchtime);
838                 td->td_runtime += runtime;
839                 td->td_incruntime += runtime;
840                 PCPU_SET(switchtime, u);
841         }
842         /* Make sure the per-thread stats are current. */
843         FOREACH_THREAD_IN_PROC(p, td) {
844                 if (td->td_incruntime == 0)
845                         continue;
846                 ruxagg(p, td);
847         }
848         calcru1(p, &p->p_rux, up, sp);
849 }
850
851 /* Collect resource usage for a single thread. */
852 void
853 rufetchtd(struct thread *td, struct rusage *ru)
854 {
855         struct proc *p;
856         uint64_t runtime, u;
857
858         p = td->td_proc;
859         PROC_STATLOCK_ASSERT(p, MA_OWNED);
860         THREAD_LOCK_ASSERT(td, MA_OWNED);
861         /*
862          * If we are getting stats for the current thread, then add in the
863          * stats that this thread has accumulated in its current time slice.
864          * We reset the thread and CPU state as if we had performed a context
865          * switch right here.
866          */
867         if (td == curthread) {
868                 u = cpu_ticks();
869                 runtime = u - PCPU_GET(switchtime);
870                 td->td_runtime += runtime;
871                 td->td_incruntime += runtime;
872                 PCPU_SET(switchtime, u);
873         }
874         ruxagg_locked(p, td);
875         *ru = td->td_ru;
876         calcru1(p, &td->td_rux, &ru->ru_utime, &ru->ru_stime);
877 }
878
879 /* XXX: the MI version is too slow to use: */
880 #ifndef __HAVE_INLINE_FLSLL
881 #define flsll(x)        (fls((x) >> 32) != 0 ? fls((x) >> 32) + 32 : fls(x))
882 #endif
883
884 static uint64_t
885 mul64_by_fraction(uint64_t a, uint64_t b, uint64_t c)
886 {
887         uint64_t acc, bh, bl;
888         int i, s, sa, sb;
889
890         /*
891          * Calculate (a * b) / c accurately enough without overflowing.  c
892          * must be nonzero, and its top bit must be 0.  a or b must be
893          * <= c, and the implementation is tuned for b <= c.
894          *
895          * The comments about times are for use in calcru1() with units of
896          * microseconds for 'a' and stathz ticks at 128 Hz for b and c.
897          *
898          * Let n be the number of top zero bits in c.  Each iteration
899          * either returns, or reduces b by right shifting it by at least n.
900          * The number of iterations is at most 1 + 64 / n, and the error is
901          * at most the number of iterations.
902          *
903          * It is very unusual to need even 2 iterations.  Previous
904          * implementations overflowed essentially by returning early in the
905          * first iteration, with n = 38 giving overflow at 105+ hours and
906          * n = 32 giving overlow at at 388+ days despite a more careful
907          * calculation.  388 days is a reasonable uptime, and the calculation
908          * needs to work for the uptime times the number of CPUs since 'a'
909          * is per-process.
910          */
911         if (a >= (uint64_t)1 << 63)
912                 return (0);             /* Unsupported arg -- can't happen. */
913         acc = 0;
914         for (i = 0; i < 128; i++) {
915                 sa = flsll(a);
916                 sb = flsll(b);
917                 if (sa + sb <= 64)
918                         /* Up to 105 hours on first iteration. */
919                         return (acc + (a * b) / c);
920                 if (a >= c) {
921                         /*
922                          * This reduction is based on a = q * c + r, with the
923                          * remainder r < c.  'a' may be large to start, and
924                          * moving bits from b into 'a' at the end of the loop
925                          * sets the top bit of 'a', so the reduction makes
926                          * significant progress.
927                          */
928                         acc += (a / c) * b;
929                         a %= c;
930                         sa = flsll(a);
931                         if (sa + sb <= 64)
932                                 /* Up to 388 days on first iteration. */
933                                 return (acc + (a * b) / c);
934                 }
935
936                 /*
937                  * This step writes a * b as a * ((bh << s) + bl) =
938                  * a * (bh << s) + a * bl = (a << s) * bh + a * bl.  The 2
939                  * additive terms are handled separately.  Splitting in
940                  * this way is linear except for rounding errors.
941                  *
942                  * s = 64 - sa is the maximum such that a << s fits in 64
943                  * bits.  Since a < c and c has at least 1 zero top bit,
944                  * sa < 64 and s > 0.  Thus this step makes progress by
945                  * reducing b (it increases 'a', but taking remainders on
946                  * the next iteration completes the reduction).
947                  *
948                  * Finally, the choice for s is just what is needed to keep
949                  * a * bl from overflowing, so we don't need complications
950                  * like a recursive call mul64_by_fraction(a, bl, c) to
951                  * handle the second additive term.
952                  */
953                 s = 64 - sa;
954                 bh = b >> s;
955                 bl = b - (bh << s);
956                 acc += (a * bl) / c;
957                 a <<= s;
958                 b = bh;
959         }
960         return (0);             /* Algorithm failure -- can't happen. */
961 }
962
963 static void
964 calcru1(struct proc *p, struct rusage_ext *ruxp, struct timeval *up,
965     struct timeval *sp)
966 {
967         /* {user, system, interrupt, total} {ticks, usec}: */
968         uint64_t ut, uu, st, su, it, tt, tu;
969
970         ut = ruxp->rux_uticks;
971         st = ruxp->rux_sticks;
972         it = ruxp->rux_iticks;
973         tt = ut + st + it;
974         if (tt == 0) {
975                 /* Avoid divide by zero */
976                 st = 1;
977                 tt = 1;
978         }
979         tu = cputick2usec(ruxp->rux_runtime);
980         if ((int64_t)tu < 0) {
981                 /* XXX: this should be an assert /phk */
982                 printf("calcru: negative runtime of %jd usec for pid %d (%s)\n",
983                     (intmax_t)tu, p->p_pid, p->p_comm);
984                 tu = ruxp->rux_tu;
985         }
986
987         /* Subdivide tu.  Avoid overflow in the multiplications. */
988         if (__predict_true(tu <= ((uint64_t)1 << 38) && tt <= (1 << 26))) {
989                 /* Up to 76 hours when stathz is 128. */
990                 uu = (tu * ut) / tt;
991                 su = (tu * st) / tt;
992         } else {
993                 uu = mul64_by_fraction(tu, ut, tt);
994                 su = mul64_by_fraction(tu, st, tt);
995         }
996
997         if (tu >= ruxp->rux_tu) {
998                 /*
999                  * The normal case, time increased.
1000                  * Enforce monotonicity of bucketed numbers.
1001                  */
1002                 if (uu < ruxp->rux_uu)
1003                         uu = ruxp->rux_uu;
1004                 if (su < ruxp->rux_su)
1005                         su = ruxp->rux_su;
1006         } else if (tu + 3 > ruxp->rux_tu || 101 * tu > 100 * ruxp->rux_tu) {
1007                 /*
1008                  * When we calibrate the cputicker, it is not uncommon to
1009                  * see the presumably fixed frequency increase slightly over
1010                  * time as a result of thermal stabilization and NTP
1011                  * discipline (of the reference clock).  We therefore ignore
1012                  * a bit of backwards slop because we  expect to catch up
1013                  * shortly.  We use a 3 microsecond limit to catch low
1014                  * counts and a 1% limit for high counts.
1015                  */
1016                 uu = ruxp->rux_uu;
1017                 su = ruxp->rux_su;
1018                 tu = ruxp->rux_tu;
1019         } else { /* tu < ruxp->rux_tu */
1020                 /*
1021                  * What happened here was likely that a laptop, which ran at
1022                  * a reduced clock frequency at boot, kicked into high gear.
1023                  * The wisdom of spamming this message in that case is
1024                  * dubious, but it might also be indicative of something
1025                  * serious, so lets keep it and hope laptops can be made
1026                  * more truthful about their CPU speed via ACPI.
1027                  */
1028                 printf("calcru: runtime went backwards from %ju usec "
1029                     "to %ju usec for pid %d (%s)\n",
1030                     (uintmax_t)ruxp->rux_tu, (uintmax_t)tu,
1031                     p->p_pid, p->p_comm);
1032         }
1033
1034         ruxp->rux_uu = uu;
1035         ruxp->rux_su = su;
1036         ruxp->rux_tu = tu;
1037
1038         up->tv_sec = uu / 1000000;
1039         up->tv_usec = uu % 1000000;
1040         sp->tv_sec = su / 1000000;
1041         sp->tv_usec = su % 1000000;
1042 }
1043
1044 #ifndef _SYS_SYSPROTO_H_
1045 struct getrusage_args {
1046         int     who;
1047         struct  rusage *rusage;
1048 };
1049 #endif
1050 int
1051 sys_getrusage(struct thread *td, struct getrusage_args *uap)
1052 {
1053         struct rusage ru;
1054         int error;
1055
1056         error = kern_getrusage(td, uap->who, &ru);
1057         if (error == 0)
1058                 error = copyout(&ru, uap->rusage, sizeof(struct rusage));
1059         return (error);
1060 }
1061
1062 int
1063 kern_getrusage(struct thread *td, int who, struct rusage *rup)
1064 {
1065         struct proc *p;
1066         int error;
1067
1068         error = 0;
1069         p = td->td_proc;
1070         PROC_LOCK(p);
1071         switch (who) {
1072         case RUSAGE_SELF:
1073                 rufetchcalc(p, rup, &rup->ru_utime,
1074                     &rup->ru_stime);
1075                 break;
1076
1077         case RUSAGE_CHILDREN:
1078                 *rup = p->p_stats->p_cru;
1079                 calccru(p, &rup->ru_utime, &rup->ru_stime);
1080                 break;
1081
1082         case RUSAGE_THREAD:
1083                 PROC_STATLOCK(p);
1084                 thread_lock(td);
1085                 rufetchtd(td, rup);
1086                 thread_unlock(td);
1087                 PROC_STATUNLOCK(p);
1088                 break;
1089
1090         default:
1091                 error = EINVAL;
1092         }
1093         PROC_UNLOCK(p);
1094         return (error);
1095 }
1096
1097 void
1098 rucollect(struct rusage *ru, struct rusage *ru2)
1099 {
1100         long *ip, *ip2;
1101         int i;
1102
1103         if (ru->ru_maxrss < ru2->ru_maxrss)
1104                 ru->ru_maxrss = ru2->ru_maxrss;
1105         ip = &ru->ru_first;
1106         ip2 = &ru2->ru_first;
1107         for (i = &ru->ru_last - &ru->ru_first; i >= 0; i--)
1108                 *ip++ += *ip2++;
1109 }
1110
1111 void
1112 ruadd(struct rusage *ru, struct rusage_ext *rux, struct rusage *ru2,
1113     struct rusage_ext *rux2)
1114 {
1115
1116         rux->rux_runtime += rux2->rux_runtime;
1117         rux->rux_uticks += rux2->rux_uticks;
1118         rux->rux_sticks += rux2->rux_sticks;
1119         rux->rux_iticks += rux2->rux_iticks;
1120         rux->rux_uu += rux2->rux_uu;
1121         rux->rux_su += rux2->rux_su;
1122         rux->rux_tu += rux2->rux_tu;
1123         rucollect(ru, ru2);
1124 }
1125
1126 /*
1127  * Aggregate tick counts into the proc's rusage_ext.
1128  */
1129 static void
1130 ruxagg_ext_locked(struct rusage_ext *rux, struct thread *td)
1131 {
1132
1133         rux->rux_runtime += td->td_incruntime;
1134         rux->rux_uticks += td->td_uticks;
1135         rux->rux_sticks += td->td_sticks;
1136         rux->rux_iticks += td->td_iticks;
1137 }
1138
1139 void
1140 ruxagg_locked(struct proc *p, struct thread *td)
1141 {
1142         THREAD_LOCK_ASSERT(td, MA_OWNED);
1143         PROC_STATLOCK_ASSERT(td->td_proc, MA_OWNED);
1144
1145         ruxagg_ext_locked(&p->p_rux, td);
1146         ruxagg_ext_locked(&td->td_rux, td);
1147         td->td_incruntime = 0;
1148         td->td_uticks = 0;
1149         td->td_iticks = 0;
1150         td->td_sticks = 0;
1151 }
1152
1153 void
1154 ruxagg(struct proc *p, struct thread *td)
1155 {
1156
1157         thread_lock(td);
1158         ruxagg_locked(p, td);
1159         thread_unlock(td);
1160 }
1161
1162 /*
1163  * Update the rusage_ext structure and fetch a valid aggregate rusage
1164  * for proc p if storage for one is supplied.
1165  */
1166 void
1167 rufetch(struct proc *p, struct rusage *ru)
1168 {
1169         struct thread *td;
1170
1171         PROC_STATLOCK_ASSERT(p, MA_OWNED);
1172
1173         *ru = p->p_ru;
1174         if (p->p_numthreads > 0)  {
1175                 FOREACH_THREAD_IN_PROC(p, td) {
1176                         ruxagg(p, td);
1177                         rucollect(ru, &td->td_ru);
1178                 }
1179         }
1180 }
1181
1182 /*
1183  * Atomically perform a rufetch and a calcru together.
1184  * Consumers, can safely assume the calcru is executed only once
1185  * rufetch is completed.
1186  */
1187 void
1188 rufetchcalc(struct proc *p, struct rusage *ru, struct timeval *up,
1189     struct timeval *sp)
1190 {
1191
1192         PROC_STATLOCK(p);
1193         rufetch(p, ru);
1194         calcru(p, up, sp);
1195         PROC_STATUNLOCK(p);
1196 }
1197
1198 /*
1199  * Allocate a new resource limits structure and initialize its
1200  * reference count and mutex pointer.
1201  */
1202 struct plimit *
1203 lim_alloc()
1204 {
1205         struct plimit *limp;
1206
1207         limp = malloc(sizeof(struct plimit), M_PLIMIT, M_WAITOK);
1208         refcount_init(&limp->pl_refcnt, 1);
1209         return (limp);
1210 }
1211
1212 struct plimit *
1213 lim_hold(struct plimit *limp)
1214 {
1215
1216         refcount_acquire(&limp->pl_refcnt);
1217         return (limp);
1218 }
1219
1220 void
1221 lim_fork(struct proc *p1, struct proc *p2)
1222 {
1223
1224         PROC_LOCK_ASSERT(p1, MA_OWNED);
1225         PROC_LOCK_ASSERT(p2, MA_OWNED);
1226
1227         p2->p_limit = lim_hold(p1->p_limit);
1228         callout_init_mtx(&p2->p_limco, &p2->p_mtx, 0);
1229         if (p1->p_cpulimit != RLIM_INFINITY)
1230                 callout_reset_sbt(&p2->p_limco, SBT_1S, 0,
1231                     lim_cb, p2, C_PREL(1));
1232 }
1233
1234 void
1235 lim_free(struct plimit *limp)
1236 {
1237
1238         if (refcount_release(&limp->pl_refcnt))
1239                 free((void *)limp, M_PLIMIT);
1240 }
1241
1242 /*
1243  * Make a copy of the plimit structure.
1244  * We share these structures copy-on-write after fork.
1245  */
1246 void
1247 lim_copy(struct plimit *dst, struct plimit *src)
1248 {
1249
1250         KASSERT(dst->pl_refcnt <= 1, ("lim_copy to shared limit"));
1251         bcopy(src->pl_rlimit, dst->pl_rlimit, sizeof(src->pl_rlimit));
1252 }
1253
1254 /*
1255  * Return the hard limit for a particular system resource.  The
1256  * which parameter specifies the index into the rlimit array.
1257  */
1258 rlim_t
1259 lim_max(struct thread *td, int which)
1260 {
1261         struct rlimit rl;
1262
1263         lim_rlimit(td, which, &rl);
1264         return (rl.rlim_max);
1265 }
1266
1267 rlim_t
1268 lim_max_proc(struct proc *p, int which)
1269 {
1270         struct rlimit rl;
1271
1272         lim_rlimit_proc(p, which, &rl);
1273         return (rl.rlim_max);
1274 }
1275
1276 /*
1277  * Return the current (soft) limit for a particular system resource.
1278  * The which parameter which specifies the index into the rlimit array
1279  */
1280 rlim_t
1281 (lim_cur)(struct thread *td, int which)
1282 {
1283         struct rlimit rl;
1284
1285         lim_rlimit(td, which, &rl);
1286         return (rl.rlim_cur);
1287 }
1288
1289 rlim_t
1290 lim_cur_proc(struct proc *p, int which)
1291 {
1292         struct rlimit rl;
1293
1294         lim_rlimit_proc(p, which, &rl);
1295         return (rl.rlim_cur);
1296 }
1297
1298 /*
1299  * Return a copy of the entire rlimit structure for the system limit
1300  * specified by 'which' in the rlimit structure pointed to by 'rlp'.
1301  */
1302 void
1303 lim_rlimit(struct thread *td, int which, struct rlimit *rlp)
1304 {
1305         struct proc *p = td->td_proc;
1306
1307         MPASS(td == curthread);
1308         KASSERT(which >= 0 && which < RLIM_NLIMITS,
1309             ("request for invalid resource limit"));
1310         *rlp = td->td_limit->pl_rlimit[which];
1311         if (p->p_sysent->sv_fixlimit != NULL)
1312                 p->p_sysent->sv_fixlimit(rlp, which);
1313 }
1314
1315 void
1316 lim_rlimit_proc(struct proc *p, int which, struct rlimit *rlp)
1317 {
1318
1319         PROC_LOCK_ASSERT(p, MA_OWNED);
1320         KASSERT(which >= 0 && which < RLIM_NLIMITS,
1321             ("request for invalid resource limit"));
1322         *rlp = p->p_limit->pl_rlimit[which];
1323         if (p->p_sysent->sv_fixlimit != NULL)
1324                 p->p_sysent->sv_fixlimit(rlp, which);
1325 }
1326
1327 void
1328 uihashinit()
1329 {
1330
1331         uihashtbl = hashinit(maxproc / 16, M_UIDINFO, &uihash);
1332         rw_init(&uihashtbl_lock, "uidinfo hash");
1333 }
1334
1335 /*
1336  * Look up a uidinfo struct for the parameter uid.
1337  * uihashtbl_lock must be locked.
1338  * Increase refcount on uidinfo struct returned.
1339  */
1340 static struct uidinfo *
1341 uilookup(uid_t uid)
1342 {
1343         struct uihashhead *uipp;
1344         struct uidinfo *uip;
1345
1346         rw_assert(&uihashtbl_lock, RA_LOCKED);
1347         uipp = UIHASH(uid);
1348         LIST_FOREACH(uip, uipp, ui_hash)
1349                 if (uip->ui_uid == uid) {
1350                         uihold(uip);
1351                         break;
1352                 }
1353
1354         return (uip);
1355 }
1356
1357 /*
1358  * Find or allocate a struct uidinfo for a particular uid.
1359  * Returns with uidinfo struct referenced.
1360  * uifree() should be called on a struct uidinfo when released.
1361  */
1362 struct uidinfo *
1363 uifind(uid_t uid)
1364 {
1365         struct uidinfo *new_uip, *uip;
1366         struct ucred *cred;
1367
1368         cred = curthread->td_ucred;
1369         if (cred->cr_uidinfo->ui_uid == uid) {
1370                 uip = cred->cr_uidinfo;
1371                 uihold(uip);
1372                 return (uip);
1373         } else if (cred->cr_ruidinfo->ui_uid == uid) {
1374                 uip = cred->cr_ruidinfo;
1375                 uihold(uip);
1376                 return (uip);
1377         }
1378
1379         rw_rlock(&uihashtbl_lock);
1380         uip = uilookup(uid);
1381         rw_runlock(&uihashtbl_lock);
1382         if (uip != NULL)
1383                 return (uip);
1384
1385         new_uip = malloc(sizeof(*new_uip), M_UIDINFO, M_WAITOK | M_ZERO);
1386         racct_create(&new_uip->ui_racct);
1387         refcount_init(&new_uip->ui_ref, 1);
1388         new_uip->ui_uid = uid;
1389
1390         rw_wlock(&uihashtbl_lock);
1391         /*
1392          * There's a chance someone created our uidinfo while we
1393          * were in malloc and not holding the lock, so we have to
1394          * make sure we don't insert a duplicate uidinfo.
1395          */
1396         if ((uip = uilookup(uid)) == NULL) {
1397                 LIST_INSERT_HEAD(UIHASH(uid), new_uip, ui_hash);
1398                 rw_wunlock(&uihashtbl_lock);
1399                 uip = new_uip;
1400         } else {
1401                 rw_wunlock(&uihashtbl_lock);
1402                 racct_destroy(&new_uip->ui_racct);
1403                 free(new_uip, M_UIDINFO);
1404         }
1405         return (uip);
1406 }
1407
1408 /*
1409  * Place another refcount on a uidinfo struct.
1410  */
1411 void
1412 uihold(struct uidinfo *uip)
1413 {
1414
1415         refcount_acquire(&uip->ui_ref);
1416 }
1417
1418 /*-
1419  * Since uidinfo structs have a long lifetime, we use an
1420  * opportunistic refcounting scheme to avoid locking the lookup hash
1421  * for each release.
1422  *
1423  * If the refcount hits 0, we need to free the structure,
1424  * which means we need to lock the hash.
1425  * Optimal case:
1426  *   After locking the struct and lowering the refcount, if we find
1427  *   that we don't need to free, simply unlock and return.
1428  * Suboptimal case:
1429  *   If refcount lowering results in need to free, bump the count
1430  *   back up, lose the lock and acquire the locks in the proper
1431  *   order to try again.
1432  */
1433 void
1434 uifree(struct uidinfo *uip)
1435 {
1436
1437         if (refcount_release_if_not_last(&uip->ui_ref))
1438                 return;
1439
1440         rw_wlock(&uihashtbl_lock);
1441         if (refcount_release(&uip->ui_ref) == 0) {
1442                 rw_wunlock(&uihashtbl_lock);
1443                 return;
1444         }
1445
1446         racct_destroy(&uip->ui_racct);
1447         LIST_REMOVE(uip, ui_hash);
1448         rw_wunlock(&uihashtbl_lock);
1449
1450         if (uip->ui_sbsize != 0)
1451                 printf("freeing uidinfo: uid = %d, sbsize = %ld\n",
1452                     uip->ui_uid, uip->ui_sbsize);
1453         if (uip->ui_proccnt != 0)
1454                 printf("freeing uidinfo: uid = %d, proccnt = %ld\n",
1455                     uip->ui_uid, uip->ui_proccnt);
1456         if (uip->ui_vmsize != 0)
1457                 printf("freeing uidinfo: uid = %d, swapuse = %lld\n",
1458                     uip->ui_uid, (unsigned long long)uip->ui_vmsize);
1459         free(uip, M_UIDINFO);
1460 }
1461
1462 #ifdef RACCT
1463 void
1464 ui_racct_foreach(void (*callback)(struct racct *racct,
1465     void *arg2, void *arg3), void (*pre)(void), void (*post)(void),
1466     void *arg2, void *arg3)
1467 {
1468         struct uidinfo *uip;
1469         struct uihashhead *uih;
1470
1471         rw_rlock(&uihashtbl_lock);
1472         if (pre != NULL)
1473                 (pre)();
1474         for (uih = &uihashtbl[uihash]; uih >= uihashtbl; uih--) {
1475                 LIST_FOREACH(uip, uih, ui_hash) {
1476                         (callback)(uip->ui_racct, arg2, arg3);
1477                 }
1478         }
1479         if (post != NULL)
1480                 (post)();
1481         rw_runlock(&uihashtbl_lock);
1482 }
1483 #endif
1484
1485 static inline int
1486 chglimit(struct uidinfo *uip, long *limit, int diff, rlim_t max, const char *name)
1487 {
1488         long new;
1489
1490         /* Don't allow them to exceed max, but allow subtraction. */
1491         new = atomic_fetchadd_long(limit, (long)diff) + diff;
1492         if (diff > 0 && max != 0) {
1493                 if (new < 0 || new > max) {
1494                         atomic_subtract_long(limit, (long)diff);
1495                         return (0);
1496                 }
1497         } else if (new < 0)
1498                 printf("negative %s for uid = %d\n", name, uip->ui_uid);
1499         return (1);
1500 }
1501
1502 /*
1503  * Change the count associated with number of processes
1504  * a given user is using.  When 'max' is 0, don't enforce a limit
1505  */
1506 int
1507 chgproccnt(struct uidinfo *uip, int diff, rlim_t max)
1508 {
1509
1510         return (chglimit(uip, &uip->ui_proccnt, diff, max, "proccnt"));
1511 }
1512
1513 /*
1514  * Change the total socket buffer size a user has used.
1515  */
1516 int
1517 chgsbsize(struct uidinfo *uip, u_int *hiwat, u_int to, rlim_t max)
1518 {
1519         int diff, rv;
1520
1521         diff = to - *hiwat;
1522         if (diff > 0 && max == 0) {
1523                 rv = 0;
1524         } else {
1525                 rv = chglimit(uip, &uip->ui_sbsize, diff, max, "sbsize");
1526                 if (rv != 0)
1527                         *hiwat = to;
1528         }
1529         return (rv);
1530 }
1531
1532 /*
1533  * Change the count associated with number of pseudo-terminals
1534  * a given user is using.  When 'max' is 0, don't enforce a limit
1535  */
1536 int
1537 chgptscnt(struct uidinfo *uip, int diff, rlim_t max)
1538 {
1539
1540         return (chglimit(uip, &uip->ui_ptscnt, diff, max, "ptscnt"));
1541 }
1542
1543 int
1544 chgkqcnt(struct uidinfo *uip, int diff, rlim_t max)
1545 {
1546
1547         return (chglimit(uip, &uip->ui_kqcnt, diff, max, "kqcnt"));
1548 }
1549
1550 int
1551 chgumtxcnt(struct uidinfo *uip, int diff, rlim_t max)
1552 {
1553
1554         return (chglimit(uip, &uip->ui_umtxcnt, diff, max, "umtxcnt"));
1555 }