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