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