]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/kern/sys_generic.c
Add missed mergeinfo.
[FreeBSD/stable/8.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  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      @(#)sys_generic.c       8.5 (Berkeley) 1/21/94
35  */
36
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39
40 #include "opt_compat.h"
41 #include "opt_ktrace.h"
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/sysproto.h>
46 #include <sys/filedesc.h>
47 #include <sys/filio.h>
48 #include <sys/fcntl.h>
49 #include <sys/file.h>
50 #include <sys/proc.h>
51 #include <sys/signalvar.h>
52 #include <sys/socketvar.h>
53 #include <sys/uio.h>
54 #include <sys/kernel.h>
55 #include <sys/ktr.h>
56 #include <sys/limits.h>
57 #include <sys/malloc.h>
58 #include <sys/poll.h>
59 #include <sys/resourcevar.h>
60 #include <sys/selinfo.h>
61 #include <sys/sleepqueue.h>
62 #include <sys/syscallsubr.h>
63 #include <sys/sysctl.h>
64 #include <sys/sysent.h>
65 #include <sys/vnode.h>
66 #include <sys/bio.h>
67 #include <sys/buf.h>
68 #include <sys/condvar.h>
69 #ifdef KTRACE
70 #include <sys/ktrace.h>
71 #endif
72
73 #include <security/audit/audit.h>
74
75 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
76 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
77 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
78
79 static int      pollout(struct thread *, struct pollfd *, struct pollfd *,
80                     u_int);
81 static int      pollscan(struct thread *, struct pollfd *, u_int);
82 static int      pollrescan(struct thread *);
83 static int      selscan(struct thread *, fd_mask **, fd_mask **, int);
84 static int      selrescan(struct thread *, fd_mask **, fd_mask **);
85 static void     selfdalloc(struct thread *, void *);
86 static void     selfdfree(struct seltd *, struct selfd *);
87 static int      dofileread(struct thread *, int, struct file *, struct uio *,
88                     off_t, int);
89 static int      dofilewrite(struct thread *, int, struct file *, struct uio *,
90                     off_t, int);
91 static void     doselwakeup(struct selinfo *, int);
92 static void     seltdinit(struct thread *);
93 static int      seltdwait(struct thread *, int);
94 static void     seltdclear(struct thread *);
95
96 /*
97  * One seltd per-thread allocated on demand as needed.
98  *
99  *      t - protected by st_mtx
100  *      k - Only accessed by curthread or read-only
101  */
102 struct seltd {
103         STAILQ_HEAD(, selfd)    st_selq;        /* (k) List of selfds. */
104         struct selfd            *st_free1;      /* (k) free fd for read set. */
105         struct selfd            *st_free2;      /* (k) free fd for write set. */
106         struct mtx              st_mtx;         /* Protects struct seltd */
107         struct cv               st_wait;        /* (t) Wait channel. */
108         int                     st_flags;       /* (t) SELTD_ flags. */
109 };
110
111 #define SELTD_PENDING   0x0001                  /* We have pending events. */
112 #define SELTD_RESCAN    0x0002                  /* Doing a rescan. */
113
114 /*
115  * One selfd allocated per-thread per-file-descriptor.
116  *      f - protected by sf_mtx
117  */
118 struct selfd {
119         STAILQ_ENTRY(selfd)     sf_link;        /* (k) fds owned by this td. */
120         TAILQ_ENTRY(selfd)      sf_threads;     /* (f) fds on this selinfo. */
121         struct selinfo          *sf_si;         /* (f) selinfo when linked. */
122         struct mtx              *sf_mtx;        /* Pointer to selinfo mtx. */
123         struct seltd            *sf_td;         /* (k) owning seltd. */
124         void                    *sf_cookie;     /* (k) fd or pollfd. */
125 };
126
127 static uma_zone_t selfd_zone;
128 static struct mtx_pool *mtxpool_select;
129
130 #ifndef _SYS_SYSPROTO_H_
131 struct read_args {
132         int     fd;
133         void    *buf;
134         size_t  nbyte;
135 };
136 #endif
137 int
138 read(td, uap)
139         struct thread *td;
140         struct read_args *uap;
141 {
142         struct uio auio;
143         struct iovec aiov;
144         int error;
145
146         if (uap->nbyte > INT_MAX)
147                 return (EINVAL);
148         aiov.iov_base = uap->buf;
149         aiov.iov_len = uap->nbyte;
150         auio.uio_iov = &aiov;
151         auio.uio_iovcnt = 1;
152         auio.uio_resid = uap->nbyte;
153         auio.uio_segflg = UIO_USERSPACE;
154         error = kern_readv(td, uap->fd, &auio);
155         return(error);
156 }
157
158 /*
159  * Positioned read system call
160  */
161 #ifndef _SYS_SYSPROTO_H_
162 struct pread_args {
163         int     fd;
164         void    *buf;
165         size_t  nbyte;
166         int     pad;
167         off_t   offset;
168 };
169 #endif
170 int
171 pread(td, uap)
172         struct thread *td;
173         struct pread_args *uap;
174 {
175         struct uio auio;
176         struct iovec aiov;
177         int error;
178
179         if (uap->nbyte > INT_MAX)
180                 return (EINVAL);
181         aiov.iov_base = uap->buf;
182         aiov.iov_len = uap->nbyte;
183         auio.uio_iov = &aiov;
184         auio.uio_iovcnt = 1;
185         auio.uio_resid = uap->nbyte;
186         auio.uio_segflg = UIO_USERSPACE;
187         error = kern_preadv(td, uap->fd, &auio, uap->offset);
188         return(error);
189 }
190
191 int
192 freebsd6_pread(td, uap)
193         struct thread *td;
194         struct freebsd6_pread_args *uap;
195 {
196         struct pread_args oargs;
197
198         oargs.fd = uap->fd;
199         oargs.buf = uap->buf;
200         oargs.nbyte = uap->nbyte;
201         oargs.offset = uap->offset;
202         return (pread(td, &oargs));
203 }
204
205 /*
206  * Scatter read system call.
207  */
208 #ifndef _SYS_SYSPROTO_H_
209 struct readv_args {
210         int     fd;
211         struct  iovec *iovp;
212         u_int   iovcnt;
213 };
214 #endif
215 int
216 readv(struct thread *td, struct readv_args *uap)
217 {
218         struct uio *auio;
219         int error;
220
221         error = copyinuio(uap->iovp, uap->iovcnt, &auio);
222         if (error)
223                 return (error);
224         error = kern_readv(td, uap->fd, auio);
225         free(auio, M_IOV);
226         return (error);
227 }
228
229 int
230 kern_readv(struct thread *td, int fd, struct uio *auio)
231 {
232         struct file *fp;
233         int error;
234
235         error = fget_read(td, fd, &fp);
236         if (error)
237                 return (error);
238         error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
239         fdrop(fp, td);
240         return (error);
241 }
242
243 /*
244  * Scatter positioned read system call.
245  */
246 #ifndef _SYS_SYSPROTO_H_
247 struct preadv_args {
248         int     fd;
249         struct  iovec *iovp;
250         u_int   iovcnt;
251         off_t   offset;
252 };
253 #endif
254 int
255 preadv(struct thread *td, struct preadv_args *uap)
256 {
257         struct uio *auio;
258         int error;
259
260         error = copyinuio(uap->iovp, uap->iovcnt, &auio);
261         if (error)
262                 return (error);
263         error = kern_preadv(td, uap->fd, auio, uap->offset);
264         free(auio, M_IOV);
265         return (error);
266 }
267
268 int
269 kern_preadv(td, fd, auio, offset)
270         struct thread *td;
271         int fd;
272         struct uio *auio;
273         off_t offset;
274 {
275         struct file *fp;
276         int error;
277
278         error = fget_read(td, fd, &fp);
279         if (error)
280                 return (error);
281         if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
282                 error = ESPIPE;
283         else if (offset < 0 && fp->f_vnode->v_type != VCHR)
284                 error = EINVAL;
285         else
286                 error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
287         fdrop(fp, td);
288         return (error);
289 }
290
291 /*
292  * Common code for readv and preadv that reads data in
293  * from a file using the passed in uio, offset, and flags.
294  */
295 static int
296 dofileread(td, fd, fp, auio, offset, flags)
297         struct thread *td;
298         int fd;
299         struct file *fp;
300         struct uio *auio;
301         off_t offset;
302         int flags;
303 {
304         ssize_t cnt;
305         int error;
306 #ifdef KTRACE
307         struct uio *ktruio = NULL;
308 #endif
309
310         /* Finish zero length reads right here */
311         if (auio->uio_resid == 0) {
312                 td->td_retval[0] = 0;
313                 return(0);
314         }
315         auio->uio_rw = UIO_READ;
316         auio->uio_offset = offset;
317         auio->uio_td = td;
318 #ifdef KTRACE
319         if (KTRPOINT(td, KTR_GENIO)) 
320                 ktruio = cloneuio(auio);
321 #endif
322         cnt = auio->uio_resid;
323         if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
324                 if (auio->uio_resid != cnt && (error == ERESTART ||
325                     error == EINTR || error == EWOULDBLOCK))
326                         error = 0;
327         }
328         cnt -= auio->uio_resid;
329 #ifdef KTRACE
330         if (ktruio != NULL) {
331                 ktruio->uio_resid = cnt;
332                 ktrgenio(fd, UIO_READ, ktruio, error);
333         }
334 #endif
335         td->td_retval[0] = cnt;
336         return (error);
337 }
338
339 #ifndef _SYS_SYSPROTO_H_
340 struct write_args {
341         int     fd;
342         const void *buf;
343         size_t  nbyte;
344 };
345 #endif
346 int
347 write(td, uap)
348         struct thread *td;
349         struct write_args *uap;
350 {
351         struct uio auio;
352         struct iovec aiov;
353         int error;
354
355         if (uap->nbyte > INT_MAX)
356                 return (EINVAL);
357         aiov.iov_base = (void *)(uintptr_t)uap->buf;
358         aiov.iov_len = uap->nbyte;
359         auio.uio_iov = &aiov;
360         auio.uio_iovcnt = 1;
361         auio.uio_resid = uap->nbyte;
362         auio.uio_segflg = UIO_USERSPACE;
363         error = kern_writev(td, uap->fd, &auio);
364         return(error);
365 }
366
367 /*
368  * Positioned write system call.
369  */
370 #ifndef _SYS_SYSPROTO_H_
371 struct pwrite_args {
372         int     fd;
373         const void *buf;
374         size_t  nbyte;
375         int     pad;
376         off_t   offset;
377 };
378 #endif
379 int
380 pwrite(td, uap)
381         struct thread *td;
382         struct pwrite_args *uap;
383 {
384         struct uio auio;
385         struct iovec aiov;
386         int error;
387
388         if (uap->nbyte > INT_MAX)
389                 return (EINVAL);
390         aiov.iov_base = (void *)(uintptr_t)uap->buf;
391         aiov.iov_len = uap->nbyte;
392         auio.uio_iov = &aiov;
393         auio.uio_iovcnt = 1;
394         auio.uio_resid = uap->nbyte;
395         auio.uio_segflg = UIO_USERSPACE;
396         error = kern_pwritev(td, uap->fd, &auio, uap->offset);
397         return(error);
398 }
399
400 int
401 freebsd6_pwrite(td, uap)
402         struct thread *td;
403         struct freebsd6_pwrite_args *uap;
404 {
405         struct pwrite_args oargs;
406
407         oargs.fd = uap->fd;
408         oargs.buf = uap->buf;
409         oargs.nbyte = uap->nbyte;
410         oargs.offset = uap->offset;
411         return (pwrite(td, &oargs));
412 }
413
414 /*
415  * Gather write system call.
416  */
417 #ifndef _SYS_SYSPROTO_H_
418 struct writev_args {
419         int     fd;
420         struct  iovec *iovp;
421         u_int   iovcnt;
422 };
423 #endif
424 int
425 writev(struct thread *td, struct writev_args *uap)
426 {
427         struct uio *auio;
428         int error;
429
430         error = copyinuio(uap->iovp, uap->iovcnt, &auio);
431         if (error)
432                 return (error);
433         error = kern_writev(td, uap->fd, auio);
434         free(auio, M_IOV);
435         return (error);
436 }
437
438 int
439 kern_writev(struct thread *td, int fd, struct uio *auio)
440 {
441         struct file *fp;
442         int error;
443
444         error = fget_write(td, fd, &fp);
445         if (error)
446                 return (error);
447         error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
448         fdrop(fp, td);
449         return (error);
450 }
451
452 /*
453  * Gather positioned write system call.
454  */
455 #ifndef _SYS_SYSPROTO_H_
456 struct pwritev_args {
457         int     fd;
458         struct  iovec *iovp;
459         u_int   iovcnt;
460         off_t   offset;
461 };
462 #endif
463 int
464 pwritev(struct thread *td, struct pwritev_args *uap)
465 {
466         struct uio *auio;
467         int error;
468
469         error = copyinuio(uap->iovp, uap->iovcnt, &auio);
470         if (error)
471                 return (error);
472         error = kern_pwritev(td, uap->fd, auio, uap->offset);
473         free(auio, M_IOV);
474         return (error);
475 }
476
477 int
478 kern_pwritev(td, fd, auio, offset)
479         struct thread *td;
480         struct uio *auio;
481         int fd;
482         off_t offset;
483 {
484         struct file *fp;
485         int error;
486
487         error = fget_write(td, fd, &fp);
488         if (error)
489                 return (error);
490         if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
491                 error = ESPIPE;
492         else if (offset < 0 && fp->f_vnode->v_type != VCHR)
493                 error = EINVAL;
494         else
495                 error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
496         fdrop(fp, td);
497         return (error);
498 }
499
500 /*
501  * Common code for writev and pwritev that writes data to
502  * a file using the passed in uio, offset, and flags.
503  */
504 static int
505 dofilewrite(td, fd, fp, auio, offset, flags)
506         struct thread *td;
507         int fd;
508         struct file *fp;
509         struct uio *auio;
510         off_t offset;
511         int flags;
512 {
513         ssize_t cnt;
514         int error;
515 #ifdef KTRACE
516         struct uio *ktruio = NULL;
517 #endif
518
519         auio->uio_rw = UIO_WRITE;
520         auio->uio_td = td;
521         auio->uio_offset = offset;
522 #ifdef KTRACE
523         if (KTRPOINT(td, KTR_GENIO))
524                 ktruio = cloneuio(auio);
525 #endif
526         cnt = auio->uio_resid;
527         if (fp->f_type == DTYPE_VNODE)
528                 bwillwrite();
529         if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
530                 if (auio->uio_resid != cnt && (error == ERESTART ||
531                     error == EINTR || error == EWOULDBLOCK))
532                         error = 0;
533                 /* Socket layer is responsible for issuing SIGPIPE. */
534                 if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
535                         PROC_LOCK(td->td_proc);
536                         tdksignal(td, SIGPIPE, NULL);
537                         PROC_UNLOCK(td->td_proc);
538                 }
539         }
540         cnt -= auio->uio_resid;
541 #ifdef KTRACE
542         if (ktruio != NULL) {
543                 ktruio->uio_resid = cnt;
544                 ktrgenio(fd, UIO_WRITE, ktruio, error);
545         }
546 #endif
547         td->td_retval[0] = cnt;
548         return (error);
549 }
550
551 /*
552  * Truncate a file given a file descriptor.
553  *
554  * Can't use fget_write() here, since must return EINVAL and not EBADF if the
555  * descriptor isn't writable.
556  */
557 int
558 kern_ftruncate(td, fd, length)
559         struct thread *td;
560         int fd;
561         off_t length;
562 {
563         struct file *fp;
564         int error;
565
566         AUDIT_ARG_FD(fd);
567         if (length < 0)
568                 return (EINVAL);
569         error = fget(td, fd, &fp);
570         if (error)
571                 return (error);
572         AUDIT_ARG_FILE(td->td_proc, fp);
573         if (!(fp->f_flag & FWRITE)) {
574                 fdrop(fp, td);
575                 return (EINVAL);
576         }
577         error = fo_truncate(fp, length, td->td_ucred, td);
578         fdrop(fp, td);
579         return (error);
580 }
581
582 #ifndef _SYS_SYSPROTO_H_
583 struct ftruncate_args {
584         int     fd;
585         int     pad;
586         off_t   length;
587 };
588 #endif
589 int
590 ftruncate(td, uap)
591         struct thread *td;
592         struct ftruncate_args *uap;
593 {
594
595         return (kern_ftruncate(td, uap->fd, uap->length));
596 }
597
598 #if defined(COMPAT_43)
599 #ifndef _SYS_SYSPROTO_H_
600 struct oftruncate_args {
601         int     fd;
602         long    length;
603 };
604 #endif
605 int
606 oftruncate(td, uap)
607         struct thread *td;
608         struct oftruncate_args *uap;
609 {
610
611         return (kern_ftruncate(td, uap->fd, uap->length));
612 }
613 #endif /* COMPAT_43 */
614
615 #ifndef _SYS_SYSPROTO_H_
616 struct ioctl_args {
617         int     fd;
618         u_long  com;
619         caddr_t data;
620 };
621 #endif
622 /* ARGSUSED */
623 int
624 ioctl(struct thread *td, struct ioctl_args *uap)
625 {
626         u_long com;
627         int arg, error;
628         u_int size;
629         caddr_t data;
630
631         if (uap->com > 0xffffffff) {
632                 printf(
633                     "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
634                     td->td_proc->p_pid, td->td_name, uap->com);
635                 uap->com &= 0xffffffff;
636         }
637         com = uap->com;
638
639         /*
640          * Interpret high order word to find amount of data to be
641          * copied to/from the user's address space.
642          */
643         size = IOCPARM_LEN(com);
644         if ((size > IOCPARM_MAX) ||
645             ((com & (IOC_VOID  | IOC_IN | IOC_OUT)) == 0) ||
646 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
647             ((com & IOC_OUT) && size == 0) ||
648 #else
649             ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
650 #endif
651             ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
652                 return (ENOTTY);
653
654         if (size > 0) {
655                 if (com & IOC_VOID) {
656                         /* Integer argument. */
657                         arg = (intptr_t)uap->data;
658                         data = (void *)&arg;
659                         size = 0;
660                 } else
661                         data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
662         } else
663                 data = (void *)&uap->data;
664         if (com & IOC_IN) {
665                 error = copyin(uap->data, data, (u_int)size);
666                 if (error) {
667                         if (size > 0)
668                                 free(data, M_IOCTLOPS);
669                         return (error);
670                 }
671         } else if (com & IOC_OUT) {
672                 /*
673                  * Zero the buffer so the user always
674                  * gets back something deterministic.
675                  */
676                 bzero(data, size);
677         }
678
679         error = kern_ioctl(td, uap->fd, com, data);
680
681         if (error == 0 && (com & IOC_OUT))
682                 error = copyout(data, uap->data, (u_int)size);
683
684         if (size > 0)
685                 free(data, M_IOCTLOPS);
686         return (error);
687 }
688
689 int
690 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
691 {
692         struct file *fp;
693         struct filedesc *fdp;
694         int error;
695         int tmp;
696
697         AUDIT_ARG_FD(fd);
698         AUDIT_ARG_CMD(com);
699         if ((error = fget(td, fd, &fp)) != 0)
700                 return (error);
701         if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
702                 fdrop(fp, td);
703                 return (EBADF);
704         }
705         fdp = td->td_proc->p_fd;
706         switch (com) {
707         case FIONCLEX:
708                 FILEDESC_XLOCK(fdp);
709                 fdp->fd_ofileflags[fd] &= ~UF_EXCLOSE;
710                 FILEDESC_XUNLOCK(fdp);
711                 goto out;
712         case FIOCLEX:
713                 FILEDESC_XLOCK(fdp);
714                 fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
715                 FILEDESC_XUNLOCK(fdp);
716                 goto out;
717         case FIONBIO:
718                 if ((tmp = *(int *)data))
719                         atomic_set_int(&fp->f_flag, FNONBLOCK);
720                 else
721                         atomic_clear_int(&fp->f_flag, FNONBLOCK);
722                 data = (void *)&tmp;
723                 break;
724         case FIOASYNC:
725                 if ((tmp = *(int *)data))
726                         atomic_set_int(&fp->f_flag, FASYNC);
727                 else
728                         atomic_clear_int(&fp->f_flag, FASYNC);
729                 data = (void *)&tmp;
730                 break;
731         }
732
733         error = fo_ioctl(fp, com, data, td->td_ucred, td);
734 out:
735         fdrop(fp, td);
736         return (error);
737 }
738
739 int
740 poll_no_poll(int events)
741 {
742         /*
743          * Return true for read/write.  If the user asked for something
744          * special, return POLLNVAL, so that clients have a way of
745          * determining reliably whether or not the extended
746          * functionality is present without hard-coding knowledge
747          * of specific filesystem implementations.
748          */
749         if (events & ~POLLSTANDARD)
750                 return (POLLNVAL);
751
752         return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
753 }
754
755 int
756 pselect(struct thread *td, struct pselect_args *uap)
757 {
758         struct timespec ts;
759         struct timeval tv, *tvp;
760         sigset_t set, *uset;
761         int error;
762
763         if (uap->ts != NULL) {
764                 error = copyin(uap->ts, &ts, sizeof(ts));
765                 if (error != 0)
766                     return (error);
767                 TIMESPEC_TO_TIMEVAL(&tv, &ts);
768                 tvp = &tv;
769         } else
770                 tvp = NULL;
771         if (uap->sm != NULL) {
772                 error = copyin(uap->sm, &set, sizeof(set));
773                 if (error != 0)
774                         return (error);
775                 uset = &set;
776         } else
777                 uset = NULL;
778         return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
779             uset, NFDBITS));
780 }
781
782 int
783 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
784     struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
785 {
786         int error;
787
788         if (uset != NULL) {
789                 error = kern_sigprocmask(td, SIG_SETMASK, uset,
790                     &td->td_oldsigmask, 0);
791                 if (error != 0)
792                         return (error);
793                 td->td_pflags |= TDP_OLDMASK;
794                 /*
795                  * Make sure that ast() is called on return to
796                  * usermode and TDP_OLDMASK is cleared, restoring old
797                  * sigmask.
798                  */
799                 thread_lock(td);
800                 td->td_flags |= TDF_ASTPENDING;
801                 thread_unlock(td);
802         }
803         error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
804         return (error);
805 }
806
807 #ifndef _SYS_SYSPROTO_H_
808 struct select_args {
809         int     nd;
810         fd_set  *in, *ou, *ex;
811         struct  timeval *tv;
812 };
813 #endif
814 int
815 select(struct thread *td, struct select_args *uap)
816 {
817         struct timeval tv, *tvp;
818         int error;
819
820         if (uap->tv != NULL) {
821                 error = copyin(uap->tv, &tv, sizeof(tv));
822                 if (error)
823                         return (error);
824                 tvp = &tv;
825         } else
826                 tvp = NULL;
827
828         return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
829             NFDBITS));
830 }
831
832 /*
833  * In the unlikely case when user specified n greater then the last
834  * open file descriptor, check that no bits are set after the last
835  * valid fd.  We must return EBADF if any is set.
836  *
837  * There are applications that rely on the behaviour.
838  *
839  * nd is fd_lastfile + 1.
840  */
841 static int
842 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
843 {
844         char *addr, *oaddr;
845         int b, i, res;
846         uint8_t bits;
847
848         if (nd >= ndu || fd_in == NULL)
849                 return (0);
850
851         oaddr = NULL;
852         bits = 0; /* silence gcc */
853         for (i = nd; i < ndu; i++) {
854                 b = i / NBBY;
855 #if BYTE_ORDER == LITTLE_ENDIAN
856                 addr = (char *)fd_in + b;
857 #else
858                 addr = (char *)fd_in;
859                 if (abi_nfdbits == NFDBITS) {
860                         addr += rounddown(b, sizeof(fd_mask)) +
861                             sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
862                 } else {
863                         addr += rounddown(b, sizeof(uint32_t)) +
864                             sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
865                 }
866 #endif
867                 if (addr != oaddr) {
868                         res = fubyte(addr);
869                         if (res == -1)
870                                 return (EFAULT);
871                         oaddr = addr;
872                         bits = res;
873                 }
874                 if ((bits & (1 << (i % NBBY))) != 0)
875                         return (EBADF);
876         }
877         return (0);
878 }
879
880 int
881 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
882     fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
883 {
884         struct filedesc *fdp;
885         /*
886          * The magic 2048 here is chosen to be just enough for FD_SETSIZE
887          * infds with the new FD_SETSIZE of 1024, and more than enough for
888          * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
889          * of 256.
890          */
891         fd_mask s_selbits[howmany(2048, NFDBITS)];
892         fd_mask *ibits[3], *obits[3], *selbits, *sbp;
893         struct timeval atv, rtv, ttv;
894         int error, lf, ndu, timo;
895         u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
896
897         if (nd < 0)
898                 return (EINVAL);
899         fdp = td->td_proc->p_fd;
900         ndu = nd;
901         lf = fdp->fd_lastfile;
902         if (nd > lf + 1)
903                 nd = lf + 1;
904
905         error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
906         if (error != 0)
907                 return (error);
908         error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
909         if (error != 0)
910                 return (error);
911         error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
912         if (error != 0)
913                 return (error);
914
915         /*
916          * Allocate just enough bits for the non-null fd_sets.  Use the
917          * preallocated auto buffer if possible.
918          */
919         nfdbits = roundup(nd, NFDBITS);
920         ncpbytes = nfdbits / NBBY;
921         ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
922         nbufbytes = 0;
923         if (fd_in != NULL)
924                 nbufbytes += 2 * ncpbytes;
925         if (fd_ou != NULL)
926                 nbufbytes += 2 * ncpbytes;
927         if (fd_ex != NULL)
928                 nbufbytes += 2 * ncpbytes;
929         if (nbufbytes <= sizeof s_selbits)
930                 selbits = &s_selbits[0];
931         else
932                 selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
933
934         /*
935          * Assign pointers into the bit buffers and fetch the input bits.
936          * Put the output buffers together so that they can be bzeroed
937          * together.
938          */
939         sbp = selbits;
940 #define getbits(name, x) \
941         do {                                                            \
942                 if (name == NULL) {                                     \
943                         ibits[x] = NULL;                                \
944                         obits[x] = NULL;                                \
945                 } else {                                                \
946                         ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp;   \
947                         obits[x] = sbp;                                 \
948                         sbp += ncpbytes / sizeof *sbp;                  \
949                         error = copyin(name, ibits[x], ncpubytes);      \
950                         if (error != 0)                                 \
951                                 goto done;                              \
952                         bzero((char *)ibits[x] + ncpubytes,             \
953                             ncpbytes - ncpubytes);                      \
954                 }                                                       \
955         } while (0)
956         getbits(fd_in, 0);
957         getbits(fd_ou, 1);
958         getbits(fd_ex, 2);
959 #undef  getbits
960
961 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
962         /*
963          * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
964          * we are running under 32-bit emulation. This should be more
965          * generic.
966          */
967 #define swizzle_fdset(bits)                                             \
968         if (abi_nfdbits != NFDBITS && bits != NULL) {                   \
969                 int i;                                                  \
970                 for (i = 0; i < ncpbytes / sizeof *sbp; i++)            \
971                         bits[i] = (bits[i] >> 32) | (bits[i] << 32);    \
972         }
973 #else
974 #define swizzle_fdset(bits)
975 #endif
976
977         /* Make sure the bit order makes it through an ABI transition */
978         swizzle_fdset(ibits[0]);
979         swizzle_fdset(ibits[1]);
980         swizzle_fdset(ibits[2]);
981         
982         if (nbufbytes != 0)
983                 bzero(selbits, nbufbytes / 2);
984
985         if (tvp != NULL) {
986                 atv = *tvp;
987                 if (itimerfix(&atv)) {
988                         error = EINVAL;
989                         goto done;
990                 }
991                 getmicrouptime(&rtv);
992                 timevaladd(&atv, &rtv);
993         } else {
994                 atv.tv_sec = 0;
995                 atv.tv_usec = 0;
996         }
997         timo = 0;
998         seltdinit(td);
999         /* Iterate until the timeout expires or descriptors become ready. */
1000         for (;;) {
1001                 error = selscan(td, ibits, obits, nd);
1002                 if (error || td->td_retval[0] != 0)
1003                         break;
1004                 if (atv.tv_sec || atv.tv_usec) {
1005                         getmicrouptime(&rtv);
1006                         if (timevalcmp(&rtv, &atv, >=))
1007                                 break;
1008                         ttv = atv;
1009                         timevalsub(&ttv, &rtv);
1010                         timo = ttv.tv_sec > 24 * 60 * 60 ?
1011                             24 * 60 * 60 * hz : tvtohz(&ttv);
1012                 }
1013                 error = seltdwait(td, timo);
1014                 if (error)
1015                         break;
1016                 error = selrescan(td, ibits, obits);
1017                 if (error || td->td_retval[0] != 0)
1018                         break;
1019         }
1020         seltdclear(td);
1021
1022 done:
1023         /* select is not restarted after signals... */
1024         if (error == ERESTART)
1025                 error = EINTR;
1026         if (error == EWOULDBLOCK)
1027                 error = 0;
1028
1029         /* swizzle bit order back, if necessary */
1030         swizzle_fdset(obits[0]);
1031         swizzle_fdset(obits[1]);
1032         swizzle_fdset(obits[2]);
1033 #undef swizzle_fdset
1034
1035 #define putbits(name, x) \
1036         if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1037                 error = error2;
1038         if (error == 0) {
1039                 int error2;
1040
1041                 putbits(fd_in, 0);
1042                 putbits(fd_ou, 1);
1043                 putbits(fd_ex, 2);
1044 #undef putbits
1045         }
1046         if (selbits != &s_selbits[0])
1047                 free(selbits, M_SELECT);
1048
1049         return (error);
1050 }
1051 /* 
1052  * Convert a select bit set to poll flags.
1053  *
1054  * The backend always returns POLLHUP/POLLERR if appropriate and we
1055  * return this as a set bit in any set.
1056  */
1057 static int select_flags[3] = {
1058     POLLRDNORM | POLLHUP | POLLERR,
1059     POLLWRNORM | POLLHUP | POLLERR,
1060     POLLRDBAND | POLLERR
1061 };
1062
1063 /*
1064  * Compute the fo_poll flags required for a fd given by the index and
1065  * bit position in the fd_mask array.
1066  */
1067 static __inline int
1068 selflags(fd_mask **ibits, int idx, fd_mask bit)
1069 {
1070         int flags;
1071         int msk;
1072
1073         flags = 0;
1074         for (msk = 0; msk < 3; msk++) {
1075                 if (ibits[msk] == NULL)
1076                         continue;
1077                 if ((ibits[msk][idx] & bit) == 0)
1078                         continue;
1079                 flags |= select_flags[msk];
1080         }
1081         return (flags);
1082 }
1083
1084 /*
1085  * Set the appropriate output bits given a mask of fired events and the
1086  * input bits originally requested.
1087  */
1088 static __inline int
1089 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1090 {
1091         int msk;
1092         int n;
1093
1094         n = 0;
1095         for (msk = 0; msk < 3; msk++) {
1096                 if ((events & select_flags[msk]) == 0)
1097                         continue;
1098                 if (ibits[msk] == NULL)
1099                         continue;
1100                 if ((ibits[msk][idx] & bit) == 0)
1101                         continue;
1102                 /*
1103                  * XXX Check for a duplicate set.  This can occur because a
1104                  * socket calls selrecord() twice for each poll() call
1105                  * resulting in two selfds per real fd.  selrescan() will
1106                  * call selsetbits twice as a result.
1107                  */
1108                 if ((obits[msk][idx] & bit) != 0)
1109                         continue;
1110                 obits[msk][idx] |= bit;
1111                 n++;
1112         }
1113
1114         return (n);
1115 }
1116
1117 /*
1118  * Traverse the list of fds attached to this thread's seltd and check for
1119  * completion.
1120  */
1121 static int
1122 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1123 {
1124         struct filedesc *fdp;
1125         struct selinfo *si;
1126         struct seltd *stp;
1127         struct selfd *sfp;
1128         struct selfd *sfn;
1129         struct file *fp;
1130         fd_mask bit;
1131         int fd, ev, n, idx;
1132
1133         fdp = td->td_proc->p_fd;
1134         stp = td->td_sel;
1135         n = 0;
1136         STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1137                 fd = (int)(uintptr_t)sfp->sf_cookie;
1138                 si = sfp->sf_si;
1139                 selfdfree(stp, sfp);
1140                 /* If the selinfo wasn't cleared the event didn't fire. */
1141                 if (si != NULL)
1142                         continue;
1143                 if ((fp = fget_unlocked(fdp, fd)) == NULL)
1144                         return (EBADF);
1145                 idx = fd / NFDBITS;
1146                 bit = (fd_mask)1 << (fd % NFDBITS);
1147                 ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1148                 fdrop(fp, td);
1149                 if (ev != 0)
1150                         n += selsetbits(ibits, obits, idx, bit, ev);
1151         }
1152         stp->st_flags = 0;
1153         td->td_retval[0] = n;
1154         return (0);
1155 }
1156
1157 /*
1158  * Perform the initial filedescriptor scan and register ourselves with
1159  * each selinfo.
1160  */
1161 static int
1162 selscan(td, ibits, obits, nfd)
1163         struct thread *td;
1164         fd_mask **ibits, **obits;
1165         int nfd;
1166 {
1167         struct filedesc *fdp;
1168         struct file *fp;
1169         fd_mask bit;
1170         int ev, flags, end, fd;
1171         int n, idx;
1172
1173         fdp = td->td_proc->p_fd;
1174         n = 0;
1175         for (idx = 0, fd = 0; fd < nfd; idx++) {
1176                 end = imin(fd + NFDBITS, nfd);
1177                 for (bit = 1; fd < end; bit <<= 1, fd++) {
1178                         /* Compute the list of events we're interested in. */
1179                         flags = selflags(ibits, idx, bit);
1180                         if (flags == 0)
1181                                 continue;
1182                         if ((fp = fget_unlocked(fdp, fd)) == NULL)
1183                                 return (EBADF);
1184                         selfdalloc(td, (void *)(uintptr_t)fd);
1185                         ev = fo_poll(fp, flags, td->td_ucred, td);
1186                         fdrop(fp, td);
1187                         if (ev != 0)
1188                                 n += selsetbits(ibits, obits, idx, bit, ev);
1189                 }
1190         }
1191
1192         td->td_retval[0] = n;
1193         return (0);
1194 }
1195
1196 #ifndef _SYS_SYSPROTO_H_
1197 struct poll_args {
1198         struct pollfd *fds;
1199         u_int   nfds;
1200         int     timeout;
1201 };
1202 #endif
1203 int
1204 poll(td, uap)
1205         struct thread *td;
1206         struct poll_args *uap;
1207 {
1208         struct pollfd *bits;
1209         struct pollfd smallbits[32];
1210         struct timeval atv, rtv, ttv;
1211         int error, timo;
1212         u_int nfds;
1213         size_t ni;
1214
1215         nfds = uap->nfds;
1216         if (nfds > maxfilesperproc && nfds > FD_SETSIZE) 
1217                 return (EINVAL);
1218         ni = nfds * sizeof(struct pollfd);
1219         if (ni > sizeof(smallbits))
1220                 bits = malloc(ni, M_TEMP, M_WAITOK);
1221         else
1222                 bits = smallbits;
1223         error = copyin(uap->fds, bits, ni);
1224         if (error)
1225                 goto done;
1226         if (uap->timeout != INFTIM) {
1227                 atv.tv_sec = uap->timeout / 1000;
1228                 atv.tv_usec = (uap->timeout % 1000) * 1000;
1229                 if (itimerfix(&atv)) {
1230                         error = EINVAL;
1231                         goto done;
1232                 }
1233                 getmicrouptime(&rtv);
1234                 timevaladd(&atv, &rtv);
1235         } else {
1236                 atv.tv_sec = 0;
1237                 atv.tv_usec = 0;
1238         }
1239         timo = 0;
1240         seltdinit(td);
1241         /* Iterate until the timeout expires or descriptors become ready. */
1242         for (;;) {
1243                 error = pollscan(td, bits, nfds);
1244                 if (error || td->td_retval[0] != 0)
1245                         break;
1246                 if (atv.tv_sec || atv.tv_usec) {
1247                         getmicrouptime(&rtv);
1248                         if (timevalcmp(&rtv, &atv, >=))
1249                                 break;
1250                         ttv = atv;
1251                         timevalsub(&ttv, &rtv);
1252                         timo = ttv.tv_sec > 24 * 60 * 60 ?
1253                             24 * 60 * 60 * hz : tvtohz(&ttv);
1254                 }
1255                 error = seltdwait(td, timo);
1256                 if (error)
1257                         break;
1258                 error = pollrescan(td);
1259                 if (error || td->td_retval[0] != 0)
1260                         break;
1261         }
1262         seltdclear(td);
1263
1264 done:
1265         /* poll is not restarted after signals... */
1266         if (error == ERESTART)
1267                 error = EINTR;
1268         if (error == EWOULDBLOCK)
1269                 error = 0;
1270         if (error == 0) {
1271                 error = pollout(td, bits, uap->fds, nfds);
1272                 if (error)
1273                         goto out;
1274         }
1275 out:
1276         if (ni > sizeof(smallbits))
1277                 free(bits, M_TEMP);
1278         return (error);
1279 }
1280
1281 static int
1282 pollrescan(struct thread *td)
1283 {
1284         struct seltd *stp;
1285         struct selfd *sfp;
1286         struct selfd *sfn;
1287         struct selinfo *si;
1288         struct filedesc *fdp;
1289         struct file *fp;
1290         struct pollfd *fd;
1291         int n;
1292
1293         n = 0;
1294         fdp = td->td_proc->p_fd;
1295         stp = td->td_sel;
1296         FILEDESC_SLOCK(fdp);
1297         STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1298                 fd = (struct pollfd *)sfp->sf_cookie;
1299                 si = sfp->sf_si;
1300                 selfdfree(stp, sfp);
1301                 /* If the selinfo wasn't cleared the event didn't fire. */
1302                 if (si != NULL)
1303                         continue;
1304                 fp = fdp->fd_ofiles[fd->fd];
1305                 if (fp == NULL) {
1306                         fd->revents = POLLNVAL;
1307                         n++;
1308                         continue;
1309                 }
1310                 /*
1311                  * Note: backend also returns POLLHUP and
1312                  * POLLERR if appropriate.
1313                  */
1314                 fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1315                 if (fd->revents != 0)
1316                         n++;
1317         }
1318         FILEDESC_SUNLOCK(fdp);
1319         stp->st_flags = 0;
1320         td->td_retval[0] = n;
1321         return (0);
1322 }
1323
1324
1325 static int
1326 pollout(td, fds, ufds, nfd)
1327         struct thread *td;
1328         struct pollfd *fds;
1329         struct pollfd *ufds;
1330         u_int nfd;
1331 {
1332         int error = 0;
1333         u_int i = 0;
1334         u_int n = 0;
1335
1336         for (i = 0; i < nfd; i++) {
1337                 error = copyout(&fds->revents, &ufds->revents,
1338                     sizeof(ufds->revents));
1339                 if (error)
1340                         return (error);
1341                 if (fds->revents != 0)
1342                         n++;
1343                 fds++;
1344                 ufds++;
1345         }
1346         td->td_retval[0] = n;
1347         return (0);
1348 }
1349
1350 static int
1351 pollscan(td, fds, nfd)
1352         struct thread *td;
1353         struct pollfd *fds;
1354         u_int nfd;
1355 {
1356         struct filedesc *fdp = td->td_proc->p_fd;
1357         int i;
1358         struct file *fp;
1359         int n = 0;
1360
1361         FILEDESC_SLOCK(fdp);
1362         for (i = 0; i < nfd; i++, fds++) {
1363                 if (fds->fd >= fdp->fd_nfiles) {
1364                         fds->revents = POLLNVAL;
1365                         n++;
1366                 } else if (fds->fd < 0) {
1367                         fds->revents = 0;
1368                 } else {
1369                         fp = fdp->fd_ofiles[fds->fd];
1370                         if (fp == NULL) {
1371                                 fds->revents = POLLNVAL;
1372                                 n++;
1373                         } else {
1374                                 /*
1375                                  * Note: backend also returns POLLHUP and
1376                                  * POLLERR if appropriate.
1377                                  */
1378                                 selfdalloc(td, fds);
1379                                 fds->revents = fo_poll(fp, fds->events,
1380                                     td->td_ucred, td);
1381                                 /*
1382                                  * POSIX requires POLLOUT to be never
1383                                  * set simultaneously with POLLHUP.
1384                                  */
1385                                 if ((fds->revents & POLLHUP) != 0)
1386                                         fds->revents &= ~POLLOUT;
1387
1388                                 if (fds->revents != 0)
1389                                         n++;
1390                         }
1391                 }
1392         }
1393         FILEDESC_SUNLOCK(fdp);
1394         td->td_retval[0] = n;
1395         return (0);
1396 }
1397
1398 /*
1399  * OpenBSD poll system call.
1400  *
1401  * XXX this isn't quite a true representation..  OpenBSD uses select ops.
1402  */
1403 #ifndef _SYS_SYSPROTO_H_
1404 struct openbsd_poll_args {
1405         struct pollfd *fds;
1406         u_int   nfds;
1407         int     timeout;
1408 };
1409 #endif
1410 int
1411 openbsd_poll(td, uap)
1412         register struct thread *td;
1413         register struct openbsd_poll_args *uap;
1414 {
1415         return (poll(td, (struct poll_args *)uap));
1416 }
1417
1418 /*
1419  * XXX This was created specifically to support netncp and netsmb.  This
1420  * allows the caller to specify a socket to wait for events on.  It returns
1421  * 0 if any events matched and an error otherwise.  There is no way to
1422  * determine which events fired.
1423  */
1424 int
1425 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1426 {
1427         struct timeval atv, rtv, ttv;
1428         int error, timo;
1429
1430         if (tvp != NULL) {
1431                 atv = *tvp;
1432                 if (itimerfix(&atv))
1433                         return (EINVAL);
1434                 getmicrouptime(&rtv);
1435                 timevaladd(&atv, &rtv);
1436         } else {
1437                 atv.tv_sec = 0;
1438                 atv.tv_usec = 0;
1439         }
1440
1441         timo = 0;
1442         seltdinit(td);
1443         /*
1444          * Iterate until the timeout expires or the socket becomes ready.
1445          */
1446         for (;;) {
1447                 selfdalloc(td, NULL);
1448                 error = sopoll(so, events, NULL, td);
1449                 /* error here is actually the ready events. */
1450                 if (error)
1451                         return (0);
1452                 if (atv.tv_sec || atv.tv_usec) {
1453                         getmicrouptime(&rtv);
1454                         if (timevalcmp(&rtv, &atv, >=)) {
1455                                 seltdclear(td);
1456                                 return (EWOULDBLOCK);
1457                         }
1458                         ttv = atv;
1459                         timevalsub(&ttv, &rtv);
1460                         timo = ttv.tv_sec > 24 * 60 * 60 ?
1461                             24 * 60 * 60 * hz : tvtohz(&ttv);
1462                 }
1463                 error = seltdwait(td, timo);
1464                 seltdclear(td);
1465                 if (error)
1466                         break;
1467         }
1468         /* XXX Duplicates ncp/smb behavior. */
1469         if (error == ERESTART)
1470                 error = 0;
1471         return (error);
1472 }
1473
1474 /*
1475  * Preallocate two selfds associated with 'cookie'.  Some fo_poll routines
1476  * have two select sets, one for read and another for write.
1477  */
1478 static void
1479 selfdalloc(struct thread *td, void *cookie)
1480 {
1481         struct seltd *stp;
1482
1483         stp = td->td_sel;
1484         if (stp->st_free1 == NULL)
1485                 stp->st_free1 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1486         stp->st_free1->sf_td = stp;
1487         stp->st_free1->sf_cookie = cookie;
1488         if (stp->st_free2 == NULL)
1489                 stp->st_free2 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1490         stp->st_free2->sf_td = stp;
1491         stp->st_free2->sf_cookie = cookie;
1492 }
1493
1494 static void
1495 selfdfree(struct seltd *stp, struct selfd *sfp)
1496 {
1497         STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1498         mtx_lock(sfp->sf_mtx);
1499         if (sfp->sf_si)
1500                 TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1501         mtx_unlock(sfp->sf_mtx);
1502         uma_zfree(selfd_zone, sfp);
1503 }
1504
1505 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1506 void
1507 seldrain(sip)
1508         struct selinfo *sip;
1509 {
1510
1511         /*
1512          * This feature is already provided by doselwakeup(), thus it is
1513          * enough to go for it.
1514          * Eventually, the context, should take care to avoid races
1515          * between thread calling select()/poll() and file descriptor
1516          * detaching, but, again, the races are just the same as
1517          * selwakeup().
1518          */
1519         doselwakeup(sip, -1);
1520 }
1521
1522 /*
1523  * Record a select request.
1524  */
1525 void
1526 selrecord(selector, sip)
1527         struct thread *selector;
1528         struct selinfo *sip;
1529 {
1530         struct selfd *sfp;
1531         struct seltd *stp;
1532         struct mtx *mtxp;
1533
1534         stp = selector->td_sel;
1535         /*
1536          * Don't record when doing a rescan.
1537          */
1538         if (stp->st_flags & SELTD_RESCAN)
1539                 return;
1540         /*
1541          * Grab one of the preallocated descriptors.
1542          */
1543         sfp = NULL;
1544         if ((sfp = stp->st_free1) != NULL)
1545                 stp->st_free1 = NULL;
1546         else if ((sfp = stp->st_free2) != NULL)
1547                 stp->st_free2 = NULL;
1548         else
1549                 panic("selrecord: No free selfd on selq");
1550         mtxp = sip->si_mtx;
1551         if (mtxp == NULL)
1552                 mtxp = mtx_pool_find(mtxpool_select, sip);
1553         /*
1554          * Initialize the sfp and queue it in the thread.
1555          */
1556         sfp->sf_si = sip;
1557         sfp->sf_mtx = mtxp;
1558         STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1559         /*
1560          * Now that we've locked the sip, check for initialization.
1561          */
1562         mtx_lock(mtxp);
1563         if (sip->si_mtx == NULL) {
1564                 sip->si_mtx = mtxp;
1565                 TAILQ_INIT(&sip->si_tdlist);
1566         }
1567         /*
1568          * Add this thread to the list of selfds listening on this selinfo.
1569          */
1570         TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1571         mtx_unlock(sip->si_mtx);
1572 }
1573
1574 /* Wake up a selecting thread. */
1575 void
1576 selwakeup(sip)
1577         struct selinfo *sip;
1578 {
1579         doselwakeup(sip, -1);
1580 }
1581
1582 /* Wake up a selecting thread, and set its priority. */
1583 void
1584 selwakeuppri(sip, pri)
1585         struct selinfo *sip;
1586         int pri;
1587 {
1588         doselwakeup(sip, pri);
1589 }
1590
1591 /*
1592  * Do a wakeup when a selectable event occurs.
1593  */
1594 static void
1595 doselwakeup(sip, pri)
1596         struct selinfo *sip;
1597         int pri;
1598 {
1599         struct selfd *sfp;
1600         struct selfd *sfn;
1601         struct seltd *stp;
1602
1603         /* If it's not initialized there can't be any waiters. */
1604         if (sip->si_mtx == NULL)
1605                 return;
1606         /*
1607          * Locking the selinfo locks all selfds associated with it.
1608          */
1609         mtx_lock(sip->si_mtx);
1610         TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1611                 /*
1612                  * Once we remove this sfp from the list and clear the
1613                  * sf_si seltdclear will know to ignore this si.
1614                  */
1615                 TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1616                 sfp->sf_si = NULL;
1617                 stp = sfp->sf_td;
1618                 mtx_lock(&stp->st_mtx);
1619                 stp->st_flags |= SELTD_PENDING;
1620                 cv_broadcastpri(&stp->st_wait, pri);
1621                 mtx_unlock(&stp->st_mtx);
1622         }
1623         mtx_unlock(sip->si_mtx);
1624 }
1625
1626 static void
1627 seltdinit(struct thread *td)
1628 {
1629         struct seltd *stp;
1630
1631         if ((stp = td->td_sel) != NULL)
1632                 goto out;
1633         td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1634         mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1635         cv_init(&stp->st_wait, "select");
1636 out:
1637         stp->st_flags = 0;
1638         STAILQ_INIT(&stp->st_selq);
1639 }
1640
1641 static int
1642 seltdwait(struct thread *td, int timo)
1643 {
1644         struct seltd *stp;
1645         int error;
1646
1647         stp = td->td_sel;
1648         /*
1649          * An event of interest may occur while we do not hold the seltd
1650          * locked so check the pending flag before we sleep.
1651          */
1652         mtx_lock(&stp->st_mtx);
1653         /*
1654          * Any further calls to selrecord will be a rescan.
1655          */
1656         stp->st_flags |= SELTD_RESCAN;
1657         if (stp->st_flags & SELTD_PENDING) {
1658                 mtx_unlock(&stp->st_mtx);
1659                 return (0);
1660         }
1661         if (timo > 0)
1662                 error = cv_timedwait_sig(&stp->st_wait, &stp->st_mtx, timo);
1663         else
1664                 error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1665         mtx_unlock(&stp->st_mtx);
1666
1667         return (error);
1668 }
1669
1670 void
1671 seltdfini(struct thread *td)
1672 {
1673         struct seltd *stp;
1674
1675         stp = td->td_sel;
1676         if (stp == NULL)
1677                 return;
1678         if (stp->st_free1)
1679                 uma_zfree(selfd_zone, stp->st_free1);
1680         if (stp->st_free2)
1681                 uma_zfree(selfd_zone, stp->st_free2);
1682         td->td_sel = NULL;
1683         free(stp, M_SELECT);
1684 }
1685
1686 /*
1687  * Remove the references to the thread from all of the objects we were
1688  * polling.
1689  */
1690 static void
1691 seltdclear(struct thread *td)
1692 {
1693         struct seltd *stp;
1694         struct selfd *sfp;
1695         struct selfd *sfn;
1696
1697         stp = td->td_sel;
1698         STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1699                 selfdfree(stp, sfp);
1700         stp->st_flags = 0;
1701 }
1702
1703 static void selectinit(void *);
1704 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1705 static void
1706 selectinit(void *dummy __unused)
1707 {
1708
1709         selfd_zone = uma_zcreate("selfd", sizeof(struct selfd), NULL, NULL,
1710             NULL, NULL, UMA_ALIGN_PTR, 0);
1711         mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);
1712 }