]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/sys_generic.c
MFV: zlib 1.3
[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 #include "opt_capsicum.h"
41 #include "opt_ktrace.h"
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/sysproto.h>
46 #include <sys/capsicum.h>
47 #include <sys/filedesc.h>
48 #include <sys/filio.h>
49 #include <sys/fcntl.h>
50 #include <sys/file.h>
51 #include <sys/lock.h>
52 #include <sys/proc.h>
53 #include <sys/signalvar.h>
54 #include <sys/socketvar.h>
55 #include <sys/uio.h>
56 #include <sys/eventfd.h>
57 #include <sys/kernel.h>
58 #include <sys/ktr.h>
59 #include <sys/limits.h>
60 #include <sys/malloc.h>
61 #include <sys/poll.h>
62 #include <sys/resourcevar.h>
63 #include <sys/selinfo.h>
64 #include <sys/sleepqueue.h>
65 #include <sys/specialfd.h>
66 #include <sys/syscallsubr.h>
67 #include <sys/sysctl.h>
68 #include <sys/sysent.h>
69 #include <sys/vnode.h>
70 #include <sys/bio.h>
71 #include <sys/buf.h>
72 #include <sys/condvar.h>
73 #ifdef KTRACE
74 #include <sys/ktrace.h>
75 #endif
76
77 #include <security/audit/audit.h>
78
79 /*
80  * The following macro defines how many bytes will be allocated from
81  * the stack instead of memory allocated when passing the IOCTL data
82  * structures from userspace and to the kernel. Some IOCTLs having
83  * small data structures are used very frequently and this small
84  * buffer on the stack gives a significant speedup improvement for
85  * those requests. The value of this define should be greater or equal
86  * to 64 bytes and should also be power of two. The data structure is
87  * currently hard-aligned to a 8-byte boundary on the stack. This
88  * should currently be sufficient for all supported platforms.
89  */
90 #define SYS_IOCTL_SMALL_SIZE    128     /* bytes */
91 #define SYS_IOCTL_SMALL_ALIGN   8       /* bytes */
92
93 #ifdef __LP64__
94 static int iosize_max_clamp = 0;
95 SYSCTL_INT(_debug, OID_AUTO, iosize_max_clamp, CTLFLAG_RW,
96     &iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX");
97 static int devfs_iosize_max_clamp = 1;
98 SYSCTL_INT(_debug, OID_AUTO, devfs_iosize_max_clamp, CTLFLAG_RW,
99     &devfs_iosize_max_clamp, 0, "Clamp max i/o size to INT_MAX for devices");
100 #endif
101
102 /*
103  * Assert that the return value of read(2) and write(2) syscalls fits
104  * into a register.  If not, an architecture will need to provide the
105  * usermode wrappers to reconstruct the result.
106  */
107 CTASSERT(sizeof(register_t) >= sizeof(size_t));
108
109 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
110 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
111 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
112
113 static int      pollout(struct thread *, struct pollfd *, struct pollfd *,
114                     u_int);
115 static int      pollscan(struct thread *, struct pollfd *, u_int);
116 static int      pollrescan(struct thread *);
117 static int      selscan(struct thread *, fd_mask **, fd_mask **, int);
118 static int      selrescan(struct thread *, fd_mask **, fd_mask **);
119 static void     selfdalloc(struct thread *, void *);
120 static void     selfdfree(struct seltd *, struct selfd *);
121 static int      dofileread(struct thread *, int, struct file *, struct uio *,
122                     off_t, int);
123 static int      dofilewrite(struct thread *, int, struct file *, struct uio *,
124                     off_t, int);
125 static void     doselwakeup(struct selinfo *, int);
126 static void     seltdinit(struct thread *);
127 static int      seltdwait(struct thread *, sbintime_t, sbintime_t);
128 static void     seltdclear(struct thread *);
129
130 /*
131  * One seltd per-thread allocated on demand as needed.
132  *
133  *      t - protected by st_mtx
134  *      k - Only accessed by curthread or read-only
135  */
136 struct seltd {
137         STAILQ_HEAD(, selfd)    st_selq;        /* (k) List of selfds. */
138         struct selfd            *st_free1;      /* (k) free fd for read set. */
139         struct selfd            *st_free2;      /* (k) free fd for write set. */
140         struct mtx              st_mtx;         /* Protects struct seltd */
141         struct cv               st_wait;        /* (t) Wait channel. */
142         int                     st_flags;       /* (t) SELTD_ flags. */
143 };
144
145 #define SELTD_PENDING   0x0001                  /* We have pending events. */
146 #define SELTD_RESCAN    0x0002                  /* Doing a rescan. */
147
148 /*
149  * One selfd allocated per-thread per-file-descriptor.
150  *      f - protected by sf_mtx
151  */
152 struct selfd {
153         STAILQ_ENTRY(selfd)     sf_link;        /* (k) fds owned by this td. */
154         TAILQ_ENTRY(selfd)      sf_threads;     /* (f) fds on this selinfo. */
155         struct selinfo          *sf_si;         /* (f) selinfo when linked. */
156         struct mtx              *sf_mtx;        /* Pointer to selinfo mtx. */
157         struct seltd            *sf_td;         /* (k) owning seltd. */
158         void                    *sf_cookie;     /* (k) fd or pollfd. */
159 };
160
161 MALLOC_DEFINE(M_SELFD, "selfd", "selfd");
162 static struct mtx_pool *mtxpool_select;
163
164 #ifdef __LP64__
165 size_t
166 devfs_iosize_max(void)
167 {
168
169         return (devfs_iosize_max_clamp || SV_CURPROC_FLAG(SV_ILP32) ?
170             INT_MAX : SSIZE_MAX);
171 }
172
173 size_t
174 iosize_max(void)
175 {
176
177         return (iosize_max_clamp || SV_CURPROC_FLAG(SV_ILP32) ?
178             INT_MAX : SSIZE_MAX);
179 }
180 #endif
181
182 #ifndef _SYS_SYSPROTO_H_
183 struct read_args {
184         int     fd;
185         void    *buf;
186         size_t  nbyte;
187 };
188 #endif
189 int
190 sys_read(struct thread *td, struct read_args *uap)
191 {
192         struct uio auio;
193         struct iovec aiov;
194         int error;
195
196         if (uap->nbyte > IOSIZE_MAX)
197                 return (EINVAL);
198         aiov.iov_base = uap->buf;
199         aiov.iov_len = uap->nbyte;
200         auio.uio_iov = &aiov;
201         auio.uio_iovcnt = 1;
202         auio.uio_resid = uap->nbyte;
203         auio.uio_segflg = UIO_USERSPACE;
204         error = kern_readv(td, uap->fd, &auio);
205         return (error);
206 }
207
208 /*
209  * Positioned read system call
210  */
211 #ifndef _SYS_SYSPROTO_H_
212 struct pread_args {
213         int     fd;
214         void    *buf;
215         size_t  nbyte;
216         int     pad;
217         off_t   offset;
218 };
219 #endif
220 int
221 sys_pread(struct thread *td, struct pread_args *uap)
222 {
223
224         return (kern_pread(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
225 }
226
227 int
228 kern_pread(struct thread *td, int fd, void *buf, size_t nbyte, off_t offset)
229 {
230         struct uio auio;
231         struct iovec aiov;
232         int error;
233
234         if (nbyte > IOSIZE_MAX)
235                 return (EINVAL);
236         aiov.iov_base = buf;
237         aiov.iov_len = nbyte;
238         auio.uio_iov = &aiov;
239         auio.uio_iovcnt = 1;
240         auio.uio_resid = nbyte;
241         auio.uio_segflg = UIO_USERSPACE;
242         error = kern_preadv(td, fd, &auio, offset);
243         return (error);
244 }
245
246 #if defined(COMPAT_FREEBSD6)
247 int
248 freebsd6_pread(struct thread *td, struct freebsd6_pread_args *uap)
249 {
250
251         return (kern_pread(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
252 }
253 #endif
254
255 /*
256  * Scatter read system call.
257  */
258 #ifndef _SYS_SYSPROTO_H_
259 struct readv_args {
260         int     fd;
261         struct  iovec *iovp;
262         u_int   iovcnt;
263 };
264 #endif
265 int
266 sys_readv(struct thread *td, struct readv_args *uap)
267 {
268         struct uio *auio;
269         int error;
270
271         error = copyinuio(uap->iovp, uap->iovcnt, &auio);
272         if (error)
273                 return (error);
274         error = kern_readv(td, uap->fd, auio);
275         free(auio, M_IOV);
276         return (error);
277 }
278
279 int
280 kern_readv(struct thread *td, int fd, struct uio *auio)
281 {
282         struct file *fp;
283         int error;
284
285         error = fget_read(td, fd, &cap_read_rights, &fp);
286         if (error)
287                 return (error);
288         error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
289         fdrop(fp, td);
290         return (error);
291 }
292
293 /*
294  * Scatter positioned read system call.
295  */
296 #ifndef _SYS_SYSPROTO_H_
297 struct preadv_args {
298         int     fd;
299         struct  iovec *iovp;
300         u_int   iovcnt;
301         off_t   offset;
302 };
303 #endif
304 int
305 sys_preadv(struct thread *td, struct preadv_args *uap)
306 {
307         struct uio *auio;
308         int error;
309
310         error = copyinuio(uap->iovp, uap->iovcnt, &auio);
311         if (error)
312                 return (error);
313         error = kern_preadv(td, uap->fd, auio, uap->offset);
314         free(auio, M_IOV);
315         return (error);
316 }
317
318 int
319 kern_preadv(struct thread *td, int fd, struct uio *auio, off_t offset)
320 {
321         struct file *fp;
322         int error;
323
324         error = fget_read(td, fd, &cap_pread_rights, &fp);
325         if (error)
326                 return (error);
327         if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
328                 error = ESPIPE;
329         else if (offset < 0 &&
330             (fp->f_vnode == NULL || fp->f_vnode->v_type != VCHR))
331                 error = EINVAL;
332         else
333                 error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
334         fdrop(fp, td);
335         return (error);
336 }
337
338 /*
339  * Common code for readv and preadv that reads data in
340  * from a file using the passed in uio, offset, and flags.
341  */
342 static int
343 dofileread(struct thread *td, int fd, struct file *fp, struct uio *auio,
344     off_t offset, int flags)
345 {
346         ssize_t cnt;
347         int error;
348 #ifdef KTRACE
349         struct uio *ktruio = NULL;
350 #endif
351
352         AUDIT_ARG_FD(fd);
353
354         /* Finish zero length reads right here */
355         if (auio->uio_resid == 0) {
356                 td->td_retval[0] = 0;
357                 return (0);
358         }
359         auio->uio_rw = UIO_READ;
360         auio->uio_offset = offset;
361         auio->uio_td = td;
362 #ifdef KTRACE
363         if (KTRPOINT(td, KTR_GENIO)) 
364                 ktruio = cloneuio(auio);
365 #endif
366         cnt = auio->uio_resid;
367         if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
368                 if (auio->uio_resid != cnt && (error == ERESTART ||
369                     error == EINTR || error == EWOULDBLOCK))
370                         error = 0;
371         }
372         cnt -= auio->uio_resid;
373 #ifdef KTRACE
374         if (ktruio != NULL) {
375                 ktruio->uio_resid = cnt;
376                 ktrgenio(fd, UIO_READ, ktruio, error);
377         }
378 #endif
379         td->td_retval[0] = cnt;
380         return (error);
381 }
382
383 #ifndef _SYS_SYSPROTO_H_
384 struct write_args {
385         int     fd;
386         const void *buf;
387         size_t  nbyte;
388 };
389 #endif
390 int
391 sys_write(struct thread *td, struct write_args *uap)
392 {
393         struct uio auio;
394         struct iovec aiov;
395         int error;
396
397         if (uap->nbyte > IOSIZE_MAX)
398                 return (EINVAL);
399         aiov.iov_base = (void *)(uintptr_t)uap->buf;
400         aiov.iov_len = uap->nbyte;
401         auio.uio_iov = &aiov;
402         auio.uio_iovcnt = 1;
403         auio.uio_resid = uap->nbyte;
404         auio.uio_segflg = UIO_USERSPACE;
405         error = kern_writev(td, uap->fd, &auio);
406         return (error);
407 }
408
409 /*
410  * Positioned write system call.
411  */
412 #ifndef _SYS_SYSPROTO_H_
413 struct pwrite_args {
414         int     fd;
415         const void *buf;
416         size_t  nbyte;
417         int     pad;
418         off_t   offset;
419 };
420 #endif
421 int
422 sys_pwrite(struct thread *td, struct pwrite_args *uap)
423 {
424
425         return (kern_pwrite(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
426 }
427
428 int
429 kern_pwrite(struct thread *td, int fd, const void *buf, size_t nbyte,
430     off_t offset)
431 {
432         struct uio auio;
433         struct iovec aiov;
434         int error;
435
436         if (nbyte > IOSIZE_MAX)
437                 return (EINVAL);
438         aiov.iov_base = (void *)(uintptr_t)buf;
439         aiov.iov_len = nbyte;
440         auio.uio_iov = &aiov;
441         auio.uio_iovcnt = 1;
442         auio.uio_resid = nbyte;
443         auio.uio_segflg = UIO_USERSPACE;
444         error = kern_pwritev(td, fd, &auio, offset);
445         return (error);
446 }
447
448 #if defined(COMPAT_FREEBSD6)
449 int
450 freebsd6_pwrite(struct thread *td, struct freebsd6_pwrite_args *uap)
451 {
452
453         return (kern_pwrite(td, uap->fd, uap->buf, uap->nbyte, uap->offset));
454 }
455 #endif
456
457 /*
458  * Gather write system call.
459  */
460 #ifndef _SYS_SYSPROTO_H_
461 struct writev_args {
462         int     fd;
463         struct  iovec *iovp;
464         u_int   iovcnt;
465 };
466 #endif
467 int
468 sys_writev(struct thread *td, struct writev_args *uap)
469 {
470         struct uio *auio;
471         int error;
472
473         error = copyinuio(uap->iovp, uap->iovcnt, &auio);
474         if (error)
475                 return (error);
476         error = kern_writev(td, uap->fd, auio);
477         free(auio, M_IOV);
478         return (error);
479 }
480
481 int
482 kern_writev(struct thread *td, int fd, struct uio *auio)
483 {
484         struct file *fp;
485         int error;
486
487         error = fget_write(td, fd, &cap_write_rights, &fp);
488         if (error)
489                 return (error);
490         error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
491         fdrop(fp, td);
492         return (error);
493 }
494
495 /*
496  * Gather positioned write system call.
497  */
498 #ifndef _SYS_SYSPROTO_H_
499 struct pwritev_args {
500         int     fd;
501         struct  iovec *iovp;
502         u_int   iovcnt;
503         off_t   offset;
504 };
505 #endif
506 int
507 sys_pwritev(struct thread *td, struct pwritev_args *uap)
508 {
509         struct uio *auio;
510         int error;
511
512         error = copyinuio(uap->iovp, uap->iovcnt, &auio);
513         if (error)
514                 return (error);
515         error = kern_pwritev(td, uap->fd, auio, uap->offset);
516         free(auio, M_IOV);
517         return (error);
518 }
519
520 int
521 kern_pwritev(struct thread *td, int fd, struct uio *auio, off_t offset)
522 {
523         struct file *fp;
524         int error;
525
526         error = fget_write(td, fd, &cap_pwrite_rights, &fp);
527         if (error)
528                 return (error);
529         if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
530                 error = ESPIPE;
531         else if (offset < 0 &&
532             (fp->f_vnode == NULL || fp->f_vnode->v_type != VCHR))
533                 error = EINVAL;
534         else
535                 error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
536         fdrop(fp, td);
537         return (error);
538 }
539
540 /*
541  * Common code for writev and pwritev that writes data to
542  * a file using the passed in uio, offset, and flags.
543  */
544 static int
545 dofilewrite(struct thread *td, int fd, struct file *fp, struct uio *auio,
546     off_t offset, int flags)
547 {
548         ssize_t cnt;
549         int error;
550 #ifdef KTRACE
551         struct uio *ktruio = NULL;
552 #endif
553
554         AUDIT_ARG_FD(fd);
555         auio->uio_rw = UIO_WRITE;
556         auio->uio_td = td;
557         auio->uio_offset = offset;
558 #ifdef KTRACE
559         if (KTRPOINT(td, KTR_GENIO))
560                 ktruio = cloneuio(auio);
561 #endif
562         cnt = auio->uio_resid;
563         error = fo_write(fp, auio, td->td_ucred, flags, td);
564         /*
565          * Socket layer is responsible for special error handling,
566          * see sousrsend().
567          */
568         if (error != 0 && fp->f_type != DTYPE_SOCKET) {
569                 if (auio->uio_resid != cnt && (error == ERESTART ||
570                     error == EINTR || error == EWOULDBLOCK))
571                         error = 0;
572                 if (error == EPIPE) {
573                         PROC_LOCK(td->td_proc);
574                         tdsignal(td, SIGPIPE);
575                         PROC_UNLOCK(td->td_proc);
576                 }
577         }
578         cnt -= auio->uio_resid;
579 #ifdef KTRACE
580         if (ktruio != NULL) {
581                 ktruio->uio_resid = cnt;
582                 ktrgenio(fd, UIO_WRITE, ktruio, error);
583         }
584 #endif
585         td->td_retval[0] = cnt;
586         return (error);
587 }
588
589 /*
590  * Truncate a file given a file descriptor.
591  *
592  * Can't use fget_write() here, since must return EINVAL and not EBADF if the
593  * descriptor isn't writable.
594  */
595 int
596 kern_ftruncate(struct thread *td, int fd, off_t length)
597 {
598         struct file *fp;
599         int error;
600
601         AUDIT_ARG_FD(fd);
602         if (length < 0)
603                 return (EINVAL);
604         error = fget(td, fd, &cap_ftruncate_rights, &fp);
605         if (error)
606                 return (error);
607         AUDIT_ARG_FILE(td->td_proc, fp);
608         if (!(fp->f_flag & FWRITE)) {
609                 fdrop(fp, td);
610                 return (EINVAL);
611         }
612         error = fo_truncate(fp, length, td->td_ucred, td);
613         fdrop(fp, td);
614         return (error);
615 }
616
617 #ifndef _SYS_SYSPROTO_H_
618 struct ftruncate_args {
619         int     fd;
620         int     pad;
621         off_t   length;
622 };
623 #endif
624 int
625 sys_ftruncate(struct thread *td, struct ftruncate_args *uap)
626 {
627
628         return (kern_ftruncate(td, uap->fd, uap->length));
629 }
630
631 #if defined(COMPAT_43)
632 #ifndef _SYS_SYSPROTO_H_
633 struct oftruncate_args {
634         int     fd;
635         long    length;
636 };
637 #endif
638 int
639 oftruncate(struct thread *td, struct oftruncate_args *uap)
640 {
641
642         return (kern_ftruncate(td, uap->fd, uap->length));
643 }
644 #endif /* COMPAT_43 */
645
646 #ifndef _SYS_SYSPROTO_H_
647 struct ioctl_args {
648         int     fd;
649         u_long  com;
650         caddr_t data;
651 };
652 #endif
653 /* ARGSUSED */
654 int
655 sys_ioctl(struct thread *td, struct ioctl_args *uap)
656 {
657         u_char smalldata[SYS_IOCTL_SMALL_SIZE] __aligned(SYS_IOCTL_SMALL_ALIGN);
658         uint32_t com;
659         int arg, error;
660         u_int size;
661         caddr_t data;
662
663 #ifdef INVARIANTS
664         if (uap->com > 0xffffffff) {
665                 printf(
666                     "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
667                     td->td_proc->p_pid, td->td_name, uap->com);
668         }
669 #endif
670         com = (uint32_t)uap->com;
671
672         /*
673          * Interpret high order word to find amount of data to be
674          * copied to/from the user's address space.
675          */
676         size = IOCPARM_LEN(com);
677         if ((size > IOCPARM_MAX) ||
678             ((com & (IOC_VOID  | IOC_IN | IOC_OUT)) == 0) ||
679 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
680             ((com & IOC_OUT) && size == 0) ||
681 #else
682             ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
683 #endif
684             ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
685                 return (ENOTTY);
686
687         if (size > 0) {
688                 if (com & IOC_VOID) {
689                         /* Integer argument. */
690                         arg = (intptr_t)uap->data;
691                         data = (void *)&arg;
692                         size = 0;
693                 } else {
694                         if (size > SYS_IOCTL_SMALL_SIZE)
695                                 data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
696                         else
697                                 data = smalldata;
698                 }
699         } else
700                 data = (void *)&uap->data;
701         if (com & IOC_IN) {
702                 error = copyin(uap->data, data, (u_int)size);
703                 if (error != 0)
704                         goto out;
705         } else if (com & IOC_OUT) {
706                 /*
707                  * Zero the buffer so the user always
708                  * gets back something deterministic.
709                  */
710                 bzero(data, size);
711         }
712
713         error = kern_ioctl(td, uap->fd, com, data);
714
715         if (error == 0 && (com & IOC_OUT))
716                 error = copyout(data, uap->data, (u_int)size);
717
718 out:
719         if (size > SYS_IOCTL_SMALL_SIZE)
720                 free(data, M_IOCTLOPS);
721         return (error);
722 }
723
724 int
725 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
726 {
727         struct file *fp;
728         struct filedesc *fdp;
729         int error, tmp, locked;
730
731         AUDIT_ARG_FD(fd);
732         AUDIT_ARG_CMD(com);
733
734         fdp = td->td_proc->p_fd;
735
736         switch (com) {
737         case FIONCLEX:
738         case FIOCLEX:
739                 FILEDESC_XLOCK(fdp);
740                 locked = LA_XLOCKED;
741                 break;
742         default:
743 #ifdef CAPABILITIES
744                 FILEDESC_SLOCK(fdp);
745                 locked = LA_SLOCKED;
746 #else
747                 locked = LA_UNLOCKED;
748 #endif
749                 break;
750         }
751
752 #ifdef CAPABILITIES
753         if ((fp = fget_noref(fdp, fd)) == NULL) {
754                 error = EBADF;
755                 goto out;
756         }
757         if ((error = cap_ioctl_check(fdp, fd, com)) != 0) {
758                 fp = NULL;      /* fhold() was not called yet */
759                 goto out;
760         }
761         if (!fhold(fp)) {
762                 error = EBADF;
763                 fp = NULL;
764                 goto out;
765         }
766         if (locked == LA_SLOCKED) {
767                 FILEDESC_SUNLOCK(fdp);
768                 locked = LA_UNLOCKED;
769         }
770 #else
771         error = fget(td, fd, &cap_ioctl_rights, &fp);
772         if (error != 0) {
773                 fp = NULL;
774                 goto out;
775         }
776 #endif
777         if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
778                 error = EBADF;
779                 goto out;
780         }
781
782         switch (com) {
783         case FIONCLEX:
784                 fdp->fd_ofiles[fd].fde_flags &= ~UF_EXCLOSE;
785                 goto out;
786         case FIOCLEX:
787                 fdp->fd_ofiles[fd].fde_flags |= UF_EXCLOSE;
788                 goto out;
789         case FIONBIO:
790                 if ((tmp = *(int *)data))
791                         atomic_set_int(&fp->f_flag, FNONBLOCK);
792                 else
793                         atomic_clear_int(&fp->f_flag, FNONBLOCK);
794                 data = (void *)&tmp;
795                 break;
796         case FIOASYNC:
797                 if ((tmp = *(int *)data))
798                         atomic_set_int(&fp->f_flag, FASYNC);
799                 else
800                         atomic_clear_int(&fp->f_flag, FASYNC);
801                 data = (void *)&tmp;
802                 break;
803         }
804
805         error = fo_ioctl(fp, com, data, td->td_ucred, td);
806 out:
807         switch (locked) {
808         case LA_XLOCKED:
809                 FILEDESC_XUNLOCK(fdp);
810                 break;
811 #ifdef CAPABILITIES
812         case LA_SLOCKED:
813                 FILEDESC_SUNLOCK(fdp);
814                 break;
815 #endif
816         default:
817                 FILEDESC_UNLOCK_ASSERT(fdp);
818                 break;
819         }
820         if (fp != NULL)
821                 fdrop(fp, td);
822         return (error);
823 }
824
825 int
826 sys_posix_fallocate(struct thread *td, struct posix_fallocate_args *uap)
827 {
828         int error;
829
830         error = kern_posix_fallocate(td, uap->fd, uap->offset, uap->len);
831         return (kern_posix_error(td, error));
832 }
833
834 int
835 kern_posix_fallocate(struct thread *td, int fd, off_t offset, off_t len)
836 {
837         struct file *fp;
838         int error;
839
840         AUDIT_ARG_FD(fd);
841         if (offset < 0 || len <= 0)
842                 return (EINVAL);
843         /* Check for wrap. */
844         if (offset > OFF_MAX - len)
845                 return (EFBIG);
846         AUDIT_ARG_FD(fd);
847         error = fget(td, fd, &cap_pwrite_rights, &fp);
848         if (error != 0)
849                 return (error);
850         AUDIT_ARG_FILE(td->td_proc, fp);
851         if ((fp->f_ops->fo_flags & DFLAG_SEEKABLE) == 0) {
852                 error = ESPIPE;
853                 goto out;
854         }
855         if ((fp->f_flag & FWRITE) == 0) {
856                 error = EBADF;
857                 goto out;
858         }
859
860         error = fo_fallocate(fp, offset, len, td);
861  out:
862         fdrop(fp, td);
863         return (error);
864 }
865
866 int
867 sys_fspacectl(struct thread *td, struct fspacectl_args *uap)
868 {
869         struct spacectl_range rqsr, rmsr;
870         int error, cerror;
871
872         error = copyin(uap->rqsr, &rqsr, sizeof(rqsr));
873         if (error != 0)
874                 return (error);
875
876         error = kern_fspacectl(td, uap->fd, uap->cmd, &rqsr, uap->flags,
877             &rmsr);
878         if (uap->rmsr != NULL) {
879                 cerror = copyout(&rmsr, uap->rmsr, sizeof(rmsr));
880                 if (error == 0)
881                         error = cerror;
882         }
883         return (error);
884 }
885
886 int
887 kern_fspacectl(struct thread *td, int fd, int cmd,
888     const struct spacectl_range *rqsr, int flags, struct spacectl_range *rmsrp)
889 {
890         struct file *fp;
891         struct spacectl_range rmsr;
892         int error;
893
894         AUDIT_ARG_FD(fd);
895         AUDIT_ARG_CMD(cmd);
896         AUDIT_ARG_FFLAGS(flags);
897
898         if (rqsr == NULL)
899                 return (EINVAL);
900         rmsr = *rqsr;
901         if (rmsrp != NULL)
902                 *rmsrp = rmsr;
903
904         if (cmd != SPACECTL_DEALLOC ||
905             rqsr->r_offset < 0 || rqsr->r_len <= 0 ||
906             rqsr->r_offset > OFF_MAX - rqsr->r_len ||
907             (flags & ~SPACECTL_F_SUPPORTED) != 0)
908                 return (EINVAL);
909
910         error = fget_write(td, fd, &cap_pwrite_rights, &fp);
911         if (error != 0)
912                 return (error);
913         AUDIT_ARG_FILE(td->td_proc, fp);
914         if ((fp->f_ops->fo_flags & DFLAG_SEEKABLE) == 0) {
915                 error = ESPIPE;
916                 goto out;
917         }
918         if ((fp->f_flag & FWRITE) == 0) {
919                 error = EBADF;
920                 goto out;
921         }
922
923         error = fo_fspacectl(fp, cmd, &rmsr.r_offset, &rmsr.r_len, flags,
924             td->td_ucred, td);
925         /* fspacectl is not restarted after signals if the file is modified. */
926         if (rmsr.r_len != rqsr->r_len && (error == ERESTART ||
927             error == EINTR || error == EWOULDBLOCK))
928                 error = 0;
929         if (rmsrp != NULL)
930                 *rmsrp = rmsr;
931 out:
932         fdrop(fp, td);
933         return (error);
934 }
935
936 int
937 kern_specialfd(struct thread *td, int type, void *arg)
938 {
939         struct file *fp;
940         struct specialfd_eventfd *ae;
941         int error, fd, fflags;
942
943         fflags = 0;
944         error = falloc_noinstall(td, &fp);
945         if (error != 0)
946                 return (error);
947
948         switch (type) {
949         case SPECIALFD_EVENTFD:
950                 ae = arg;
951                 if ((ae->flags & EFD_CLOEXEC) != 0)
952                         fflags |= O_CLOEXEC;
953                 error = eventfd_create_file(td, fp, ae->initval, ae->flags);
954                 break;
955         default:
956                 error = EINVAL;
957                 break;
958         }
959
960         if (error == 0)
961                 error = finstall(td, fp, &fd, fflags, NULL);
962         fdrop(fp, td);
963         if (error == 0)
964                 td->td_retval[0] = fd;
965         return (error);
966 }
967
968 int
969 sys___specialfd(struct thread *td, struct __specialfd_args *args)
970 {
971         struct specialfd_eventfd ae;
972         int error;
973
974         switch (args->type) {
975         case SPECIALFD_EVENTFD:
976                 if (args->len != sizeof(struct specialfd_eventfd)) {
977                         error = EINVAL;
978                         break;
979                 }
980                 error = copyin(args->req, &ae, sizeof(ae));
981                 if (error != 0)
982                         break;
983                 if ((ae.flags & ~(EFD_CLOEXEC | EFD_NONBLOCK |
984                     EFD_SEMAPHORE)) != 0) {
985                         error = EINVAL;
986                         break;
987                 }
988                 error = kern_specialfd(td, args->type, &ae);
989                 break;
990         default:
991                 error = EINVAL;
992                 break;
993         }
994         return (error);
995 }
996
997 int
998 poll_no_poll(int events)
999 {
1000         /*
1001          * Return true for read/write.  If the user asked for something
1002          * special, return POLLNVAL, so that clients have a way of
1003          * determining reliably whether or not the extended
1004          * functionality is present without hard-coding knowledge
1005          * of specific filesystem implementations.
1006          */
1007         if (events & ~POLLSTANDARD)
1008                 return (POLLNVAL);
1009
1010         return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
1011 }
1012
1013 int
1014 sys_pselect(struct thread *td, struct pselect_args *uap)
1015 {
1016         struct timespec ts;
1017         struct timeval tv, *tvp;
1018         sigset_t set, *uset;
1019         int error;
1020
1021         if (uap->ts != NULL) {
1022                 error = copyin(uap->ts, &ts, sizeof(ts));
1023                 if (error != 0)
1024                     return (error);
1025                 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1026                 tvp = &tv;
1027         } else
1028                 tvp = NULL;
1029         if (uap->sm != NULL) {
1030                 error = copyin(uap->sm, &set, sizeof(set));
1031                 if (error != 0)
1032                         return (error);
1033                 uset = &set;
1034         } else
1035                 uset = NULL;
1036         return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
1037             uset, NFDBITS));
1038 }
1039
1040 int
1041 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
1042     struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
1043 {
1044         int error;
1045
1046         if (uset != NULL) {
1047                 error = kern_sigprocmask(td, SIG_SETMASK, uset,
1048                     &td->td_oldsigmask, 0);
1049                 if (error != 0)
1050                         return (error);
1051                 td->td_pflags |= TDP_OLDMASK;
1052                 /*
1053                  * Make sure that ast() is called on return to
1054                  * usermode and TDP_OLDMASK is cleared, restoring old
1055                  * sigmask.
1056                  */
1057                 ast_sched(td, TDA_SIGSUSPEND);
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(td, 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(td, 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 (!timespecvalid_interval(tsp))
1505                         return (EINVAL);
1506                 if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
1507                         sbt = 0;
1508                 else {
1509                         ts = *tsp;
1510                         if (ts.tv_sec > INT32_MAX / 2) {
1511                                 over = ts.tv_sec - INT32_MAX / 2;
1512                                 ts.tv_sec -= over;
1513                         } else
1514                                 over = 0;
1515                         tmp = tstosbt(ts);
1516                         precision = tmp;
1517                         precision >>= tc_precexp;
1518                         if (TIMESEL(&sbt, tmp))
1519                                 sbt += tc_tick_sbt;
1520                         sbt += tmp;
1521                 }
1522         } else
1523                 sbt = -1;
1524
1525         if (uset != NULL) {
1526                 error = kern_sigprocmask(td, SIG_SETMASK, uset,
1527                     &td->td_oldsigmask, 0);
1528                 if (error)
1529                         return (error);
1530                 td->td_pflags |= TDP_OLDMASK;
1531                 /*
1532                  * Make sure that ast() is called on return to
1533                  * usermode and TDP_OLDMASK is cleared, restoring old
1534                  * sigmask.
1535                  */
1536                 ast_sched(td, TDA_SIGSUSPEND);
1537         }
1538
1539         seltdinit(td);
1540         /* Iterate until the timeout expires or descriptors become ready. */
1541         for (;;) {
1542                 error = pollscan(td, kfds, nfds);
1543                 if (error || td->td_retval[0] != 0)
1544                         break;
1545                 error = seltdwait(td, sbt, precision);
1546                 if (error)
1547                         break;
1548                 error = pollrescan(td);
1549                 if (error || td->td_retval[0] != 0)
1550                         break;
1551         }
1552         seltdclear(td);
1553
1554         /* poll is not restarted after signals... */
1555         if (error == ERESTART)
1556                 error = EINTR;
1557         if (error == EWOULDBLOCK)
1558                 error = 0;
1559         return (error);
1560 }
1561
1562 int
1563 sys_ppoll(struct thread *td, struct ppoll_args *uap)
1564 {
1565         struct timespec ts, *tsp;
1566         sigset_t set, *ssp;
1567         int error;
1568
1569         if (uap->ts != NULL) {
1570                 error = copyin(uap->ts, &ts, sizeof(ts));
1571                 if (error)
1572                         return (error);
1573                 tsp = &ts;
1574         } else
1575                 tsp = NULL;
1576         if (uap->set != NULL) {
1577                 error = copyin(uap->set, &set, sizeof(set));
1578                 if (error)
1579                         return (error);
1580                 ssp = &set;
1581         } else
1582                 ssp = NULL;
1583         return (kern_poll(td, uap->fds, uap->nfds, tsp, ssp));
1584 }
1585
1586 /*
1587  * ufds points to an array in user space.
1588  */
1589 int
1590 kern_poll(struct thread *td, struct pollfd *ufds, u_int nfds,
1591     struct timespec *tsp, sigset_t *set)
1592 {
1593         struct pollfd *kfds;
1594         struct pollfd stackfds[32];
1595         int error;
1596
1597         if (kern_poll_maxfds(nfds))
1598                 return (EINVAL);
1599         if (nfds > nitems(stackfds))
1600                 kfds = mallocarray(nfds, sizeof(*kfds), M_TEMP, M_WAITOK);
1601         else
1602                 kfds = stackfds;
1603         error = copyin(ufds, kfds, nfds * sizeof(*kfds));
1604         if (error != 0)
1605                 goto out;
1606
1607         error = kern_poll_kfds(td, kfds, nfds, tsp, set);
1608         if (error == 0)
1609                 error = pollout(td, kfds, ufds, nfds);
1610
1611 out:
1612         if (nfds > nitems(stackfds))
1613                 free(kfds, M_TEMP);
1614         return (error);
1615 }
1616
1617 bool
1618 kern_poll_maxfds(u_int nfds)
1619 {
1620
1621         /*
1622          * This is kinda bogus.  We have fd limits, but that is not
1623          * really related to the size of the pollfd array.  Make sure
1624          * we let the process use at least FD_SETSIZE entries and at
1625          * least enough for the system-wide limits.  We want to be reasonably
1626          * safe, but not overly restrictive.
1627          */
1628         return (nfds > maxfilesperproc && nfds > FD_SETSIZE);
1629 }
1630
1631 static int
1632 pollrescan(struct thread *td)
1633 {
1634         struct seltd *stp;
1635         struct selfd *sfp;
1636         struct selfd *sfn;
1637         struct selinfo *si;
1638         struct filedesc *fdp;
1639         struct file *fp;
1640         struct pollfd *fd;
1641         int n, error;
1642         bool only_user;
1643
1644         n = 0;
1645         fdp = td->td_proc->p_fd;
1646         stp = td->td_sel;
1647         only_user = FILEDESC_IS_ONLY_USER(fdp);
1648         STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1649                 fd = (struct pollfd *)sfp->sf_cookie;
1650                 si = sfp->sf_si;
1651                 selfdfree(stp, sfp);
1652                 /* If the selinfo wasn't cleared the event didn't fire. */
1653                 if (si != NULL)
1654                         continue;
1655                 if (only_user)
1656                         error = fget_only_user(fdp, fd->fd, &cap_event_rights, &fp);
1657                 else
1658                         error = fget_unlocked(td, fd->fd, &cap_event_rights, &fp);
1659                 if (__predict_false(error != 0)) {
1660                         fd->revents = POLLNVAL;
1661                         n++;
1662                         continue;
1663                 }
1664                 /*
1665                  * Note: backend also returns POLLHUP and
1666                  * POLLERR if appropriate.
1667                  */
1668                 fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1669                 if (only_user)
1670                         fput_only_user(fdp, fp);
1671                 else
1672                         fdrop(fp, td);
1673                 if (fd->revents != 0)
1674                         n++;
1675         }
1676         stp->st_flags = 0;
1677         td->td_retval[0] = n;
1678         return (0);
1679 }
1680
1681 static int
1682 pollout(struct thread *td, struct pollfd *fds, struct pollfd *ufds, u_int nfd)
1683 {
1684         int error = 0;
1685         u_int i = 0;
1686         u_int n = 0;
1687
1688         for (i = 0; i < nfd; i++) {
1689                 error = copyout(&fds->revents, &ufds->revents,
1690                     sizeof(ufds->revents));
1691                 if (error)
1692                         return (error);
1693                 if (fds->revents != 0)
1694                         n++;
1695                 fds++;
1696                 ufds++;
1697         }
1698         td->td_retval[0] = n;
1699         return (0);
1700 }
1701
1702 static int
1703 pollscan(struct thread *td, struct pollfd *fds, u_int nfd)
1704 {
1705         struct filedesc *fdp;
1706         struct file *fp;
1707         int i, n, error;
1708         bool only_user;
1709
1710         n = 0;
1711         fdp = td->td_proc->p_fd;
1712         only_user = FILEDESC_IS_ONLY_USER(fdp);
1713         for (i = 0; i < nfd; i++, fds++) {
1714                 if (fds->fd < 0) {
1715                         fds->revents = 0;
1716                         continue;
1717                 }
1718                 if (only_user)
1719                         error = fget_only_user(fdp, fds->fd, &cap_event_rights, &fp);
1720                 else
1721                         error = fget_unlocked(td, fds->fd, &cap_event_rights, &fp);
1722                 if (__predict_false(error != 0)) {
1723                         fds->revents = POLLNVAL;
1724                         n++;
1725                         continue;
1726                 }
1727                 /*
1728                  * Note: backend also returns POLLHUP and
1729                  * POLLERR if appropriate.
1730                  */
1731                 selfdalloc(td, fds);
1732                 fds->revents = fo_poll(fp, fds->events,
1733                     td->td_ucred, td);
1734                 if (only_user)
1735                         fput_only_user(fdp, fp);
1736                 else
1737                         fdrop(fp, td);
1738                 /*
1739                  * POSIX requires POLLOUT to be never
1740                  * set simultaneously with POLLHUP.
1741                  */
1742                 if ((fds->revents & POLLHUP) != 0)
1743                         fds->revents &= ~POLLOUT;
1744
1745                 if (fds->revents != 0)
1746                         n++;
1747         }
1748         td->td_retval[0] = n;
1749         return (0);
1750 }
1751
1752 /*
1753  * XXX This was created specifically to support netncp and netsmb.  This
1754  * allows the caller to specify a socket to wait for events on.  It returns
1755  * 0 if any events matched and an error otherwise.  There is no way to
1756  * determine which events fired.
1757  */
1758 int
1759 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1760 {
1761         struct timeval rtv;
1762         sbintime_t asbt, precision, rsbt;
1763         int error;
1764
1765         precision = 0;  /* stupid gcc! */
1766         if (tvp != NULL) {
1767                 rtv = *tvp;
1768                 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 || 
1769                     rtv.tv_usec >= 1000000)
1770                         return (EINVAL);
1771                 if (!timevalisset(&rtv))
1772                         asbt = 0;
1773                 else if (rtv.tv_sec <= INT32_MAX) {
1774                         rsbt = tvtosbt(rtv);
1775                         precision = rsbt;
1776                         precision >>= tc_precexp;
1777                         if (TIMESEL(&asbt, rsbt))
1778                                 asbt += tc_tick_sbt;
1779                         if (asbt <= SBT_MAX - rsbt)
1780                                 asbt += rsbt;
1781                         else
1782                                 asbt = -1;
1783                 } else
1784                         asbt = -1;
1785         } else
1786                 asbt = -1;
1787         seltdinit(td);
1788         /*
1789          * Iterate until the timeout expires or the socket becomes ready.
1790          */
1791         for (;;) {
1792                 selfdalloc(td, NULL);
1793                 if (sopoll(so, events, NULL, td) != 0) {
1794                         error = 0;
1795                         break;
1796                 }
1797                 error = seltdwait(td, asbt, precision);
1798                 if (error)
1799                         break;
1800         }
1801         seltdclear(td);
1802         /* XXX Duplicates ncp/smb behavior. */
1803         if (error == ERESTART)
1804                 error = 0;
1805         return (error);
1806 }
1807
1808 /*
1809  * Preallocate two selfds associated with 'cookie'.  Some fo_poll routines
1810  * have two select sets, one for read and another for write.
1811  */
1812 static void
1813 selfdalloc(struct thread *td, void *cookie)
1814 {
1815         struct seltd *stp;
1816
1817         stp = td->td_sel;
1818         if (stp->st_free1 == NULL)
1819                 stp->st_free1 = malloc(sizeof(*stp->st_free1), M_SELFD, M_WAITOK|M_ZERO);
1820         stp->st_free1->sf_td = stp;
1821         stp->st_free1->sf_cookie = cookie;
1822         if (stp->st_free2 == NULL)
1823                 stp->st_free2 = malloc(sizeof(*stp->st_free2), M_SELFD, M_WAITOK|M_ZERO);
1824         stp->st_free2->sf_td = stp;
1825         stp->st_free2->sf_cookie = cookie;
1826 }
1827
1828 static void
1829 selfdfree(struct seltd *stp, struct selfd *sfp)
1830 {
1831         STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1832         /*
1833          * Paired with doselwakeup.
1834          */
1835         if (atomic_load_acq_ptr((uintptr_t *)&sfp->sf_si) != (uintptr_t)NULL) {
1836                 mtx_lock(sfp->sf_mtx);
1837                 if (sfp->sf_si != NULL) {
1838                         TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1839                 }
1840                 mtx_unlock(sfp->sf_mtx);
1841         }
1842         free(sfp, M_SELFD);
1843 }
1844
1845 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1846 void
1847 seldrain(struct selinfo *sip)
1848 {
1849
1850         /*
1851          * This feature is already provided by doselwakeup(), thus it is
1852          * enough to go for it.
1853          * Eventually, the context, should take care to avoid races
1854          * between thread calling select()/poll() and file descriptor
1855          * detaching, but, again, the races are just the same as
1856          * selwakeup().
1857          */
1858         doselwakeup(sip, -1);
1859 }
1860
1861 /*
1862  * Record a select request.
1863  */
1864 void
1865 selrecord(struct thread *selector, struct selinfo *sip)
1866 {
1867         struct selfd *sfp;
1868         struct seltd *stp;
1869         struct mtx *mtxp;
1870
1871         stp = selector->td_sel;
1872         /*
1873          * Don't record when doing a rescan.
1874          */
1875         if (stp->st_flags & SELTD_RESCAN)
1876                 return;
1877         /*
1878          * Grab one of the preallocated descriptors.
1879          */
1880         sfp = NULL;
1881         if ((sfp = stp->st_free1) != NULL)
1882                 stp->st_free1 = NULL;
1883         else if ((sfp = stp->st_free2) != NULL)
1884                 stp->st_free2 = NULL;
1885         else
1886                 panic("selrecord: No free selfd on selq");
1887         mtxp = sip->si_mtx;
1888         if (mtxp == NULL)
1889                 mtxp = mtx_pool_find(mtxpool_select, sip);
1890         /*
1891          * Initialize the sfp and queue it in the thread.
1892          */
1893         sfp->sf_si = sip;
1894         sfp->sf_mtx = mtxp;
1895         STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1896         /*
1897          * Now that we've locked the sip, check for initialization.
1898          */
1899         mtx_lock(mtxp);
1900         if (sip->si_mtx == NULL) {
1901                 sip->si_mtx = mtxp;
1902                 TAILQ_INIT(&sip->si_tdlist);
1903         }
1904         /*
1905          * Add this thread to the list of selfds listening on this selinfo.
1906          */
1907         TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1908         mtx_unlock(sip->si_mtx);
1909 }
1910
1911 /* Wake up a selecting thread. */
1912 void
1913 selwakeup(struct selinfo *sip)
1914 {
1915         doselwakeup(sip, -1);
1916 }
1917
1918 /* Wake up a selecting thread, and set its priority. */
1919 void
1920 selwakeuppri(struct selinfo *sip, int pri)
1921 {
1922         doselwakeup(sip, pri);
1923 }
1924
1925 /*
1926  * Do a wakeup when a selectable event occurs.
1927  */
1928 static void
1929 doselwakeup(struct selinfo *sip, int pri)
1930 {
1931         struct selfd *sfp;
1932         struct selfd *sfn;
1933         struct seltd *stp;
1934
1935         /* If it's not initialized there can't be any waiters. */
1936         if (sip->si_mtx == NULL)
1937                 return;
1938         /*
1939          * Locking the selinfo locks all selfds associated with it.
1940          */
1941         mtx_lock(sip->si_mtx);
1942         TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1943                 /*
1944                  * Once we remove this sfp from the list and clear the
1945                  * sf_si seltdclear will know to ignore this si.
1946                  */
1947                 TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1948                 stp = sfp->sf_td;
1949                 mtx_lock(&stp->st_mtx);
1950                 stp->st_flags |= SELTD_PENDING;
1951                 cv_broadcastpri(&stp->st_wait, pri);
1952                 mtx_unlock(&stp->st_mtx);
1953                 /*
1954                  * Paired with selfdfree.
1955                  *
1956                  * Storing this only after the wakeup provides an invariant that
1957                  * stp is not used after selfdfree returns.
1958                  */
1959                 atomic_store_rel_ptr((uintptr_t *)&sfp->sf_si, (uintptr_t)NULL);
1960         }
1961         mtx_unlock(sip->si_mtx);
1962 }
1963
1964 static void
1965 seltdinit(struct thread *td)
1966 {
1967         struct seltd *stp;
1968
1969         stp = td->td_sel;
1970         if (stp != NULL) {
1971                 MPASS(stp->st_flags == 0);
1972                 MPASS(STAILQ_EMPTY(&stp->st_selq));
1973                 return;
1974         }
1975         stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1976         mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1977         cv_init(&stp->st_wait, "select");
1978         stp->st_flags = 0;
1979         STAILQ_INIT(&stp->st_selq);
1980         td->td_sel = stp;
1981 }
1982
1983 static int
1984 seltdwait(struct thread *td, sbintime_t sbt, sbintime_t precision)
1985 {
1986         struct seltd *stp;
1987         int error;
1988
1989         stp = td->td_sel;
1990         /*
1991          * An event of interest may occur while we do not hold the seltd
1992          * locked so check the pending flag before we sleep.
1993          */
1994         mtx_lock(&stp->st_mtx);
1995         /*
1996          * Any further calls to selrecord will be a rescan.
1997          */
1998         stp->st_flags |= SELTD_RESCAN;
1999         if (stp->st_flags & SELTD_PENDING) {
2000                 mtx_unlock(&stp->st_mtx);
2001                 return (0);
2002         }
2003         if (sbt == 0)
2004                 error = EWOULDBLOCK;
2005         else if (sbt != -1)
2006                 error = cv_timedwait_sig_sbt(&stp->st_wait, &stp->st_mtx,
2007                     sbt, precision, C_ABSOLUTE);
2008         else
2009                 error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
2010         mtx_unlock(&stp->st_mtx);
2011
2012         return (error);
2013 }
2014
2015 void
2016 seltdfini(struct thread *td)
2017 {
2018         struct seltd *stp;
2019
2020         stp = td->td_sel;
2021         if (stp == NULL)
2022                 return;
2023         MPASS(stp->st_flags == 0);
2024         MPASS(STAILQ_EMPTY(&stp->st_selq));
2025         if (stp->st_free1)
2026                 free(stp->st_free1, M_SELFD);
2027         if (stp->st_free2)
2028                 free(stp->st_free2, M_SELFD);
2029         td->td_sel = NULL;
2030         cv_destroy(&stp->st_wait);
2031         mtx_destroy(&stp->st_mtx);
2032         free(stp, M_SELECT);
2033 }
2034
2035 /*
2036  * Remove the references to the thread from all of the objects we were
2037  * polling.
2038  */
2039 static void
2040 seltdclear(struct thread *td)
2041 {
2042         struct seltd *stp;
2043         struct selfd *sfp;
2044         struct selfd *sfn;
2045
2046         stp = td->td_sel;
2047         STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
2048                 selfdfree(stp, sfp);
2049         stp->st_flags = 0;
2050 }
2051
2052 static void selectinit(void *);
2053 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
2054 static void
2055 selectinit(void *dummy __unused)
2056 {
2057
2058         mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);
2059 }
2060
2061 /*
2062  * Set up a syscall return value that follows the convention specified for
2063  * posix_* functions.
2064  */
2065 int
2066 kern_posix_error(struct thread *td, int error)
2067 {
2068
2069         if (error <= 0)
2070                 return (error);
2071         td->td_errno = error;
2072         td->td_pflags |= TDP_NERRNO;
2073         td->td_retval[0] = error;
2074         return (0);
2075 }