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