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