Merge from vendor branch LESS:
[dragonfly.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  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      @(#)kern_resource.c     8.5 (Berkeley) 1/21/94
39  * $FreeBSD: src/sys/kern/kern_resource.c,v 1.55.2.5 2001/11/03 01:41:08 ps Exp $
40  * $DragonFly: src/sys/kern/kern_resource.c,v 1.32 2007/05/03 23:04:31 dillon Exp $
41  */
42
43 #include "opt_compat.h"
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/sysproto.h>
48 #include <sys/file.h>
49 #include <sys/kern_syscall.h>
50 #include <sys/kernel.h>
51 #include <sys/resourcevar.h>
52 #include <sys/malloc.h>
53 #include <sys/proc.h>
54 #include <sys/time.h>
55 #include <sys/lockf.h>
56
57 #include <vm/vm.h>
58 #include <vm/vm_param.h>
59 #include <sys/lock.h>
60 #include <vm/pmap.h>
61 #include <vm/vm_map.h>
62
63 #include <sys/thread2.h>
64
65 static int donice (struct proc *chgp, int n);
66
67 static MALLOC_DEFINE(M_UIDINFO, "uidinfo", "uidinfo structures");
68 #define UIHASH(uid)     (&uihashtbl[(uid) & uihash])
69 static LIST_HEAD(uihashhead, uidinfo) *uihashtbl;
70 static u_long uihash;           /* size of hash table - 1 */
71
72 static struct uidinfo   *uicreate (uid_t uid);
73 static struct uidinfo   *uilookup (uid_t uid);
74
75 /*
76  * Resource controls and accounting.
77  */
78
79 struct getpriority_info {
80         int low;
81         int who;
82 };
83
84 static int getpriority_callback(struct proc *p, void *data);
85
86 int
87 sys_getpriority(struct getpriority_args *uap)
88 {
89         struct getpriority_info info;
90         struct proc *curp = curproc;
91         struct proc *p;
92         int low = PRIO_MAX + 1;
93
94         switch (uap->which) {
95         case PRIO_PROCESS:
96                 if (uap->who == 0)
97                         p = curp;
98                 else
99                         p = pfind(uap->who);
100                 if (p == 0)
101                         break;
102                 if (!PRISON_CHECK(curp->p_ucred, p->p_ucred))
103                         break;
104                 low = p->p_nice;
105                 break;
106
107         case PRIO_PGRP: 
108         {
109                 struct pgrp *pg;
110
111                 if (uap->who == 0)
112                         pg = curp->p_pgrp;
113                 else if ((pg = pgfind(uap->who)) == NULL)
114                         break;
115                 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
116                         if ((PRISON_CHECK(curp->p_ucred, p->p_ucred) && p->p_nice < low))
117                                 low = p->p_nice;
118                 }
119                 break;
120         }
121         case PRIO_USER:
122                 if (uap->who == 0)
123                         uap->who = curp->p_ucred->cr_uid;
124                 info.low = low;
125                 info.who = uap->who;
126                 allproc_scan(getpriority_callback, &info);
127                 low = info.low;
128                 break;
129
130         default:
131                 return (EINVAL);
132         }
133         if (low == PRIO_MAX + 1)
134                 return (ESRCH);
135         uap->sysmsg_result = low;
136         return (0);
137 }
138
139 /*
140  * Figure out the current lowest nice priority for processes owned
141  * by the specified user.
142  */
143 static
144 int
145 getpriority_callback(struct proc *p, void *data)
146 {
147         struct getpriority_info *info = data;
148
149         if (PRISON_CHECK(curproc->p_ucred, p->p_ucred) &&
150             p->p_ucred->cr_uid == info->who &&
151             p->p_nice < info->low) {
152                 info->low = p->p_nice;
153         }
154         return(0);
155 }
156
157 struct setpriority_info {
158         int prio;
159         int who;
160         int error;
161         int found;
162 };
163
164 static int setpriority_callback(struct proc *p, void *data);
165
166 int
167 sys_setpriority(struct setpriority_args *uap)
168 {
169         struct setpriority_info info;
170         struct proc *curp = curproc;
171         struct proc *p;
172         int found = 0, error = 0;
173
174         switch (uap->which) {
175         case PRIO_PROCESS:
176                 if (uap->who == 0)
177                         p = curp;
178                 else
179                         p = pfind(uap->who);
180                 if (p == 0)
181                         break;
182                 if (!PRISON_CHECK(curp->p_ucred, p->p_ucred))
183                         break;
184                 error = donice(p, uap->prio);
185                 found++;
186                 break;
187
188         case PRIO_PGRP: 
189         {
190                 struct pgrp *pg;
191
192                 if (uap->who == 0)
193                         pg = curp->p_pgrp;
194                 else if ((pg = pgfind(uap->who)) == NULL)
195                         break;
196                 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
197                         if (PRISON_CHECK(curp->p_ucred, p->p_ucred)) {
198                                 error = donice(p, uap->prio);
199                                 found++;
200                         }
201                 }
202                 break;
203         }
204         case PRIO_USER:
205                 if (uap->who == 0)
206                         uap->who = curp->p_ucred->cr_uid;
207                 info.prio = uap->prio;
208                 info.who = uap->who;
209                 info.error = 0;
210                 info.found = 0;
211                 allproc_scan(setpriority_callback, &info);
212                 error = info.error;
213                 found = info.found;
214                 break;
215
216         default:
217                 return (EINVAL);
218         }
219         if (found == 0)
220                 return (ESRCH);
221         return (error);
222 }
223
224 static
225 int
226 setpriority_callback(struct proc *p, void *data)
227 {
228         struct setpriority_info *info = data;
229         int error;
230
231         if (p->p_ucred->cr_uid == info->who &&
232             PRISON_CHECK(curproc->p_ucred, p->p_ucred)) {
233                 error = donice(p, info->prio);
234                 if (error)
235                         info->error = error;
236                 ++info->found;
237         }
238         return(0);
239 }
240
241 static int
242 donice(struct proc *chgp, int n)
243 {
244         struct proc *curp = curproc;
245         struct ucred *cr = curp->p_ucred;
246         struct lwp *lp;
247
248         if (cr->cr_uid && cr->cr_ruid &&
249             cr->cr_uid != chgp->p_ucred->cr_uid &&
250             cr->cr_ruid != chgp->p_ucred->cr_uid)
251                 return (EPERM);
252         if (n > PRIO_MAX)
253                 n = PRIO_MAX;
254         if (n < PRIO_MIN)
255                 n = PRIO_MIN;
256         if (n < chgp->p_nice && suser_cred(cr, 0))
257                 return (EACCES);
258         chgp->p_nice = n;
259         FOREACH_LWP_IN_PROC(lp, chgp)
260                 chgp->p_usched->resetpriority(lp);
261         return (0);
262 }
263
264 int
265 sys_lwp_rtprio(struct lwp_rtprio_args *uap)
266 {
267         struct proc *p = curproc;
268         struct lwp *lp;
269         struct rtprio rtp;
270         struct ucred *cr = p->p_ucred;
271         int error;
272
273         error = copyin(uap->rtp, &rtp, sizeof(struct rtprio));
274         if (error)
275                 return error;
276
277         if (uap->pid < 0) {
278                 return EINVAL;
279         } else if (uap->pid == 0) {
280                 /* curproc already loaded on p */
281         } else {
282                 p = pfind(uap->pid);
283         }
284
285         if (p == 0) {
286                 return ESRCH;
287         }
288
289         if (uap->tid < -1) {
290                 return EINVAL;
291         } else if (uap->tid == -1) {
292                 /*
293                  * sadly, tid can be 0 so we can't use 0 here
294                  * like sys_rtprio()
295                  */
296                 lp = curthread->td_lwp;
297         } else {
298                 FOREACH_LWP_IN_PROC(lp, p) {
299                         if (lp->lwp_tid == uap->tid) {
300                                 break;
301                         }
302                 }
303                 if (!lp) {
304                         return ESRCH;
305                 }
306         }
307
308         switch (uap->function) {
309         case RTP_LOOKUP:
310                 return (copyout(&lp->lwp_rtprio, uap->rtp,
311                                 sizeof(struct rtprio)));
312         case RTP_SET:
313                 if (cr->cr_uid && cr->cr_ruid &&
314                     cr->cr_uid != p->p_ucred->cr_uid &&
315                     cr->cr_ruid != p->p_ucred->cr_uid) {
316                         return EPERM;
317                 }
318                 /* disallow setting rtprio in most cases if not superuser */
319                 if (suser_cred(cr, 0)) {
320                         /* can't set someone else's */
321                         if (uap->pid) { /* XXX */
322                                 return EPERM;
323                         }
324                         /* can't set realtime priority */
325 /*
326  * Realtime priority has to be restricted for reasons which should be
327  * obvious. However, for idle priority, there is a potential for
328  * system deadlock if an idleprio process gains a lock on a resource
329  * that other processes need (and the idleprio process can't run
330  * due to a CPU-bound normal process). Fix me! XXX
331  */
332                         if (RTP_PRIO_IS_REALTIME(rtp.type)) {
333                                 return EPERM;
334                         }
335                 }
336                 switch (rtp.type) {
337 #ifdef RTP_PRIO_FIFO
338                 case RTP_PRIO_FIFO:
339 #endif
340                 case RTP_PRIO_REALTIME:
341                 case RTP_PRIO_NORMAL:
342                 case RTP_PRIO_IDLE:
343                         if (rtp.prio > RTP_PRIO_MAX)
344                                 return EINVAL;
345                         lp->lwp_rtprio = rtp;
346                         return 0;
347                 default:
348                         return EINVAL;
349                 }
350         default:
351                 return EINVAL;
352         }
353         panic("can't get here");
354 }
355
356 /*
357  * Set realtime priority
358  */
359 /* ARGSUSED */
360 int
361 sys_rtprio(struct rtprio_args *uap)
362 {
363         struct proc *curp = curproc;
364         struct proc *p;
365         struct lwp *lp;
366         struct ucred *cr = curp->p_ucred;
367         struct rtprio rtp;
368         int error;
369
370         error = copyin(uap->rtp, &rtp, sizeof(struct rtprio));
371         if (error)
372                 return (error);
373
374         if (uap->pid == 0)
375                 p = curp;
376         else
377                 p = pfind(uap->pid);
378
379         if (p == 0)
380                 return (ESRCH);
381
382         /* XXX lwp */
383         lp = FIRST_LWP_IN_PROC(p);
384         switch (uap->function) {
385         case RTP_LOOKUP:
386                 return (copyout(&lp->lwp_rtprio, uap->rtp, sizeof(struct rtprio)));
387         case RTP_SET:
388                 if (cr->cr_uid && cr->cr_ruid &&
389                     cr->cr_uid != p->p_ucred->cr_uid &&
390                     cr->cr_ruid != p->p_ucred->cr_uid)
391                         return (EPERM);
392                 /* disallow setting rtprio in most cases if not superuser */
393                 if (suser_cred(cr, 0)) {
394                         /* can't set someone else's */
395                         if (uap->pid)
396                                 return (EPERM);
397                         /* can't set realtime priority */
398 /*
399  * Realtime priority has to be restricted for reasons which should be
400  * obvious. However, for idle priority, there is a potential for
401  * system deadlock if an idleprio process gains a lock on a resource
402  * that other processes need (and the idleprio process can't run
403  * due to a CPU-bound normal process). Fix me! XXX
404  */
405                         if (RTP_PRIO_IS_REALTIME(rtp.type))
406                                 return (EPERM);
407                 }
408                 switch (rtp.type) {
409 #ifdef RTP_PRIO_FIFO
410                 case RTP_PRIO_FIFO:
411 #endif
412                 case RTP_PRIO_REALTIME:
413                 case RTP_PRIO_NORMAL:
414                 case RTP_PRIO_IDLE:
415                         if (rtp.prio > RTP_PRIO_MAX)
416                                 return (EINVAL);
417                         lp->lwp_rtprio = rtp;
418                         return (0);
419                 default:
420                         return (EINVAL);
421                 }
422
423         default:
424                 return (EINVAL);
425         }
426 }
427
428 int
429 sys_setrlimit(struct __setrlimit_args *uap)
430 {
431         struct rlimit alim;
432         int error;
433
434         error = copyin(uap->rlp, &alim, sizeof(alim));
435         if (error)
436                 return (error);
437
438         error = kern_setrlimit(uap->which, &alim);
439
440         return (error);
441 }
442
443 int
444 sys_getrlimit(struct __getrlimit_args *uap)
445 {
446         struct rlimit lim;
447         int error;
448
449         error = kern_getrlimit(uap->which, &lim);
450
451         if (error == 0)
452                 error = copyout(&lim, uap->rlp, sizeof(*uap->rlp));
453         return error;
454 }
455
456 /*
457  * Transform the running time and tick information in lwp lp's thread into user,
458  * system, and interrupt time usage.
459  *
460  * Since we are limited to statclock tick granularity this is a statisical
461  * calculation which will be correct over the long haul, but should not be
462  * expected to measure fine grained deltas.
463  */
464 void
465 calcru(struct lwp *lp, struct timeval *up, struct timeval *sp)
466 {
467         struct thread *td = lp->lwp_thread;
468
469         /*
470          * Calculate at the statclock level.  YYY if the thread is owned by
471          * another cpu we need to forward the request to the other cpu, or
472          * have a token to interlock the information.
473          */
474         crit_enter();
475         up->tv_sec = td->td_uticks / 1000000;
476         up->tv_usec = td->td_uticks % 1000000;
477         sp->tv_sec = td->td_sticks / 1000000;
478         sp->tv_usec = td->td_sticks % 1000000;
479         crit_exit();
480 }
481
482 /*
483  * Aggregate resource statistics of all lwps of a process.
484  *
485  * proc.p_ru keeps track of all statistics directly related to a proc.  This
486  * consists of RSS usage and nswap information and aggregate numbers for all
487  * former lwps of this proc.
488  *
489  * proc.p_cru is the sum of all stats of reaped children.
490  *
491  * lwp.lwp_ru contains the stats directly related to one specific lwp, meaning
492  * packet, scheduler switch or page fault counts, etc.  This information gets
493  * added to lwp.lwp_proc.p_ru when the lwp exits.
494  */
495 void
496 calcru_proc(struct proc *p, struct rusage *ru)
497 {
498         struct timeval upt, spt;
499         long *rip1, *rip2;
500         struct lwp *lp;
501
502         *ru = p->p_ru;
503
504         FOREACH_LWP_IN_PROC(lp, p) {
505                 calcru(lp, &upt, &spt);
506                 timevaladd(&ru->ru_utime, &upt);
507                 timevaladd(&ru->ru_stime, &spt);
508                 for (rip1 = &ru->ru_first, rip2 = &lp->lwp_ru.ru_first;
509                      rip1 <= &ru->ru_last;
510                      rip1++, rip2++)
511                         *rip1 += *rip2;
512         }
513 }
514
515
516 /* ARGSUSED */
517 int
518 sys_getrusage(struct getrusage_args *uap)
519 {
520         struct rusage ru;
521         struct rusage *rup;
522
523         switch (uap->who) {
524
525         case RUSAGE_SELF:
526                 rup = &ru;
527                 calcru_proc(curproc, rup);
528                 break;
529
530         case RUSAGE_CHILDREN:
531                 rup = &curproc->p_cru;
532                 break;
533
534         default:
535                 return (EINVAL);
536         }
537         return (copyout((caddr_t)rup, (caddr_t)uap->rusage,
538             sizeof (struct rusage)));
539 }
540
541 void
542 ruadd(struct rusage *ru, struct rusage *ru2)
543 {
544         long *ip, *ip2;
545         int i;
546
547         timevaladd(&ru->ru_utime, &ru2->ru_utime);
548         timevaladd(&ru->ru_stime, &ru2->ru_stime);
549         if (ru->ru_maxrss < ru2->ru_maxrss)
550                 ru->ru_maxrss = ru2->ru_maxrss;
551         ip = &ru->ru_first; ip2 = &ru2->ru_first;
552         for (i = &ru->ru_last - &ru->ru_first; i >= 0; i--)
553                 *ip++ += *ip2++;
554 }
555
556 /*
557  * Find the uidinfo structure for a uid.  This structure is used to
558  * track the total resource consumption (process count, socket buffer
559  * size, etc.) for the uid and impose limits.
560  */
561 void
562 uihashinit(void)
563 {
564         uihashtbl = hashinit(maxproc / 16, M_UIDINFO, &uihash);
565 }
566
567 static struct uidinfo *
568 uilookup(uid_t uid)
569 {
570         struct  uihashhead *uipp;
571         struct  uidinfo *uip;
572
573         uipp = UIHASH(uid);
574         LIST_FOREACH(uip, uipp, ui_hash) {
575                 if (uip->ui_uid == uid)
576                         break;
577         }
578         return (uip);
579 }
580
581 static struct uidinfo *
582 uicreate(uid_t uid)
583 {
584         struct  uidinfo *uip, *norace;
585
586         /*
587          * Allocate space and check for a race
588          */
589         MALLOC(uip, struct uidinfo *, sizeof(*uip), M_UIDINFO, M_WAITOK);
590         norace = uilookup(uid);
591         if (norace != NULL) {
592                 FREE(uip, M_UIDINFO);
593                 return (norace);
594         }
595
596         /*
597          * Initialize structure and enter it into the hash table
598          */
599         LIST_INSERT_HEAD(UIHASH(uid), uip, ui_hash);
600         uip->ui_uid = uid;
601         uip->ui_proccnt = 0;
602         uip->ui_sbsize = 0;
603         uip->ui_ref = 0;
604         uip->ui_posixlocks = 0;
605         varsymset_init(&uip->ui_varsymset, NULL);
606         return (uip);
607 }
608
609 struct uidinfo *
610 uifind(uid_t uid)
611 {
612         struct  uidinfo *uip;
613
614         uip = uilookup(uid);
615         if (uip == NULL)
616                 uip = uicreate(uid);
617         uip->ui_ref++;
618         return (uip);
619 }
620
621 static __inline void
622 uifree(struct uidinfo *uip)
623 {
624         if (uip->ui_sbsize != 0)
625                 /* XXX no %qd in kernel.  Truncate. */
626                 kprintf("freeing uidinfo: uid = %d, sbsize = %ld\n",
627                     uip->ui_uid, (long)uip->ui_sbsize);
628         if (uip->ui_proccnt != 0)
629                 kprintf("freeing uidinfo: uid = %d, proccnt = %ld\n",
630                     uip->ui_uid, uip->ui_proccnt);
631         LIST_REMOVE(uip, ui_hash);
632         varsymset_clean(&uip->ui_varsymset);
633         FREE(uip, M_UIDINFO);
634 }
635
636 void
637 uihold(struct uidinfo *uip)
638 {
639         ++uip->ui_ref;
640         KKASSERT(uip->ui_ref > 0);
641 }
642
643 void
644 uidrop(struct uidinfo *uip)
645 {
646         KKASSERT(uip->ui_ref > 0);
647         if (--uip->ui_ref == 0)
648                 uifree(uip);
649 }
650
651 void
652 uireplace(struct uidinfo **puip, struct uidinfo *nuip)
653 {
654         uidrop(*puip);
655         *puip = nuip;
656 }
657
658 /*
659  * Change the count associated with number of processes
660  * a given user is using.  When 'max' is 0, don't enforce a limit
661  */
662 int
663 chgproccnt(struct uidinfo *uip, int diff, int max)
664 {
665         /* don't allow them to exceed max, but allow subtraction */
666         if (diff > 0 && uip->ui_proccnt + diff > max && max != 0)
667                 return (0);
668         uip->ui_proccnt += diff;
669         if (uip->ui_proccnt < 0)
670                 kprintf("negative proccnt for uid = %d\n", uip->ui_uid);
671         return (1);
672 }
673
674 /*
675  * Change the total socket buffer size a user has used.
676  */
677 int
678 chgsbsize(struct uidinfo *uip, u_long *hiwat, u_long to, rlim_t max)
679 {
680         rlim_t new;
681
682         crit_enter();
683         new = uip->ui_sbsize + to - *hiwat;
684         /* don't allow them to exceed max, but allow subtraction */
685         if (to > *hiwat && new > max) {
686                 crit_exit();
687                 return (0);
688         }
689         uip->ui_sbsize = new;
690         *hiwat = to;
691         if (uip->ui_sbsize < 0)
692                 kprintf("negative sbsize for uid = %d\n", uip->ui_uid);
693         crit_exit();
694         return (1);
695 }
696