xref: /freebsd/sys/kern/sys_generic.c (revision d1b6899e83a28eedca46b95bb090e3e476642166)
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  * 4. 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/capability.h>
48 #include <sys/filedesc.h>
49 #include <sys/filio.h>
50 #include <sys/fcntl.h>
51 #include <sys/file.h>
52 #include <sys/proc.h>
53 #include <sys/signalvar.h>
54 #include <sys/socketvar.h>
55 #include <sys/uio.h>
56 #include <sys/kernel.h>
57 #include <sys/ktr.h>
58 #include <sys/limits.h>
59 #include <sys/malloc.h>
60 #include <sys/poll.h>
61 #include <sys/resourcevar.h>
62 #include <sys/selinfo.h>
63 #include <sys/sleepqueue.h>
64 #include <sys/syscallsubr.h>
65 #include <sys/sysctl.h>
66 #include <sys/sysent.h>
67 #include <sys/vnode.h>
68 #include <sys/bio.h>
69 #include <sys/buf.h>
70 #include <sys/condvar.h>
71 #ifdef KTRACE
72 #include <sys/ktrace.h>
73 #endif
74 
75 #include <security/audit/audit.h>
76 
77 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
78 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
79 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
80 
81 static int	pollout(struct thread *, struct pollfd *, struct pollfd *,
82 		    u_int);
83 static int	pollscan(struct thread *, struct pollfd *, u_int);
84 static int	pollrescan(struct thread *);
85 static int	selscan(struct thread *, fd_mask **, fd_mask **, int);
86 static int	selrescan(struct thread *, fd_mask **, fd_mask **);
87 static void	selfdalloc(struct thread *, void *);
88 static void	selfdfree(struct seltd *, struct selfd *);
89 static int	dofileread(struct thread *, int, struct file *, struct uio *,
90 		    off_t, int);
91 static int	dofilewrite(struct thread *, int, struct file *, struct uio *,
92 		    off_t, int);
93 static void	doselwakeup(struct selinfo *, int);
94 static void	seltdinit(struct thread *);
95 static int	seltdwait(struct thread *, int);
96 static void	seltdclear(struct thread *);
97 
98 /*
99  * One seltd per-thread allocated on demand as needed.
100  *
101  *	t - protected by st_mtx
102  * 	k - Only accessed by curthread or read-only
103  */
104 struct seltd {
105 	STAILQ_HEAD(, selfd)	st_selq;	/* (k) List of selfds. */
106 	struct selfd		*st_free1;	/* (k) free fd for read set. */
107 	struct selfd		*st_free2;	/* (k) free fd for write set. */
108 	struct mtx		st_mtx;		/* Protects struct seltd */
109 	struct cv		st_wait;	/* (t) Wait channel. */
110 	int			st_flags;	/* (t) SELTD_ flags. */
111 };
112 
113 #define	SELTD_PENDING	0x0001			/* We have pending events. */
114 #define	SELTD_RESCAN	0x0002			/* Doing a rescan. */
115 
116 /*
117  * One selfd allocated per-thread per-file-descriptor.
118  *	f - protected by sf_mtx
119  */
120 struct selfd {
121 	STAILQ_ENTRY(selfd)	sf_link;	/* (k) fds owned by this td. */
122 	TAILQ_ENTRY(selfd)	sf_threads;	/* (f) fds on this selinfo. */
123 	struct selinfo		*sf_si;		/* (f) selinfo when linked. */
124 	struct mtx		*sf_mtx;	/* Pointer to selinfo mtx. */
125 	struct seltd		*sf_td;		/* (k) owning seltd. */
126 	void			*sf_cookie;	/* (k) fd or pollfd. */
127 };
128 
129 static uma_zone_t selfd_zone;
130 static struct mtx_pool *mtxpool_select;
131 
132 #ifndef _SYS_SYSPROTO_H_
133 struct read_args {
134 	int	fd;
135 	void	*buf;
136 	size_t	nbyte;
137 };
138 #endif
139 int
140 read(td, uap)
141 	struct thread *td;
142 	struct read_args *uap;
143 {
144 	struct uio auio;
145 	struct iovec aiov;
146 	int error;
147 
148 	if (uap->nbyte > INT_MAX)
149 		return (EINVAL);
150 	aiov.iov_base = uap->buf;
151 	aiov.iov_len = uap->nbyte;
152 	auio.uio_iov = &aiov;
153 	auio.uio_iovcnt = 1;
154 	auio.uio_resid = uap->nbyte;
155 	auio.uio_segflg = UIO_USERSPACE;
156 	error = kern_readv(td, uap->fd, &auio);
157 	return(error);
158 }
159 
160 /*
161  * Positioned read system call
162  */
163 #ifndef _SYS_SYSPROTO_H_
164 struct pread_args {
165 	int	fd;
166 	void	*buf;
167 	size_t	nbyte;
168 	int	pad;
169 	off_t	offset;
170 };
171 #endif
172 int
173 pread(td, uap)
174 	struct thread *td;
175 	struct pread_args *uap;
176 {
177 	struct uio auio;
178 	struct iovec aiov;
179 	int error;
180 
181 	if (uap->nbyte > INT_MAX)
182 		return (EINVAL);
183 	aiov.iov_base = uap->buf;
184 	aiov.iov_len = uap->nbyte;
185 	auio.uio_iov = &aiov;
186 	auio.uio_iovcnt = 1;
187 	auio.uio_resid = uap->nbyte;
188 	auio.uio_segflg = UIO_USERSPACE;
189 	error = kern_preadv(td, uap->fd, &auio, uap->offset);
190 	return(error);
191 }
192 
193 int
194 freebsd6_pread(td, uap)
195 	struct thread *td;
196 	struct freebsd6_pread_args *uap;
197 {
198 	struct pread_args oargs;
199 
200 	oargs.fd = uap->fd;
201 	oargs.buf = uap->buf;
202 	oargs.nbyte = uap->nbyte;
203 	oargs.offset = uap->offset;
204 	return (pread(td, &oargs));
205 }
206 
207 /*
208  * Scatter read system call.
209  */
210 #ifndef _SYS_SYSPROTO_H_
211 struct readv_args {
212 	int	fd;
213 	struct	iovec *iovp;
214 	u_int	iovcnt;
215 };
216 #endif
217 int
218 readv(struct thread *td, struct readv_args *uap)
219 {
220 	struct uio *auio;
221 	int error;
222 
223 	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
224 	if (error)
225 		return (error);
226 	error = kern_readv(td, uap->fd, auio);
227 	free(auio, M_IOV);
228 	return (error);
229 }
230 
231 int
232 kern_readv(struct thread *td, int fd, struct uio *auio)
233 {
234 	struct file *fp;
235 	int error;
236 
237 	error = fget_read(td, fd, CAP_READ | CAP_SEEK, &fp);
238 	if (error)
239 		return (error);
240 	error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
241 	fdrop(fp, td);
242 	return (error);
243 }
244 
245 /*
246  * Scatter positioned read system call.
247  */
248 #ifndef _SYS_SYSPROTO_H_
249 struct preadv_args {
250 	int	fd;
251 	struct	iovec *iovp;
252 	u_int	iovcnt;
253 	off_t	offset;
254 };
255 #endif
256 int
257 preadv(struct thread *td, struct preadv_args *uap)
258 {
259 	struct uio *auio;
260 	int error;
261 
262 	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
263 	if (error)
264 		return (error);
265 	error = kern_preadv(td, uap->fd, auio, uap->offset);
266 	free(auio, M_IOV);
267 	return (error);
268 }
269 
270 int
271 kern_preadv(td, fd, auio, offset)
272 	struct thread *td;
273 	int fd;
274 	struct uio *auio;
275 	off_t offset;
276 {
277 	struct file *fp;
278 	int error;
279 
280 	error = fget_read(td, fd, CAP_READ, &fp);
281 	if (error)
282 		return (error);
283 	if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
284 		error = ESPIPE;
285 	else if (offset < 0 && fp->f_vnode->v_type != VCHR)
286 		error = EINVAL;
287 	else
288 		error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
289 	fdrop(fp, td);
290 	return (error);
291 }
292 
293 /*
294  * Common code for readv and preadv that reads data in
295  * from a file using the passed in uio, offset, and flags.
296  */
297 static int
298 dofileread(td, fd, fp, auio, offset, flags)
299 	struct thread *td;
300 	int fd;
301 	struct file *fp;
302 	struct uio *auio;
303 	off_t offset;
304 	int flags;
305 {
306 	ssize_t cnt;
307 	int error;
308 #ifdef KTRACE
309 	struct uio *ktruio = NULL;
310 #endif
311 
312 	/* Finish zero length reads right here */
313 	if (auio->uio_resid == 0) {
314 		td->td_retval[0] = 0;
315 		return(0);
316 	}
317 	auio->uio_rw = UIO_READ;
318 	auio->uio_offset = offset;
319 	auio->uio_td = td;
320 #ifdef KTRACE
321 	if (KTRPOINT(td, KTR_GENIO))
322 		ktruio = cloneuio(auio);
323 #endif
324 	cnt = auio->uio_resid;
325 	if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
326 		if (auio->uio_resid != cnt && (error == ERESTART ||
327 		    error == EINTR || error == EWOULDBLOCK))
328 			error = 0;
329 	}
330 	cnt -= auio->uio_resid;
331 #ifdef KTRACE
332 	if (ktruio != NULL) {
333 		ktruio->uio_resid = cnt;
334 		ktrgenio(fd, UIO_READ, ktruio, error);
335 	}
336 #endif
337 	td->td_retval[0] = cnt;
338 	return (error);
339 }
340 
341 #ifndef _SYS_SYSPROTO_H_
342 struct write_args {
343 	int	fd;
344 	const void *buf;
345 	size_t	nbyte;
346 };
347 #endif
348 int
349 write(td, uap)
350 	struct thread *td;
351 	struct write_args *uap;
352 {
353 	struct uio auio;
354 	struct iovec aiov;
355 	int error;
356 
357 	if (uap->nbyte > INT_MAX)
358 		return (EINVAL);
359 	aiov.iov_base = (void *)(uintptr_t)uap->buf;
360 	aiov.iov_len = uap->nbyte;
361 	auio.uio_iov = &aiov;
362 	auio.uio_iovcnt = 1;
363 	auio.uio_resid = uap->nbyte;
364 	auio.uio_segflg = UIO_USERSPACE;
365 	error = kern_writev(td, uap->fd, &auio);
366 	return(error);
367 }
368 
369 /*
370  * Positioned write system call.
371  */
372 #ifndef _SYS_SYSPROTO_H_
373 struct pwrite_args {
374 	int	fd;
375 	const void *buf;
376 	size_t	nbyte;
377 	int	pad;
378 	off_t	offset;
379 };
380 #endif
381 int
382 pwrite(td, uap)
383 	struct thread *td;
384 	struct pwrite_args *uap;
385 {
386 	struct uio auio;
387 	struct iovec aiov;
388 	int error;
389 
390 	if (uap->nbyte > INT_MAX)
391 		return (EINVAL);
392 	aiov.iov_base = (void *)(uintptr_t)uap->buf;
393 	aiov.iov_len = uap->nbyte;
394 	auio.uio_iov = &aiov;
395 	auio.uio_iovcnt = 1;
396 	auio.uio_resid = uap->nbyte;
397 	auio.uio_segflg = UIO_USERSPACE;
398 	error = kern_pwritev(td, uap->fd, &auio, uap->offset);
399 	return(error);
400 }
401 
402 int
403 freebsd6_pwrite(td, uap)
404 	struct thread *td;
405 	struct freebsd6_pwrite_args *uap;
406 {
407 	struct pwrite_args oargs;
408 
409 	oargs.fd = uap->fd;
410 	oargs.buf = uap->buf;
411 	oargs.nbyte = uap->nbyte;
412 	oargs.offset = uap->offset;
413 	return (pwrite(td, &oargs));
414 }
415 
416 /*
417  * Gather write system call.
418  */
419 #ifndef _SYS_SYSPROTO_H_
420 struct writev_args {
421 	int	fd;
422 	struct	iovec *iovp;
423 	u_int	iovcnt;
424 };
425 #endif
426 int
427 writev(struct thread *td, struct writev_args *uap)
428 {
429 	struct uio *auio;
430 	int error;
431 
432 	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
433 	if (error)
434 		return (error);
435 	error = kern_writev(td, uap->fd, auio);
436 	free(auio, M_IOV);
437 	return (error);
438 }
439 
440 int
441 kern_writev(struct thread *td, int fd, struct uio *auio)
442 {
443 	struct file *fp;
444 	int error;
445 
446 	error = fget_write(td, fd, CAP_WRITE | CAP_SEEK, &fp);
447 	if (error)
448 		return (error);
449 	error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
450 	fdrop(fp, td);
451 	return (error);
452 }
453 
454 /*
455  * Gather positioned write system call.
456  */
457 #ifndef _SYS_SYSPROTO_H_
458 struct pwritev_args {
459 	int	fd;
460 	struct	iovec *iovp;
461 	u_int	iovcnt;
462 	off_t	offset;
463 };
464 #endif
465 int
466 pwritev(struct thread *td, struct pwritev_args *uap)
467 {
468 	struct uio *auio;
469 	int error;
470 
471 	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
472 	if (error)
473 		return (error);
474 	error = kern_pwritev(td, uap->fd, auio, uap->offset);
475 	free(auio, M_IOV);
476 	return (error);
477 }
478 
479 int
480 kern_pwritev(td, fd, auio, offset)
481 	struct thread *td;
482 	struct uio *auio;
483 	int fd;
484 	off_t offset;
485 {
486 	struct file *fp;
487 	int error;
488 
489 	error = fget_write(td, fd, CAP_WRITE, &fp);
490 	if (error)
491 		return (error);
492 	if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
493 		error = ESPIPE;
494 	else if (offset < 0 && fp->f_vnode->v_type != VCHR)
495 		error = EINVAL;
496 	else
497 		error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
498 	fdrop(fp, td);
499 	return (error);
500 }
501 
502 /*
503  * Common code for writev and pwritev that writes data to
504  * a file using the passed in uio, offset, and flags.
505  */
506 static int
507 dofilewrite(td, fd, fp, auio, offset, flags)
508 	struct thread *td;
509 	int fd;
510 	struct file *fp;
511 	struct uio *auio;
512 	off_t offset;
513 	int flags;
514 {
515 	ssize_t cnt;
516 	int error;
517 #ifdef KTRACE
518 	struct uio *ktruio = NULL;
519 #endif
520 
521 	auio->uio_rw = UIO_WRITE;
522 	auio->uio_td = td;
523 	auio->uio_offset = offset;
524 #ifdef KTRACE
525 	if (KTRPOINT(td, KTR_GENIO))
526 		ktruio = cloneuio(auio);
527 #endif
528 	cnt = auio->uio_resid;
529 	if (fp->f_type == DTYPE_VNODE)
530 		bwillwrite();
531 	if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
532 		if (auio->uio_resid != cnt && (error == ERESTART ||
533 		    error == EINTR || error == EWOULDBLOCK))
534 			error = 0;
535 		/* Socket layer is responsible for issuing SIGPIPE. */
536 		if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
537 			PROC_LOCK(td->td_proc);
538 			tdsignal(td, SIGPIPE);
539 			PROC_UNLOCK(td->td_proc);
540 		}
541 	}
542 	cnt -= auio->uio_resid;
543 #ifdef KTRACE
544 	if (ktruio != NULL) {
545 		ktruio->uio_resid = cnt;
546 		ktrgenio(fd, UIO_WRITE, ktruio, error);
547 	}
548 #endif
549 	td->td_retval[0] = cnt;
550 	return (error);
551 }
552 
553 /*
554  * Truncate a file given a file descriptor.
555  *
556  * Can't use fget_write() here, since must return EINVAL and not EBADF if the
557  * descriptor isn't writable.
558  */
559 int
560 kern_ftruncate(td, fd, length)
561 	struct thread *td;
562 	int fd;
563 	off_t length;
564 {
565 	struct file *fp;
566 	int error;
567 
568 	AUDIT_ARG_FD(fd);
569 	if (length < 0)
570 		return (EINVAL);
571 	error = fget(td, fd, CAP_FTRUNCATE, &fp);
572 	if (error)
573 		return (error);
574 	AUDIT_ARG_FILE(td->td_proc, fp);
575 	if (!(fp->f_flag & FWRITE)) {
576 		fdrop(fp, td);
577 		return (EINVAL);
578 	}
579 	error = fo_truncate(fp, length, td->td_ucred, td);
580 	fdrop(fp, td);
581 	return (error);
582 }
583 
584 #ifndef _SYS_SYSPROTO_H_
585 struct ftruncate_args {
586 	int	fd;
587 	int	pad;
588 	off_t	length;
589 };
590 #endif
591 int
592 ftruncate(td, uap)
593 	struct thread *td;
594 	struct ftruncate_args *uap;
595 {
596 
597 	return (kern_ftruncate(td, uap->fd, uap->length));
598 }
599 
600 #if defined(COMPAT_43)
601 #ifndef _SYS_SYSPROTO_H_
602 struct oftruncate_args {
603 	int	fd;
604 	long	length;
605 };
606 #endif
607 int
608 oftruncate(td, uap)
609 	struct thread *td;
610 	struct oftruncate_args *uap;
611 {
612 
613 	return (kern_ftruncate(td, uap->fd, uap->length));
614 }
615 #endif /* COMPAT_43 */
616 
617 #ifndef _SYS_SYSPROTO_H_
618 struct ioctl_args {
619 	int	fd;
620 	u_long	com;
621 	caddr_t	data;
622 };
623 #endif
624 /* ARGSUSED */
625 int
626 ioctl(struct thread *td, struct ioctl_args *uap)
627 {
628 	u_long com;
629 	int arg, error;
630 	u_int size;
631 	caddr_t data;
632 
633 	if (uap->com > 0xffffffff) {
634 		printf(
635 		    "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
636 		    td->td_proc->p_pid, td->td_name, uap->com);
637 		uap->com &= 0xffffffff;
638 	}
639 	com = uap->com;
640 
641 	/*
642 	 * Interpret high order word to find amount of data to be
643 	 * copied to/from the user's address space.
644 	 */
645 	size = IOCPARM_LEN(com);
646 	if ((size > IOCPARM_MAX) ||
647 	    ((com & (IOC_VOID  | IOC_IN | IOC_OUT)) == 0) ||
648 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
649 	    ((com & IOC_OUT) && size == 0) ||
650 #else
651 	    ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
652 #endif
653 	    ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
654 		return (ENOTTY);
655 
656 	if (size > 0) {
657 		if (com & IOC_VOID) {
658 			/* Integer argument. */
659 			arg = (intptr_t)uap->data;
660 			data = (void *)&arg;
661 			size = 0;
662 		} else
663 			data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
664 	} else
665 		data = (void *)&uap->data;
666 	if (com & IOC_IN) {
667 		error = copyin(uap->data, data, (u_int)size);
668 		if (error) {
669 			if (size > 0)
670 				free(data, M_IOCTLOPS);
671 			return (error);
672 		}
673 	} else if (com & IOC_OUT) {
674 		/*
675 		 * Zero the buffer so the user always
676 		 * gets back something deterministic.
677 		 */
678 		bzero(data, size);
679 	}
680 
681 	error = kern_ioctl(td, uap->fd, com, data);
682 
683 	if (error == 0 && (com & IOC_OUT))
684 		error = copyout(data, uap->data, (u_int)size);
685 
686 	if (size > 0)
687 		free(data, M_IOCTLOPS);
688 	return (error);
689 }
690 
691 int
692 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
693 {
694 	struct file *fp;
695 	struct filedesc *fdp;
696 	int error;
697 	int tmp;
698 
699 	AUDIT_ARG_FD(fd);
700 	AUDIT_ARG_CMD(com);
701 	if ((error = fget(td, fd, CAP_IOCTL, &fp)) != 0)
702 		return (error);
703 	if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
704 		fdrop(fp, td);
705 		return (EBADF);
706 	}
707 	fdp = td->td_proc->p_fd;
708 	switch (com) {
709 	case FIONCLEX:
710 		FILEDESC_XLOCK(fdp);
711 		fdp->fd_ofileflags[fd] &= ~UF_EXCLOSE;
712 		FILEDESC_XUNLOCK(fdp);
713 		goto out;
714 	case FIOCLEX:
715 		FILEDESC_XLOCK(fdp);
716 		fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
717 		FILEDESC_XUNLOCK(fdp);
718 		goto out;
719 	case FIONBIO:
720 		if ((tmp = *(int *)data))
721 			atomic_set_int(&fp->f_flag, FNONBLOCK);
722 		else
723 			atomic_clear_int(&fp->f_flag, FNONBLOCK);
724 		data = (void *)&tmp;
725 		break;
726 	case FIOASYNC:
727 		if ((tmp = *(int *)data))
728 			atomic_set_int(&fp->f_flag, FASYNC);
729 		else
730 			atomic_clear_int(&fp->f_flag, FASYNC);
731 		data = (void *)&tmp;
732 		break;
733 	}
734 
735 	error = fo_ioctl(fp, com, data, td->td_ucred, td);
736 out:
737 	fdrop(fp, td);
738 	return (error);
739 }
740 
741 int
742 poll_no_poll(int events)
743 {
744 	/*
745 	 * Return true for read/write.  If the user asked for something
746 	 * special, return POLLNVAL, so that clients have a way of
747 	 * determining reliably whether or not the extended
748 	 * functionality is present without hard-coding knowledge
749 	 * of specific filesystem implementations.
750 	 */
751 	if (events & ~POLLSTANDARD)
752 		return (POLLNVAL);
753 
754 	return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
755 }
756 
757 int
758 pselect(struct thread *td, struct pselect_args *uap)
759 {
760 	struct timespec ts;
761 	struct timeval tv, *tvp;
762 	sigset_t set, *uset;
763 	int error;
764 
765 	if (uap->ts != NULL) {
766 		error = copyin(uap->ts, &ts, sizeof(ts));
767 		if (error != 0)
768 		    return (error);
769 		TIMESPEC_TO_TIMEVAL(&tv, &ts);
770 		tvp = &tv;
771 	} else
772 		tvp = NULL;
773 	if (uap->sm != NULL) {
774 		error = copyin(uap->sm, &set, sizeof(set));
775 		if (error != 0)
776 			return (error);
777 		uset = &set;
778 	} else
779 		uset = NULL;
780 	return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
781 	    uset, NFDBITS));
782 }
783 
784 int
785 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
786     struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
787 {
788 	int error;
789 
790 	if (uset != NULL) {
791 		error = kern_sigprocmask(td, SIG_SETMASK, uset,
792 		    &td->td_oldsigmask, 0);
793 		if (error != 0)
794 			return (error);
795 		td->td_pflags |= TDP_OLDMASK;
796 		/*
797 		 * Make sure that ast() is called on return to
798 		 * usermode and TDP_OLDMASK is cleared, restoring old
799 		 * sigmask.
800 		 */
801 		thread_lock(td);
802 		td->td_flags |= TDF_ASTPENDING;
803 		thread_unlock(td);
804 	}
805 	error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
806 	return (error);
807 }
808 
809 #ifndef _SYS_SYSPROTO_H_
810 struct select_args {
811 	int	nd;
812 	fd_set	*in, *ou, *ex;
813 	struct	timeval *tv;
814 };
815 #endif
816 int
817 select(struct thread *td, struct select_args *uap)
818 {
819 	struct timeval tv, *tvp;
820 	int error;
821 
822 	if (uap->tv != NULL) {
823 		error = copyin(uap->tv, &tv, sizeof(tv));
824 		if (error)
825 			return (error);
826 		tvp = &tv;
827 	} else
828 		tvp = NULL;
829 
830 	return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
831 	    NFDBITS));
832 }
833 
834 int
835 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
836     fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
837 {
838 	struct filedesc *fdp;
839 	/*
840 	 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
841 	 * infds with the new FD_SETSIZE of 1024, and more than enough for
842 	 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
843 	 * of 256.
844 	 */
845 	fd_mask s_selbits[howmany(2048, NFDBITS)];
846 	fd_mask *ibits[3], *obits[3], *selbits, *sbp;
847 	struct timeval atv, rtv, ttv;
848 	int error, timo;
849 	u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
850 
851 	if (nd < 0)
852 		return (EINVAL);
853 	fdp = td->td_proc->p_fd;
854 	if (nd > fdp->fd_lastfile + 1)
855 		nd = fdp->fd_lastfile + 1;
856 
857 	/*
858 	 * Allocate just enough bits for the non-null fd_sets.  Use the
859 	 * preallocated auto buffer if possible.
860 	 */
861 	nfdbits = roundup(nd, NFDBITS);
862 	ncpbytes = nfdbits / NBBY;
863 	ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
864 	nbufbytes = 0;
865 	if (fd_in != NULL)
866 		nbufbytes += 2 * ncpbytes;
867 	if (fd_ou != NULL)
868 		nbufbytes += 2 * ncpbytes;
869 	if (fd_ex != NULL)
870 		nbufbytes += 2 * ncpbytes;
871 	if (nbufbytes <= sizeof s_selbits)
872 		selbits = &s_selbits[0];
873 	else
874 		selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
875 
876 	/*
877 	 * Assign pointers into the bit buffers and fetch the input bits.
878 	 * Put the output buffers together so that they can be bzeroed
879 	 * together.
880 	 */
881 	sbp = selbits;
882 #define	getbits(name, x) \
883 	do {								\
884 		if (name == NULL) {					\
885 			ibits[x] = NULL;				\
886 			obits[x] = NULL;				\
887 		} else {						\
888 			ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp;	\
889 			obits[x] = sbp;					\
890 			sbp += ncpbytes / sizeof *sbp;			\
891 			error = copyin(name, ibits[x], ncpubytes);	\
892 			if (error != 0)					\
893 				goto done;				\
894 			bzero((char *)ibits[x] + ncpubytes,		\
895 			    ncpbytes - ncpubytes);			\
896 		}							\
897 	} while (0)
898 	getbits(fd_in, 0);
899 	getbits(fd_ou, 1);
900 	getbits(fd_ex, 2);
901 #undef	getbits
902 
903 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
904 	/*
905 	 * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
906 	 * we are running under 32-bit emulation. This should be more
907 	 * generic.
908 	 */
909 #define swizzle_fdset(bits)						\
910 	if (abi_nfdbits != NFDBITS && bits != NULL) {			\
911 		int i;							\
912 		for (i = 0; i < ncpbytes / sizeof *sbp; i++)		\
913 			bits[i] = (bits[i] >> 32) | (bits[i] << 32);	\
914 	}
915 #else
916 #define swizzle_fdset(bits)
917 #endif
918 
919 	/* Make sure the bit order makes it through an ABI transition */
920 	swizzle_fdset(ibits[0]);
921 	swizzle_fdset(ibits[1]);
922 	swizzle_fdset(ibits[2]);
923 
924 	if (nbufbytes != 0)
925 		bzero(selbits, nbufbytes / 2);
926 
927 	if (tvp != NULL) {
928 		atv = *tvp;
929 		if (itimerfix(&atv)) {
930 			error = EINVAL;
931 			goto done;
932 		}
933 		getmicrouptime(&rtv);
934 		timevaladd(&atv, &rtv);
935 	} else {
936 		atv.tv_sec = 0;
937 		atv.tv_usec = 0;
938 	}
939 	timo = 0;
940 	seltdinit(td);
941 	/* Iterate until the timeout expires or descriptors become ready. */
942 	for (;;) {
943 		error = selscan(td, ibits, obits, nd);
944 		if (error || td->td_retval[0] != 0)
945 			break;
946 		if (atv.tv_sec || atv.tv_usec) {
947 			getmicrouptime(&rtv);
948 			if (timevalcmp(&rtv, &atv, >=))
949 				break;
950 			ttv = atv;
951 			timevalsub(&ttv, &rtv);
952 			timo = ttv.tv_sec > 24 * 60 * 60 ?
953 			    24 * 60 * 60 * hz : tvtohz(&ttv);
954 		}
955 		error = seltdwait(td, timo);
956 		if (error)
957 			break;
958 		error = selrescan(td, ibits, obits);
959 		if (error || td->td_retval[0] != 0)
960 			break;
961 	}
962 	seltdclear(td);
963 
964 done:
965 	/* select is not restarted after signals... */
966 	if (error == ERESTART)
967 		error = EINTR;
968 	if (error == EWOULDBLOCK)
969 		error = 0;
970 
971 	/* swizzle bit order back, if necessary */
972 	swizzle_fdset(obits[0]);
973 	swizzle_fdset(obits[1]);
974 	swizzle_fdset(obits[2]);
975 #undef swizzle_fdset
976 
977 #define	putbits(name, x) \
978 	if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
979 		error = error2;
980 	if (error == 0) {
981 		int error2;
982 
983 		putbits(fd_in, 0);
984 		putbits(fd_ou, 1);
985 		putbits(fd_ex, 2);
986 #undef putbits
987 	}
988 	if (selbits != &s_selbits[0])
989 		free(selbits, M_SELECT);
990 
991 	return (error);
992 }
993 /*
994  * Convert a select bit set to poll flags.
995  *
996  * The backend always returns POLLHUP/POLLERR if appropriate and we
997  * return this as a set bit in any set.
998  */
999 static int select_flags[3] = {
1000     POLLRDNORM | POLLHUP | POLLERR,
1001     POLLWRNORM | POLLHUP | POLLERR,
1002     POLLRDBAND | POLLERR
1003 };
1004 
1005 /*
1006  * Compute the fo_poll flags required for a fd given by the index and
1007  * bit position in the fd_mask array.
1008  */
1009 static __inline int
1010 selflags(fd_mask **ibits, int idx, fd_mask bit)
1011 {
1012 	int flags;
1013 	int msk;
1014 
1015 	flags = 0;
1016 	for (msk = 0; msk < 3; msk++) {
1017 		if (ibits[msk] == NULL)
1018 			continue;
1019 		if ((ibits[msk][idx] & bit) == 0)
1020 			continue;
1021 		flags |= select_flags[msk];
1022 	}
1023 	return (flags);
1024 }
1025 
1026 /*
1027  * Set the appropriate output bits given a mask of fired events and the
1028  * input bits originally requested.
1029  */
1030 static __inline int
1031 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1032 {
1033 	int msk;
1034 	int n;
1035 
1036 	n = 0;
1037 	for (msk = 0; msk < 3; msk++) {
1038 		if ((events & select_flags[msk]) == 0)
1039 			continue;
1040 		if (ibits[msk] == NULL)
1041 			continue;
1042 		if ((ibits[msk][idx] & bit) == 0)
1043 			continue;
1044 		/*
1045 		 * XXX Check for a duplicate set.  This can occur because a
1046 		 * socket calls selrecord() twice for each poll() call
1047 		 * resulting in two selfds per real fd.  selrescan() will
1048 		 * call selsetbits twice as a result.
1049 		 */
1050 		if ((obits[msk][idx] & bit) != 0)
1051 			continue;
1052 		obits[msk][idx] |= bit;
1053 		n++;
1054 	}
1055 
1056 	return (n);
1057 }
1058 
1059 static __inline int
1060 getselfd_cap(struct filedesc *fdp, int fd, struct file **fpp)
1061 {
1062 	struct file *fp;
1063 #ifdef CAPABILITIES
1064 	struct file *fp_fromcap;
1065 	int error;
1066 #endif
1067 
1068 	if ((fp = fget_unlocked(fdp, fd)) == NULL)
1069 		return (EBADF);
1070 #ifdef CAPABILITIES
1071 	/*
1072 	 * If the file descriptor is for a capability, test rights and use
1073 	 * the file descriptor references by the capability.
1074 	 */
1075 	error = cap_funwrap(fp, CAP_POLL_EVENT, &fp_fromcap);
1076 	if (error) {
1077 		fdrop(fp, curthread);
1078 		return (error);
1079 	}
1080 	if (fp != fp_fromcap) {
1081 		fhold(fp_fromcap);
1082 		fdrop(fp, curthread);
1083 		fp = fp_fromcap;
1084 	}
1085 #endif /* CAPABILITIES */
1086 	*fpp = fp;
1087 	return (0);
1088 }
1089 
1090 /*
1091  * Traverse the list of fds attached to this thread's seltd and check for
1092  * completion.
1093  */
1094 static int
1095 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1096 {
1097 	struct filedesc *fdp;
1098 	struct selinfo *si;
1099 	struct seltd *stp;
1100 	struct selfd *sfp;
1101 	struct selfd *sfn;
1102 	struct file *fp;
1103 	fd_mask bit;
1104 	int fd, ev, n, idx;
1105 	int error;
1106 
1107 	fdp = td->td_proc->p_fd;
1108 	stp = td->td_sel;
1109 	n = 0;
1110 	STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1111 		fd = (int)(uintptr_t)sfp->sf_cookie;
1112 		si = sfp->sf_si;
1113 		selfdfree(stp, sfp);
1114 		/* If the selinfo wasn't cleared the event didn't fire. */
1115 		if (si != NULL)
1116 			continue;
1117 		error = getselfd_cap(fdp, fd, &fp);
1118 		if (error)
1119 			return (error);
1120 		idx = fd / NFDBITS;
1121 		bit = (fd_mask)1 << (fd % NFDBITS);
1122 		ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1123 		fdrop(fp, td);
1124 		if (ev != 0)
1125 			n += selsetbits(ibits, obits, idx, bit, ev);
1126 	}
1127 	stp->st_flags = 0;
1128 	td->td_retval[0] = n;
1129 	return (0);
1130 }
1131 
1132 /*
1133  * Perform the initial filedescriptor scan and register ourselves with
1134  * each selinfo.
1135  */
1136 static int
1137 selscan(td, ibits, obits, nfd)
1138 	struct thread *td;
1139 	fd_mask **ibits, **obits;
1140 	int nfd;
1141 {
1142 	struct filedesc *fdp;
1143 	struct file *fp;
1144 	fd_mask bit;
1145 	int ev, flags, end, fd;
1146 	int n, idx;
1147 	int error;
1148 
1149 	fdp = td->td_proc->p_fd;
1150 	n = 0;
1151 	for (idx = 0, fd = 0; fd < nfd; idx++) {
1152 		end = imin(fd + NFDBITS, nfd);
1153 		for (bit = 1; fd < end; bit <<= 1, fd++) {
1154 			/* Compute the list of events we're interested in. */
1155 			flags = selflags(ibits, idx, bit);
1156 			if (flags == 0)
1157 				continue;
1158 			error = getselfd_cap(fdp, fd, &fp);
1159 			if (error)
1160 				return (error);
1161 			selfdalloc(td, (void *)(uintptr_t)fd);
1162 			ev = fo_poll(fp, flags, td->td_ucred, td);
1163 			fdrop(fp, td);
1164 			if (ev != 0)
1165 				n += selsetbits(ibits, obits, idx, bit, ev);
1166 		}
1167 	}
1168 
1169 	td->td_retval[0] = n;
1170 	return (0);
1171 }
1172 
1173 #ifndef _SYS_SYSPROTO_H_
1174 struct poll_args {
1175 	struct pollfd *fds;
1176 	u_int	nfds;
1177 	int	timeout;
1178 };
1179 #endif
1180 int
1181 poll(td, uap)
1182 	struct thread *td;
1183 	struct poll_args *uap;
1184 {
1185 	struct pollfd *bits;
1186 	struct pollfd smallbits[32];
1187 	struct timeval atv, rtv, ttv;
1188 	int error = 0, timo;
1189 	u_int nfds;
1190 	size_t ni;
1191 
1192 	nfds = uap->nfds;
1193 	if (nfds > maxfilesperproc && nfds > FD_SETSIZE)
1194 		return (EINVAL);
1195 	ni = nfds * sizeof(struct pollfd);
1196 	if (ni > sizeof(smallbits))
1197 		bits = malloc(ni, M_TEMP, M_WAITOK);
1198 	else
1199 		bits = smallbits;
1200 	error = copyin(uap->fds, bits, ni);
1201 	if (error)
1202 		goto done;
1203 	if (uap->timeout != INFTIM) {
1204 		atv.tv_sec = uap->timeout / 1000;
1205 		atv.tv_usec = (uap->timeout % 1000) * 1000;
1206 		if (itimerfix(&atv)) {
1207 			error = EINVAL;
1208 			goto done;
1209 		}
1210 		getmicrouptime(&rtv);
1211 		timevaladd(&atv, &rtv);
1212 	} else {
1213 		atv.tv_sec = 0;
1214 		atv.tv_usec = 0;
1215 	}
1216 	timo = 0;
1217 	seltdinit(td);
1218 	/* Iterate until the timeout expires or descriptors become ready. */
1219 	for (;;) {
1220 		error = pollscan(td, bits, nfds);
1221 		if (error || td->td_retval[0] != 0)
1222 			break;
1223 		if (atv.tv_sec || atv.tv_usec) {
1224 			getmicrouptime(&rtv);
1225 			if (timevalcmp(&rtv, &atv, >=))
1226 				break;
1227 			ttv = atv;
1228 			timevalsub(&ttv, &rtv);
1229 			timo = ttv.tv_sec > 24 * 60 * 60 ?
1230 			    24 * 60 * 60 * hz : tvtohz(&ttv);
1231 		}
1232 		error = seltdwait(td, timo);
1233 		if (error)
1234 			break;
1235 		error = pollrescan(td);
1236 		if (error || td->td_retval[0] != 0)
1237 			break;
1238 	}
1239 	seltdclear(td);
1240 
1241 done:
1242 	/* poll is not restarted after signals... */
1243 	if (error == ERESTART)
1244 		error = EINTR;
1245 	if (error == EWOULDBLOCK)
1246 		error = 0;
1247 	if (error == 0) {
1248 		error = pollout(td, bits, uap->fds, nfds);
1249 		if (error)
1250 			goto out;
1251 	}
1252 out:
1253 	if (ni > sizeof(smallbits))
1254 		free(bits, M_TEMP);
1255 	return (error);
1256 }
1257 
1258 static int
1259 pollrescan(struct thread *td)
1260 {
1261 	struct seltd *stp;
1262 	struct selfd *sfp;
1263 	struct selfd *sfn;
1264 	struct selinfo *si;
1265 	struct filedesc *fdp;
1266 	struct file *fp;
1267 	struct pollfd *fd;
1268 	int n;
1269 
1270 	n = 0;
1271 	fdp = td->td_proc->p_fd;
1272 	stp = td->td_sel;
1273 	FILEDESC_SLOCK(fdp);
1274 	STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1275 		fd = (struct pollfd *)sfp->sf_cookie;
1276 		si = sfp->sf_si;
1277 		selfdfree(stp, sfp);
1278 		/* If the selinfo wasn't cleared the event didn't fire. */
1279 		if (si != NULL)
1280 			continue;
1281 		fp = fdp->fd_ofiles[fd->fd];
1282 		if (fp == NULL) {
1283 			fd->revents = POLLNVAL;
1284 			n++;
1285 			continue;
1286 		}
1287 		/*
1288 		 * Note: backend also returns POLLHUP and
1289 		 * POLLERR if appropriate.
1290 		 */
1291 		fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1292 		if (fd->revents != 0)
1293 			n++;
1294 	}
1295 	FILEDESC_SUNLOCK(fdp);
1296 	stp->st_flags = 0;
1297 	td->td_retval[0] = n;
1298 	return (0);
1299 }
1300 
1301 
1302 static int
1303 pollout(td, fds, ufds, nfd)
1304 	struct thread *td;
1305 	struct pollfd *fds;
1306 	struct pollfd *ufds;
1307 	u_int nfd;
1308 {
1309 	int error = 0;
1310 	u_int i = 0;
1311 	u_int n = 0;
1312 
1313 	for (i = 0; i < nfd; i++) {
1314 		error = copyout(&fds->revents, &ufds->revents,
1315 		    sizeof(ufds->revents));
1316 		if (error)
1317 			return (error);
1318 		if (fds->revents != 0)
1319 			n++;
1320 		fds++;
1321 		ufds++;
1322 	}
1323 	td->td_retval[0] = n;
1324 	return (0);
1325 }
1326 
1327 static int
1328 pollscan(td, fds, nfd)
1329 	struct thread *td;
1330 	struct pollfd *fds;
1331 	u_int nfd;
1332 {
1333 	struct filedesc *fdp = td->td_proc->p_fd;
1334 	int i;
1335 	struct file *fp;
1336 	int n = 0;
1337 
1338 	FILEDESC_SLOCK(fdp);
1339 	for (i = 0; i < nfd; i++, fds++) {
1340 		if (fds->fd >= fdp->fd_nfiles) {
1341 			fds->revents = POLLNVAL;
1342 			n++;
1343 		} else if (fds->fd < 0) {
1344 			fds->revents = 0;
1345 		} else {
1346 			fp = fdp->fd_ofiles[fds->fd];
1347 			if (fp == NULL) {
1348 				fds->revents = POLLNVAL;
1349 				n++;
1350 			} else {
1351 				/*
1352 				 * Note: backend also returns POLLHUP and
1353 				 * POLLERR if appropriate.
1354 				 */
1355 				selfdalloc(td, fds);
1356 				fds->revents = fo_poll(fp, fds->events,
1357 				    td->td_ucred, td);
1358 				/*
1359 				 * POSIX requires POLLOUT to be never
1360 				 * set simultaneously with POLLHUP.
1361 				 */
1362 				if ((fds->revents & POLLHUP) != 0)
1363 					fds->revents &= ~POLLOUT;
1364 
1365 				if (fds->revents != 0)
1366 					n++;
1367 			}
1368 		}
1369 	}
1370 	FILEDESC_SUNLOCK(fdp);
1371 	td->td_retval[0] = n;
1372 	return (0);
1373 }
1374 
1375 /*
1376  * OpenBSD poll system call.
1377  *
1378  * XXX this isn't quite a true representation..  OpenBSD uses select ops.
1379  */
1380 #ifndef _SYS_SYSPROTO_H_
1381 struct openbsd_poll_args {
1382 	struct pollfd *fds;
1383 	u_int	nfds;
1384 	int	timeout;
1385 };
1386 #endif
1387 int
1388 openbsd_poll(td, uap)
1389 	register struct thread *td;
1390 	register struct openbsd_poll_args *uap;
1391 {
1392 	return (poll(td, (struct poll_args *)uap));
1393 }
1394 
1395 /*
1396  * XXX This was created specifically to support netncp and netsmb.  This
1397  * allows the caller to specify a socket to wait for events on.  It returns
1398  * 0 if any events matched and an error otherwise.  There is no way to
1399  * determine which events fired.
1400  */
1401 int
1402 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1403 {
1404 	struct timeval atv, rtv, ttv;
1405 	int error, timo;
1406 
1407 	if (tvp != NULL) {
1408 		atv = *tvp;
1409 		if (itimerfix(&atv))
1410 			return (EINVAL);
1411 		getmicrouptime(&rtv);
1412 		timevaladd(&atv, &rtv);
1413 	} else {
1414 		atv.tv_sec = 0;
1415 		atv.tv_usec = 0;
1416 	}
1417 
1418 	timo = 0;
1419 	seltdinit(td);
1420 	/*
1421 	 * Iterate until the timeout expires or the socket becomes ready.
1422 	 */
1423 	for (;;) {
1424 		selfdalloc(td, NULL);
1425 		error = sopoll(so, events, NULL, td);
1426 		/* error here is actually the ready events. */
1427 		if (error)
1428 			return (0);
1429 		if (atv.tv_sec || atv.tv_usec) {
1430 			getmicrouptime(&rtv);
1431 			if (timevalcmp(&rtv, &atv, >=)) {
1432 				seltdclear(td);
1433 				return (EWOULDBLOCK);
1434 			}
1435 			ttv = atv;
1436 			timevalsub(&ttv, &rtv);
1437 			timo = ttv.tv_sec > 24 * 60 * 60 ?
1438 			    24 * 60 * 60 * hz : tvtohz(&ttv);
1439 		}
1440 		error = seltdwait(td, timo);
1441 		seltdclear(td);
1442 		if (error)
1443 			break;
1444 	}
1445 	/* XXX Duplicates ncp/smb behavior. */
1446 	if (error == ERESTART)
1447 		error = 0;
1448 	return (error);
1449 }
1450 
1451 /*
1452  * Preallocate two selfds associated with 'cookie'.  Some fo_poll routines
1453  * have two select sets, one for read and another for write.
1454  */
1455 static void
1456 selfdalloc(struct thread *td, void *cookie)
1457 {
1458 	struct seltd *stp;
1459 
1460 	stp = td->td_sel;
1461 	if (stp->st_free1 == NULL)
1462 		stp->st_free1 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1463 	stp->st_free1->sf_td = stp;
1464 	stp->st_free1->sf_cookie = cookie;
1465 	if (stp->st_free2 == NULL)
1466 		stp->st_free2 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1467 	stp->st_free2->sf_td = stp;
1468 	stp->st_free2->sf_cookie = cookie;
1469 }
1470 
1471 static void
1472 selfdfree(struct seltd *stp, struct selfd *sfp)
1473 {
1474 	STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1475 	mtx_lock(sfp->sf_mtx);
1476 	if (sfp->sf_si)
1477 		TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1478 	mtx_unlock(sfp->sf_mtx);
1479 	uma_zfree(selfd_zone, sfp);
1480 }
1481 
1482 /*
1483  * Record a select request.
1484  */
1485 void
1486 selrecord(selector, sip)
1487 	struct thread *selector;
1488 	struct selinfo *sip;
1489 {
1490 	struct selfd *sfp;
1491 	struct seltd *stp;
1492 	struct mtx *mtxp;
1493 
1494 	stp = selector->td_sel;
1495 	/*
1496 	 * Don't record when doing a rescan.
1497 	 */
1498 	if (stp->st_flags & SELTD_RESCAN)
1499 		return;
1500 	/*
1501 	 * Grab one of the preallocated descriptors.
1502 	 */
1503 	sfp = NULL;
1504 	if ((sfp = stp->st_free1) != NULL)
1505 		stp->st_free1 = NULL;
1506 	else if ((sfp = stp->st_free2) != NULL)
1507 		stp->st_free2 = NULL;
1508 	else
1509 		panic("selrecord: No free selfd on selq");
1510 	mtxp = sip->si_mtx;
1511 	if (mtxp == NULL)
1512 		mtxp = mtx_pool_find(mtxpool_select, sip);
1513 	/*
1514 	 * Initialize the sfp and queue it in the thread.
1515 	 */
1516 	sfp->sf_si = sip;
1517 	sfp->sf_mtx = mtxp;
1518 	STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1519 	/*
1520 	 * Now that we've locked the sip, check for initialization.
1521 	 */
1522 	mtx_lock(mtxp);
1523 	if (sip->si_mtx == NULL) {
1524 		sip->si_mtx = mtxp;
1525 		TAILQ_INIT(&sip->si_tdlist);
1526 	}
1527 	/*
1528 	 * Add this thread to the list of selfds listening on this selinfo.
1529 	 */
1530 	TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1531 	mtx_unlock(sip->si_mtx);
1532 }
1533 
1534 /* Wake up a selecting thread. */
1535 void
1536 selwakeup(sip)
1537 	struct selinfo *sip;
1538 {
1539 	doselwakeup(sip, -1);
1540 }
1541 
1542 /* Wake up a selecting thread, and set its priority. */
1543 void
1544 selwakeuppri(sip, pri)
1545 	struct selinfo *sip;
1546 	int pri;
1547 {
1548 	doselwakeup(sip, pri);
1549 }
1550 
1551 /*
1552  * Do a wakeup when a selectable event occurs.
1553  */
1554 static void
1555 doselwakeup(sip, pri)
1556 	struct selinfo *sip;
1557 	int pri;
1558 {
1559 	struct selfd *sfp;
1560 	struct selfd *sfn;
1561 	struct seltd *stp;
1562 
1563 	/* If it's not initialized there can't be any waiters. */
1564 	if (sip->si_mtx == NULL)
1565 		return;
1566 	/*
1567 	 * Locking the selinfo locks all selfds associated with it.
1568 	 */
1569 	mtx_lock(sip->si_mtx);
1570 	TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1571 		/*
1572 		 * Once we remove this sfp from the list and clear the
1573 		 * sf_si seltdclear will know to ignore this si.
1574 		 */
1575 		TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1576 		sfp->sf_si = NULL;
1577 		stp = sfp->sf_td;
1578 		mtx_lock(&stp->st_mtx);
1579 		stp->st_flags |= SELTD_PENDING;
1580 		cv_broadcastpri(&stp->st_wait, pri);
1581 		mtx_unlock(&stp->st_mtx);
1582 	}
1583 	mtx_unlock(sip->si_mtx);
1584 }
1585 
1586 static void
1587 seltdinit(struct thread *td)
1588 {
1589 	struct seltd *stp;
1590 
1591 	if ((stp = td->td_sel) != NULL)
1592 		goto out;
1593 	td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1594 	mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1595 	cv_init(&stp->st_wait, "select");
1596 out:
1597 	stp->st_flags = 0;
1598 	STAILQ_INIT(&stp->st_selq);
1599 }
1600 
1601 static int
1602 seltdwait(struct thread *td, int timo)
1603 {
1604 	struct seltd *stp;
1605 	int error;
1606 
1607 	stp = td->td_sel;
1608 	/*
1609 	 * An event of interest may occur while we do not hold the seltd
1610 	 * locked so check the pending flag before we sleep.
1611 	 */
1612 	mtx_lock(&stp->st_mtx);
1613 	/*
1614 	 * Any further calls to selrecord will be a rescan.
1615 	 */
1616 	stp->st_flags |= SELTD_RESCAN;
1617 	if (stp->st_flags & SELTD_PENDING) {
1618 		mtx_unlock(&stp->st_mtx);
1619 		return (0);
1620 	}
1621 	if (timo > 0)
1622 		error = cv_timedwait_sig(&stp->st_wait, &stp->st_mtx, timo);
1623 	else
1624 		error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1625 	mtx_unlock(&stp->st_mtx);
1626 
1627 	return (error);
1628 }
1629 
1630 void
1631 seltdfini(struct thread *td)
1632 {
1633 	struct seltd *stp;
1634 
1635 	stp = td->td_sel;
1636 	if (stp == NULL)
1637 		return;
1638 	if (stp->st_free1)
1639 		uma_zfree(selfd_zone, stp->st_free1);
1640 	if (stp->st_free2)
1641 		uma_zfree(selfd_zone, stp->st_free2);
1642 	td->td_sel = NULL;
1643 	free(stp, M_SELECT);
1644 }
1645 
1646 /*
1647  * Remove the references to the thread from all of the objects we were
1648  * polling.
1649  */
1650 static void
1651 seltdclear(struct thread *td)
1652 {
1653 	struct seltd *stp;
1654 	struct selfd *sfp;
1655 	struct selfd *sfn;
1656 
1657 	stp = td->td_sel;
1658 	STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1659 		selfdfree(stp, sfp);
1660 	stp->st_flags = 0;
1661 }
1662 
1663 static void selectinit(void *);
1664 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1665 static void
1666 selectinit(void *dummy __unused)
1667 {
1668 
1669 	selfd_zone = uma_zcreate("selfd", sizeof(struct selfd), NULL, NULL,
1670 	    NULL, NULL, UMA_ALIGN_PTR, 0);
1671 	mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);
1672 }
1673