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