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