]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/sys_generic.c
compat_freebsd4: Check for errors from subyte() in freebsd4_uname()
[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         if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
564                 if (auio->uio_resid != cnt && (error == ERESTART ||
565                     error == EINTR || error == EWOULDBLOCK))
566                         error = 0;
567                 /* Socket layer is responsible for issuing SIGPIPE. */
568                 if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
569                         PROC_LOCK(td->td_proc);
570                         tdsignal(td, SIGPIPE);
571                         PROC_UNLOCK(td->td_proc);
572                 }
573         }
574         cnt -= auio->uio_resid;
575 #ifdef KTRACE
576         if (ktruio != NULL) {
577                 ktruio->uio_resid = cnt;
578                 ktrgenio(fd, UIO_WRITE, ktruio, error);
579         }
580 #endif
581         td->td_retval[0] = cnt;
582         return (error);
583 }
584
585 /*
586  * Truncate a file given a file descriptor.
587  *
588  * Can't use fget_write() here, since must return EINVAL and not EBADF if the
589  * descriptor isn't writable.
590  */
591 int
592 kern_ftruncate(struct thread *td, int fd, off_t length)
593 {
594         struct file *fp;
595         int error;
596
597         AUDIT_ARG_FD(fd);
598         if (length < 0)
599                 return (EINVAL);
600         error = fget(td, fd, &cap_ftruncate_rights, &fp);
601         if (error)
602                 return (error);
603         AUDIT_ARG_FILE(td->td_proc, fp);
604         if (!(fp->f_flag & FWRITE)) {
605                 fdrop(fp, td);
606                 return (EINVAL);
607         }
608         error = fo_truncate(fp, length, td->td_ucred, td);
609         fdrop(fp, td);
610         return (error);
611 }
612
613 #ifndef _SYS_SYSPROTO_H_
614 struct ftruncate_args {
615         int     fd;
616         int     pad;
617         off_t   length;
618 };
619 #endif
620 int
621 sys_ftruncate(struct thread *td, struct ftruncate_args *uap)
622 {
623
624         return (kern_ftruncate(td, uap->fd, uap->length));
625 }
626
627 #if defined(COMPAT_43)
628 #ifndef _SYS_SYSPROTO_H_
629 struct oftruncate_args {
630         int     fd;
631         long    length;
632 };
633 #endif
634 int
635 oftruncate(struct thread *td, struct oftruncate_args *uap)
636 {
637
638         return (kern_ftruncate(td, uap->fd, uap->length));
639 }
640 #endif /* COMPAT_43 */
641
642 #ifndef _SYS_SYSPROTO_H_
643 struct ioctl_args {
644         int     fd;
645         u_long  com;
646         caddr_t data;
647 };
648 #endif
649 /* ARGSUSED */
650 int
651 sys_ioctl(struct thread *td, struct ioctl_args *uap)
652 {
653         u_char smalldata[SYS_IOCTL_SMALL_SIZE] __aligned(SYS_IOCTL_SMALL_ALIGN);
654         uint32_t com;
655         int arg, error;
656         u_int size;
657         caddr_t data;
658
659 #ifdef INVARIANTS
660         if (uap->com > 0xffffffff) {
661                 printf(
662                     "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
663                     td->td_proc->p_pid, td->td_name, uap->com);
664         }
665 #endif
666         com = (uint32_t)uap->com;
667
668         /*
669          * Interpret high order word to find amount of data to be
670          * copied to/from the user's address space.
671          */
672         size = IOCPARM_LEN(com);
673         if ((size > IOCPARM_MAX) ||
674             ((com & (IOC_VOID  | IOC_IN | IOC_OUT)) == 0) ||
675 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
676             ((com & IOC_OUT) && size == 0) ||
677 #else
678             ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
679 #endif
680             ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
681                 return (ENOTTY);
682
683         if (size > 0) {
684                 if (com & IOC_VOID) {
685                         /* Integer argument. */
686                         arg = (intptr_t)uap->data;
687                         data = (void *)&arg;
688                         size = 0;
689                 } else {
690                         if (size > SYS_IOCTL_SMALL_SIZE)
691                                 data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
692                         else
693                                 data = smalldata;
694                 }
695         } else
696                 data = (void *)&uap->data;
697         if (com & IOC_IN) {
698                 error = copyin(uap->data, data, (u_int)size);
699                 if (error != 0)
700                         goto out;
701         } else if (com & IOC_OUT) {
702                 /*
703                  * Zero the buffer so the user always
704                  * gets back something deterministic.
705                  */
706                 bzero(data, size);
707         }
708
709         error = kern_ioctl(td, uap->fd, com, data);
710
711         if (error == 0 && (com & IOC_OUT))
712                 error = copyout(data, uap->data, (u_int)size);
713
714 out:
715         if (size > SYS_IOCTL_SMALL_SIZE)
716                 free(data, M_IOCTLOPS);
717         return (error);
718 }
719
720 int
721 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
722 {
723         struct file *fp;
724         struct filedesc *fdp;
725         int error, tmp, locked;
726
727         AUDIT_ARG_FD(fd);
728         AUDIT_ARG_CMD(com);
729
730         fdp = td->td_proc->p_fd;
731
732         switch (com) {
733         case FIONCLEX:
734         case FIOCLEX:
735                 FILEDESC_XLOCK(fdp);
736                 locked = LA_XLOCKED;
737                 break;
738         default:
739 #ifdef CAPABILITIES
740                 FILEDESC_SLOCK(fdp);
741                 locked = LA_SLOCKED;
742 #else
743                 locked = LA_UNLOCKED;
744 #endif
745                 break;
746         }
747
748 #ifdef CAPABILITIES
749         if ((fp = fget_locked(fdp, fd)) == NULL) {
750                 error = EBADF;
751                 goto out;
752         }
753         if ((error = cap_ioctl_check(fdp, fd, com)) != 0) {
754                 fp = NULL;      /* fhold() was not called yet */
755                 goto out;
756         }
757         if (!fhold(fp)) {
758                 error = EBADF;
759                 fp = NULL;
760                 goto out;
761         }
762         if (locked == LA_SLOCKED) {
763                 FILEDESC_SUNLOCK(fdp);
764                 locked = LA_UNLOCKED;
765         }
766 #else
767         error = fget(td, fd, &cap_ioctl_rights, &fp);
768         if (error != 0) {
769                 fp = NULL;
770                 goto out;
771         }
772 #endif
773         if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
774                 error = EBADF;
775                 goto out;
776         }
777
778         switch (com) {
779         case FIONCLEX:
780                 fdp->fd_ofiles[fd].fde_flags &= ~UF_EXCLOSE;
781                 goto out;
782         case FIOCLEX:
783                 fdp->fd_ofiles[fd].fde_flags |= UF_EXCLOSE;
784                 goto out;
785         case FIONBIO:
786                 if ((tmp = *(int *)data))
787                         atomic_set_int(&fp->f_flag, FNONBLOCK);
788                 else
789                         atomic_clear_int(&fp->f_flag, FNONBLOCK);
790                 data = (void *)&tmp;
791                 break;
792         case FIOASYNC:
793                 if ((tmp = *(int *)data))
794                         atomic_set_int(&fp->f_flag, FASYNC);
795                 else
796                         atomic_clear_int(&fp->f_flag, FASYNC);
797                 data = (void *)&tmp;
798                 break;
799         }
800
801         error = fo_ioctl(fp, com, data, td->td_ucred, td);
802 out:
803         switch (locked) {
804         case LA_XLOCKED:
805                 FILEDESC_XUNLOCK(fdp);
806                 break;
807 #ifdef CAPABILITIES
808         case LA_SLOCKED:
809                 FILEDESC_SUNLOCK(fdp);
810                 break;
811 #endif
812         default:
813                 FILEDESC_UNLOCK_ASSERT(fdp);
814                 break;
815         }
816         if (fp != NULL)
817                 fdrop(fp, td);
818         return (error);
819 }
820
821 int
822 sys_posix_fallocate(struct thread *td, struct posix_fallocate_args *uap)
823 {
824         int error;
825
826         error = kern_posix_fallocate(td, uap->fd, uap->offset, uap->len);
827         return (kern_posix_error(td, error));
828 }
829
830 int
831 kern_posix_fallocate(struct thread *td, int fd, off_t offset, off_t len)
832 {
833         struct file *fp;
834         int error;
835
836         AUDIT_ARG_FD(fd);
837         if (offset < 0 || len <= 0)
838                 return (EINVAL);
839         /* Check for wrap. */
840         if (offset > OFF_MAX - len)
841                 return (EFBIG);
842         AUDIT_ARG_FD(fd);
843         error = fget(td, fd, &cap_pwrite_rights, &fp);
844         if (error != 0)
845                 return (error);
846         AUDIT_ARG_FILE(td->td_proc, fp);
847         if ((fp->f_ops->fo_flags & DFLAG_SEEKABLE) == 0) {
848                 error = ESPIPE;
849                 goto out;
850         }
851         if ((fp->f_flag & FWRITE) == 0) {
852                 error = EBADF;
853                 goto out;
854         }
855
856         error = fo_fallocate(fp, offset, len, td);
857  out:
858         fdrop(fp, td);
859         return (error);
860 }
861
862 int
863 kern_specialfd(struct thread *td, int type, void *arg)
864 {
865         struct file *fp;
866         struct specialfd_eventfd *ae;
867         int error, fd, fflags;
868
869         fflags = 0;
870         error = falloc_noinstall(td, &fp);
871         if (error != 0)
872                 return (error);
873
874         switch (type) {
875         case SPECIALFD_EVENTFD:
876                 ae = arg;
877                 if ((ae->flags & EFD_CLOEXEC) != 0)
878                         fflags |= O_CLOEXEC;
879                 error = eventfd_create_file(td, fp, ae->initval, ae->flags);
880                 break;
881         default:
882                 error = EINVAL;
883                 break;
884         }
885
886         if (error == 0)
887                 error = finstall(td, fp, &fd, fflags, NULL);
888         fdrop(fp, td);
889         if (error == 0)
890                 td->td_retval[0] = fd;
891         return (error);
892 }
893
894 int
895 sys___specialfd(struct thread *td, struct __specialfd_args *args)
896 {
897         struct specialfd_eventfd ae;
898         int error;
899
900         switch (args->type) {
901         case SPECIALFD_EVENTFD:
902                 if (args->len != sizeof(struct specialfd_eventfd)) {
903                         error = EINVAL;
904                         break;
905                 }
906                 error = copyin(args->req, &ae, sizeof(ae));
907                 if (error != 0)
908                         break;
909                 if ((ae.flags & ~(EFD_CLOEXEC | EFD_NONBLOCK |
910                     EFD_SEMAPHORE)) != 0) {
911                         error = EINVAL;
912                         break;
913                 }
914                 error = kern_specialfd(td, args->type, &ae);
915                 break;
916         default:
917                 error = EINVAL;
918                 break;
919         }
920         return (error);
921 }
922
923 int
924 poll_no_poll(int events)
925 {
926         /*
927          * Return true for read/write.  If the user asked for something
928          * special, return POLLNVAL, so that clients have a way of
929          * determining reliably whether or not the extended
930          * functionality is present without hard-coding knowledge
931          * of specific filesystem implementations.
932          */
933         if (events & ~POLLSTANDARD)
934                 return (POLLNVAL);
935
936         return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
937 }
938
939 int
940 sys_pselect(struct thread *td, struct pselect_args *uap)
941 {
942         struct timespec ts;
943         struct timeval tv, *tvp;
944         sigset_t set, *uset;
945         int error;
946
947         if (uap->ts != NULL) {
948                 error = copyin(uap->ts, &ts, sizeof(ts));
949                 if (error != 0)
950                     return (error);
951                 TIMESPEC_TO_TIMEVAL(&tv, &ts);
952                 tvp = &tv;
953         } else
954                 tvp = NULL;
955         if (uap->sm != NULL) {
956                 error = copyin(uap->sm, &set, sizeof(set));
957                 if (error != 0)
958                         return (error);
959                 uset = &set;
960         } else
961                 uset = NULL;
962         return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
963             uset, NFDBITS));
964 }
965
966 int
967 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
968     struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
969 {
970         int error;
971
972         if (uset != NULL) {
973                 error = kern_sigprocmask(td, SIG_SETMASK, uset,
974                     &td->td_oldsigmask, 0);
975                 if (error != 0)
976                         return (error);
977                 td->td_pflags |= TDP_OLDMASK;
978                 /*
979                  * Make sure that ast() is called on return to
980                  * usermode and TDP_OLDMASK is cleared, restoring old
981                  * sigmask.
982                  */
983                 thread_lock(td);
984                 td->td_flags |= TDF_ASTPENDING;
985                 thread_unlock(td);
986         }
987         error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
988         return (error);
989 }
990
991 #ifndef _SYS_SYSPROTO_H_
992 struct select_args {
993         int     nd;
994         fd_set  *in, *ou, *ex;
995         struct  timeval *tv;
996 };
997 #endif
998 int
999 sys_select(struct thread *td, struct select_args *uap)
1000 {
1001         struct timeval tv, *tvp;
1002         int error;
1003
1004         if (uap->tv != NULL) {
1005                 error = copyin(uap->tv, &tv, sizeof(tv));
1006                 if (error)
1007                         return (error);
1008                 tvp = &tv;
1009         } else
1010                 tvp = NULL;
1011
1012         return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
1013             NFDBITS));
1014 }
1015
1016 /*
1017  * In the unlikely case when user specified n greater then the last
1018  * open file descriptor, check that no bits are set after the last
1019  * valid fd.  We must return EBADF if any is set.
1020  *
1021  * There are applications that rely on the behaviour.
1022  *
1023  * nd is fd_nfiles.
1024  */
1025 static int
1026 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
1027 {
1028         char *addr, *oaddr;
1029         int b, i, res;
1030         uint8_t bits;
1031
1032         if (nd >= ndu || fd_in == NULL)
1033                 return (0);
1034
1035         oaddr = NULL;
1036         bits = 0; /* silence gcc */
1037         for (i = nd; i < ndu; i++) {
1038                 b = i / NBBY;
1039 #if BYTE_ORDER == LITTLE_ENDIAN
1040                 addr = (char *)fd_in + b;
1041 #else
1042                 addr = (char *)fd_in;
1043                 if (abi_nfdbits == NFDBITS) {
1044                         addr += rounddown(b, sizeof(fd_mask)) +
1045                             sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
1046                 } else {
1047                         addr += rounddown(b, sizeof(uint32_t)) +
1048                             sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
1049                 }
1050 #endif
1051                 if (addr != oaddr) {
1052                         res = fubyte(addr);
1053                         if (res == -1)
1054                                 return (EFAULT);
1055                         oaddr = addr;
1056                         bits = res;
1057                 }
1058                 if ((bits & (1 << (i % NBBY))) != 0)
1059                         return (EBADF);
1060         }
1061         return (0);
1062 }
1063
1064 int
1065 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
1066     fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
1067 {
1068         struct filedesc *fdp;
1069         /*
1070          * The magic 2048 here is chosen to be just enough for FD_SETSIZE
1071          * infds with the new FD_SETSIZE of 1024, and more than enough for
1072          * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
1073          * of 256.
1074          */
1075         fd_mask s_selbits[howmany(2048, NFDBITS)];
1076         fd_mask *ibits[3], *obits[3], *selbits, *sbp;
1077         struct timeval rtv;
1078         sbintime_t asbt, precision, rsbt;
1079         u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
1080         int error, lf, ndu;
1081
1082         if (nd < 0)
1083                 return (EINVAL);
1084         fdp = td->td_proc->p_fd;
1085         ndu = nd;
1086         lf = fdp->fd_nfiles;
1087         if (nd > lf)
1088                 nd = lf;
1089
1090         error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
1091         if (error != 0)
1092                 return (error);
1093         error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
1094         if (error != 0)
1095                 return (error);
1096         error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
1097         if (error != 0)
1098                 return (error);
1099
1100         /*
1101          * Allocate just enough bits for the non-null fd_sets.  Use the
1102          * preallocated auto buffer if possible.
1103          */
1104         nfdbits = roundup(nd, NFDBITS);
1105         ncpbytes = nfdbits / NBBY;
1106         ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
1107         nbufbytes = 0;
1108         if (fd_in != NULL)
1109                 nbufbytes += 2 * ncpbytes;
1110         if (fd_ou != NULL)
1111                 nbufbytes += 2 * ncpbytes;
1112         if (fd_ex != NULL)
1113                 nbufbytes += 2 * ncpbytes;
1114         if (nbufbytes <= sizeof s_selbits)
1115                 selbits = &s_selbits[0];
1116         else
1117                 selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
1118
1119         /*
1120          * Assign pointers into the bit buffers and fetch the input bits.
1121          * Put the output buffers together so that they can be bzeroed
1122          * together.
1123          */
1124         sbp = selbits;
1125 #define getbits(name, x) \
1126         do {                                                            \
1127                 if (name == NULL) {                                     \
1128                         ibits[x] = NULL;                                \
1129                         obits[x] = NULL;                                \
1130                 } else {                                                \
1131                         ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp;   \
1132                         obits[x] = sbp;                                 \
1133                         sbp += ncpbytes / sizeof *sbp;                  \
1134                         error = copyin(name, ibits[x], ncpubytes);      \
1135                         if (error != 0)                                 \
1136                                 goto done;                              \
1137                         if (ncpbytes != ncpubytes)                      \
1138                                 bzero((char *)ibits[x] + ncpubytes,     \
1139                                     ncpbytes - ncpubytes);              \
1140                 }                                                       \
1141         } while (0)
1142         getbits(fd_in, 0);
1143         getbits(fd_ou, 1);
1144         getbits(fd_ex, 2);
1145 #undef  getbits
1146
1147 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
1148         /*
1149          * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
1150          * we are running under 32-bit emulation. This should be more
1151          * generic.
1152          */
1153 #define swizzle_fdset(bits)                                             \
1154         if (abi_nfdbits != NFDBITS && bits != NULL) {                   \
1155                 int i;                                                  \
1156                 for (i = 0; i < ncpbytes / sizeof *sbp; i++)            \
1157                         bits[i] = (bits[i] >> 32) | (bits[i] << 32);    \
1158         }
1159 #else
1160 #define swizzle_fdset(bits)
1161 #endif
1162
1163         /* Make sure the bit order makes it through an ABI transition */
1164         swizzle_fdset(ibits[0]);
1165         swizzle_fdset(ibits[1]);
1166         swizzle_fdset(ibits[2]);
1167
1168         if (nbufbytes != 0)
1169                 bzero(selbits, nbufbytes / 2);
1170
1171         precision = 0;
1172         if (tvp != NULL) {
1173                 rtv = *tvp;
1174                 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1175                     rtv.tv_usec >= 1000000) {
1176                         error = EINVAL;
1177                         goto done;
1178                 }
1179                 if (!timevalisset(&rtv))
1180                         asbt = 0;
1181                 else if (rtv.tv_sec <= INT32_MAX) {
1182                         rsbt = tvtosbt(rtv);
1183                         precision = rsbt;
1184                         precision >>= tc_precexp;
1185                         if (TIMESEL(&asbt, rsbt))
1186                                 asbt += tc_tick_sbt;
1187                         if (asbt <= SBT_MAX - rsbt)
1188                                 asbt += rsbt;
1189                         else
1190                                 asbt = -1;
1191                 } else
1192                         asbt = -1;
1193         } else
1194                 asbt = -1;
1195         seltdinit(td);
1196         /* Iterate until the timeout expires or descriptors become ready. */
1197         for (;;) {
1198                 error = selscan(td, ibits, obits, nd);
1199                 if (error || td->td_retval[0] != 0)
1200                         break;
1201                 error = seltdwait(td, asbt, precision);
1202                 if (error)
1203                         break;
1204                 error = selrescan(td, ibits, obits);
1205                 if (error || td->td_retval[0] != 0)
1206                         break;
1207         }
1208         seltdclear(td);
1209
1210 done:
1211         /* select is not restarted after signals... */
1212         if (error == ERESTART)
1213                 error = EINTR;
1214         if (error == EWOULDBLOCK)
1215                 error = 0;
1216
1217         /* swizzle bit order back, if necessary */
1218         swizzle_fdset(obits[0]);
1219         swizzle_fdset(obits[1]);
1220         swizzle_fdset(obits[2]);
1221 #undef swizzle_fdset
1222
1223 #define putbits(name, x) \
1224         if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1225                 error = error2;
1226         if (error == 0) {
1227                 int error2;
1228
1229                 putbits(fd_in, 0);
1230                 putbits(fd_ou, 1);
1231                 putbits(fd_ex, 2);
1232 #undef putbits
1233         }
1234         if (selbits != &s_selbits[0])
1235                 free(selbits, M_SELECT);
1236
1237         return (error);
1238 }
1239 /* 
1240  * Convert a select bit set to poll flags.
1241  *
1242  * The backend always returns POLLHUP/POLLERR if appropriate and we
1243  * return this as a set bit in any set.
1244  */
1245 static const int select_flags[3] = {
1246     POLLRDNORM | POLLHUP | POLLERR,
1247     POLLWRNORM | POLLHUP | POLLERR,
1248     POLLRDBAND | POLLERR
1249 };
1250
1251 /*
1252  * Compute the fo_poll flags required for a fd given by the index and
1253  * bit position in the fd_mask array.
1254  */
1255 static __inline int
1256 selflags(fd_mask **ibits, int idx, fd_mask bit)
1257 {
1258         int flags;
1259         int msk;
1260
1261         flags = 0;
1262         for (msk = 0; msk < 3; msk++) {
1263                 if (ibits[msk] == NULL)
1264                         continue;
1265                 if ((ibits[msk][idx] & bit) == 0)
1266                         continue;
1267                 flags |= select_flags[msk];
1268         }
1269         return (flags);
1270 }
1271
1272 /*
1273  * Set the appropriate output bits given a mask of fired events and the
1274  * input bits originally requested.
1275  */
1276 static __inline int
1277 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1278 {
1279         int msk;
1280         int n;
1281
1282         n = 0;
1283         for (msk = 0; msk < 3; msk++) {
1284                 if ((events & select_flags[msk]) == 0)
1285                         continue;
1286                 if (ibits[msk] == NULL)
1287                         continue;
1288                 if ((ibits[msk][idx] & bit) == 0)
1289                         continue;
1290                 /*
1291                  * XXX Check for a duplicate set.  This can occur because a
1292                  * socket calls selrecord() twice for each poll() call
1293                  * resulting in two selfds per real fd.  selrescan() will
1294                  * call selsetbits twice as a result.
1295                  */
1296                 if ((obits[msk][idx] & bit) != 0)
1297                         continue;
1298                 obits[msk][idx] |= bit;
1299                 n++;
1300         }
1301
1302         return (n);
1303 }
1304
1305 /*
1306  * Traverse the list of fds attached to this thread's seltd and check for
1307  * completion.
1308  */
1309 static int
1310 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1311 {
1312         struct filedesc *fdp;
1313         struct selinfo *si;
1314         struct seltd *stp;
1315         struct selfd *sfp;
1316         struct selfd *sfn;
1317         struct file *fp;
1318         fd_mask bit;
1319         int fd, ev, n, idx;
1320         int error;
1321         bool only_user;
1322
1323         fdp = td->td_proc->p_fd;
1324         stp = td->td_sel;
1325         n = 0;
1326         only_user = FILEDESC_IS_ONLY_USER(fdp);
1327         STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1328                 fd = (int)(uintptr_t)sfp->sf_cookie;
1329                 si = sfp->sf_si;
1330                 selfdfree(stp, sfp);
1331                 /* If the selinfo wasn't cleared the event didn't fire. */
1332                 if (si != NULL)
1333                         continue;
1334                 if (only_user)
1335                         error = fget_only_user(fdp, fd, &cap_event_rights, &fp);
1336                 else
1337                         error = fget_unlocked(fdp, fd, &cap_event_rights, &fp);
1338                 if (__predict_false(error != 0))
1339                         return (error);
1340                 idx = fd / NFDBITS;
1341                 bit = (fd_mask)1 << (fd % NFDBITS);
1342                 ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1343                 if (only_user)
1344                         fput_only_user(fdp, fp);
1345                 else
1346                         fdrop(fp, td);
1347                 if (ev != 0)
1348                         n += selsetbits(ibits, obits, idx, bit, ev);
1349         }
1350         stp->st_flags = 0;
1351         td->td_retval[0] = n;
1352         return (0);
1353 }
1354
1355 /*
1356  * Perform the initial filedescriptor scan and register ourselves with
1357  * each selinfo.
1358  */
1359 static int
1360 selscan(struct thread *td, fd_mask **ibits, fd_mask **obits, int nfd)
1361 {
1362         struct filedesc *fdp;
1363         struct file *fp;
1364         fd_mask bit;
1365         int ev, flags, end, fd;
1366         int n, idx;
1367         int error;
1368         bool only_user;
1369
1370         fdp = td->td_proc->p_fd;
1371         n = 0;
1372         only_user = FILEDESC_IS_ONLY_USER(fdp);
1373         for (idx = 0, fd = 0; fd < nfd; idx++) {
1374                 end = imin(fd + NFDBITS, nfd);
1375                 for (bit = 1; fd < end; bit <<= 1, fd++) {
1376                         /* Compute the list of events we're interested in. */
1377                         flags = selflags(ibits, idx, bit);
1378                         if (flags == 0)
1379                                 continue;
1380                         if (only_user)
1381                                 error = fget_only_user(fdp, fd, &cap_event_rights, &fp);
1382                         else
1383                                 error = fget_unlocked(fdp, fd, &cap_event_rights, &fp);
1384                         if (__predict_false(error != 0))
1385                                 return (error);
1386                         selfdalloc(td, (void *)(uintptr_t)fd);
1387                         ev = fo_poll(fp, flags, td->td_ucred, td);
1388                         if (only_user)
1389                                 fput_only_user(fdp, fp);
1390                         else
1391                                 fdrop(fp, td);
1392                         if (ev != 0)
1393                                 n += selsetbits(ibits, obits, idx, bit, ev);
1394                 }
1395         }
1396
1397         td->td_retval[0] = n;
1398         return (0);
1399 }
1400
1401 int
1402 sys_poll(struct thread *td, struct poll_args *uap)
1403 {
1404         struct timespec ts, *tsp;
1405
1406         if (uap->timeout != INFTIM) {
1407                 if (uap->timeout < 0)
1408                         return (EINVAL);
1409                 ts.tv_sec = uap->timeout / 1000;
1410                 ts.tv_nsec = (uap->timeout % 1000) * 1000000;
1411                 tsp = &ts;
1412         } else
1413                 tsp = NULL;
1414
1415         return (kern_poll(td, uap->fds, uap->nfds, tsp, NULL));
1416 }
1417
1418 /*
1419  * kfds points to an array in the kernel.
1420  */
1421 int
1422 kern_poll_kfds(struct thread *td, struct pollfd *kfds, u_int nfds,
1423     struct timespec *tsp, sigset_t *uset)
1424 {
1425         sbintime_t sbt, precision, tmp;
1426         time_t over;
1427         struct timespec ts;
1428         int error;
1429
1430         precision = 0;
1431         if (tsp != NULL) {
1432                 if (!timespecvalid_interval(tsp))
1433                         return (EINVAL);
1434                 if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
1435                         sbt = 0;
1436                 else {
1437                         ts = *tsp;
1438                         if (ts.tv_sec > INT32_MAX / 2) {
1439                                 over = ts.tv_sec - INT32_MAX / 2;
1440                                 ts.tv_sec -= over;
1441                         } else
1442                                 over = 0;
1443                         tmp = tstosbt(ts);
1444                         precision = tmp;
1445                         precision >>= tc_precexp;
1446                         if (TIMESEL(&sbt, tmp))
1447                                 sbt += tc_tick_sbt;
1448                         sbt += tmp;
1449                 }
1450         } else
1451                 sbt = -1;
1452
1453         if (uset != NULL) {
1454                 error = kern_sigprocmask(td, SIG_SETMASK, uset,
1455                     &td->td_oldsigmask, 0);
1456                 if (error)
1457                         return (error);
1458                 td->td_pflags |= TDP_OLDMASK;
1459                 /*
1460                  * Make sure that ast() is called on return to
1461                  * usermode and TDP_OLDMASK is cleared, restoring old
1462                  * sigmask.
1463                  */
1464                 thread_lock(td);
1465                 td->td_flags |= TDF_ASTPENDING;
1466                 thread_unlock(td);
1467         }
1468
1469         seltdinit(td);
1470         /* Iterate until the timeout expires or descriptors become ready. */
1471         for (;;) {
1472                 error = pollscan(td, kfds, nfds);
1473                 if (error || td->td_retval[0] != 0)
1474                         break;
1475                 error = seltdwait(td, sbt, precision);
1476                 if (error)
1477                         break;
1478                 error = pollrescan(td);
1479                 if (error || td->td_retval[0] != 0)
1480                         break;
1481         }
1482         seltdclear(td);
1483
1484         /* poll is not restarted after signals... */
1485         if (error == ERESTART)
1486                 error = EINTR;
1487         if (error == EWOULDBLOCK)
1488                 error = 0;
1489         return (error);
1490 }
1491
1492 int
1493 sys_ppoll(struct thread *td, struct ppoll_args *uap)
1494 {
1495         struct timespec ts, *tsp;
1496         sigset_t set, *ssp;
1497         int error;
1498
1499         if (uap->ts != NULL) {
1500                 error = copyin(uap->ts, &ts, sizeof(ts));
1501                 if (error)
1502                         return (error);
1503                 tsp = &ts;
1504         } else
1505                 tsp = NULL;
1506         if (uap->set != NULL) {
1507                 error = copyin(uap->set, &set, sizeof(set));
1508                 if (error)
1509                         return (error);
1510                 ssp = &set;
1511         } else
1512                 ssp = NULL;
1513         return (kern_poll(td, uap->fds, uap->nfds, tsp, ssp));
1514 }
1515
1516 /*
1517  * ufds points to an array in user space.
1518  */
1519 int
1520 kern_poll(struct thread *td, struct pollfd *ufds, u_int nfds,
1521     struct timespec *tsp, sigset_t *set)
1522 {
1523         struct pollfd *kfds;
1524         struct pollfd stackfds[32];
1525         int error;
1526
1527         if (kern_poll_maxfds(nfds))
1528                 return (EINVAL);
1529         if (nfds > nitems(stackfds))
1530                 kfds = mallocarray(nfds, sizeof(*kfds), M_TEMP, M_WAITOK);
1531         else
1532                 kfds = stackfds;
1533         error = copyin(ufds, kfds, nfds * sizeof(*kfds));
1534         if (error != 0)
1535                 goto out;
1536
1537         error = kern_poll_kfds(td, kfds, nfds, tsp, set);
1538         if (error == 0)
1539                 error = pollout(td, kfds, ufds, nfds);
1540
1541 out:
1542         if (nfds > nitems(stackfds))
1543                 free(kfds, M_TEMP);
1544         return (error);
1545 }
1546
1547 bool
1548 kern_poll_maxfds(u_int nfds)
1549 {
1550
1551         /*
1552          * This is kinda bogus.  We have fd limits, but that is not
1553          * really related to the size of the pollfd array.  Make sure
1554          * we let the process use at least FD_SETSIZE entries and at
1555          * least enough for the system-wide limits.  We want to be reasonably
1556          * safe, but not overly restrictive.
1557          */
1558         return (nfds > maxfilesperproc && nfds > FD_SETSIZE);
1559 }
1560
1561 static int
1562 pollrescan(struct thread *td)
1563 {
1564         struct seltd *stp;
1565         struct selfd *sfp;
1566         struct selfd *sfn;
1567         struct selinfo *si;
1568         struct filedesc *fdp;
1569         struct file *fp;
1570         struct pollfd *fd;
1571         int n, error;
1572         bool only_user;
1573
1574         n = 0;
1575         fdp = td->td_proc->p_fd;
1576         stp = td->td_sel;
1577         only_user = FILEDESC_IS_ONLY_USER(fdp);
1578         STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1579                 fd = (struct pollfd *)sfp->sf_cookie;
1580                 si = sfp->sf_si;
1581                 selfdfree(stp, sfp);
1582                 /* If the selinfo wasn't cleared the event didn't fire. */
1583                 if (si != NULL)
1584                         continue;
1585                 if (only_user)
1586                         error = fget_only_user(fdp, fd->fd, &cap_event_rights, &fp);
1587                 else
1588                         error = fget_unlocked(fdp, fd->fd, &cap_event_rights, &fp);
1589                 if (__predict_false(error != 0)) {
1590                         fd->revents = POLLNVAL;
1591                         n++;
1592                         continue;
1593                 }
1594                 /*
1595                  * Note: backend also returns POLLHUP and
1596                  * POLLERR if appropriate.
1597                  */
1598                 fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1599                 if (only_user)
1600                         fput_only_user(fdp, fp);
1601                 else
1602                         fdrop(fp, td);
1603                 if (fd->revents != 0)
1604                         n++;
1605         }
1606         stp->st_flags = 0;
1607         td->td_retval[0] = n;
1608         return (0);
1609 }
1610
1611 static int
1612 pollout(struct thread *td, struct pollfd *fds, struct pollfd *ufds, u_int nfd)
1613 {
1614         int error = 0;
1615         u_int i = 0;
1616         u_int n = 0;
1617
1618         for (i = 0; i < nfd; i++) {
1619                 error = copyout(&fds->revents, &ufds->revents,
1620                     sizeof(ufds->revents));
1621                 if (error)
1622                         return (error);
1623                 if (fds->revents != 0)
1624                         n++;
1625                 fds++;
1626                 ufds++;
1627         }
1628         td->td_retval[0] = n;
1629         return (0);
1630 }
1631
1632 static int
1633 pollscan(struct thread *td, struct pollfd *fds, u_int nfd)
1634 {
1635         struct filedesc *fdp;
1636         struct file *fp;
1637         int i, n, error;
1638         bool only_user;
1639
1640         n = 0;
1641         fdp = td->td_proc->p_fd;
1642         only_user = FILEDESC_IS_ONLY_USER(fdp);
1643         for (i = 0; i < nfd; i++, fds++) {
1644                 if (fds->fd < 0) {
1645                         fds->revents = 0;
1646                         continue;
1647                 }
1648                 if (only_user)
1649                         error = fget_only_user(fdp, fds->fd, &cap_event_rights, &fp);
1650                 else
1651                         error = fget_unlocked(fdp, fds->fd, &cap_event_rights, &fp);
1652                 if (__predict_false(error != 0)) {
1653                         fds->revents = POLLNVAL;
1654                         n++;
1655                         continue;
1656                 }
1657                 /*
1658                  * Note: backend also returns POLLHUP and
1659                  * POLLERR if appropriate.
1660                  */
1661                 selfdalloc(td, fds);
1662                 fds->revents = fo_poll(fp, fds->events,
1663                     td->td_ucred, td);
1664                 if (only_user)
1665                         fput_only_user(fdp, fp);
1666                 else
1667                         fdrop(fp, td);
1668                 /*
1669                  * POSIX requires POLLOUT to be never
1670                  * set simultaneously with POLLHUP.
1671                  */
1672                 if ((fds->revents & POLLHUP) != 0)
1673                         fds->revents &= ~POLLOUT;
1674
1675                 if (fds->revents != 0)
1676                         n++;
1677         }
1678         td->td_retval[0] = n;
1679         return (0);
1680 }
1681
1682 /*
1683  * XXX This was created specifically to support netncp and netsmb.  This
1684  * allows the caller to specify a socket to wait for events on.  It returns
1685  * 0 if any events matched and an error otherwise.  There is no way to
1686  * determine which events fired.
1687  */
1688 int
1689 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1690 {
1691         struct timeval rtv;
1692         sbintime_t asbt, precision, rsbt;
1693         int error;
1694
1695         precision = 0;  /* stupid gcc! */
1696         if (tvp != NULL) {
1697                 rtv = *tvp;
1698                 if (rtv.tv_sec < 0 || rtv.tv_usec < 0 || 
1699                     rtv.tv_usec >= 1000000)
1700                         return (EINVAL);
1701                 if (!timevalisset(&rtv))
1702                         asbt = 0;
1703                 else if (rtv.tv_sec <= INT32_MAX) {
1704                         rsbt = tvtosbt(rtv);
1705                         precision = rsbt;
1706                         precision >>= tc_precexp;
1707                         if (TIMESEL(&asbt, rsbt))
1708                                 asbt += tc_tick_sbt;
1709                         if (asbt <= SBT_MAX - rsbt)
1710                                 asbt += rsbt;
1711                         else
1712                                 asbt = -1;
1713                 } else
1714                         asbt = -1;
1715         } else
1716                 asbt = -1;
1717         seltdinit(td);
1718         /*
1719          * Iterate until the timeout expires or the socket becomes ready.
1720          */
1721         for (;;) {
1722                 selfdalloc(td, NULL);
1723                 if (sopoll(so, events, NULL, td) != 0) {
1724                         error = 0;
1725                         break;
1726                 }
1727                 error = seltdwait(td, asbt, precision);
1728                 if (error)
1729                         break;
1730         }
1731         seltdclear(td);
1732         /* XXX Duplicates ncp/smb behavior. */
1733         if (error == ERESTART)
1734                 error = 0;
1735         return (error);
1736 }
1737
1738 /*
1739  * Preallocate two selfds associated with 'cookie'.  Some fo_poll routines
1740  * have two select sets, one for read and another for write.
1741  */
1742 static void
1743 selfdalloc(struct thread *td, void *cookie)
1744 {
1745         struct seltd *stp;
1746
1747         stp = td->td_sel;
1748         if (stp->st_free1 == NULL)
1749                 stp->st_free1 = malloc(sizeof(*stp->st_free1), M_SELFD, M_WAITOK|M_ZERO);
1750         stp->st_free1->sf_td = stp;
1751         stp->st_free1->sf_cookie = cookie;
1752         if (stp->st_free2 == NULL)
1753                 stp->st_free2 = malloc(sizeof(*stp->st_free2), M_SELFD, M_WAITOK|M_ZERO);
1754         stp->st_free2->sf_td = stp;
1755         stp->st_free2->sf_cookie = cookie;
1756 }
1757
1758 static void
1759 selfdfree(struct seltd *stp, struct selfd *sfp)
1760 {
1761         STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1762         /*
1763          * Paired with doselwakeup.
1764          */
1765         if (atomic_load_acq_ptr((uintptr_t *)&sfp->sf_si) != (uintptr_t)NULL) {
1766                 mtx_lock(sfp->sf_mtx);
1767                 if (sfp->sf_si != NULL) {
1768                         TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1769                 }
1770                 mtx_unlock(sfp->sf_mtx);
1771         }
1772         free(sfp, M_SELFD);
1773 }
1774
1775 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1776 void
1777 seldrain(struct selinfo *sip)
1778 {
1779
1780         /*
1781          * This feature is already provided by doselwakeup(), thus it is
1782          * enough to go for it.
1783          * Eventually, the context, should take care to avoid races
1784          * between thread calling select()/poll() and file descriptor
1785          * detaching, but, again, the races are just the same as
1786          * selwakeup().
1787          */
1788         doselwakeup(sip, -1);
1789 }
1790
1791 /*
1792  * Record a select request.
1793  */
1794 void
1795 selrecord(struct thread *selector, struct selinfo *sip)
1796 {
1797         struct selfd *sfp;
1798         struct seltd *stp;
1799         struct mtx *mtxp;
1800
1801         stp = selector->td_sel;
1802         /*
1803          * Don't record when doing a rescan.
1804          */
1805         if (stp->st_flags & SELTD_RESCAN)
1806                 return;
1807         /*
1808          * Grab one of the preallocated descriptors.
1809          */
1810         sfp = NULL;
1811         if ((sfp = stp->st_free1) != NULL)
1812                 stp->st_free1 = NULL;
1813         else if ((sfp = stp->st_free2) != NULL)
1814                 stp->st_free2 = NULL;
1815         else
1816                 panic("selrecord: No free selfd on selq");
1817         mtxp = sip->si_mtx;
1818         if (mtxp == NULL)
1819                 mtxp = mtx_pool_find(mtxpool_select, sip);
1820         /*
1821          * Initialize the sfp and queue it in the thread.
1822          */
1823         sfp->sf_si = sip;
1824         sfp->sf_mtx = mtxp;
1825         STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1826         /*
1827          * Now that we've locked the sip, check for initialization.
1828          */
1829         mtx_lock(mtxp);
1830         if (sip->si_mtx == NULL) {
1831                 sip->si_mtx = mtxp;
1832                 TAILQ_INIT(&sip->si_tdlist);
1833         }
1834         /*
1835          * Add this thread to the list of selfds listening on this selinfo.
1836          */
1837         TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1838         mtx_unlock(sip->si_mtx);
1839 }
1840
1841 /* Wake up a selecting thread. */
1842 void
1843 selwakeup(struct selinfo *sip)
1844 {
1845         doselwakeup(sip, -1);
1846 }
1847
1848 /* Wake up a selecting thread, and set its priority. */
1849 void
1850 selwakeuppri(struct selinfo *sip, int pri)
1851 {
1852         doselwakeup(sip, pri);
1853 }
1854
1855 /*
1856  * Do a wakeup when a selectable event occurs.
1857  */
1858 static void
1859 doselwakeup(struct selinfo *sip, int pri)
1860 {
1861         struct selfd *sfp;
1862         struct selfd *sfn;
1863         struct seltd *stp;
1864
1865         /* If it's not initialized there can't be any waiters. */
1866         if (sip->si_mtx == NULL)
1867                 return;
1868         /*
1869          * Locking the selinfo locks all selfds associated with it.
1870          */
1871         mtx_lock(sip->si_mtx);
1872         TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1873                 /*
1874                  * Once we remove this sfp from the list and clear the
1875                  * sf_si seltdclear will know to ignore this si.
1876                  */
1877                 TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1878                 stp = sfp->sf_td;
1879                 mtx_lock(&stp->st_mtx);
1880                 stp->st_flags |= SELTD_PENDING;
1881                 cv_broadcastpri(&stp->st_wait, pri);
1882                 mtx_unlock(&stp->st_mtx);
1883                 /*
1884                  * Paired with selfdfree.
1885                  *
1886                  * Storing this only after the wakeup provides an invariant that
1887                  * stp is not used after selfdfree returns.
1888                  */
1889                 atomic_store_rel_ptr((uintptr_t *)&sfp->sf_si, (uintptr_t)NULL);
1890         }
1891         mtx_unlock(sip->si_mtx);
1892 }
1893
1894 static void
1895 seltdinit(struct thread *td)
1896 {
1897         struct seltd *stp;
1898
1899         stp = td->td_sel;
1900         if (stp != NULL) {
1901                 MPASS(stp->st_flags == 0);
1902                 MPASS(STAILQ_EMPTY(&stp->st_selq));
1903                 return;
1904         }
1905         stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1906         mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1907         cv_init(&stp->st_wait, "select");
1908         stp->st_flags = 0;
1909         STAILQ_INIT(&stp->st_selq);
1910         td->td_sel = stp;
1911 }
1912
1913 static int
1914 seltdwait(struct thread *td, sbintime_t sbt, sbintime_t precision)
1915 {
1916         struct seltd *stp;
1917         int error;
1918
1919         stp = td->td_sel;
1920         /*
1921          * An event of interest may occur while we do not hold the seltd
1922          * locked so check the pending flag before we sleep.
1923          */
1924         mtx_lock(&stp->st_mtx);
1925         /*
1926          * Any further calls to selrecord will be a rescan.
1927          */
1928         stp->st_flags |= SELTD_RESCAN;
1929         if (stp->st_flags & SELTD_PENDING) {
1930                 mtx_unlock(&stp->st_mtx);
1931                 return (0);
1932         }
1933         if (sbt == 0)
1934                 error = EWOULDBLOCK;
1935         else if (sbt != -1)
1936                 error = cv_timedwait_sig_sbt(&stp->st_wait, &stp->st_mtx,
1937                     sbt, precision, C_ABSOLUTE);
1938         else
1939                 error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1940         mtx_unlock(&stp->st_mtx);
1941
1942         return (error);
1943 }
1944
1945 void
1946 seltdfini(struct thread *td)
1947 {
1948         struct seltd *stp;
1949
1950         stp = td->td_sel;
1951         if (stp == NULL)
1952                 return;
1953         MPASS(stp->st_flags == 0);
1954         MPASS(STAILQ_EMPTY(&stp->st_selq));
1955         if (stp->st_free1)
1956                 free(stp->st_free1, M_SELFD);
1957         if (stp->st_free2)
1958                 free(stp->st_free2, M_SELFD);
1959         td->td_sel = NULL;
1960         cv_destroy(&stp->st_wait);
1961         mtx_destroy(&stp->st_mtx);
1962         free(stp, M_SELECT);
1963 }
1964
1965 /*
1966  * Remove the references to the thread from all of the objects we were
1967  * polling.
1968  */
1969 static void
1970 seltdclear(struct thread *td)
1971 {
1972         struct seltd *stp;
1973         struct selfd *sfp;
1974         struct selfd *sfn;
1975
1976         stp = td->td_sel;
1977         STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1978                 selfdfree(stp, sfp);
1979         stp->st_flags = 0;
1980 }
1981
1982 static void selectinit(void *);
1983 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1984 static void
1985 selectinit(void *dummy __unused)
1986 {
1987
1988         mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);
1989 }
1990
1991 /*
1992  * Set up a syscall return value that follows the convention specified for
1993  * posix_* functions.
1994  */
1995 int
1996 kern_posix_error(struct thread *td, int error)
1997 {
1998
1999         if (error <= 0)
2000                 return (error);
2001         td->td_errno = error;
2002         td->td_pflags |= TDP_NERRNO;
2003         td->td_retval[0] = error;
2004         return (0);
2005 }