]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/kern/kern_resource.c
MFC 219968:
[FreeBSD/stable/8.git] / sys / kern / kern_resource.c
1 /*-
2  * Copyright (c) 1982, 1986, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      @(#)kern_resource.c     8.5 (Berkeley) 1/21/94
35  */
36
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39
40 #include "opt_compat.h"
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/resourcevar.h>
54 #include <sys/rwlock.h>
55 #include <sys/sched.h>
56 #include <sys/sx.h>
57 #include <sys/syscallsubr.h>
58 #include <sys/sysent.h>
59 #include <sys/time.h>
60 #include <sys/umtx.h>
61
62 #include <vm/vm.h>
63 #include <vm/vm_param.h>
64 #include <vm/pmap.h>
65 #include <vm/vm_map.h>
66
67
68 static MALLOC_DEFINE(M_PLIMIT, "plimit", "plimit structures");
69 static MALLOC_DEFINE(M_UIDINFO, "uidinfo", "uidinfo structures");
70 #define UIHASH(uid)     (&uihashtbl[(uid) & uihash])
71 static struct rwlock uihashtbl_lock;
72 static LIST_HEAD(uihashhead, uidinfo) *uihashtbl;
73 static u_long uihash;           /* size of hash table - 1 */
74
75 static void     calcru1(struct proc *p, struct rusage_ext *ruxp,
76                     struct timeval *up, struct timeval *sp);
77 static int      donice(struct thread *td, struct proc *chgp, int n);
78 static struct uidinfo *uilookup(uid_t uid);
79 static void     ruxagg_locked(struct rusage_ext *rux, struct thread *td);
80
81 /*
82  * Resource controls and accounting.
83  */
84 #ifndef _SYS_SYSPROTO_H_
85 struct getpriority_args {
86         int     which;
87         int     who;
88 };
89 #endif
90 int
91 getpriority(td, uap)
92         struct thread *td;
93         register struct getpriority_args *uap;
94 {
95         struct proc *p;
96         struct pgrp *pg;
97         int error, low;
98
99         error = 0;
100         low = PRIO_MAX + 1;
101         switch (uap->which) {
102
103         case PRIO_PROCESS:
104                 if (uap->who == 0)
105                         low = td->td_proc->p_nice;
106                 else {
107                         p = pfind(uap->who);
108                         if (p == NULL)
109                                 break;
110                         if (p_cansee(td, p) == 0)
111                                 low = p->p_nice;
112                         PROC_UNLOCK(p);
113                 }
114                 break;
115
116         case PRIO_PGRP:
117                 sx_slock(&proctree_lock);
118                 if (uap->who == 0) {
119                         pg = td->td_proc->p_pgrp;
120                         PGRP_LOCK(pg);
121                 } else {
122                         pg = pgfind(uap->who);
123                         if (pg == NULL) {
124                                 sx_sunlock(&proctree_lock);
125                                 break;
126                         }
127                 }
128                 sx_sunlock(&proctree_lock);
129                 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
130                         PROC_LOCK(p);
131                         if (p_cansee(td, p) == 0) {
132                                 if (p->p_nice < low)
133                                         low = p->p_nice;
134                         }
135                         PROC_UNLOCK(p);
136                 }
137                 PGRP_UNLOCK(pg);
138                 break;
139
140         case PRIO_USER:
141                 if (uap->who == 0)
142                         uap->who = td->td_ucred->cr_uid;
143                 sx_slock(&allproc_lock);
144                 FOREACH_PROC_IN_SYSTEM(p) {
145                         PROC_LOCK(p);
146                         if (p->p_state == PRS_NORMAL &&
147                             p_cansee(td, p) == 0 &&
148                             p->p_ucred->cr_uid == uap->who) {
149                                 if (p->p_nice < low)
150                                         low = p->p_nice;
151                         }
152                         PROC_UNLOCK(p);
153                 }
154                 sx_sunlock(&allproc_lock);
155                 break;
156
157         default:
158                 error = EINVAL;
159                 break;
160         }
161         if (low == PRIO_MAX + 1 && error == 0)
162                 error = ESRCH;
163         td->td_retval[0] = low;
164         return (error);
165 }
166
167 #ifndef _SYS_SYSPROTO_H_
168 struct setpriority_args {
169         int     which;
170         int     who;
171         int     prio;
172 };
173 #endif
174 int
175 setpriority(td, uap)
176         struct thread *td;
177         struct setpriority_args *uap;
178 {
179         struct proc *curp, *p;
180         struct pgrp *pg;
181         int found = 0, error = 0;
182
183         curp = td->td_proc;
184         switch (uap->which) {
185         case PRIO_PROCESS:
186                 if (uap->who == 0) {
187                         PROC_LOCK(curp);
188                         error = donice(td, curp, uap->prio);
189                         PROC_UNLOCK(curp);
190                 } else {
191                         p = pfind(uap->who);
192                         if (p == NULL)
193                                 break;
194                         error = p_cansee(td, p);
195                         if (error == 0)
196                                 error = donice(td, p, uap->prio);
197                         PROC_UNLOCK(p);
198                 }
199                 found++;
200                 break;
201
202         case PRIO_PGRP:
203                 sx_slock(&proctree_lock);
204                 if (uap->who == 0) {
205                         pg = curp->p_pgrp;
206                         PGRP_LOCK(pg);
207                 } else {
208                         pg = pgfind(uap->who);
209                         if (pg == NULL) {
210                                 sx_sunlock(&proctree_lock);
211                                 break;
212                         }
213                 }
214                 sx_sunlock(&proctree_lock);
215                 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
216                         PROC_LOCK(p);
217                         if (p_cansee(td, p) == 0) {
218                                 error = donice(td, p, uap->prio);
219                                 found++;
220                         }
221                         PROC_UNLOCK(p);
222                 }
223                 PGRP_UNLOCK(pg);
224                 break;
225
226         case PRIO_USER:
227                 if (uap->who == 0)
228                         uap->who = td->td_ucred->cr_uid;
229                 sx_slock(&allproc_lock);
230                 FOREACH_PROC_IN_SYSTEM(p) {
231                         PROC_LOCK(p);
232                         if (p->p_ucred->cr_uid == uap->who &&
233                             p_cansee(td, p) == 0) {
234                                 error = donice(td, p, uap->prio);
235                                 found++;
236                         }
237                         PROC_UNLOCK(p);
238                 }
239                 sx_sunlock(&allproc_lock);
240                 break;
241
242         default:
243                 error = EINVAL;
244                 break;
245         }
246         if (found == 0 && error == 0)
247                 error = ESRCH;
248         return (error);
249 }
250
251 /*
252  * Set "nice" for a (whole) process.
253  */
254 static int
255 donice(struct thread *td, struct proc *p, int n)
256 {
257         int error;
258
259         PROC_LOCK_ASSERT(p, MA_OWNED);
260         if ((error = p_cansched(td, p)))
261                 return (error);
262         if (n > PRIO_MAX)
263                 n = PRIO_MAX;
264         if (n < PRIO_MIN)
265                 n = PRIO_MIN;
266         if (n < p->p_nice && priv_check(td, PRIV_SCHED_SETPRIORITY) != 0)
267                 return (EACCES);
268         sched_nice(p, n);
269         return (0);
270 }
271
272 /*
273  * Set realtime priority for LWP.
274  */
275 #ifndef _SYS_SYSPROTO_H_
276 struct rtprio_thread_args {
277         int             function;
278         lwpid_t         lwpid;
279         struct rtprio   *rtp;
280 };
281 #endif
282 int
283 rtprio_thread(struct thread *td, struct rtprio_thread_args *uap)
284 {
285         struct proc *p;
286         struct rtprio rtp;
287         struct thread *td1;
288         int cierror, error;
289
290         /* Perform copyin before acquiring locks if needed. */
291         if (uap->function == RTP_SET)
292                 cierror = copyin(uap->rtp, &rtp, sizeof(struct rtprio));
293         else
294                 cierror = 0;
295
296         /*
297          * Though lwpid is unique, only current process is supported
298          * since there is no efficient way to look up a LWP yet.
299          */
300         p = td->td_proc;
301         PROC_LOCK(p);
302
303         switch (uap->function) {
304         case RTP_LOOKUP:
305                 if ((error = p_cansee(td, p)))
306                         break;
307                 if (uap->lwpid == 0 || uap->lwpid == td->td_tid)
308                         td1 = td;
309                 else
310                         td1 = thread_find(p, uap->lwpid);
311                 if (td1 != NULL)
312                         pri_to_rtp(td1, &rtp);
313                 else
314                         error = ESRCH;
315                 PROC_UNLOCK(p);
316                 return (copyout(&rtp, uap->rtp, sizeof(struct rtprio)));
317         case RTP_SET:
318                 if ((error = p_cansched(td, p)) || (error = cierror))
319                         break;
320
321                 /* Disallow setting rtprio in most cases if not superuser. */
322 /*
323  * Realtime priority has to be restricted for reasons which should be
324  * obvious.  However, for idle priority, there is a potential for
325  * system deadlock if an idleprio process gains a lock on a resource
326  * that other processes need (and the idleprio process can't run
327  * due to a CPU-bound normal process).  Fix me!  XXX
328  */
329 #if 0
330                 if (RTP_PRIO_IS_REALTIME(rtp.type)) {
331 #else
332                 if (rtp.type != RTP_PRIO_NORMAL) {
333 #endif
334                         error = priv_check(td, PRIV_SCHED_RTPRIO);
335                         if (error)
336                                 break;
337                 }
338
339                 if (uap->lwpid == 0 || uap->lwpid == td->td_tid)
340                         td1 = td;
341                 else
342                         td1 = thread_find(p, uap->lwpid);
343                 if (td1 != NULL)
344                         error = rtp_to_pri(&rtp, td1);
345                 else
346                         error = ESRCH;
347                 break;
348         default:
349                 error = EINVAL;
350                 break;
351         }
352         PROC_UNLOCK(p);
353         return (error);
354 }
355
356 /*
357  * Set realtime priority.
358  */
359 #ifndef _SYS_SYSPROTO_H_
360 struct rtprio_args {
361         int             function;
362         pid_t           pid;
363         struct rtprio   *rtp;
364 };
365 #endif
366 int
367 rtprio(td, uap)
368         struct thread *td;              /* curthread */
369         register struct rtprio_args *uap;
370 {
371         struct proc *p;
372         struct thread *tdp;
373         struct rtprio rtp;
374         int cierror, error;
375
376         /* Perform copyin before acquiring locks if needed. */
377         if (uap->function == RTP_SET)
378                 cierror = copyin(uap->rtp, &rtp, sizeof(struct rtprio));
379         else
380                 cierror = 0;
381
382         if (uap->pid == 0) {
383                 p = td->td_proc;
384                 PROC_LOCK(p);
385         } else {
386                 p = pfind(uap->pid);
387                 if (p == NULL)
388                         return (ESRCH);
389         }
390
391         switch (uap->function) {
392         case RTP_LOOKUP:
393                 if ((error = p_cansee(td, p)))
394                         break;
395                 /*
396                  * Return OUR priority if no pid specified,
397                  * or if one is, report the highest priority
398                  * in the process.  There isn't much more you can do as
399                  * there is only room to return a single priority.
400                  * Note: specifying our own pid is not the same
401                  * as leaving it zero.
402                  */
403                 if (uap->pid == 0) {
404                         pri_to_rtp(td, &rtp);
405                 } else {
406                         struct rtprio rtp2;
407
408                         rtp.type = RTP_PRIO_IDLE;
409                         rtp.prio = RTP_PRIO_MAX;
410                         FOREACH_THREAD_IN_PROC(p, tdp) {
411                                 pri_to_rtp(tdp, &rtp2);
412                                 if (rtp2.type <  rtp.type ||
413                                     (rtp2.type == rtp.type &&
414                                     rtp2.prio < rtp.prio)) {
415                                         rtp.type = rtp2.type;
416                                         rtp.prio = rtp2.prio;
417                                 }
418                         }
419                 }
420                 PROC_UNLOCK(p);
421                 return (copyout(&rtp, uap->rtp, sizeof(struct rtprio)));
422         case RTP_SET:
423                 if ((error = p_cansched(td, p)) || (error = cierror))
424                         break;
425
426                 /* Disallow setting rtprio in most cases if not superuser. */
427 /*
428  * Realtime priority has to be restricted for reasons which should be
429  * obvious.  However, for idle priority, there is a potential for
430  * system deadlock if an idleprio process gains a lock on a resource
431  * that other processes need (and the idleprio process can't run
432  * due to a CPU-bound normal process).  Fix me!  XXX
433  */
434 #if 0
435                 if (RTP_PRIO_IS_REALTIME(rtp.type)) {
436 #else
437                 if (rtp.type != RTP_PRIO_NORMAL) {
438 #endif
439                         error = priv_check(td, PRIV_SCHED_RTPRIO);
440                         if (error)
441                                 break;
442                 }
443
444                 /*
445                  * If we are setting our own priority, set just our
446                  * thread but if we are doing another process,
447                  * do all the threads on that process. If we
448                  * specify our own pid we do the latter.
449                  */
450                 if (uap->pid == 0) {
451                         error = rtp_to_pri(&rtp, td);
452                 } else {
453                         FOREACH_THREAD_IN_PROC(p, td) {
454                                 if ((error = rtp_to_pri(&rtp, td)) != 0)
455                                         break;
456                         }
457                 }
458                 break;
459         default:
460                 error = EINVAL;
461                 break;
462         }
463         PROC_UNLOCK(p);
464         return (error);
465 }
466
467 int
468 rtp_to_pri(struct rtprio *rtp, struct thread *td)
469 {
470         u_char  newpri;
471         u_char  oldpri;
472
473         switch (RTP_PRIO_BASE(rtp->type)) {
474         case RTP_PRIO_REALTIME:
475                 if (rtp->prio > RTP_PRIO_MAX)
476                         return (EINVAL);
477                 newpri = PRI_MIN_REALTIME + rtp->prio;
478                 break;
479         case RTP_PRIO_NORMAL:
480                 if (rtp->prio > (PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE))
481                         return (EINVAL);
482                 newpri = PRI_MIN_TIMESHARE + rtp->prio;
483                 break;
484         case RTP_PRIO_IDLE:
485                 if (rtp->prio > RTP_PRIO_MAX)
486                         return (EINVAL);
487                 newpri = PRI_MIN_IDLE + rtp->prio;
488                 break;
489         default:
490                 return (EINVAL);
491         }
492
493         thread_lock(td);
494         sched_class(td, rtp->type);     /* XXX fix */
495         oldpri = td->td_user_pri;
496         sched_user_prio(td, newpri);
497         if (curthread == td)
498                 sched_prio(curthread, td->td_user_pri); /* XXX dubious */
499         if (TD_ON_UPILOCK(td) && oldpri != newpri) {
500                 thread_unlock(td);
501                 umtx_pi_adjust(td, oldpri);
502         } else
503                 thread_unlock(td);
504         return (0);
505 }
506
507 void
508 pri_to_rtp(struct thread *td, struct rtprio *rtp)
509 {
510
511         thread_lock(td);
512         switch (PRI_BASE(td->td_pri_class)) {
513         case PRI_REALTIME:
514                 rtp->prio = td->td_base_user_pri - PRI_MIN_REALTIME;
515                 break;
516         case PRI_TIMESHARE:
517                 rtp->prio = td->td_base_user_pri - PRI_MIN_TIMESHARE;
518                 break;
519         case PRI_IDLE:
520                 rtp->prio = td->td_base_user_pri - PRI_MIN_IDLE;
521                 break;
522         default:
523                 break;
524         }
525         rtp->type = td->td_pri_class;
526         thread_unlock(td);
527 }
528
529 #if defined(COMPAT_43)
530 #ifndef _SYS_SYSPROTO_H_
531 struct osetrlimit_args {
532         u_int   which;
533         struct  orlimit *rlp;
534 };
535 #endif
536 int
537 osetrlimit(td, uap)
538         struct thread *td;
539         register struct osetrlimit_args *uap;
540 {
541         struct orlimit olim;
542         struct rlimit lim;
543         int error;
544
545         if ((error = copyin(uap->rlp, &olim, sizeof(struct orlimit))))
546                 return (error);
547         lim.rlim_cur = olim.rlim_cur;
548         lim.rlim_max = olim.rlim_max;
549         error = kern_setrlimit(td, uap->which, &lim);
550         return (error);
551 }
552
553 #ifndef _SYS_SYSPROTO_H_
554 struct ogetrlimit_args {
555         u_int   which;
556         struct  orlimit *rlp;
557 };
558 #endif
559 int
560 ogetrlimit(td, uap)
561         struct thread *td;
562         register struct ogetrlimit_args *uap;
563 {
564         struct orlimit olim;
565         struct rlimit rl;
566         struct proc *p;
567         int error;
568
569         if (uap->which >= RLIM_NLIMITS)
570                 return (EINVAL);
571         p = td->td_proc;
572         PROC_LOCK(p);
573         lim_rlimit(p, uap->which, &rl);
574         PROC_UNLOCK(p);
575
576         /*
577          * XXX would be more correct to convert only RLIM_INFINITY to the
578          * old RLIM_INFINITY and fail with EOVERFLOW for other larger
579          * values.  Most 64->32 and 32->16 conversions, including not
580          * unimportant ones of uids are even more broken than what we
581          * do here (they blindly truncate).  We don't do this correctly
582          * here since we have little experience with EOVERFLOW yet.
583          * Elsewhere, getuid() can't fail...
584          */
585         olim.rlim_cur = rl.rlim_cur > 0x7fffffff ? 0x7fffffff : rl.rlim_cur;
586         olim.rlim_max = rl.rlim_max > 0x7fffffff ? 0x7fffffff : rl.rlim_max;
587         error = copyout(&olim, uap->rlp, sizeof(olim));
588         return (error);
589 }
590 #endif /* COMPAT_43 */
591
592 #ifndef _SYS_SYSPROTO_H_
593 struct __setrlimit_args {
594         u_int   which;
595         struct  rlimit *rlp;
596 };
597 #endif
598 int
599 setrlimit(td, uap)
600         struct thread *td;
601         register struct __setrlimit_args *uap;
602 {
603         struct rlimit alim;
604         int error;
605
606         if ((error = copyin(uap->rlp, &alim, sizeof(struct rlimit))))
607                 return (error);
608         error = kern_setrlimit(td, uap->which, &alim);
609         return (error);
610 }
611
612 static void
613 lim_cb(void *arg)
614 {
615         struct rlimit rlim;
616         struct thread *td;
617         struct proc *p;
618
619         p = arg;
620         PROC_LOCK_ASSERT(p, MA_OWNED);
621         /*
622          * Check if the process exceeds its cpu resource allocation.  If
623          * it reaches the max, arrange to kill the process in ast().
624          */
625         if (p->p_cpulimit == RLIM_INFINITY)
626                 return;
627         PROC_SLOCK(p);
628         FOREACH_THREAD_IN_PROC(p, td) {
629                 ruxagg(p, td);
630         }
631         PROC_SUNLOCK(p);
632         if (p->p_rux.rux_runtime > p->p_cpulimit * cpu_tickrate()) {
633                 lim_rlimit(p, RLIMIT_CPU, &rlim);
634                 if (p->p_rux.rux_runtime >= rlim.rlim_max * cpu_tickrate()) {
635                         killproc(p, "exceeded maximum CPU limit");
636                 } else {
637                         if (p->p_cpulimit < rlim.rlim_max)
638                                 p->p_cpulimit += 5;
639                         psignal(p, SIGXCPU);
640                 }
641         }
642         if ((p->p_flag & P_WEXIT) == 0)
643                 callout_reset(&p->p_limco, hz, lim_cb, p);
644 }
645
646 int
647 kern_setrlimit(td, which, limp)
648         struct thread *td;
649         u_int which;
650         struct rlimit *limp;
651 {
652         struct plimit *newlim, *oldlim;
653         struct proc *p;
654         register struct rlimit *alimp;
655         struct rlimit oldssiz;
656         int error;
657
658         if (which >= RLIM_NLIMITS)
659                 return (EINVAL);
660
661         /*
662          * Preserve historical bugs by treating negative limits as unsigned.
663          */
664         if (limp->rlim_cur < 0)
665                 limp->rlim_cur = RLIM_INFINITY;
666         if (limp->rlim_max < 0)
667                 limp->rlim_max = RLIM_INFINITY;
668
669         oldssiz.rlim_cur = 0;
670         p = td->td_proc;
671         newlim = lim_alloc();
672         PROC_LOCK(p);
673         oldlim = p->p_limit;
674         alimp = &oldlim->pl_rlimit[which];
675         if (limp->rlim_cur > alimp->rlim_max ||
676             limp->rlim_max > alimp->rlim_max)
677                 if ((error = priv_check(td, PRIV_PROC_SETRLIMIT))) {
678                         PROC_UNLOCK(p);
679                         lim_free(newlim);
680                         return (error);
681                 }
682         if (limp->rlim_cur > limp->rlim_max)
683                 limp->rlim_cur = limp->rlim_max;
684         lim_copy(newlim, oldlim);
685         alimp = &newlim->pl_rlimit[which];
686
687         switch (which) {
688
689         case RLIMIT_CPU:
690                 if (limp->rlim_cur != RLIM_INFINITY &&
691                     p->p_cpulimit == RLIM_INFINITY)
692                         callout_reset(&p->p_limco, hz, lim_cb, p);
693                 p->p_cpulimit = limp->rlim_cur;
694                 break;
695         case RLIMIT_DATA:
696                 if (limp->rlim_cur > maxdsiz)
697                         limp->rlim_cur = maxdsiz;
698                 if (limp->rlim_max > maxdsiz)
699                         limp->rlim_max = maxdsiz;
700                 break;
701
702         case RLIMIT_STACK:
703                 if (limp->rlim_cur > maxssiz)
704                         limp->rlim_cur = maxssiz;
705                 if (limp->rlim_max > maxssiz)
706                         limp->rlim_max = maxssiz;
707                 oldssiz = *alimp;
708                 if (td->td_proc->p_sysent->sv_fixlimit != NULL)
709                         td->td_proc->p_sysent->sv_fixlimit(&oldssiz,
710                             RLIMIT_STACK);
711                 break;
712
713         case RLIMIT_NOFILE:
714                 if (limp->rlim_cur > maxfilesperproc)
715                         limp->rlim_cur = maxfilesperproc;
716                 if (limp->rlim_max > maxfilesperproc)
717                         limp->rlim_max = maxfilesperproc;
718                 break;
719
720         case RLIMIT_NPROC:
721                 if (limp->rlim_cur > maxprocperuid)
722                         limp->rlim_cur = maxprocperuid;
723                 if (limp->rlim_max > maxprocperuid)
724                         limp->rlim_max = maxprocperuid;
725                 if (limp->rlim_cur < 1)
726                         limp->rlim_cur = 1;
727                 if (limp->rlim_max < 1)
728                         limp->rlim_max = 1;
729                 break;
730         }
731         if (td->td_proc->p_sysent->sv_fixlimit != NULL)
732                 td->td_proc->p_sysent->sv_fixlimit(limp, which);
733         *alimp = *limp;
734         p->p_limit = newlim;
735         PROC_UNLOCK(p);
736         lim_free(oldlim);
737
738         if (which == RLIMIT_STACK) {
739                 /*
740                  * Stack is allocated to the max at exec time with only
741                  * "rlim_cur" bytes accessible.  If stack limit is going
742                  * up make more accessible, if going down make inaccessible.
743                  */
744                 if (limp->rlim_cur != oldssiz.rlim_cur) {
745                         vm_offset_t addr;
746                         vm_size_t size;
747                         vm_prot_t prot;
748
749                         if (limp->rlim_cur > oldssiz.rlim_cur) {
750                                 prot = p->p_sysent->sv_stackprot;
751                                 size = limp->rlim_cur - oldssiz.rlim_cur;
752                                 addr = p->p_sysent->sv_usrstack -
753                                     limp->rlim_cur;
754                         } else {
755                                 prot = VM_PROT_NONE;
756                                 size = oldssiz.rlim_cur - limp->rlim_cur;
757                                 addr = p->p_sysent->sv_usrstack -
758                                     oldssiz.rlim_cur;
759                         }
760                         addr = trunc_page(addr);
761                         size = round_page(size);
762                         (void)vm_map_protect(&p->p_vmspace->vm_map,
763                             addr, addr + size, prot, FALSE);
764                 }
765         }
766
767         return (0);
768 }
769
770 #ifndef _SYS_SYSPROTO_H_
771 struct __getrlimit_args {
772         u_int   which;
773         struct  rlimit *rlp;
774 };
775 #endif
776 /* ARGSUSED */
777 int
778 getrlimit(td, uap)
779         struct thread *td;
780         register struct __getrlimit_args *uap;
781 {
782         struct rlimit rlim;
783         struct proc *p;
784         int error;
785
786         if (uap->which >= RLIM_NLIMITS)
787                 return (EINVAL);
788         p = td->td_proc;
789         PROC_LOCK(p);
790         lim_rlimit(p, uap->which, &rlim);
791         PROC_UNLOCK(p);
792         error = copyout(&rlim, uap->rlp, sizeof(struct rlimit));
793         return (error);
794 }
795
796 /*
797  * Transform the running time and tick information for children of proc p
798  * into user and system time usage.
799  */
800 void
801 calccru(p, up, sp)
802         struct proc *p;
803         struct timeval *up;
804         struct timeval *sp;
805 {
806
807         PROC_LOCK_ASSERT(p, MA_OWNED);
808         calcru1(p, &p->p_crux, up, sp);
809 }
810
811 /*
812  * Transform the running time and tick information in proc p into user
813  * and system time usage.  If appropriate, include the current time slice
814  * on this CPU.
815  */
816 void
817 calcru(struct proc *p, struct timeval *up, struct timeval *sp)
818 {
819         struct thread *td;
820         uint64_t u;
821
822         PROC_LOCK_ASSERT(p, MA_OWNED);
823         PROC_SLOCK_ASSERT(p, MA_OWNED);
824         /*
825          * If we are getting stats for the current process, then add in the
826          * stats that this thread has accumulated in its current time slice.
827          * We reset the thread and CPU state as if we had performed a context
828          * switch right here.
829          */
830         td = curthread;
831         if (td->td_proc == p) {
832                 u = cpu_ticks();
833                 p->p_rux.rux_runtime += u - PCPU_GET(switchtime);
834                 PCPU_SET(switchtime, u);
835         }
836         /* Make sure the per-thread stats are current. */
837         FOREACH_THREAD_IN_PROC(p, td) {
838                 if (td->td_incruntime == 0)
839                         continue;
840                 ruxagg(p, td);
841         }
842         calcru1(p, &p->p_rux, up, sp);
843 }
844
845 static void
846 calcru1(struct proc *p, struct rusage_ext *ruxp, struct timeval *up,
847     struct timeval *sp)
848 {
849         /* {user, system, interrupt, total} {ticks, usec}: */
850         u_int64_t ut, uu, st, su, it, tt, tu;
851
852         ut = ruxp->rux_uticks;
853         st = ruxp->rux_sticks;
854         it = ruxp->rux_iticks;
855         tt = ut + st + it;
856         if (tt == 0) {
857                 /* Avoid divide by zero */
858                 st = 1;
859                 tt = 1;
860         }
861         tu = cputick2usec(ruxp->rux_runtime);
862         if ((int64_t)tu < 0) {
863                 /* XXX: this should be an assert /phk */
864                 printf("calcru: negative runtime of %jd usec for pid %d (%s)\n",
865                     (intmax_t)tu, p->p_pid, p->p_comm);
866                 tu = ruxp->rux_tu;
867         }
868
869         if (tu >= ruxp->rux_tu) {
870                 /*
871                  * The normal case, time increased.
872                  * Enforce monotonicity of bucketed numbers.
873                  */
874                 uu = (tu * ut) / tt;
875                 if (uu < ruxp->rux_uu)
876                         uu = ruxp->rux_uu;
877                 su = (tu * st) / tt;
878                 if (su < ruxp->rux_su)
879                         su = ruxp->rux_su;
880         } else if (tu + 3 > ruxp->rux_tu || 101 * tu > 100 * ruxp->rux_tu) {
881                 /*
882                  * When we calibrate the cputicker, it is not uncommon to
883                  * see the presumably fixed frequency increase slightly over
884                  * time as a result of thermal stabilization and NTP
885                  * discipline (of the reference clock).  We therefore ignore
886                  * a bit of backwards slop because we  expect to catch up
887                  * shortly.  We use a 3 microsecond limit to catch low
888                  * counts and a 1% limit for high counts.
889                  */
890                 uu = ruxp->rux_uu;
891                 su = ruxp->rux_su;
892                 tu = ruxp->rux_tu;
893         } else { /* tu < ruxp->rux_tu */
894                 /*
895                  * What happened here was likely that a laptop, which ran at
896                  * a reduced clock frequency at boot, kicked into high gear.
897                  * The wisdom of spamming this message in that case is
898                  * dubious, but it might also be indicative of something
899                  * serious, so lets keep it and hope laptops can be made
900                  * more truthful about their CPU speed via ACPI.
901                  */
902                 printf("calcru: runtime went backwards from %ju usec "
903                     "to %ju usec for pid %d (%s)\n",
904                     (uintmax_t)ruxp->rux_tu, (uintmax_t)tu,
905                     p->p_pid, p->p_comm);
906                 uu = (tu * ut) / tt;
907                 su = (tu * st) / tt;
908         }
909
910         ruxp->rux_uu = uu;
911         ruxp->rux_su = su;
912         ruxp->rux_tu = tu;
913
914         up->tv_sec = uu / 1000000;
915         up->tv_usec = uu % 1000000;
916         sp->tv_sec = su / 1000000;
917         sp->tv_usec = su % 1000000;
918 }
919
920 #ifndef _SYS_SYSPROTO_H_
921 struct getrusage_args {
922         int     who;
923         struct  rusage *rusage;
924 };
925 #endif
926 int
927 getrusage(td, uap)
928         register struct thread *td;
929         register struct getrusage_args *uap;
930 {
931         struct rusage ru;
932         int error;
933
934         error = kern_getrusage(td, uap->who, &ru);
935         if (error == 0)
936                 error = copyout(&ru, uap->rusage, sizeof(struct rusage));
937         return (error);
938 }
939
940 int
941 kern_getrusage(struct thread *td, int who, struct rusage *rup)
942 {
943         struct proc *p;
944         int error;
945
946         error = 0;
947         p = td->td_proc;
948         PROC_LOCK(p);
949         switch (who) {
950         case RUSAGE_SELF:
951                 rufetchcalc(p, rup, &rup->ru_utime,
952                     &rup->ru_stime);
953                 break;
954
955         case RUSAGE_CHILDREN:
956                 *rup = p->p_stats->p_cru;
957                 calccru(p, &rup->ru_utime, &rup->ru_stime);
958                 break;
959
960         case RUSAGE_THREAD:
961                 PROC_SLOCK(p);
962                 ruxagg(p, td);
963                 PROC_SUNLOCK(p);
964                 thread_lock(td);
965                 *rup = td->td_ru;
966                 calcru1(p, &td->td_rux, &rup->ru_utime, &rup->ru_stime);
967                 thread_unlock(td);
968                 break;
969
970         default:
971                 error = EINVAL;
972         }
973         PROC_UNLOCK(p);
974         return (error);
975 }
976
977 void
978 rucollect(struct rusage *ru, struct rusage *ru2)
979 {
980         long *ip, *ip2;
981         int i;
982
983         if (ru->ru_maxrss < ru2->ru_maxrss)
984                 ru->ru_maxrss = ru2->ru_maxrss;
985         ip = &ru->ru_first;
986         ip2 = &ru2->ru_first;
987         for (i = &ru->ru_last - &ru->ru_first; i >= 0; i--)
988                 *ip++ += *ip2++;
989 }
990
991 void
992 ruadd(struct rusage *ru, struct rusage_ext *rux, struct rusage *ru2,
993     struct rusage_ext *rux2)
994 {
995
996         rux->rux_runtime += rux2->rux_runtime;
997         rux->rux_uticks += rux2->rux_uticks;
998         rux->rux_sticks += rux2->rux_sticks;
999         rux->rux_iticks += rux2->rux_iticks;
1000         rux->rux_uu += rux2->rux_uu;
1001         rux->rux_su += rux2->rux_su;
1002         rux->rux_tu += rux2->rux_tu;
1003         rucollect(ru, ru2);
1004 }
1005
1006 /*
1007  * Aggregate tick counts into the proc's rusage_ext.
1008  */
1009 static void
1010 ruxagg_locked(struct rusage_ext *rux, struct thread *td)
1011 {
1012
1013         THREAD_LOCK_ASSERT(td, MA_OWNED);
1014         PROC_SLOCK_ASSERT(td->td_proc, MA_OWNED);
1015         rux->rux_runtime += td->td_incruntime;
1016         rux->rux_uticks += td->td_uticks;
1017         rux->rux_sticks += td->td_sticks;
1018         rux->rux_iticks += td->td_iticks;
1019 }
1020
1021 void
1022 ruxagg(struct proc *p, struct thread *td)
1023 {
1024
1025         thread_lock(td);
1026         ruxagg_locked(&p->p_rux, td);
1027         ruxagg_locked(&td->td_rux, td);
1028         td->td_incruntime = 0;
1029         td->td_uticks = 0;
1030         td->td_iticks = 0;
1031         td->td_sticks = 0;
1032         thread_unlock(td);
1033 }
1034
1035 /*
1036  * Update the rusage_ext structure and fetch a valid aggregate rusage
1037  * for proc p if storage for one is supplied.
1038  */
1039 void
1040 rufetch(struct proc *p, struct rusage *ru)
1041 {
1042         struct thread *td;
1043
1044         PROC_SLOCK_ASSERT(p, MA_OWNED);
1045
1046         *ru = p->p_ru;
1047         if (p->p_numthreads > 0)  {
1048                 FOREACH_THREAD_IN_PROC(p, td) {
1049                         ruxagg(p, td);
1050                         rucollect(ru, &td->td_ru);
1051                 }
1052         }
1053 }
1054
1055 /*
1056  * Atomically perform a rufetch and a calcru together.
1057  * Consumers, can safely assume the calcru is executed only once
1058  * rufetch is completed.
1059  */
1060 void
1061 rufetchcalc(struct proc *p, struct rusage *ru, struct timeval *up,
1062     struct timeval *sp)
1063 {
1064
1065         PROC_SLOCK(p);
1066         rufetch(p, ru);
1067         calcru(p, up, sp);
1068         PROC_SUNLOCK(p);
1069 }
1070
1071 /*
1072  * Allocate a new resource limits structure and initialize its
1073  * reference count and mutex pointer.
1074  */
1075 struct plimit *
1076 lim_alloc()
1077 {
1078         struct plimit *limp;
1079
1080         limp = malloc(sizeof(struct plimit), M_PLIMIT, M_WAITOK);
1081         refcount_init(&limp->pl_refcnt, 1);
1082         return (limp);
1083 }
1084
1085 struct plimit *
1086 lim_hold(limp)
1087         struct plimit *limp;
1088 {
1089
1090         refcount_acquire(&limp->pl_refcnt);
1091         return (limp);
1092 }
1093
1094 void
1095 lim_fork(struct proc *p1, struct proc *p2)
1096 {
1097         p2->p_limit = lim_hold(p1->p_limit);
1098         callout_init_mtx(&p2->p_limco, &p2->p_mtx, 0);
1099         if (p1->p_cpulimit != RLIM_INFINITY)
1100                 callout_reset(&p2->p_limco, hz, lim_cb, p2);
1101 }
1102
1103 void
1104 lim_free(limp)
1105         struct plimit *limp;
1106 {
1107
1108         KASSERT(limp->pl_refcnt > 0, ("plimit refcnt underflow"));
1109         if (refcount_release(&limp->pl_refcnt))
1110                 free((void *)limp, M_PLIMIT);
1111 }
1112
1113 /*
1114  * Make a copy of the plimit structure.
1115  * We share these structures copy-on-write after fork.
1116  */
1117 void
1118 lim_copy(dst, src)
1119         struct plimit *dst, *src;
1120 {
1121
1122         KASSERT(dst->pl_refcnt == 1, ("lim_copy to shared limit"));
1123         bcopy(src->pl_rlimit, dst->pl_rlimit, sizeof(src->pl_rlimit));
1124 }
1125
1126 /*
1127  * Return the hard limit for a particular system resource.  The
1128  * which parameter specifies the index into the rlimit array.
1129  */
1130 rlim_t
1131 lim_max(struct proc *p, int which)
1132 {
1133         struct rlimit rl;
1134
1135         lim_rlimit(p, which, &rl);
1136         return (rl.rlim_max);
1137 }
1138
1139 /*
1140  * Return the current (soft) limit for a particular system resource.
1141  * The which parameter which specifies the index into the rlimit array
1142  */
1143 rlim_t
1144 lim_cur(struct proc *p, int which)
1145 {
1146         struct rlimit rl;
1147
1148         lim_rlimit(p, which, &rl);
1149         return (rl.rlim_cur);
1150 }
1151
1152 /*
1153  * Return a copy of the entire rlimit structure for the system limit
1154  * specified by 'which' in the rlimit structure pointed to by 'rlp'.
1155  */
1156 void
1157 lim_rlimit(struct proc *p, int which, struct rlimit *rlp)
1158 {
1159
1160         PROC_LOCK_ASSERT(p, MA_OWNED);
1161         KASSERT(which >= 0 && which < RLIM_NLIMITS,
1162             ("request for invalid resource limit"));
1163         *rlp = p->p_limit->pl_rlimit[which];
1164         if (p->p_sysent->sv_fixlimit != NULL)
1165                 p->p_sysent->sv_fixlimit(rlp, which);
1166 }
1167
1168 /*
1169  * Find the uidinfo structure for a uid.  This structure is used to
1170  * track the total resource consumption (process count, socket buffer
1171  * size, etc.) for the uid and impose limits.
1172  */
1173 void
1174 uihashinit()
1175 {
1176
1177         uihashtbl = hashinit(maxproc / 16, M_UIDINFO, &uihash);
1178         rw_init(&uihashtbl_lock, "uidinfo hash");
1179 }
1180
1181 /*
1182  * Look up a uidinfo struct for the parameter uid.
1183  * uihashtbl_lock must be locked.
1184  */
1185 static struct uidinfo *
1186 uilookup(uid)
1187         uid_t uid;
1188 {
1189         struct uihashhead *uipp;
1190         struct uidinfo *uip;
1191
1192         rw_assert(&uihashtbl_lock, RA_LOCKED);
1193         uipp = UIHASH(uid);
1194         LIST_FOREACH(uip, uipp, ui_hash)
1195                 if (uip->ui_uid == uid)
1196                         break;
1197
1198         return (uip);
1199 }
1200
1201 /*
1202  * Find or allocate a struct uidinfo for a particular uid.
1203  * Increase refcount on uidinfo struct returned.
1204  * uifree() should be called on a struct uidinfo when released.
1205  */
1206 struct uidinfo *
1207 uifind(uid)
1208         uid_t uid;
1209 {
1210         struct uidinfo *old_uip, *uip;
1211
1212         rw_rlock(&uihashtbl_lock);
1213         uip = uilookup(uid);
1214         if (uip == NULL) {
1215                 rw_runlock(&uihashtbl_lock);
1216                 uip = malloc(sizeof(*uip), M_UIDINFO, M_WAITOK | M_ZERO);
1217                 rw_wlock(&uihashtbl_lock);
1218                 /*
1219                  * There's a chance someone created our uidinfo while we
1220                  * were in malloc and not holding the lock, so we have to
1221                  * make sure we don't insert a duplicate uidinfo.
1222                  */
1223                 if ((old_uip = uilookup(uid)) != NULL) {
1224                         /* Someone else beat us to it. */
1225                         free(uip, M_UIDINFO);
1226                         uip = old_uip;
1227                 } else {
1228                         refcount_init(&uip->ui_ref, 0);
1229                         uip->ui_uid = uid;
1230                         mtx_init(&uip->ui_vmsize_mtx, "ui_vmsize", NULL,
1231                             MTX_DEF);
1232                         LIST_INSERT_HEAD(UIHASH(uid), uip, ui_hash);
1233                 }
1234         }
1235         uihold(uip);
1236         rw_unlock(&uihashtbl_lock);
1237         return (uip);
1238 }
1239
1240 /*
1241  * Place another refcount on a uidinfo struct.
1242  */
1243 void
1244 uihold(uip)
1245         struct uidinfo *uip;
1246 {
1247
1248         refcount_acquire(&uip->ui_ref);
1249 }
1250
1251 /*-
1252  * Since uidinfo structs have a long lifetime, we use an
1253  * opportunistic refcounting scheme to avoid locking the lookup hash
1254  * for each release.
1255  *
1256  * If the refcount hits 0, we need to free the structure,
1257  * which means we need to lock the hash.
1258  * Optimal case:
1259  *   After locking the struct and lowering the refcount, if we find
1260  *   that we don't need to free, simply unlock and return.
1261  * Suboptimal case:
1262  *   If refcount lowering results in need to free, bump the count
1263  *   back up, lose the lock and acquire the locks in the proper
1264  *   order to try again.
1265  */
1266 void
1267 uifree(uip)
1268         struct uidinfo *uip;
1269 {
1270         int old;
1271
1272         /* Prepare for optimal case. */
1273         old = uip->ui_ref;
1274         if (old > 1 && atomic_cmpset_int(&uip->ui_ref, old, old - 1))
1275                 return;
1276
1277         /* Prepare for suboptimal case. */
1278         rw_wlock(&uihashtbl_lock);
1279         if (refcount_release(&uip->ui_ref)) {
1280                 LIST_REMOVE(uip, ui_hash);
1281                 rw_wunlock(&uihashtbl_lock);
1282                 if (uip->ui_sbsize != 0)
1283                         printf("freeing uidinfo: uid = %d, sbsize = %ld\n",
1284                             uip->ui_uid, uip->ui_sbsize);
1285                 if (uip->ui_proccnt != 0)
1286                         printf("freeing uidinfo: uid = %d, proccnt = %ld\n",
1287                             uip->ui_uid, uip->ui_proccnt);
1288                 if (uip->ui_vmsize != 0)
1289                         printf("freeing uidinfo: uid = %d, swapuse = %lld\n",
1290                             uip->ui_uid, (unsigned long long)uip->ui_vmsize);
1291                 mtx_destroy(&uip->ui_vmsize_mtx);
1292                 free(uip, M_UIDINFO);
1293                 return;
1294         }
1295         /*
1296          * Someone added a reference between atomic_cmpset_int() and
1297          * rw_wlock(&uihashtbl_lock).
1298          */
1299         rw_wunlock(&uihashtbl_lock);
1300 }
1301
1302 /*
1303  * Change the count associated with number of processes
1304  * a given user is using.  When 'max' is 0, don't enforce a limit
1305  */
1306 int
1307 chgproccnt(uip, diff, max)
1308         struct  uidinfo *uip;
1309         int     diff;
1310         rlim_t  max;
1311 {
1312
1313         /* Don't allow them to exceed max, but allow subtraction. */
1314         if (diff > 0 && max != 0) {
1315                 if (atomic_fetchadd_long(&uip->ui_proccnt, (long)diff) + diff > max) {
1316                         atomic_subtract_long(&uip->ui_proccnt, (long)diff);
1317                         return (0);
1318                 }
1319         } else {
1320                 atomic_add_long(&uip->ui_proccnt, (long)diff);
1321                 if (uip->ui_proccnt < 0)
1322                         printf("negative proccnt for uid = %d\n", uip->ui_uid);
1323         }
1324         return (1);
1325 }
1326
1327 /*
1328  * Change the total socket buffer size a user has used.
1329  */
1330 int
1331 chgsbsize(uip, hiwat, to, max)
1332         struct  uidinfo *uip;
1333         u_int  *hiwat;
1334         u_int   to;
1335         rlim_t  max;
1336 {
1337         int diff;
1338
1339         diff = to - *hiwat;
1340         if (diff > 0) {
1341                 if (atomic_fetchadd_long(&uip->ui_sbsize, (long)diff) + diff > max) {
1342                         atomic_subtract_long(&uip->ui_sbsize, (long)diff);
1343                         return (0);
1344                 }
1345         } else {
1346                 atomic_add_long(&uip->ui_sbsize, (long)diff);
1347                 if (uip->ui_sbsize < 0)
1348                         printf("negative sbsize for uid = %d\n", uip->ui_uid);
1349         }
1350         *hiwat = to;
1351         return (1);
1352 }
1353
1354 /*
1355  * Change the count associated with number of pseudo-terminals
1356  * a given user is using.  When 'max' is 0, don't enforce a limit
1357  */
1358 int
1359 chgptscnt(uip, diff, max)
1360         struct  uidinfo *uip;
1361         int     diff;
1362         rlim_t  max;
1363 {
1364
1365         /* Don't allow them to exceed max, but allow subtraction. */
1366         if (diff > 0 && max != 0) {
1367                 if (atomic_fetchadd_long(&uip->ui_ptscnt, (long)diff) + diff > max) {
1368                         atomic_subtract_long(&uip->ui_ptscnt, (long)diff);
1369                         return (0);
1370                 }
1371         } else {
1372                 atomic_add_long(&uip->ui_ptscnt, (long)diff);
1373                 if (uip->ui_ptscnt < 0)
1374                         printf("negative ptscnt for uid = %d\n", uip->ui_uid);
1375         }
1376         return (1);
1377 }