45035fe4e953363cb9c4e678fe7400033006e2b9
[dragonfly.git] / sys / kern / sys_generic.c
1 /*
2  * Copyright (c) 1982, 1986, 1989, 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  *      @(#)sys_generic.c       8.5 (Berkeley) 1/21/94
39  * $FreeBSD: src/sys/kern/sys_generic.c,v 1.55.2.10 2001/03/17 10:39:32 peter Exp $
40  * $DragonFly: src/sys/kern/sys_generic.c,v 1.7 2003/07/24 01:41:25 dillon Exp $
41  */
42
43 #include "opt_ktrace.h"
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/sysproto.h>
48 #include <sys/filedesc.h>
49 #include <sys/filio.h>
50 #include <sys/fcntl.h>
51 #include <sys/file.h>
52 #include <sys/proc.h>
53 #include <sys/signalvar.h>
54 #include <sys/socketvar.h>
55 #include <sys/uio.h>
56 #include <sys/kernel.h>
57 #include <sys/malloc.h>
58 #include <sys/poll.h>
59 #include <sys/resourcevar.h>
60 #include <sys/sysctl.h>
61 #include <sys/sysent.h>
62 #include <sys/buf.h>
63 #ifdef KTRACE
64 #include <sys/ktrace.h>
65 #endif
66 #include <vm/vm.h>
67 #include <vm/vm_page.h>
68 #include <sys/file2.h>
69
70 #include <machine/limits.h>
71
72 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
73 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
74 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
75
76 static int      pollscan __P((struct proc *, struct pollfd *, u_int));
77 static int      selscan __P((struct proc *, fd_mask **, fd_mask **, int));
78 static int      dofileread __P((struct file *, int, void *,
79                     size_t, off_t, int));
80 static int      dofilewrite __P((struct file *, int,
81                     const void *, size_t, off_t, int));
82
83 struct file*
84 holdfp(fdp, fd, flag)
85         struct filedesc* fdp;
86         int fd, flag;
87 {
88         struct file* fp;
89
90         if (((u_int)fd) >= fdp->fd_nfiles ||
91             (fp = fdp->fd_ofiles[fd]) == NULL ||
92             (fp->f_flag & flag) == 0) {
93                 return (NULL);
94         }
95         fhold(fp);
96         return (fp);
97 }
98
99 /*
100  * Read system call.
101  */
102 int
103 read(struct read_args *uap)
104 {
105         struct thread *td = curthread;
106         struct proc *p = td->td_proc;
107         struct file *fp;
108         int error;
109
110         KKASSERT(p);
111         if ((fp = holdfp(p->p_fd, uap->fd, FREAD)) == NULL)
112                 return (EBADF);
113         error = dofileread(fp, uap->fd, uap->buf, uap->nbyte, (off_t)-1, 0);
114         fdrop(fp, td);
115         return(error);
116 }
117
118 /*
119  * Pread system call
120  */
121 int
122 pread(struct pread_args *uap)
123 {
124         struct thread *td = curthread;
125         struct proc *p = td->td_proc;
126         struct file *fp;
127         int error;
128
129         KKASSERT(p);
130         if ((fp = holdfp(p->p_fd, uap->fd, FREAD)) == NULL)
131                 return (EBADF);
132         if (fp->f_type != DTYPE_VNODE) {
133                 error = ESPIPE;
134         } else {
135             error = dofileread(fp, uap->fd, uap->buf, uap->nbyte, 
136                 uap->offset, FOF_OFFSET);
137         }
138         fdrop(fp, td);
139         return(error);
140 }
141
142 /*
143  * Code common for read and pread
144  */
145 int
146 dofileread(fp, fd, buf, nbyte, offset, flags)
147         struct file *fp;
148         int fd, flags;
149         void *buf;
150         size_t nbyte;
151         off_t offset;
152 {
153         struct thread *td = curthread;
154         struct proc *p = td->td_proc;
155         struct uio auio;
156         struct iovec aiov;
157         long cnt, error = 0;
158 #ifdef KTRACE
159         struct iovec ktriov;
160         struct uio ktruio;
161         int didktr = 0;
162 #endif
163
164         aiov.iov_base = (caddr_t)buf;
165         aiov.iov_len = nbyte;
166         auio.uio_iov = &aiov;
167         auio.uio_iovcnt = 1;
168         auio.uio_offset = offset;
169         if (nbyte > INT_MAX)
170                 return (EINVAL);
171         auio.uio_resid = nbyte;
172         auio.uio_rw = UIO_READ;
173         auio.uio_segflg = UIO_USERSPACE;
174         auio.uio_td = td;
175 #ifdef KTRACE
176         /*
177          * if tracing, save a copy of iovec
178          */
179         if (KTRPOINT(td, KTR_GENIO)) {
180                 ktriov = aiov;
181                 ktruio = auio;
182                 didktr = 1;
183         }
184 #endif
185         cnt = nbyte;
186
187         if ((error = fo_read(fp, &auio, fp->f_cred, flags, td))) {
188                 if (auio.uio_resid != cnt && (error == ERESTART ||
189                     error == EINTR || error == EWOULDBLOCK))
190                         error = 0;
191         }
192         cnt -= auio.uio_resid;
193 #ifdef KTRACE
194         if (didktr && error == 0) {
195                 ktruio.uio_iov = &ktriov;
196                 ktruio.uio_resid = cnt;
197                 ktrgenio(p->p_tracep, fd, UIO_READ, &ktruio, error);
198         }
199 #endif
200         p->p_retval[0] = cnt;
201         return (error);
202 }
203
204 /*
205  * Scatter read system call.
206  */
207 int
208 readv(struct readv_args *uap)
209 {
210         struct thread *td = curthread;
211         struct proc *p = td->td_proc;
212         struct file *fp;
213         struct filedesc *fdp = p->p_fd;
214         struct uio auio;
215         struct iovec *iov;
216         struct iovec *needfree;
217         struct iovec aiov[UIO_SMALLIOV];
218         long i, cnt, error = 0;
219         u_int iovlen;
220 #ifdef KTRACE
221         struct iovec *ktriov = NULL;
222         struct uio ktruio;
223 #endif
224
225         if ((fp = holdfp(fdp, uap->fd, FREAD)) == NULL)
226                 return (EBADF);
227         /* note: can't use iovlen until iovcnt is validated */
228         iovlen = uap->iovcnt * sizeof (struct iovec);
229         if (uap->iovcnt > UIO_SMALLIOV) {
230                 if (uap->iovcnt > UIO_MAXIOV)
231                         return (EINVAL);
232                 MALLOC(iov, struct iovec *, iovlen, M_IOV, M_WAITOK);
233                 needfree = iov;
234         } else {
235                 iov = aiov;
236                 needfree = NULL;
237         }
238         auio.uio_iov = iov;
239         auio.uio_iovcnt = uap->iovcnt;
240         auio.uio_rw = UIO_READ;
241         auio.uio_segflg = UIO_USERSPACE;
242         auio.uio_td = td;
243         auio.uio_offset = -1;
244         if ((error = copyin((caddr_t)uap->iovp, (caddr_t)iov, iovlen)))
245                 goto done;
246         auio.uio_resid = 0;
247         for (i = 0; i < uap->iovcnt; i++) {
248                 if (iov->iov_len > INT_MAX - auio.uio_resid) {
249                         error = EINVAL;
250                         goto done;
251                 }
252                 auio.uio_resid += iov->iov_len;
253                 iov++;
254         }
255 #ifdef KTRACE
256         /*
257          * if tracing, save a copy of iovec
258          */
259         if (KTRPOINT(td, KTR_GENIO))  {
260                 MALLOC(ktriov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
261                 bcopy((caddr_t)auio.uio_iov, (caddr_t)ktriov, iovlen);
262                 ktruio = auio;
263         }
264 #endif
265         cnt = auio.uio_resid;
266         if ((error = fo_read(fp, &auio, fp->f_cred, 0, td))) {
267                 if (auio.uio_resid != cnt && (error == ERESTART ||
268                     error == EINTR || error == EWOULDBLOCK))
269                         error = 0;
270         }
271         cnt -= auio.uio_resid;
272 #ifdef KTRACE
273         if (ktriov != NULL) {
274                 if (error == 0) {
275                         ktruio.uio_iov = ktriov;
276                         ktruio.uio_resid = cnt;
277                         ktrgenio(p->p_tracep, uap->fd, UIO_READ, &ktruio,
278                             error);
279                 }
280                 FREE(ktriov, M_TEMP);
281         }
282 #endif
283         p->p_retval[0] = cnt;
284 done:
285         fdrop(fp, td);
286         if (needfree)
287                 FREE(needfree, M_IOV);
288         return (error);
289 }
290
291 /*
292  * Write system call
293  */
294 int
295 write(struct write_args *uap)
296 {
297         struct thread *td = curthread;
298         struct proc *p = td->td_proc;
299         struct file *fp;
300         int error;
301
302         KKASSERT(p);
303
304         if ((fp = holdfp(p->p_fd, uap->fd, FWRITE)) == NULL)
305                 return (EBADF);
306         error = dofilewrite(fp, uap->fd, uap->buf, uap->nbyte, (off_t)-1, 0);
307         fdrop(fp, td);
308         return(error);
309 }
310
311 /*
312  * Pwrite system call
313  */
314 int
315 pwrite(struct pwrite_args *uap)
316 {
317         struct thread *td = curthread;
318         struct proc *p = td->td_proc;
319         struct file *fp;
320         int error;
321
322         KKASSERT(p);
323         if ((fp = holdfp(p->p_fd, uap->fd, FWRITE)) == NULL)
324                 return (EBADF);
325         if (fp->f_type != DTYPE_VNODE) {
326                 error = ESPIPE;
327         } else {
328             error = dofilewrite(fp, uap->fd, uap->buf, uap->nbyte,
329                 uap->offset, FOF_OFFSET);
330         }
331         fdrop(fp, td);
332         return(error);
333 }
334
335 static int
336 dofilewrite(
337         struct file *fp,
338         int fd,
339         const void *buf,
340         size_t nbyte,
341         off_t offset,
342         int flags
343 ) {
344         struct thread *td = curthread;
345         struct proc *p = td->td_proc;
346         struct uio auio;
347         struct iovec aiov;
348         long cnt, error = 0;
349 #ifdef KTRACE
350         struct iovec ktriov;
351         struct uio ktruio;
352         int didktr = 0;
353 #endif
354
355         aiov.iov_base = (void *)(uintptr_t)buf;
356         aiov.iov_len = nbyte;
357         auio.uio_iov = &aiov;
358         auio.uio_iovcnt = 1;
359         auio.uio_offset = offset;
360         if (nbyte > INT_MAX)
361                 return (EINVAL);
362         auio.uio_resid = nbyte;
363         auio.uio_rw = UIO_WRITE;
364         auio.uio_segflg = UIO_USERSPACE;
365         auio.uio_td = td;
366 #ifdef KTRACE
367         /*
368          * if tracing, save a copy of iovec and uio
369          */
370         if (KTRPOINT(td, KTR_GENIO)) {
371                 ktriov = aiov;
372                 ktruio = auio;
373                 didktr = 1;
374         }
375 #endif
376         cnt = nbyte;
377         if (fp->f_type == DTYPE_VNODE)
378                 bwillwrite();
379         if ((error = fo_write(fp, &auio, fp->f_cred, flags, td))) {
380                 if (auio.uio_resid != cnt && (error == ERESTART ||
381                     error == EINTR || error == EWOULDBLOCK))
382                         error = 0;
383                 if (error == EPIPE)
384                         psignal(p, SIGPIPE);
385         }
386         cnt -= auio.uio_resid;
387 #ifdef KTRACE
388         if (didktr && error == 0) {
389                 ktruio.uio_iov = &ktriov;
390                 ktruio.uio_resid = cnt;
391                 ktrgenio(p->p_tracep, fd, UIO_WRITE, &ktruio, error);
392         }
393 #endif
394         p->p_retval[0] = cnt;
395         return (error);
396 }
397
398 /*
399  * Gather write system call
400  */
401 int
402 writev(struct writev_args *uap)
403 {
404         struct thread *td = curthread;
405         struct proc *p = td->td_proc;
406         struct file *fp;
407         struct filedesc *fdp;
408         struct uio auio;
409         struct iovec *iov;
410         struct iovec *needfree;
411         struct iovec aiov[UIO_SMALLIOV];
412         long i, cnt, error = 0;
413         u_int iovlen;
414 #ifdef KTRACE
415         struct iovec *ktriov = NULL;
416         struct uio ktruio;
417 #endif
418
419         KKASSERT(p);
420         fdp = p->p_fd;
421
422         if ((fp = holdfp(fdp, uap->fd, FWRITE)) == NULL)
423                 return (EBADF);
424         /* note: can't use iovlen until iovcnt is validated */
425         iovlen = uap->iovcnt * sizeof (struct iovec);
426         if (uap->iovcnt > UIO_SMALLIOV) {
427                 if (uap->iovcnt > UIO_MAXIOV) {
428                         needfree = NULL;
429                         error = EINVAL;
430                         goto done;
431                 }
432                 MALLOC(iov, struct iovec *, iovlen, M_IOV, M_WAITOK);
433                 needfree = iov;
434         } else {
435                 iov = aiov;
436                 needfree = NULL;
437         }
438         auio.uio_iov = iov;
439         auio.uio_iovcnt = uap->iovcnt;
440         auio.uio_rw = UIO_WRITE;
441         auio.uio_segflg = UIO_USERSPACE;
442         auio.uio_td = td;
443         auio.uio_offset = -1;
444         if ((error = copyin((caddr_t)uap->iovp, (caddr_t)iov, iovlen)))
445                 goto done;
446         auio.uio_resid = 0;
447         for (i = 0; i < uap->iovcnt; i++) {
448                 if (iov->iov_len > INT_MAX - auio.uio_resid) {
449                         error = EINVAL;
450                         goto done;
451                 }
452                 auio.uio_resid += iov->iov_len;
453                 iov++;
454         }
455 #ifdef KTRACE
456         /*
457          * if tracing, save a copy of iovec and uio
458          */
459         if (KTRPOINT(td, KTR_GENIO))  {
460                 MALLOC(ktriov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
461                 bcopy((caddr_t)auio.uio_iov, (caddr_t)ktriov, iovlen);
462                 ktruio = auio;
463         }
464 #endif
465         cnt = auio.uio_resid;
466         if (fp->f_type == DTYPE_VNODE)
467                 bwillwrite();
468         if ((error = fo_write(fp, &auio, fp->f_cred, 0, td))) {
469                 if (auio.uio_resid != cnt && (error == ERESTART ||
470                     error == EINTR || error == EWOULDBLOCK))
471                         error = 0;
472                 if (error == EPIPE)
473                         psignal(p, SIGPIPE);
474         }
475         cnt -= auio.uio_resid;
476 #ifdef KTRACE
477         if (ktriov != NULL) {
478                 if (error == 0) {
479                         ktruio.uio_iov = ktriov;
480                         ktruio.uio_resid = cnt;
481                         ktrgenio(p->p_tracep, uap->fd, UIO_WRITE, &ktruio,
482                             error);
483                 }
484                 FREE(ktriov, M_TEMP);
485         }
486 #endif
487         p->p_retval[0] = cnt;
488 done:
489         fdrop(fp, td);
490         if (needfree)
491                 FREE(needfree, M_IOV);
492         return (error);
493 }
494
495 /*
496  * Ioctl system call
497  */
498 /* ARGSUSED */
499 int
500 ioctl(struct ioctl_args *uap)
501 {
502         struct thread *td = curthread;
503         struct proc *p = td->td_proc;
504         struct file *fp;
505         struct filedesc *fdp;
506         u_long com;
507         int error;
508         register u_int size;
509         caddr_t data, memp;
510         int tmp;
511 #define STK_PARAMS      128
512         union {
513             char stkbuf[STK_PARAMS];
514             long align;
515         } ubuf;
516
517         KKASSERT(p);
518         fdp = p->p_fd;
519         if ((u_int)uap->fd >= fdp->fd_nfiles ||
520             (fp = fdp->fd_ofiles[uap->fd]) == NULL)
521                 return (EBADF);
522
523         if ((fp->f_flag & (FREAD | FWRITE)) == 0)
524                 return (EBADF);
525
526         switch (com = uap->com) {
527         case FIONCLEX:
528                 fdp->fd_ofileflags[uap->fd] &= ~UF_EXCLOSE;
529                 return (0);
530         case FIOCLEX:
531                 fdp->fd_ofileflags[uap->fd] |= UF_EXCLOSE;
532                 return (0);
533         }
534
535         /*
536          * Interpret high order word to find amount of data to be
537          * copied to/from the user's address space.
538          */
539         size = IOCPARM_LEN(com);
540         if (size > IOCPARM_MAX)
541                 return (ENOTTY);
542
543         fhold(fp);
544
545         memp = NULL;
546         if (size > sizeof (ubuf.stkbuf)) {
547                 memp = (caddr_t)malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
548                 data = memp;
549         } else {
550                 data = ubuf.stkbuf;
551         }
552         if (com&IOC_IN) {
553                 if (size) {
554                         error = copyin(uap->data, data, (u_int)size);
555                         if (error) {
556                                 if (memp)
557                                         free(memp, M_IOCTLOPS);
558                                 fdrop(fp, td);
559                                 return (error);
560                         }
561                 } else {
562                         *(caddr_t *)data = uap->data;
563                 }
564         } else if ((com&IOC_OUT) && size) {
565                 /*
566                  * Zero the buffer so the user always
567                  * gets back something deterministic.
568                  */
569                 bzero(data, size);
570         } else if (com&IOC_VOID) {
571                 *(caddr_t *)data = uap->data;
572         }
573
574         switch (com) {
575
576         case FIONBIO:
577                 if ((tmp = *(int *)data))
578                         fp->f_flag |= FNONBLOCK;
579                 else
580                         fp->f_flag &= ~FNONBLOCK;
581                 error = fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, td);
582                 break;
583
584         case FIOASYNC:
585                 if ((tmp = *(int *)data))
586                         fp->f_flag |= FASYNC;
587                 else
588                         fp->f_flag &= ~FASYNC;
589                 error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp, td);
590                 break;
591
592         default:
593                 error = fo_ioctl(fp, com, data, td);
594                 /*
595                  * Copy any data to user, size was
596                  * already set and checked above.
597                  */
598                 if (error == 0 && (com&IOC_OUT) && size)
599                         error = copyout(data, uap->data, (u_int)size);
600                 break;
601         }
602         if (memp)
603                 free(memp, M_IOCTLOPS);
604         fdrop(fp, td);
605         return (error);
606 }
607
608 static int      nselcoll;       /* Select collisions since boot */
609 int     selwait;
610 SYSCTL_INT(_kern, OID_AUTO, nselcoll, CTLFLAG_RD, &nselcoll, 0, "");
611
612 /*
613  * Select system call.
614  */
615 int
616 select(struct select_args *uap)
617 {
618         struct proc *p = curproc;
619
620         /*
621          * The magic 2048 here is chosen to be just enough for FD_SETSIZE
622          * infds with the new FD_SETSIZE of 1024, and more than enough for
623          * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
624          * of 256.
625          */
626         fd_mask s_selbits[howmany(2048, NFDBITS)];
627         fd_mask *ibits[3], *obits[3], *selbits, *sbp;
628         struct timeval atv, rtv, ttv;
629         int s, ncoll, error, timo;
630         u_int nbufbytes, ncpbytes, nfdbits;
631
632         if (uap->nd < 0)
633                 return (EINVAL);
634         if (uap->nd > p->p_fd->fd_nfiles)
635                 uap->nd = p->p_fd->fd_nfiles;   /* forgiving; slightly wrong */
636
637         /*
638          * Allocate just enough bits for the non-null fd_sets.  Use the
639          * preallocated auto buffer if possible.
640          */
641         nfdbits = roundup(uap->nd, NFDBITS);
642         ncpbytes = nfdbits / NBBY;
643         nbufbytes = 0;
644         if (uap->in != NULL)
645                 nbufbytes += 2 * ncpbytes;
646         if (uap->ou != NULL)
647                 nbufbytes += 2 * ncpbytes;
648         if (uap->ex != NULL)
649                 nbufbytes += 2 * ncpbytes;
650         if (nbufbytes <= sizeof s_selbits)
651                 selbits = &s_selbits[0];
652         else
653                 selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
654
655         /*
656          * Assign pointers into the bit buffers and fetch the input bits.
657          * Put the output buffers together so that they can be bzeroed
658          * together.
659          */
660         sbp = selbits;
661 #define getbits(name, x) \
662         do {                                                            \
663                 if (uap->name == NULL)                                  \
664                         ibits[x] = NULL;                                \
665                 else {                                                  \
666                         ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp;   \
667                         obits[x] = sbp;                                 \
668                         sbp += ncpbytes / sizeof *sbp;                  \
669                         error = copyin(uap->name, ibits[x], ncpbytes);  \
670                         if (error != 0)                                 \
671                                 goto done;                              \
672                 }                                                       \
673         } while (0)
674         getbits(in, 0);
675         getbits(ou, 1);
676         getbits(ex, 2);
677 #undef  getbits
678         if (nbufbytes != 0)
679                 bzero(selbits, nbufbytes / 2);
680
681         if (uap->tv) {
682                 error = copyin((caddr_t)uap->tv, (caddr_t)&atv,
683                         sizeof (atv));
684                 if (error)
685                         goto done;
686                 if (itimerfix(&atv)) {
687                         error = EINVAL;
688                         goto done;
689                 }
690                 getmicrouptime(&rtv);
691                 timevaladd(&atv, &rtv);
692         } else {
693                 atv.tv_sec = 0;
694                 atv.tv_usec = 0;
695         }
696         timo = 0;
697 retry:
698         ncoll = nselcoll;
699         p->p_flag |= P_SELECT;
700         error = selscan(p, ibits, obits, uap->nd);
701         if (error || p->p_retval[0])
702                 goto done;
703         if (atv.tv_sec || atv.tv_usec) {
704                 getmicrouptime(&rtv);
705                 if (timevalcmp(&rtv, &atv, >=)) 
706                         goto done;
707                 ttv = atv;
708                 timevalsub(&ttv, &rtv);
709                 timo = ttv.tv_sec > 24 * 60 * 60 ?
710                     24 * 60 * 60 * hz : tvtohz(&ttv);
711         }
712         s = splhigh();
713         if ((p->p_flag & P_SELECT) == 0 || nselcoll != ncoll) {
714                 splx(s);
715                 goto retry;
716         }
717         p->p_flag &= ~P_SELECT;
718
719         error = tsleep((caddr_t)&selwait, PCATCH, "select", timo);
720         
721         splx(s);
722         if (error == 0)
723                 goto retry;
724 done:
725         p->p_flag &= ~P_SELECT;
726         /* select is not restarted after signals... */
727         if (error == ERESTART)
728                 error = EINTR;
729         if (error == EWOULDBLOCK)
730                 error = 0;
731 #define putbits(name, x) \
732         if (uap->name && (error2 = copyout(obits[x], uap->name, ncpbytes))) \
733                 error = error2;
734         if (error == 0) {
735                 int error2;
736
737                 putbits(in, 0);
738                 putbits(ou, 1);
739                 putbits(ex, 2);
740 #undef putbits
741         }
742         if (selbits != &s_selbits[0])
743                 free(selbits, M_SELECT);
744         return (error);
745 }
746
747 static int
748 selscan(struct proc *p, fd_mask **ibits, fd_mask **obits, int nfd)
749 {
750         struct thread *td = p->p_thread;
751         struct filedesc *fdp = p->p_fd;
752         int msk, i, fd;
753         fd_mask bits;
754         struct file *fp;
755         int n = 0;
756         /* Note: backend also returns POLLHUP/POLLERR if appropriate. */
757         static int flag[3] = { POLLRDNORM, POLLWRNORM, POLLRDBAND };
758
759         for (msk = 0; msk < 3; msk++) {
760                 if (ibits[msk] == NULL)
761                         continue;
762                 for (i = 0; i < nfd; i += NFDBITS) {
763                         bits = ibits[msk][i/NFDBITS];
764                         /* ffs(int mask) not portable, fd_mask is long */
765                         for (fd = i; bits && fd < nfd; fd++, bits >>= 1) {
766                                 if (!(bits & 1))
767                                         continue;
768                                 fp = fdp->fd_ofiles[fd];
769                                 if (fp == NULL)
770                                         return (EBADF);
771                                 if (fo_poll(fp, flag[msk], fp->f_cred, td)) {
772                                         obits[msk][(fd)/NFDBITS] |=
773                                             ((fd_mask)1 << ((fd) % NFDBITS));
774                                         n++;
775                                 }
776                         }
777                 }
778         }
779         p->p_retval[0] = n;
780         return (0);
781 }
782
783 /*
784  * Poll system call.
785  */
786 int
787 poll(struct poll_args *uap)
788 {
789         caddr_t bits;
790         char smallbits[32 * sizeof(struct pollfd)];
791         struct timeval atv, rtv, ttv;
792         int s, ncoll, error = 0, timo;
793         u_int nfds;
794         size_t ni;
795         struct proc *p = curproc;
796
797         nfds = SCARG(uap, nfds);
798         /*
799          * This is kinda bogus.  We have fd limits, but that is not
800          * really related to the size of the pollfd array.  Make sure
801          * we let the process use at least FD_SETSIZE entries and at
802          * least enough for the current limits.  We want to be reasonably
803          * safe, but not overly restrictive.
804          */
805         if (nfds > p->p_rlimit[RLIMIT_NOFILE].rlim_cur && nfds > FD_SETSIZE)
806                 return (EINVAL);
807         ni = nfds * sizeof(struct pollfd);
808         if (ni > sizeof(smallbits))
809                 bits = malloc(ni, M_TEMP, M_WAITOK);
810         else
811                 bits = smallbits;
812         error = copyin(SCARG(uap, fds), bits, ni);
813         if (error)
814                 goto done;
815         if (SCARG(uap, timeout) != INFTIM) {
816                 atv.tv_sec = SCARG(uap, timeout) / 1000;
817                 atv.tv_usec = (SCARG(uap, timeout) % 1000) * 1000;
818                 if (itimerfix(&atv)) {
819                         error = EINVAL;
820                         goto done;
821                 }
822                 getmicrouptime(&rtv);
823                 timevaladd(&atv, &rtv);
824         } else {
825                 atv.tv_sec = 0;
826                 atv.tv_usec = 0;
827         }
828         timo = 0;
829 retry:
830         ncoll = nselcoll;
831         p->p_flag |= P_SELECT;
832         error = pollscan(p, (struct pollfd *)bits, nfds);
833         if (error || p->p_retval[0])
834                 goto done;
835         if (atv.tv_sec || atv.tv_usec) {
836                 getmicrouptime(&rtv);
837                 if (timevalcmp(&rtv, &atv, >=))
838                         goto done;
839                 ttv = atv;
840                 timevalsub(&ttv, &rtv);
841                 timo = ttv.tv_sec > 24 * 60 * 60 ?
842                     24 * 60 * 60 * hz : tvtohz(&ttv);
843         } 
844         s = splhigh(); 
845         if ((p->p_flag & P_SELECT) == 0 || nselcoll != ncoll) {
846                 splx(s);
847                 goto retry;
848         }
849         p->p_flag &= ~P_SELECT;
850         error = tsleep((caddr_t)&selwait, PCATCH, "poll", timo);
851         splx(s);
852         if (error == 0)
853                 goto retry;
854 done:
855         p->p_flag &= ~P_SELECT;
856         /* poll is not restarted after signals... */
857         if (error == ERESTART)
858                 error = EINTR;
859         if (error == EWOULDBLOCK)
860                 error = 0;
861         if (error == 0) {
862                 error = copyout(bits, SCARG(uap, fds), ni);
863                 if (error)
864                         goto out;
865         }
866 out:
867         if (ni > sizeof(smallbits))
868                 free(bits, M_TEMP);
869         return (error);
870 }
871
872 static int
873 pollscan(struct proc *p, struct pollfd *fds, u_int nfd)
874 {
875         struct thread *td = p->p_thread;
876         struct filedesc *fdp = p->p_fd;
877         int i;
878         struct file *fp;
879         int n = 0;
880
881         for (i = 0; i < nfd; i++, fds++) {
882                 if (fds->fd >= fdp->fd_nfiles) {
883                         fds->revents = POLLNVAL;
884                         n++;
885                 } else if (fds->fd < 0) {
886                         fds->revents = 0;
887                 } else {
888                         fp = fdp->fd_ofiles[fds->fd];
889                         if (fp == NULL) {
890                                 fds->revents = POLLNVAL;
891                                 n++;
892                         } else {
893                                 /*
894                                  * Note: backend also returns POLLHUP and
895                                  * POLLERR if appropriate.
896                                  */
897                                 fds->revents = fo_poll(fp, fds->events,
898                                     fp->f_cred, td);
899                                 if (fds->revents != 0)
900                                         n++;
901                         }
902                 }
903         }
904         p->p_retval[0] = n;
905         return (0);
906 }
907
908 /*
909  * OpenBSD poll system call.
910  * XXX this isn't quite a true representation..  OpenBSD uses select ops.
911  */
912 int
913 openbsd_poll(struct openbsd_poll_args *uap)
914 {
915         return (poll((struct poll_args *)uap));
916 }
917
918 /*ARGSUSED*/
919 int
920 seltrue(dev_t dev, int events, struct thread *td)
921 {
922         return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
923 }
924
925 /*
926  * Record a select request.  A global wait must be used since a process/thread
927  * might go away after recording its request.
928  */
929 void
930 selrecord(struct thread *selector, struct selinfo *sip)
931 {
932         struct proc *p;
933         pid_t mypid;
934
935         if ((p = selector->td_proc) == NULL)
936                 panic("selrecord: thread needs a process");
937
938         mypid = p->p_pid;
939         if (sip->si_pid == mypid)
940                 return;
941         if (sip->si_pid && (p = pfind(sip->si_pid)) &&
942             p->p_wchan == (caddr_t)&selwait) {
943                 sip->si_flags |= SI_COLL;
944         } else {
945                 sip->si_pid = mypid;
946         }
947 }
948
949 /*
950  * Do a wakeup when a selectable event occurs.
951  */
952 void
953 selwakeup(struct selinfo *sip)
954 {
955         struct proc *p;
956         int s;
957
958         if (sip->si_pid == 0)
959                 return;
960         if (sip->si_flags & SI_COLL) {
961                 nselcoll++;
962                 sip->si_flags &= ~SI_COLL;
963                 wakeup((caddr_t)&selwait);      /* YYY fixable */
964         }
965         p = pfind(sip->si_pid);
966         sip->si_pid = 0;
967         if (p != NULL) {
968                 s = splhigh();
969                 if (p->p_wchan == (caddr_t)&selwait) {
970                         if (p->p_stat == SSLEEP)
971                                 setrunnable(p);
972                         else
973                                 unsleep(p->p_thread);
974                 } else if (p->p_flag & P_SELECT)
975                         p->p_flag &= ~P_SELECT;
976                 splx(s);
977         }
978 }
979