]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/sys_generic.c
zfs: merge openzfs/zfs@dbda45160
[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
37 #include <sys/cdefs.h>
38 #include "opt_capsicum.h"
39 #include "opt_ktrace.h"
40
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/sysproto.h>
44 #include <sys/capsicum.h>
45 #include <sys/filedesc.h>
46 #include <sys/filio.h>
47 #include <sys/fcntl.h>
48 #include <sys/file.h>
49 #include <sys/lock.h>
50 #include <sys/proc.h>
51 #include <sys/signalvar.h>
52 #include <sys/socketvar.h>
53 #include <sys/uio.h>
54 #include <sys/eventfd.h>
55 #include <sys/kernel.h>
56 #include <sys/ktr.h>
57 #include <sys/limits.h>
58 #include <sys/malloc.h>
59 #include <sys/poll.h>
60 #include <sys/resourcevar.h>
61 #include <sys/selinfo.h>
62 #include <sys/sleepqueue.h>
63 #include <sys/specialfd.h>
64 #include <sys/syscallsubr.h>
65 #include <sys/sysctl.h>
66 #include <sys/sysent.h>
67 #include <sys/vnode.h>
68 #include <sys/bio.h>
69 #include <sys/buf.h>
70 #include <sys/condvar.h>
71 #ifdef KTRACE
72 #include <sys/ktrace.h>
73 #endif
74
75 #include <security/audit/audit.h>
76
77 /*
78  * The following macro defines how many bytes will be allocated from
79  * the stack instead of memory allocated when passing the IOCTL data
80  * structures from userspace and to the kernel. Some IOCTLs having
81  * small data structures are used very frequently and this small
82  * buffer on the stack gives a significant speedup improvement for
83  * those requests. The value of this define should be greater or equal
84  * to 64 bytes and should also be power of two. The data structure is
85  * currently hard-aligned to a 8-byte boundary on the stack. This
86  * should currently be sufficient for all supported platforms.
87  */
88 #define SYS_IOCTL_SMALL_SIZE    128     /* bytes */
89 #define SYS_IOCTL_SMALL_ALIGN   8       /* bytes */
90
91 #ifdef __LP64__
92 static int iosize_max_clamp = 0;
93 SYSCTL_INT(_debug, OID_AUTO, iosize_max_clamp, CTLFLAG_RW,
94     &iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX");
95 static int devfs_iosize_max_clamp = 1;
96 SYSCTL_INT(_debug, OID_AUTO, devfs_iosize_max_clamp, CTLFLAG_RW,
97     &devfs_iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX for devices");
98 #endif
99
100 /*
101  * Assert that the return value of read(2) and write(2) syscalls fits
102  * into a register.  If not, an architecture will need to provide the
103  * usermode wrappers to reconstruct the result.
104  */
105 CTASSERT(sizeof(register_t) >= sizeof(size_t));
106
107 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
108 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
109 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
110
111 static int      pollout(struct thread *, struct pollfd *, struct pollfd *,
112                     u_int);
113 static int      pollscan(struct thread *, struct pollfd *, u_int);
114 static int      pollrescan(struct thread *);
115 static int      selscan(struct thread *, fd_mask **, fd_mask **, int);
116 static int      selrescan(struct thread *, fd_mask **, fd_mask **);
117 static void     selfdalloc(struct thread *, void *);
118 static void     selfdfree(struct seltd *, struct selfd *);
119 static int      dofileread(struct thread *, int, struct file *, struct uio *,
120                     off_t, int);
121 static int      dofilewrite(struct thread *, int, struct file *, struct uio *,
122                     off_t, int);
123 static void     doselwakeup(struct selinfo *, int);
124 static void     seltdinit(struct thread *);
125 static int      seltdwait(struct thread *, sbintime_t, sbintime_t);
126 static void     seltdclear(struct thread *);
127
128 /*
129  * One seltd per-thread allocated on demand as needed.
130  *
131  *      t - protected by st_mtx
132  *      k - Only accessed by curthread or read-only
133  */
134 struct seltd {
135         STAILQ_HEAD(, selfd)    st_selq;        /* (k) List of selfds. */
136         struct selfd            *st_free1;      /* (k) free fd for read set. */
137         struct selfd            *st_free2;      /* (k) free fd for write set. */
138         struct mtx              st_mtx;         /* Protects struct seltd */
139         struct cv               st_wait;        /* (t) Wait channel. */
140         int                     st_flags;       /* (t) SELTD_ flags. */
141 };
142
143 #define SELTD_PENDING   0x0001                  /* We have pending events. */
144 #define SELTD_RESCAN    0x0002                  /* Doing a rescan. */
145
146 /*
147  * One selfd allocated per-thread per-file-descriptor.
148  *      f - protected by sf_mtx
149  */
150 struct selfd {
151         STAILQ_ENTRY(selfd)     sf_link;        /* (k) fds owned by this td. */
152         TAILQ_ENTRY(selfd)      sf_threads;     /* (f) fds on this selinfo. */
153         struct selinfo          *sf_si;         /* (f) selinfo when linked. */
154         struct mtx              *sf_mtx;        /* Pointer to selinfo mtx. */
155         struct seltd            *sf_td;         /* (k) owning seltd. */
156         void                    *sf_cookie;     /* (k) fd or pollfd. */
157 };
158
159 MALLOC_DEFINE(M_SELFD, "selfd", "selfd");
160 static struct mtx_pool *mtxpool_select;
161
162 #ifdef __LP64__
163 size_t
164 devfs_iosize_max(void)
165 {
166
167         return (devfs_iosize_max_clamp || SV_CURPROC_FLAG(SV_ILP32) ?
168             INT_MAX : SSIZE_MAX);
169 }
170
171 size_t
172 iosize_max(void)
173 {
174
175         return (iosize_max_clamp || SV_CURPROC_FLAG(SV_ILP32) ?
176             INT_MAX : SSIZE_MAX);
177 }
178 #endif
179
180 #ifndef _SYS_SYSPROTO_H_
181 struct read_args {
182         int     fd;
183         void    *buf;
184         size_t  nbyte;
185 };
186 #endif
187 int
188 sys_read(struct thread *td, struct read_args *uap)
189 {
190         struct uio auio;
191         struct iovec aiov;
192         int error;
193
194         if (uap->nbyte > IOSIZE_MAX)
195                 return (EINVAL);
196         aiov.iov_base = uap->buf;
197         aiov.iov_len = uap->nbyte;
198         auio.uio_iov = &aiov;
199         auio.uio_iovcnt = 1;
200         auio.uio_resid = uap->nbyte;
201         auio.uio_segflg = UIO_USERSPACE;
202         error = kern_readv(td, uap->fd, &auio);
203         return (error);
204 }
205
206 /*
207  * Positioned read system call
208  */
209 #ifndef _SYS_SYSPROTO_H_
210 struct pread_args {
211         int     fd;
212         void    *buf;
213         size_t  nbyte;
214         int     pad;
215         off_t   offset;
216 };
217 #endif
218 int
219 sys_pread(struct thread *td, struct pread_args *uap)
220 {
221
222         return (kern_pread(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
223 }
224
225 int
226 kern_pread(struct thread *td, int fd, void *buf, size_t nbyte, off_t offset)
227 {
228         struct uio auio;
229         struct iovec aiov;
230         int error;
231
232         if (nbyte > IOSIZE_MAX)
233                 return (EINVAL);
234         aiov.iov_base = buf;
235         aiov.iov_len = nbyte;
236         auio.uio_iov = &aiov;
237         auio.uio_iovcnt = 1;
238         auio.uio_resid = nbyte;
239         auio.uio_segflg = UIO_USERSPACE;
240         error = kern_preadv(td, fd, &auio, offset);
241         return (error);
242 }
243
244 #if defined(COMPAT_FREEBSD6)
245 int
246 freebsd6_pread(struct thread *td, struct freebsd6_pread_args *uap)
247 {
248
249         return (kern_pread(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
250 }
251 #endif
252
253 /*
254  * Scatter read system call.
255  */
256 #ifndef _SYS_SYSPROTO_H_
257 struct readv_args {
258         int     fd;
259         struct  iovec *iovp;
260         u_int   iovcnt;
261 };
262 #endif
263 int
264 sys_readv(struct thread *td, struct readv_args *uap)
265 {
266         struct uio *auio;
267         int error;
268
269         error = copyinuio(uap->iovp, uap->iovcnt, &auio);
270         if (error)
271                 return (error);
272         error = kern_readv(td, uap->fd, auio);
273         free(auio, M_IOV);
274         return (error);
275 }
276
277 int
278 kern_readv(struct thread *td, int fd, struct uio *auio)
279 {
280         struct file *fp;
281         int error;
282
283         error = fget_read(td, fd, &cap_read_rights, &fp);
284         if (error)
285                 return (error);
286         error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
287         fdrop(fp, td);
288         return (error);
289 }
290
291 /*
292  * Scatter positioned read system call.
293  */
294 #ifndef _SYS_SYSPROTO_H_
295 struct preadv_args {
296         int     fd;
297         struct  iovec *iovp;
298         u_int   iovcnt;
299         off_t   offset;
300 };
301 #endif
302 int
303 sys_preadv(struct thread *td, struct preadv_args *uap)
304 {
305         struct uio *auio;
306         int error;
307
308         error = copyinuio(uap->iovp, uap->iovcnt, &auio);
309         if (error)
310                 return (error);
311         error = kern_preadv(td, uap->fd, auio, uap->offset);
312         free(auio, M_IOV);
313         return (error);
314 }
315
316 int
317 kern_preadv(struct thread *td, int fd, struct uio *auio, off_t offset)
318 {
319         struct file *fp;
320         int error;
321
322         error = fget_read(td, fd, &cap_pread_rights, &fp);
323         if (error)
324                 return (error);
325         if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
326                 error = ESPIPE;
327         else if (offset < 0 &&
328             (fp->f_vnode == NULL || fp->f_vnode->v_type != VCHR))
329                 error = EINVAL;
330         else
331                 error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
332         fdrop(fp, td);
333         return (error);
334 }
335
336 /*
337  * Common code for readv and preadv that reads data in
338  * from a file using the passed in uio, offset, and flags.
339  */
340 static int
341 dofileread(struct thread *td, int fd, struct file *fp, struct uio *auio,
342     off_t offset, int flags)
343 {
344         ssize_t cnt;
345         int error;
346 #ifdef KTRACE
347         struct uio *ktruio = NULL;
348 #endif
349
350         AUDIT_ARG_FD(fd);
351
352         /* Finish zero length reads right here */
353         if (auio->uio_resid == 0) {
354                 td->td_retval[0] = 0;
355                 return (0);
356         }
357         auio->uio_rw = UIO_READ;
358         auio->uio_offset = offset;
359         auio->uio_td = td;
360 #ifdef KTRACE
361         if (KTRPOINT(td, KTR_GENIO)) 
362                 ktruio = cloneuio(auio);
363 #endif
364         cnt = auio->uio_resid;
365         if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
366                 if (auio->uio_resid != cnt && (error == ERESTART ||
367                     error == EINTR || error == EWOULDBLOCK))
368                         error = 0;
369         }
370         cnt -= auio->uio_resid;
371 #ifdef KTRACE
372         if (ktruio != NULL) {
373                 ktruio->uio_resid = cnt;
374                 ktrgenio(fd, UIO_READ, ktruio, error);
375         }
376 #endif
377         td->td_retval[0] = cnt;
378         return (error);
379 }
380
381 #ifndef _SYS_SYSPROTO_H_
382 struct write_args {
383         int     fd;
384         const void *buf;
385         size_t  nbyte;
386 };
387 #endif
388 int
389 sys_write(struct thread *td, struct write_args *uap)
390 {
391         struct uio auio;
392         struct iovec aiov;
393         int error;
394
395         if (uap->nbyte > IOSIZE_MAX)
396                 return (EINVAL);
397         aiov.iov_base = (void *)(uintptr_t)uap->buf;
398         aiov.iov_len = uap->nbyte;
399         auio.uio_iov = &aiov;
400         auio.uio_iovcnt = 1;
401         auio.uio_resid = uap->nbyte;
402         auio.uio_segflg = UIO_USERSPACE;
403         error = kern_writev(td, uap->fd, &auio);
404         return (error);
405 }
406
407 /*
408  * Positioned write system call.
409  */
410 #ifndef _SYS_SYSPROTO_H_
411 struct pwrite_args {
412         int     fd;
413         const void *buf;
414         size_t  nbyte;
415         int     pad;
416         off_t   offset;
417 };
418 #endif
419 int
420 sys_pwrite(struct thread *td, struct pwrite_args *uap)
421 {
422
423         return (kern_pwrite(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
424 }
425
426 int
427 kern_pwrite(struct thread *td, int fd, const void *buf, size_t nbyte,
428     off_t offset)
429 {
430         struct uio auio;
431         struct iovec aiov;
432         int error;
433
434         if (nbyte > IOSIZE_MAX)
435                 return (EINVAL);
436         aiov.iov_base = (void *)(uintptr_t)buf;
437         aiov.iov_len = nbyte;
438         auio.uio_iov = &aiov;
439         auio.uio_iovcnt = 1;
440         auio.uio_resid = nbyte;
441         auio.uio_segflg = UIO_USERSPACE;
442         error = kern_pwritev(td, fd, &auio, offset);
443         return (error);
444 }
445
446 #if defined(COMPAT_FREEBSD6)
447 int
448 freebsd6_pwrite(struct thread *td, struct freebsd6_pwrite_args *uap)
449 {
450
451         return (kern_pwrite(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
452 }
453 #endif
454
455 /*
456  * Gather write system call.
457  */
458 #ifndef _SYS_SYSPROTO_H_
459 struct writev_args {
460         int     fd;
461         struct  iovec *iovp;
462         u_int   iovcnt;
463 };
464 #endif
465 int
466 sys_writev(struct thread *td, struct writev_args *uap)
467 {
468         struct uio *auio;
469         int error;
470
471         error = copyinuio(uap->iovp, uap->iovcnt, &auio);
472         if (error)
473                 return (error);
474         error = kern_writev(td, uap->fd, auio);
475         free(auio, M_IOV);
476         return (error);
477 }
478
479 int
480 kern_writev(struct thread *td, int fd, struct uio *auio)
481 {
482         struct file *fp;
483         int error;
484
485         error = fget_write(td, fd, &cap_write_rights, &fp);
486         if (error)
487                 return (error);
488         error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
489         fdrop(fp, td);
490         return (error);
491 }
492
493 /*
494  * Gather positioned write system call.
495  */
496 #ifndef _SYS_SYSPROTO_H_
497 struct pwritev_args {
498         int     fd;
499         struct  iovec *iovp;
500         u_int   iovcnt;
501         off_t   offset;
502 };
503 #endif
504 int
505 sys_pwritev(struct thread *td, struct pwritev_args *uap)
506 {
507         struct uio *auio;
508         int error;
509
510         error = copyinuio(uap->iovp, uap->iovcnt, &auio);
511         if (error)
512                 return (error);
513         error = kern_pwritev(td, uap->fd, auio, uap->offset);
514         free(auio, M_IOV);
515         return (error);
516 }
517
518 int
519 kern_pwritev(struct thread *td, int fd, struct uio *auio, off_t offset)
520 {
521         struct file *fp;
522         int error;
523
524         error = fget_write(td, fd, &cap_pwrite_rights, &fp);
525         if (error)
526                 return (error);
527         if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
528                 error = ESPIPE;
529         else if (offset < 0 &&
530             (fp->f_vnode == NULL || fp->f_vnode->v_type != VCHR))
531                 error = EINVAL;
532         else
533                 error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
534         fdrop(fp, td);
535         return (error);
536 }
537
538 /*
539  * Common code for writev and pwritev that writes data to
540  * a file using the passed in uio, offset, and flags.
541  */
542 static int
543 dofilewrite(struct thread *td, int fd, struct file *fp, struct uio *auio,
544     off_t offset, int flags)
545 {
546         ssize_t cnt;
547         int error;
548 #ifdef KTRACE
549         struct uio *ktruio = NULL;
550 #endif
551
552         AUDIT_ARG_FD(fd);
553         auio->uio_rw = UIO_WRITE;
554         auio->uio_td = td;
555         auio->uio_offset = offset;
556 #ifdef KTRACE
557         if (KTRPOINT(td, KTR_GENIO))
558                 ktruio = cloneuio(auio);
559 #endif
560         cnt = auio->uio_resid;
561         error = fo_write(fp, auio, td->td_ucred, flags, td);
562         /*
563          * Socket layer is responsible for special error handling,
564          * see sousrsend().
565          */
566         if (error != 0 && fp->f_type != DTYPE_SOCKET) {
567                 if (auio->uio_resid != cnt && (error == ERESTART ||
568                     error == EINTR || error == EWOULDBLOCK))
569                         error = 0;
570                 if (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_noref(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                 ast_sched(td, TDA_SIGSUSPEND);
1056         }
1057         error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
1058         return (error);
1059 }
1060
1061 #ifndef _SYS_SYSPROTO_H_
1062 struct select_args {
1063         int     nd;
1064         fd_set  *in, *ou, *ex;
1065         struct  timeval *tv;
1066 };
1067 #endif
1068 int
1069 sys_select(struct thread *td, struct select_args *uap)
1070 {
1071         struct timeval tv, *tvp;
1072         int error;
1073
1074         if (uap->tv != NULL) {
1075                 error = copyin(uap->tv, &tv, sizeof(tv));
1076                 if (error)
1077                         return (error);
1078                 tvp = &tv;
1079         } else
1080                 tvp = NULL;
1081
1082         return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
1083             NFDBITS));
1084 }
1085
1086 /*
1087  * In the unlikely case when user specified n greater then the last
1088  * open file descriptor, check that no bits are set after the last
1089  * valid fd.  We must return EBADF if any is set.
1090  *
1091  * There are applications that rely on the behaviour.
1092  *
1093  * nd is fd_nfiles.
1094  */
1095 static int
1096 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
1097 {
1098         char *addr, *oaddr;
1099         int b, i, res;
1100         uint8_t bits;
1101
1102         if (nd >= ndu || fd_in == NULL)
1103                 return (0);
1104
1105         oaddr = NULL;
1106         bits = 0; /* silence gcc */
1107         for (i = nd; i < ndu; i++) {
1108                 b = i / NBBY;
1109 #if BYTE_ORDER == LITTLE_ENDIAN
1110                 addr = (char *)fd_in + b;
1111 #else
1112                 addr = (char *)fd_in;
1113                 if (abi_nfdbits == NFDBITS) {
1114                         addr += rounddown(b, sizeof(fd_mask)) +
1115                             sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
1116                 } else {
1117                         addr += rounddown(b, sizeof(uint32_t)) +
1118                             sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
1119                 }
1120 #endif
1121                 if (addr != oaddr) {
1122                         res = fubyte(addr);
1123                         if (res == -1)
1124                                 return (EFAULT);
1125                         oaddr = addr;
1126                         bits = res;
1127                 }
1128                 if ((bits & (1 << (i % NBBY))) != 0)
1129                         return (EBADF);
1130         }
1131         return (0);
1132 }
1133
1134 int
1135 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
1136     fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
1137 {
1138         struct filedesc *fdp;
1139         /*
1140          * The magic 2048 here is chosen to be just enough for FD_SETSIZE
1141          * infds with the new FD_SETSIZE of 1024, and more than enough for
1142          * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
1143          * of 256.
1144          */
1145         fd_mask s_selbits[howmany(2048, NFDBITS)];
1146         fd_mask *ibits[3], *obits[3], *selbits, *sbp;
1147         struct timeval rtv;
1148         sbintime_t asbt, precision, rsbt;
1149         u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
1150         int error, lf, ndu;
1151
1152         if (nd < 0)
1153                 return (EINVAL);
1154         fdp = td->td_proc->p_fd;
1155         ndu = nd;
1156         lf = fdp->fd_nfiles;
1157         if (nd > lf)
1158                 nd = lf;
1159
1160         error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
1161         if (error != 0)
1162                 return (error);
1163         error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
1164         if (error != 0)
1165                 return (error);
1166         error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
1167         if (error != 0)
1168                 return (error);
1169
1170         /*
1171          * Allocate just enough bits for the non-null fd_sets.  Use the
1172          * preallocated auto buffer if possible.
1173          */
1174         nfdbits = roundup(nd, NFDBITS);
1175         ncpbytes = nfdbits / NBBY;
1176         ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
1177         nbufbytes = 0;
1178         if (fd_in != NULL)
1179                 nbufbytes += 2 * ncpbytes;
1180         if (fd_ou != NULL)
1181                 nbufbytes += 2 * ncpbytes;
1182         if (fd_ex != NULL)
1183                 nbufbytes += 2 * ncpbytes;
1184         if (nbufbytes <= sizeof s_selbits)
1185                 selbits = &s_selbits[0];
1186         else
1187                 selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
1188
1189         /*
1190          * Assign pointers into the bit buffers and fetch the input bits.
1191          * Put the output buffers together so that they can be bzeroed
1192          * together.
1193          */
1194         sbp = selbits;
1195 #define getbits(name, x) \
1196         do {                                                            \
1197                 if (name == NULL) {                                     \
1198                         ibits[x] = NULL;                                \
1199                         obits[x] = NULL;                                \
1200                 } else {                                                \
1201                         ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp;   \
1202                         obits[x] = sbp;                                 \
1203                         sbp += ncpbytes / sizeof *sbp;                  \
1204                         error = copyin(name, ibits[x], ncpubytes);      \
1205                         if (error != 0)                                 \
1206                                 goto done;                              \
1207                         if (ncpbytes != ncpubytes)                      \
1208                                 bzero((char *)ibits[x] + ncpubytes,     \
1209                                     ncpbytes - ncpubytes);              \
1210                 }                                                       \
1211         } while (0)
1212         getbits(fd_in, 0);
1213         getbits(fd_ou, 1);
1214         getbits(fd_ex, 2);
1215 #undef  getbits
1216
1217 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
1218         /*
1219          * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
1220          * we are running under 32-bit emulation. This should be more
1221          * generic.
1222          */
1223 #define swizzle_fdset(bits)                                             \
1224         if (abi_nfdbits != NFDBITS && bits != NULL) {                   \
1225                 int i;                                                  \
1226                 for (i = 0; i < ncpbytes / sizeof *sbp; i++)            \
1227                         bits[i] = (bits[i] >> 32) | (bits[i] << 32);    \
1228         }
1229 #else
1230 #define swizzle_fdset(bits)
1231 #endif
1232
1233         /* Make sure the bit order makes it through an ABI transition */
1234         swizzle_fdset(ibits[0]);
1235         swizzle_fdset(ibits[1]);
1236         swizzle_fdset(ibits[2]);
1237
1238         if (nbufbytes != 0)
1239                 bzero(selbits, nbufbytes / 2);
1240
1241         precision = 0;
1242         if (tvp != NULL) {
1243                 rtv = *tvp;
1244                 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1245                     rtv.tv_usec >= 1000000) {
1246                         error = EINVAL;
1247                         goto done;
1248                 }
1249                 if (!timevalisset(&rtv))
1250                         asbt = 0;
1251                 else if (rtv.tv_sec <= INT32_MAX) {
1252                         rsbt = tvtosbt(rtv);
1253                         precision = rsbt;
1254                         precision >>= tc_precexp;
1255                         if (TIMESEL(&asbt, rsbt))
1256                                 asbt += tc_tick_sbt;
1257                         if (asbt <= SBT_MAX - rsbt)
1258                                 asbt += rsbt;
1259                         else
1260                                 asbt = -1;
1261                 } else
1262                         asbt = -1;
1263         } else
1264                 asbt = -1;
1265         seltdinit(td);
1266         /* Iterate until the timeout expires or descriptors become ready. */
1267         for (;;) {
1268                 error = selscan(td, ibits, obits, nd);
1269                 if (error || td->td_retval[0] != 0)
1270                         break;
1271                 error = seltdwait(td, asbt, precision);
1272                 if (error)
1273                         break;
1274                 error = selrescan(td, ibits, obits);
1275                 if (error || td->td_retval[0] != 0)
1276                         break;
1277         }
1278         seltdclear(td);
1279
1280 done:
1281         /* select is not restarted after signals... */
1282         if (error == ERESTART)
1283                 error = EINTR;
1284         if (error == EWOULDBLOCK)
1285                 error = 0;
1286
1287         /* swizzle bit order back, if necessary */
1288         swizzle_fdset(obits[0]);
1289         swizzle_fdset(obits[1]);
1290         swizzle_fdset(obits[2]);
1291 #undef swizzle_fdset
1292
1293 #define putbits(name, x) \
1294         if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1295                 error = error2;
1296         if (error == 0) {
1297                 int error2;
1298
1299                 putbits(fd_in, 0);
1300                 putbits(fd_ou, 1);
1301                 putbits(fd_ex, 2);
1302 #undef putbits
1303         }
1304         if (selbits != &s_selbits[0])
1305                 free(selbits, M_SELECT);
1306
1307         return (error);
1308 }
1309 /* 
1310  * Convert a select bit set to poll flags.
1311  *
1312  * The backend always returns POLLHUP/POLLERR if appropriate and we
1313  * return this as a set bit in any set.
1314  */
1315 static const int select_flags[3] = {
1316     POLLRDNORM | POLLHUP | POLLERR,
1317     POLLWRNORM | POLLHUP | POLLERR,
1318     POLLRDBAND | POLLERR
1319 };
1320
1321 /*
1322  * Compute the fo_poll flags required for a fd given by the index and
1323  * bit position in the fd_mask array.
1324  */
1325 static __inline int
1326 selflags(fd_mask **ibits, int idx, fd_mask bit)
1327 {
1328         int flags;
1329         int msk;
1330
1331         flags = 0;
1332         for (msk = 0; msk < 3; msk++) {
1333                 if (ibits[msk] == NULL)
1334                         continue;
1335                 if ((ibits[msk][idx] & bit) == 0)
1336                         continue;
1337                 flags |= select_flags[msk];
1338         }
1339         return (flags);
1340 }
1341
1342 /*
1343  * Set the appropriate output bits given a mask of fired events and the
1344  * input bits originally requested.
1345  */
1346 static __inline int
1347 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1348 {
1349         int msk;
1350         int n;
1351
1352         n = 0;
1353         for (msk = 0; msk < 3; msk++) {
1354                 if ((events & select_flags[msk]) == 0)
1355                         continue;
1356                 if (ibits[msk] == NULL)
1357                         continue;
1358                 if ((ibits[msk][idx] & bit) == 0)
1359                         continue;
1360                 /*
1361                  * XXX Check for a duplicate set.  This can occur because a
1362                  * socket calls selrecord() twice for each poll() call
1363                  * resulting in two selfds per real fd.  selrescan() will
1364                  * call selsetbits twice as a result.
1365                  */
1366                 if ((obits[msk][idx] & bit) != 0)
1367                         continue;
1368                 obits[msk][idx] |= bit;
1369                 n++;
1370         }
1371
1372         return (n);
1373 }
1374
1375 /*
1376  * Traverse the list of fds attached to this thread's seltd and check for
1377  * completion.
1378  */
1379 static int
1380 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1381 {
1382         struct filedesc *fdp;
1383         struct selinfo *si;
1384         struct seltd *stp;
1385         struct selfd *sfp;
1386         struct selfd *sfn;
1387         struct file *fp;
1388         fd_mask bit;
1389         int fd, ev, n, idx;
1390         int error;
1391         bool only_user;
1392
1393         fdp = td->td_proc->p_fd;
1394         stp = td->td_sel;
1395         n = 0;
1396         only_user = FILEDESC_IS_ONLY_USER(fdp);
1397         STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1398                 fd = (int)(uintptr_t)sfp->sf_cookie;
1399                 si = sfp->sf_si;
1400                 selfdfree(stp, sfp);
1401                 /* If the selinfo wasn't cleared the event didn't fire. */
1402                 if (si != NULL)
1403                         continue;
1404                 if (only_user)
1405                         error = fget_only_user(fdp, fd, &cap_event_rights, &fp);
1406                 else
1407                         error = fget_unlocked(td, fd, &cap_event_rights, &fp);
1408                 if (__predict_false(error != 0))
1409                         return (error);
1410                 idx = fd / NFDBITS;
1411                 bit = (fd_mask)1 << (fd % NFDBITS);
1412                 ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1413                 if (only_user)
1414                         fput_only_user(fdp, fp);
1415                 else
1416                         fdrop(fp, td);
1417                 if (ev != 0)
1418                         n += selsetbits(ibits, obits, idx, bit, ev);
1419         }
1420         stp->st_flags = 0;
1421         td->td_retval[0] = n;
1422         return (0);
1423 }
1424
1425 /*
1426  * Perform the initial filedescriptor scan and register ourselves with
1427  * each selinfo.
1428  */
1429 static int
1430 selscan(struct thread *td, fd_mask **ibits, fd_mask **obits, int nfd)
1431 {
1432         struct filedesc *fdp;
1433         struct file *fp;
1434         fd_mask bit;
1435         int ev, flags, end, fd;
1436         int n, idx;
1437         int error;
1438         bool only_user;
1439
1440         fdp = td->td_proc->p_fd;
1441         n = 0;
1442         only_user = FILEDESC_IS_ONLY_USER(fdp);
1443         for (idx = 0, fd = 0; fd < nfd; idx++) {
1444                 end = imin(fd + NFDBITS, nfd);
1445                 for (bit = 1; fd < end; bit <<= 1, fd++) {
1446                         /* Compute the list of events we're interested in. */
1447                         flags = selflags(ibits, idx, bit);
1448                         if (flags == 0)
1449                                 continue;
1450                         if (only_user)
1451                                 error = fget_only_user(fdp, fd, &cap_event_rights, &fp);
1452                         else
1453                                 error = fget_unlocked(td, fd, &cap_event_rights, &fp);
1454                         if (__predict_false(error != 0))
1455                                 return (error);
1456                         selfdalloc(td, (void *)(uintptr_t)fd);
1457                         ev = fo_poll(fp, flags, td->td_ucred, td);
1458                         if (only_user)
1459                                 fput_only_user(fdp, fp);
1460                         else
1461                                 fdrop(fp, td);
1462                         if (ev != 0)
1463                                 n += selsetbits(ibits, obits, idx, bit, ev);
1464                 }
1465         }
1466
1467         td->td_retval[0] = n;
1468         return (0);
1469 }
1470
1471 int
1472 sys_poll(struct thread *td, struct poll_args *uap)
1473 {
1474         struct timespec ts, *tsp;
1475
1476         if (uap->timeout != INFTIM) {
1477                 if (uap->timeout < 0)
1478                         return (EINVAL);
1479                 ts.tv_sec = uap->timeout / 1000;
1480                 ts.tv_nsec = (uap->timeout % 1000) * 1000000;
1481                 tsp = &ts;
1482         } else
1483                 tsp = NULL;
1484
1485         return (kern_poll(td, uap->fds, uap->nfds, tsp, NULL));
1486 }
1487
1488 /*
1489  * kfds points to an array in the kernel.
1490  */
1491 int
1492 kern_poll_kfds(struct thread *td, struct pollfd *kfds, u_int nfds,
1493     struct timespec *tsp, sigset_t *uset)
1494 {
1495         sbintime_t sbt, precision, tmp;
1496         time_t over;
1497         struct timespec ts;
1498         int error;
1499
1500         precision = 0;
1501         if (tsp != NULL) {
1502                 if (!timespecvalid_interval(tsp))
1503                         return (EINVAL);
1504                 if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
1505                         sbt = 0;
1506                 else {
1507                         ts = *tsp;
1508                         if (ts.tv_sec > INT32_MAX / 2) {
1509                                 over = ts.tv_sec - INT32_MAX / 2;
1510                                 ts.tv_sec -= over;
1511                         } else
1512                                 over = 0;
1513                         tmp = tstosbt(ts);
1514                         precision = tmp;
1515                         precision >>= tc_precexp;
1516                         if (TIMESEL(&sbt, tmp))
1517                                 sbt += tc_tick_sbt;
1518                         sbt += tmp;
1519                 }
1520         } else
1521                 sbt = -1;
1522
1523         if (uset != NULL) {
1524                 error = kern_sigprocmask(td, SIG_SETMASK, uset,
1525                     &td->td_oldsigmask, 0);
1526                 if (error)
1527                         return (error);
1528                 td->td_pflags |= TDP_OLDMASK;
1529                 /*
1530                  * Make sure that ast() is called on return to
1531                  * usermode and TDP_OLDMASK is cleared, restoring old
1532                  * sigmask.
1533                  */
1534                 ast_sched(td, TDA_SIGSUSPEND);
1535         }
1536
1537         seltdinit(td);
1538         /* Iterate until the timeout expires or descriptors become ready. */
1539         for (;;) {
1540                 error = pollscan(td, kfds, nfds);
1541                 if (error || td->td_retval[0] != 0)
1542                         break;
1543                 error = seltdwait(td, sbt, precision);
1544                 if (error)
1545                         break;
1546                 error = pollrescan(td);
1547                 if (error || td->td_retval[0] != 0)
1548                         break;
1549         }
1550         seltdclear(td);
1551
1552         /* poll is not restarted after signals... */
1553         if (error == ERESTART)
1554                 error = EINTR;
1555         if (error == EWOULDBLOCK)
1556                 error = 0;
1557         return (error);
1558 }
1559
1560 int
1561 sys_ppoll(struct thread *td, struct ppoll_args *uap)
1562 {
1563         struct timespec ts, *tsp;
1564         sigset_t set, *ssp;
1565         int error;
1566
1567         if (uap->ts != NULL) {
1568                 error = copyin(uap->ts, &ts, sizeof(ts));
1569                 if (error)
1570                         return (error);
1571                 tsp = &ts;
1572         } else
1573                 tsp = NULL;
1574         if (uap->set != NULL) {
1575                 error = copyin(uap->set, &set, sizeof(set));
1576                 if (error)
1577                         return (error);
1578                 ssp = &set;
1579         } else
1580                 ssp = NULL;
1581         return (kern_poll(td, uap->fds, uap->nfds, tsp, ssp));
1582 }
1583
1584 /*
1585  * ufds points to an array in user space.
1586  */
1587 int
1588 kern_poll(struct thread *td, struct pollfd *ufds, u_int nfds,
1589     struct timespec *tsp, sigset_t *set)
1590 {
1591         struct pollfd *kfds;
1592         struct pollfd stackfds[32];
1593         int error;
1594
1595         if (kern_poll_maxfds(nfds))
1596                 return (EINVAL);
1597         if (nfds > nitems(stackfds))
1598                 kfds = mallocarray(nfds, sizeof(*kfds), M_TEMP, M_WAITOK);
1599         else
1600                 kfds = stackfds;
1601         error = copyin(ufds, kfds, nfds * sizeof(*kfds));
1602         if (error != 0)
1603                 goto out;
1604
1605         error = kern_poll_kfds(td, kfds, nfds, tsp, set);
1606         if (error == 0)
1607                 error = pollout(td, kfds, ufds, nfds);
1608
1609 out:
1610         if (nfds > nitems(stackfds))
1611                 free(kfds, M_TEMP);
1612         return (error);
1613 }
1614
1615 bool
1616 kern_poll_maxfds(u_int nfds)
1617 {
1618
1619         /*
1620          * This is kinda bogus.  We have fd limits, but that is not
1621          * really related to the size of the pollfd array.  Make sure
1622          * we let the process use at least FD_SETSIZE entries and at
1623          * least enough for the system-wide limits.  We want to be reasonably
1624          * safe, but not overly restrictive.
1625          */
1626         return (nfds > maxfilesperproc && nfds > FD_SETSIZE);
1627 }
1628
1629 static int
1630 pollrescan(struct thread *td)
1631 {
1632         struct seltd *stp;
1633         struct selfd *sfp;
1634         struct selfd *sfn;
1635         struct selinfo *si;
1636         struct filedesc *fdp;
1637         struct file *fp;
1638         struct pollfd *fd;
1639         int n, error;
1640         bool only_user;
1641
1642         n = 0;
1643         fdp = td->td_proc->p_fd;
1644         stp = td->td_sel;
1645         only_user = FILEDESC_IS_ONLY_USER(fdp);
1646         STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1647                 fd = (struct pollfd *)sfp->sf_cookie;
1648                 si = sfp->sf_si;
1649                 selfdfree(stp, sfp);
1650                 /* If the selinfo wasn't cleared the event didn't fire. */
1651                 if (si != NULL)
1652                         continue;
1653                 if (only_user)
1654                         error = fget_only_user(fdp, fd->fd, &cap_event_rights, &fp);
1655                 else
1656                         error = fget_unlocked(td, fd->fd, &cap_event_rights, &fp);
1657                 if (__predict_false(error != 0)) {
1658                         fd->revents = POLLNVAL;
1659                         n++;
1660                         continue;
1661                 }
1662                 /*
1663                  * Note: backend also returns POLLHUP and
1664                  * POLLERR if appropriate.
1665                  */
1666                 fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1667                 if (only_user)
1668                         fput_only_user(fdp, fp);
1669                 else
1670                         fdrop(fp, td);
1671                 if (fd->revents != 0)
1672                         n++;
1673         }
1674         stp->st_flags = 0;
1675         td->td_retval[0] = n;
1676         return (0);
1677 }
1678
1679 static int
1680 pollout(struct thread *td, struct pollfd *fds, struct pollfd *ufds, u_int nfd)
1681 {
1682         int error = 0;
1683         u_int i = 0;
1684         u_int n = 0;
1685
1686         for (i = 0; i < nfd; i++) {
1687                 error = copyout(&fds->revents, &ufds->revents,
1688                     sizeof(ufds->revents));
1689                 if (error)
1690                         return (error);
1691                 if (fds->revents != 0)
1692                         n++;
1693                 fds++;
1694                 ufds++;
1695         }
1696         td->td_retval[0] = n;
1697         return (0);
1698 }
1699
1700 static int
1701 pollscan(struct thread *td, struct pollfd *fds, u_int nfd)
1702 {
1703         struct filedesc *fdp;
1704         struct file *fp;
1705         int i, n, error;
1706         bool only_user;
1707
1708         n = 0;
1709         fdp = td->td_proc->p_fd;
1710         only_user = FILEDESC_IS_ONLY_USER(fdp);
1711         for (i = 0; i < nfd; i++, fds++) {
1712                 if (fds->fd < 0) {
1713                         fds->revents = 0;
1714                         continue;
1715                 }
1716                 if (only_user)
1717                         error = fget_only_user(fdp, fds->fd, &cap_event_rights, &fp);
1718                 else
1719                         error = fget_unlocked(td, fds->fd, &cap_event_rights, &fp);
1720                 if (__predict_false(error != 0)) {
1721                         fds->revents = POLLNVAL;
1722                         n++;
1723                         continue;
1724                 }
1725                 /*
1726                  * Note: backend also returns POLLHUP and
1727                  * POLLERR if appropriate.
1728                  */
1729                 selfdalloc(td, fds);
1730                 fds->revents = fo_poll(fp, fds->events,
1731                     td->td_ucred, td);
1732                 if (only_user)
1733                         fput_only_user(fdp, fp);
1734                 else
1735                         fdrop(fp, td);
1736                 /*
1737                  * POSIX requires POLLOUT to be never
1738                  * set simultaneously with POLLHUP.
1739                  */
1740                 if ((fds->revents & POLLHUP) != 0)
1741                         fds->revents &= ~POLLOUT;
1742
1743                 if (fds->revents != 0)
1744                         n++;
1745         }
1746         td->td_retval[0] = n;
1747         return (0);
1748 }
1749
1750 /*
1751  * XXX This was created specifically to support netncp and netsmb.  This
1752  * allows the caller to specify a socket to wait for events on.  It returns
1753  * 0 if any events matched and an error otherwise.  There is no way to
1754  * determine which events fired.
1755  */
1756 int
1757 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1758 {
1759         struct timeval rtv;
1760         sbintime_t asbt, precision, rsbt;
1761         int error;
1762
1763         precision = 0;  /* stupid gcc! */
1764         if (tvp != NULL) {
1765                 rtv = *tvp;
1766                 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 || 
1767                     rtv.tv_usec >= 1000000)
1768                         return (EINVAL);
1769                 if (!timevalisset(&rtv))
1770                         asbt = 0;
1771                 else if (rtv.tv_sec <= INT32_MAX) {
1772                         rsbt = tvtosbt(rtv);
1773                         precision = rsbt;
1774                         precision >>= tc_precexp;
1775                         if (TIMESEL(&asbt, rsbt))
1776                                 asbt += tc_tick_sbt;
1777                         if (asbt <= SBT_MAX - rsbt)
1778                                 asbt += rsbt;
1779                         else
1780                                 asbt = -1;
1781                 } else
1782                         asbt = -1;
1783         } else
1784                 asbt = -1;
1785         seltdinit(td);
1786         /*
1787          * Iterate until the timeout expires or the socket becomes ready.
1788          */
1789         for (;;) {
1790                 selfdalloc(td, NULL);
1791                 if (sopoll(so, events, NULL, td) != 0) {
1792                         error = 0;
1793                         break;
1794                 }
1795                 error = seltdwait(td, asbt, precision);
1796                 if (error)
1797                         break;
1798         }
1799         seltdclear(td);
1800         /* XXX Duplicates ncp/smb behavior. */
1801         if (error == ERESTART)
1802                 error = 0;
1803         return (error);
1804 }
1805
1806 /*
1807  * Preallocate two selfds associated with 'cookie'.  Some fo_poll routines
1808  * have two select sets, one for read and another for write.
1809  */
1810 static void
1811 selfdalloc(struct thread *td, void *cookie)
1812 {
1813         struct seltd *stp;
1814
1815         stp = td->td_sel;
1816         if (stp->st_free1 == NULL)
1817                 stp->st_free1 = malloc(sizeof(*stp->st_free1), M_SELFD, M_WAITOK|M_ZERO);
1818         stp->st_free1->sf_td = stp;
1819         stp->st_free1->sf_cookie = cookie;
1820         if (stp->st_free2 == NULL)
1821                 stp->st_free2 = malloc(sizeof(*stp->st_free2), M_SELFD, M_WAITOK|M_ZERO);
1822         stp->st_free2->sf_td = stp;
1823         stp->st_free2->sf_cookie = cookie;
1824 }
1825
1826 static void
1827 selfdfree(struct seltd *stp, struct selfd *sfp)
1828 {
1829         STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1830         /*
1831          * Paired with doselwakeup.
1832          */
1833         if (atomic_load_acq_ptr((uintptr_t *)&sfp->sf_si) != (uintptr_t)NULL) {
1834                 mtx_lock(sfp->sf_mtx);
1835                 if (sfp->sf_si != NULL) {
1836                         TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1837                 }
1838                 mtx_unlock(sfp->sf_mtx);
1839         }
1840         free(sfp, M_SELFD);
1841 }
1842
1843 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1844 void
1845 seldrain(struct selinfo *sip)
1846 {
1847
1848         /*
1849          * This feature is already provided by doselwakeup(), thus it is
1850          * enough to go for it.
1851          * Eventually, the context, should take care to avoid races
1852          * between thread calling select()/poll() and file descriptor
1853          * detaching, but, again, the races are just the same as
1854          * selwakeup().
1855          */
1856         doselwakeup(sip, -1);
1857 }
1858
1859 /*
1860  * Record a select request.
1861  */
1862 void
1863 selrecord(struct thread *selector, struct selinfo *sip)
1864 {
1865         struct selfd *sfp;
1866         struct seltd *stp;
1867         struct mtx *mtxp;
1868
1869         stp = selector->td_sel;
1870         /*
1871          * Don't record when doing a rescan.
1872          */
1873         if (stp->st_flags & SELTD_RESCAN)
1874                 return;
1875         /*
1876          * Grab one of the preallocated descriptors.
1877          */
1878         sfp = NULL;
1879         if ((sfp = stp->st_free1) != NULL)
1880                 stp->st_free1 = NULL;
1881         else if ((sfp = stp->st_free2) != NULL)
1882                 stp->st_free2 = NULL;
1883         else
1884                 panic("selrecord: No free selfd on selq");
1885         mtxp = sip->si_mtx;
1886         if (mtxp == NULL)
1887                 mtxp = mtx_pool_find(mtxpool_select, sip);
1888         /*
1889          * Initialize the sfp and queue it in the thread.
1890          */
1891         sfp->sf_si = sip;
1892         sfp->sf_mtx = mtxp;
1893         STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1894         /*
1895          * Now that we've locked the sip, check for initialization.
1896          */
1897         mtx_lock(mtxp);
1898         if (sip->si_mtx == NULL) {
1899                 sip->si_mtx = mtxp;
1900                 TAILQ_INIT(&sip->si_tdlist);
1901         }
1902         /*
1903          * Add this thread to the list of selfds listening on this selinfo.
1904          */
1905         TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1906         mtx_unlock(sip->si_mtx);
1907 }
1908
1909 /* Wake up a selecting thread. */
1910 void
1911 selwakeup(struct selinfo *sip)
1912 {
1913         doselwakeup(sip, -1);
1914 }
1915
1916 /* Wake up a selecting thread, and set its priority. */
1917 void
1918 selwakeuppri(struct selinfo *sip, int pri)
1919 {
1920         doselwakeup(sip, pri);
1921 }
1922
1923 /*
1924  * Do a wakeup when a selectable event occurs.
1925  */
1926 static void
1927 doselwakeup(struct selinfo *sip, int pri)
1928 {
1929         struct selfd *sfp;
1930         struct selfd *sfn;
1931         struct seltd *stp;
1932
1933         /* If it's not initialized there can't be any waiters. */
1934         if (sip->si_mtx == NULL)
1935                 return;
1936         /*
1937          * Locking the selinfo locks all selfds associated with it.
1938          */
1939         mtx_lock(sip->si_mtx);
1940         TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1941                 /*
1942                  * Once we remove this sfp from the list and clear the
1943                  * sf_si seltdclear will know to ignore this si.
1944                  */
1945                 TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1946                 stp = sfp->sf_td;
1947                 mtx_lock(&stp->st_mtx);
1948                 stp->st_flags |= SELTD_PENDING;
1949                 cv_broadcastpri(&stp->st_wait, pri);
1950                 mtx_unlock(&stp->st_mtx);
1951                 /*
1952                  * Paired with selfdfree.
1953                  *
1954                  * Storing this only after the wakeup provides an invariant that
1955                  * stp is not used after selfdfree returns.
1956                  */
1957                 atomic_store_rel_ptr((uintptr_t *)&sfp->sf_si, (uintptr_t)NULL);
1958         }
1959         mtx_unlock(sip->si_mtx);
1960 }
1961
1962 static void
1963 seltdinit(struct thread *td)
1964 {
1965         struct seltd *stp;
1966
1967         stp = td->td_sel;
1968         if (stp != NULL) {
1969                 MPASS(stp->st_flags == 0);
1970                 MPASS(STAILQ_EMPTY(&stp->st_selq));
1971                 return;
1972         }
1973         stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1974         mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1975         cv_init(&stp->st_wait, "select");
1976         stp->st_flags = 0;
1977         STAILQ_INIT(&stp->st_selq);
1978         td->td_sel = stp;
1979 }
1980
1981 static int
1982 seltdwait(struct thread *td, sbintime_t sbt, sbintime_t precision)
1983 {
1984         struct seltd *stp;
1985         int error;
1986
1987         stp = td->td_sel;
1988         /*
1989          * An event of interest may occur while we do not hold the seltd
1990          * locked so check the pending flag before we sleep.
1991          */
1992         mtx_lock(&stp->st_mtx);
1993         /*
1994          * Any further calls to selrecord will be a rescan.
1995          */
1996         stp->st_flags |= SELTD_RESCAN;
1997         if (stp->st_flags & SELTD_PENDING) {
1998                 mtx_unlock(&stp->st_mtx);
1999                 return (0);
2000         }
2001         if (sbt == 0)
2002                 error = EWOULDBLOCK;
2003         else if (sbt != -1)
2004                 error = cv_timedwait_sig_sbt(&stp->st_wait, &stp->st_mtx,
2005                     sbt, precision, C_ABSOLUTE);
2006         else
2007                 error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
2008         mtx_unlock(&stp->st_mtx);
2009
2010         return (error);
2011 }
2012
2013 void
2014 seltdfini(struct thread *td)
2015 {
2016         struct seltd *stp;
2017
2018         stp = td->td_sel;
2019         if (stp == NULL)
2020                 return;
2021         MPASS(stp->st_flags == 0);
2022         MPASS(STAILQ_EMPTY(&stp->st_selq));
2023         if (stp->st_free1)
2024                 free(stp->st_free1, M_SELFD);
2025         if (stp->st_free2)
2026                 free(stp->st_free2, M_SELFD);
2027         td->td_sel = NULL;
2028         cv_destroy(&stp->st_wait);
2029         mtx_destroy(&stp->st_mtx);
2030         free(stp, M_SELECT);
2031 }
2032
2033 /*
2034  * Remove the references to the thread from all of the objects we were
2035  * polling.
2036  */
2037 static void
2038 seltdclear(struct thread *td)
2039 {
2040         struct seltd *stp;
2041         struct selfd *sfp;
2042         struct selfd *sfn;
2043
2044         stp = td->td_sel;
2045         STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
2046                 selfdfree(stp, sfp);
2047         stp->st_flags = 0;
2048 }
2049
2050 static void selectinit(void *);
2051 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
2052 static void
2053 selectinit(void *dummy __unused)
2054 {
2055
2056         mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);
2057 }
2058
2059 /*
2060  * Set up a syscall return value that follows the convention specified for
2061  * posix_* functions.
2062  */
2063 int
2064 kern_posix_error(struct thread *td, int error)
2065 {
2066
2067         if (error <= 0)
2068                 return (error);
2069         td->td_errno = error;
2070         td->td_pflags |= TDP_NERRNO;
2071         td->td_retval[0] = error;
2072         return (0);
2073 }