xref: /freebsd/sys/kern/sys_generic.c (revision bb15ca603fa442c72dde3f3cb8b46db6970e3950)
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 sys_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 sys_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 (sys_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 sys_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 sys_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 sys_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 sys_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 (sys_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 sys_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 sys_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 sys_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 sys_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 sys_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 sys_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 /*
835  * In the unlikely case when user specified n greater then the last
836  * open file descriptor, check that no bits are set after the last
837  * valid fd.  We must return EBADF if any is set.
838  *
839  * There are applications that rely on the behaviour.
840  *
841  * nd is fd_lastfile + 1.
842  */
843 static int
844 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
845 {
846 	char *addr, *oaddr;
847 	int b, i, res;
848 	uint8_t bits;
849 
850 	if (nd >= ndu || fd_in == NULL)
851 		return (0);
852 
853 	oaddr = NULL;
854 	bits = 0; /* silence gcc */
855 	for (i = nd; i < ndu; i++) {
856 		b = i / NBBY;
857 #if BYTE_ORDER == LITTLE_ENDIAN
858 		addr = (char *)fd_in + b;
859 #else
860 		addr = (char *)fd_in;
861 		if (abi_nfdbits == NFDBITS) {
862 			addr += rounddown(b, sizeof(fd_mask)) +
863 			    sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
864 		} else {
865 			addr += rounddown(b, sizeof(uint32_t)) +
866 			    sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
867 		}
868 #endif
869 		if (addr != oaddr) {
870 			res = fubyte(addr);
871 			if (res == -1)
872 				return (EFAULT);
873 			oaddr = addr;
874 			bits = res;
875 		}
876 		if ((bits & (1 << (i % NBBY))) != 0)
877 			return (EBADF);
878 	}
879 	return (0);
880 }
881 
882 int
883 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
884     fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
885 {
886 	struct filedesc *fdp;
887 	/*
888 	 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
889 	 * infds with the new FD_SETSIZE of 1024, and more than enough for
890 	 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
891 	 * of 256.
892 	 */
893 	fd_mask s_selbits[howmany(2048, NFDBITS)];
894 	fd_mask *ibits[3], *obits[3], *selbits, *sbp;
895 	struct timeval atv, rtv, ttv;
896 	int error, lf, ndu, timo;
897 	u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
898 
899 	if (nd < 0)
900 		return (EINVAL);
901 	fdp = td->td_proc->p_fd;
902 	ndu = nd;
903 	lf = fdp->fd_lastfile;
904 	if (nd > lf + 1)
905 		nd = lf + 1;
906 
907 	error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
908 	if (error != 0)
909 		return (error);
910 	error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
911 	if (error != 0)
912 		return (error);
913 	error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
914 	if (error != 0)
915 		return (error);
916 
917 	/*
918 	 * Allocate just enough bits for the non-null fd_sets.  Use the
919 	 * preallocated auto buffer if possible.
920 	 */
921 	nfdbits = roundup(nd, NFDBITS);
922 	ncpbytes = nfdbits / NBBY;
923 	ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
924 	nbufbytes = 0;
925 	if (fd_in != NULL)
926 		nbufbytes += 2 * ncpbytes;
927 	if (fd_ou != NULL)
928 		nbufbytes += 2 * ncpbytes;
929 	if (fd_ex != NULL)
930 		nbufbytes += 2 * ncpbytes;
931 	if (nbufbytes <= sizeof s_selbits)
932 		selbits = &s_selbits[0];
933 	else
934 		selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
935 
936 	/*
937 	 * Assign pointers into the bit buffers and fetch the input bits.
938 	 * Put the output buffers together so that they can be bzeroed
939 	 * together.
940 	 */
941 	sbp = selbits;
942 #define	getbits(name, x) \
943 	do {								\
944 		if (name == NULL) {					\
945 			ibits[x] = NULL;				\
946 			obits[x] = NULL;				\
947 		} else {						\
948 			ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp;	\
949 			obits[x] = sbp;					\
950 			sbp += ncpbytes / sizeof *sbp;			\
951 			error = copyin(name, ibits[x], ncpubytes);	\
952 			if (error != 0)					\
953 				goto done;				\
954 			bzero((char *)ibits[x] + ncpubytes,		\
955 			    ncpbytes - ncpubytes);			\
956 		}							\
957 	} while (0)
958 	getbits(fd_in, 0);
959 	getbits(fd_ou, 1);
960 	getbits(fd_ex, 2);
961 #undef	getbits
962 
963 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
964 	/*
965 	 * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
966 	 * we are running under 32-bit emulation. This should be more
967 	 * generic.
968 	 */
969 #define swizzle_fdset(bits)						\
970 	if (abi_nfdbits != NFDBITS && bits != NULL) {			\
971 		int i;							\
972 		for (i = 0; i < ncpbytes / sizeof *sbp; i++)		\
973 			bits[i] = (bits[i] >> 32) | (bits[i] << 32);	\
974 	}
975 #else
976 #define swizzle_fdset(bits)
977 #endif
978 
979 	/* Make sure the bit order makes it through an ABI transition */
980 	swizzle_fdset(ibits[0]);
981 	swizzle_fdset(ibits[1]);
982 	swizzle_fdset(ibits[2]);
983 
984 	if (nbufbytes != 0)
985 		bzero(selbits, nbufbytes / 2);
986 
987 	if (tvp != NULL) {
988 		atv = *tvp;
989 		if (itimerfix(&atv)) {
990 			error = EINVAL;
991 			goto done;
992 		}
993 		getmicrouptime(&rtv);
994 		timevaladd(&atv, &rtv);
995 	} else {
996 		atv.tv_sec = 0;
997 		atv.tv_usec = 0;
998 	}
999 	timo = 0;
1000 	seltdinit(td);
1001 	/* Iterate until the timeout expires or descriptors become ready. */
1002 	for (;;) {
1003 		error = selscan(td, ibits, obits, nd);
1004 		if (error || td->td_retval[0] != 0)
1005 			break;
1006 		if (atv.tv_sec || atv.tv_usec) {
1007 			getmicrouptime(&rtv);
1008 			if (timevalcmp(&rtv, &atv, >=))
1009 				break;
1010 			ttv = atv;
1011 			timevalsub(&ttv, &rtv);
1012 			timo = ttv.tv_sec > 24 * 60 * 60 ?
1013 			    24 * 60 * 60 * hz : tvtohz(&ttv);
1014 		}
1015 		error = seltdwait(td, timo);
1016 		if (error)
1017 			break;
1018 		error = selrescan(td, ibits, obits);
1019 		if (error || td->td_retval[0] != 0)
1020 			break;
1021 	}
1022 	seltdclear(td);
1023 
1024 done:
1025 	/* select is not restarted after signals... */
1026 	if (error == ERESTART)
1027 		error = EINTR;
1028 	if (error == EWOULDBLOCK)
1029 		error = 0;
1030 
1031 	/* swizzle bit order back, if necessary */
1032 	swizzle_fdset(obits[0]);
1033 	swizzle_fdset(obits[1]);
1034 	swizzle_fdset(obits[2]);
1035 #undef swizzle_fdset
1036 
1037 #define	putbits(name, x) \
1038 	if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1039 		error = error2;
1040 	if (error == 0) {
1041 		int error2;
1042 
1043 		putbits(fd_in, 0);
1044 		putbits(fd_ou, 1);
1045 		putbits(fd_ex, 2);
1046 #undef putbits
1047 	}
1048 	if (selbits != &s_selbits[0])
1049 		free(selbits, M_SELECT);
1050 
1051 	return (error);
1052 }
1053 /*
1054  * Convert a select bit set to poll flags.
1055  *
1056  * The backend always returns POLLHUP/POLLERR if appropriate and we
1057  * return this as a set bit in any set.
1058  */
1059 static int select_flags[3] = {
1060     POLLRDNORM | POLLHUP | POLLERR,
1061     POLLWRNORM | POLLHUP | POLLERR,
1062     POLLRDBAND | POLLERR
1063 };
1064 
1065 /*
1066  * Compute the fo_poll flags required for a fd given by the index and
1067  * bit position in the fd_mask array.
1068  */
1069 static __inline int
1070 selflags(fd_mask **ibits, int idx, fd_mask bit)
1071 {
1072 	int flags;
1073 	int msk;
1074 
1075 	flags = 0;
1076 	for (msk = 0; msk < 3; msk++) {
1077 		if (ibits[msk] == NULL)
1078 			continue;
1079 		if ((ibits[msk][idx] & bit) == 0)
1080 			continue;
1081 		flags |= select_flags[msk];
1082 	}
1083 	return (flags);
1084 }
1085 
1086 /*
1087  * Set the appropriate output bits given a mask of fired events and the
1088  * input bits originally requested.
1089  */
1090 static __inline int
1091 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1092 {
1093 	int msk;
1094 	int n;
1095 
1096 	n = 0;
1097 	for (msk = 0; msk < 3; msk++) {
1098 		if ((events & select_flags[msk]) == 0)
1099 			continue;
1100 		if (ibits[msk] == NULL)
1101 			continue;
1102 		if ((ibits[msk][idx] & bit) == 0)
1103 			continue;
1104 		/*
1105 		 * XXX Check for a duplicate set.  This can occur because a
1106 		 * socket calls selrecord() twice for each poll() call
1107 		 * resulting in two selfds per real fd.  selrescan() will
1108 		 * call selsetbits twice as a result.
1109 		 */
1110 		if ((obits[msk][idx] & bit) != 0)
1111 			continue;
1112 		obits[msk][idx] |= bit;
1113 		n++;
1114 	}
1115 
1116 	return (n);
1117 }
1118 
1119 static __inline int
1120 getselfd_cap(struct filedesc *fdp, int fd, struct file **fpp)
1121 {
1122 	struct file *fp;
1123 #ifdef CAPABILITIES
1124 	struct file *fp_fromcap;
1125 	int error;
1126 #endif
1127 
1128 	if ((fp = fget_unlocked(fdp, fd)) == NULL)
1129 		return (EBADF);
1130 #ifdef CAPABILITIES
1131 	/*
1132 	 * If the file descriptor is for a capability, test rights and use
1133 	 * the file descriptor references by the capability.
1134 	 */
1135 	error = cap_funwrap(fp, CAP_POLL_EVENT, &fp_fromcap);
1136 	if (error) {
1137 		fdrop(fp, curthread);
1138 		return (error);
1139 	}
1140 	if (fp != fp_fromcap) {
1141 		fhold(fp_fromcap);
1142 		fdrop(fp, curthread);
1143 		fp = fp_fromcap;
1144 	}
1145 #endif /* CAPABILITIES */
1146 	*fpp = fp;
1147 	return (0);
1148 }
1149 
1150 /*
1151  * Traverse the list of fds attached to this thread's seltd and check for
1152  * completion.
1153  */
1154 static int
1155 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1156 {
1157 	struct filedesc *fdp;
1158 	struct selinfo *si;
1159 	struct seltd *stp;
1160 	struct selfd *sfp;
1161 	struct selfd *sfn;
1162 	struct file *fp;
1163 	fd_mask bit;
1164 	int fd, ev, n, idx;
1165 	int error;
1166 
1167 	fdp = td->td_proc->p_fd;
1168 	stp = td->td_sel;
1169 	n = 0;
1170 	STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1171 		fd = (int)(uintptr_t)sfp->sf_cookie;
1172 		si = sfp->sf_si;
1173 		selfdfree(stp, sfp);
1174 		/* If the selinfo wasn't cleared the event didn't fire. */
1175 		if (si != NULL)
1176 			continue;
1177 		error = getselfd_cap(fdp, fd, &fp);
1178 		if (error)
1179 			return (error);
1180 		idx = fd / NFDBITS;
1181 		bit = (fd_mask)1 << (fd % NFDBITS);
1182 		ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1183 		fdrop(fp, td);
1184 		if (ev != 0)
1185 			n += selsetbits(ibits, obits, idx, bit, ev);
1186 	}
1187 	stp->st_flags = 0;
1188 	td->td_retval[0] = n;
1189 	return (0);
1190 }
1191 
1192 /*
1193  * Perform the initial filedescriptor scan and register ourselves with
1194  * each selinfo.
1195  */
1196 static int
1197 selscan(td, ibits, obits, nfd)
1198 	struct thread *td;
1199 	fd_mask **ibits, **obits;
1200 	int nfd;
1201 {
1202 	struct filedesc *fdp;
1203 	struct file *fp;
1204 	fd_mask bit;
1205 	int ev, flags, end, fd;
1206 	int n, idx;
1207 	int error;
1208 
1209 	fdp = td->td_proc->p_fd;
1210 	n = 0;
1211 	for (idx = 0, fd = 0; fd < nfd; idx++) {
1212 		end = imin(fd + NFDBITS, nfd);
1213 		for (bit = 1; fd < end; bit <<= 1, fd++) {
1214 			/* Compute the list of events we're interested in. */
1215 			flags = selflags(ibits, idx, bit);
1216 			if (flags == 0)
1217 				continue;
1218 			error = getselfd_cap(fdp, fd, &fp);
1219 			if (error)
1220 				return (error);
1221 			selfdalloc(td, (void *)(uintptr_t)fd);
1222 			ev = fo_poll(fp, flags, td->td_ucred, td);
1223 			fdrop(fp, td);
1224 			if (ev != 0)
1225 				n += selsetbits(ibits, obits, idx, bit, ev);
1226 		}
1227 	}
1228 
1229 	td->td_retval[0] = n;
1230 	return (0);
1231 }
1232 
1233 #ifndef _SYS_SYSPROTO_H_
1234 struct poll_args {
1235 	struct pollfd *fds;
1236 	u_int	nfds;
1237 	int	timeout;
1238 };
1239 #endif
1240 int
1241 sys_poll(td, uap)
1242 	struct thread *td;
1243 	struct poll_args *uap;
1244 {
1245 	struct pollfd *bits;
1246 	struct pollfd smallbits[32];
1247 	struct timeval atv, rtv, ttv;
1248 	int error = 0, timo;
1249 	u_int nfds;
1250 	size_t ni;
1251 
1252 	nfds = uap->nfds;
1253 	if (nfds > maxfilesperproc && nfds > FD_SETSIZE)
1254 		return (EINVAL);
1255 	ni = nfds * sizeof(struct pollfd);
1256 	if (ni > sizeof(smallbits))
1257 		bits = malloc(ni, M_TEMP, M_WAITOK);
1258 	else
1259 		bits = smallbits;
1260 	error = copyin(uap->fds, bits, ni);
1261 	if (error)
1262 		goto done;
1263 	if (uap->timeout != INFTIM) {
1264 		atv.tv_sec = uap->timeout / 1000;
1265 		atv.tv_usec = (uap->timeout % 1000) * 1000;
1266 		if (itimerfix(&atv)) {
1267 			error = EINVAL;
1268 			goto done;
1269 		}
1270 		getmicrouptime(&rtv);
1271 		timevaladd(&atv, &rtv);
1272 	} else {
1273 		atv.tv_sec = 0;
1274 		atv.tv_usec = 0;
1275 	}
1276 	timo = 0;
1277 	seltdinit(td);
1278 	/* Iterate until the timeout expires or descriptors become ready. */
1279 	for (;;) {
1280 		error = pollscan(td, bits, nfds);
1281 		if (error || td->td_retval[0] != 0)
1282 			break;
1283 		if (atv.tv_sec || atv.tv_usec) {
1284 			getmicrouptime(&rtv);
1285 			if (timevalcmp(&rtv, &atv, >=))
1286 				break;
1287 			ttv = atv;
1288 			timevalsub(&ttv, &rtv);
1289 			timo = ttv.tv_sec > 24 * 60 * 60 ?
1290 			    24 * 60 * 60 * hz : tvtohz(&ttv);
1291 		}
1292 		error = seltdwait(td, timo);
1293 		if (error)
1294 			break;
1295 		error = pollrescan(td);
1296 		if (error || td->td_retval[0] != 0)
1297 			break;
1298 	}
1299 	seltdclear(td);
1300 
1301 done:
1302 	/* poll is not restarted after signals... */
1303 	if (error == ERESTART)
1304 		error = EINTR;
1305 	if (error == EWOULDBLOCK)
1306 		error = 0;
1307 	if (error == 0) {
1308 		error = pollout(td, bits, uap->fds, nfds);
1309 		if (error)
1310 			goto out;
1311 	}
1312 out:
1313 	if (ni > sizeof(smallbits))
1314 		free(bits, M_TEMP);
1315 	return (error);
1316 }
1317 
1318 static int
1319 pollrescan(struct thread *td)
1320 {
1321 	struct seltd *stp;
1322 	struct selfd *sfp;
1323 	struct selfd *sfn;
1324 	struct selinfo *si;
1325 	struct filedesc *fdp;
1326 	struct file *fp;
1327 	struct pollfd *fd;
1328 	int n;
1329 
1330 	n = 0;
1331 	fdp = td->td_proc->p_fd;
1332 	stp = td->td_sel;
1333 	FILEDESC_SLOCK(fdp);
1334 	STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1335 		fd = (struct pollfd *)sfp->sf_cookie;
1336 		si = sfp->sf_si;
1337 		selfdfree(stp, sfp);
1338 		/* If the selinfo wasn't cleared the event didn't fire. */
1339 		if (si != NULL)
1340 			continue;
1341 		fp = fdp->fd_ofiles[fd->fd];
1342 #ifdef CAPABILITIES
1343 		if ((fp == NULL)
1344 		    || (cap_funwrap(fp, CAP_POLL_EVENT, &fp) != 0)) {
1345 #else
1346 		if (fp == NULL) {
1347 #endif
1348 			fd->revents = POLLNVAL;
1349 			n++;
1350 			continue;
1351 		}
1352 
1353 		/*
1354 		 * Note: backend also returns POLLHUP and
1355 		 * POLLERR if appropriate.
1356 		 */
1357 		fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1358 		if (fd->revents != 0)
1359 			n++;
1360 	}
1361 	FILEDESC_SUNLOCK(fdp);
1362 	stp->st_flags = 0;
1363 	td->td_retval[0] = n;
1364 	return (0);
1365 }
1366 
1367 
1368 static int
1369 pollout(td, fds, ufds, nfd)
1370 	struct thread *td;
1371 	struct pollfd *fds;
1372 	struct pollfd *ufds;
1373 	u_int nfd;
1374 {
1375 	int error = 0;
1376 	u_int i = 0;
1377 	u_int n = 0;
1378 
1379 	for (i = 0; i < nfd; i++) {
1380 		error = copyout(&fds->revents, &ufds->revents,
1381 		    sizeof(ufds->revents));
1382 		if (error)
1383 			return (error);
1384 		if (fds->revents != 0)
1385 			n++;
1386 		fds++;
1387 		ufds++;
1388 	}
1389 	td->td_retval[0] = n;
1390 	return (0);
1391 }
1392 
1393 static int
1394 pollscan(td, fds, nfd)
1395 	struct thread *td;
1396 	struct pollfd *fds;
1397 	u_int nfd;
1398 {
1399 	struct filedesc *fdp = td->td_proc->p_fd;
1400 	int i;
1401 	struct file *fp;
1402 	int n = 0;
1403 
1404 	FILEDESC_SLOCK(fdp);
1405 	for (i = 0; i < nfd; i++, fds++) {
1406 		if (fds->fd >= fdp->fd_nfiles) {
1407 			fds->revents = POLLNVAL;
1408 			n++;
1409 		} else if (fds->fd < 0) {
1410 			fds->revents = 0;
1411 		} else {
1412 			fp = fdp->fd_ofiles[fds->fd];
1413 #ifdef CAPABILITIES
1414 			if ((fp == NULL)
1415 			    || (cap_funwrap(fp, CAP_POLL_EVENT, &fp) != 0)) {
1416 #else
1417 			if (fp == NULL) {
1418 #endif
1419 				fds->revents = POLLNVAL;
1420 				n++;
1421 			} else {
1422 				/*
1423 				 * Note: backend also returns POLLHUP and
1424 				 * POLLERR if appropriate.
1425 				 */
1426 				selfdalloc(td, fds);
1427 				fds->revents = fo_poll(fp, fds->events,
1428 				    td->td_ucred, td);
1429 				/*
1430 				 * POSIX requires POLLOUT to be never
1431 				 * set simultaneously with POLLHUP.
1432 				 */
1433 				if ((fds->revents & POLLHUP) != 0)
1434 					fds->revents &= ~POLLOUT;
1435 
1436 				if (fds->revents != 0)
1437 					n++;
1438 			}
1439 		}
1440 	}
1441 	FILEDESC_SUNLOCK(fdp);
1442 	td->td_retval[0] = n;
1443 	return (0);
1444 }
1445 
1446 /*
1447  * OpenBSD poll system call.
1448  *
1449  * XXX this isn't quite a true representation..  OpenBSD uses select ops.
1450  */
1451 #ifndef _SYS_SYSPROTO_H_
1452 struct openbsd_poll_args {
1453 	struct pollfd *fds;
1454 	u_int	nfds;
1455 	int	timeout;
1456 };
1457 #endif
1458 int
1459 sys_openbsd_poll(td, uap)
1460 	register struct thread *td;
1461 	register struct openbsd_poll_args *uap;
1462 {
1463 	return (sys_poll(td, (struct poll_args *)uap));
1464 }
1465 
1466 /*
1467  * XXX This was created specifically to support netncp and netsmb.  This
1468  * allows the caller to specify a socket to wait for events on.  It returns
1469  * 0 if any events matched and an error otherwise.  There is no way to
1470  * determine which events fired.
1471  */
1472 int
1473 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1474 {
1475 	struct timeval atv, rtv, ttv;
1476 	int error, timo;
1477 
1478 	if (tvp != NULL) {
1479 		atv = *tvp;
1480 		if (itimerfix(&atv))
1481 			return (EINVAL);
1482 		getmicrouptime(&rtv);
1483 		timevaladd(&atv, &rtv);
1484 	} else {
1485 		atv.tv_sec = 0;
1486 		atv.tv_usec = 0;
1487 	}
1488 
1489 	timo = 0;
1490 	seltdinit(td);
1491 	/*
1492 	 * Iterate until the timeout expires or the socket becomes ready.
1493 	 */
1494 	for (;;) {
1495 		selfdalloc(td, NULL);
1496 		error = sopoll(so, events, NULL, td);
1497 		/* error here is actually the ready events. */
1498 		if (error)
1499 			return (0);
1500 		if (atv.tv_sec || atv.tv_usec) {
1501 			getmicrouptime(&rtv);
1502 			if (timevalcmp(&rtv, &atv, >=)) {
1503 				seltdclear(td);
1504 				return (EWOULDBLOCK);
1505 			}
1506 			ttv = atv;
1507 			timevalsub(&ttv, &rtv);
1508 			timo = ttv.tv_sec > 24 * 60 * 60 ?
1509 			    24 * 60 * 60 * hz : tvtohz(&ttv);
1510 		}
1511 		error = seltdwait(td, timo);
1512 		seltdclear(td);
1513 		if (error)
1514 			break;
1515 	}
1516 	/* XXX Duplicates ncp/smb behavior. */
1517 	if (error == ERESTART)
1518 		error = 0;
1519 	return (error);
1520 }
1521 
1522 /*
1523  * Preallocate two selfds associated with 'cookie'.  Some fo_poll routines
1524  * have two select sets, one for read and another for write.
1525  */
1526 static void
1527 selfdalloc(struct thread *td, void *cookie)
1528 {
1529 	struct seltd *stp;
1530 
1531 	stp = td->td_sel;
1532 	if (stp->st_free1 == NULL)
1533 		stp->st_free1 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1534 	stp->st_free1->sf_td = stp;
1535 	stp->st_free1->sf_cookie = cookie;
1536 	if (stp->st_free2 == NULL)
1537 		stp->st_free2 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1538 	stp->st_free2->sf_td = stp;
1539 	stp->st_free2->sf_cookie = cookie;
1540 }
1541 
1542 static void
1543 selfdfree(struct seltd *stp, struct selfd *sfp)
1544 {
1545 	STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1546 	mtx_lock(sfp->sf_mtx);
1547 	if (sfp->sf_si)
1548 		TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1549 	mtx_unlock(sfp->sf_mtx);
1550 	uma_zfree(selfd_zone, sfp);
1551 }
1552 
1553 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1554 void
1555 seldrain(sip)
1556         struct selinfo *sip;
1557 {
1558 
1559 	/*
1560 	 * This feature is already provided by doselwakeup(), thus it is
1561 	 * enough to go for it.
1562 	 * Eventually, the context, should take care to avoid races
1563 	 * between thread calling select()/poll() and file descriptor
1564 	 * detaching, but, again, the races are just the same as
1565 	 * selwakeup().
1566 	 */
1567         doselwakeup(sip, -1);
1568 }
1569 
1570 /*
1571  * Record a select request.
1572  */
1573 void
1574 selrecord(selector, sip)
1575 	struct thread *selector;
1576 	struct selinfo *sip;
1577 {
1578 	struct selfd *sfp;
1579 	struct seltd *stp;
1580 	struct mtx *mtxp;
1581 
1582 	stp = selector->td_sel;
1583 	/*
1584 	 * Don't record when doing a rescan.
1585 	 */
1586 	if (stp->st_flags & SELTD_RESCAN)
1587 		return;
1588 	/*
1589 	 * Grab one of the preallocated descriptors.
1590 	 */
1591 	sfp = NULL;
1592 	if ((sfp = stp->st_free1) != NULL)
1593 		stp->st_free1 = NULL;
1594 	else if ((sfp = stp->st_free2) != NULL)
1595 		stp->st_free2 = NULL;
1596 	else
1597 		panic("selrecord: No free selfd on selq");
1598 	mtxp = sip->si_mtx;
1599 	if (mtxp == NULL)
1600 		mtxp = mtx_pool_find(mtxpool_select, sip);
1601 	/*
1602 	 * Initialize the sfp and queue it in the thread.
1603 	 */
1604 	sfp->sf_si = sip;
1605 	sfp->sf_mtx = mtxp;
1606 	STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1607 	/*
1608 	 * Now that we've locked the sip, check for initialization.
1609 	 */
1610 	mtx_lock(mtxp);
1611 	if (sip->si_mtx == NULL) {
1612 		sip->si_mtx = mtxp;
1613 		TAILQ_INIT(&sip->si_tdlist);
1614 	}
1615 	/*
1616 	 * Add this thread to the list of selfds listening on this selinfo.
1617 	 */
1618 	TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1619 	mtx_unlock(sip->si_mtx);
1620 }
1621 
1622 /* Wake up a selecting thread. */
1623 void
1624 selwakeup(sip)
1625 	struct selinfo *sip;
1626 {
1627 	doselwakeup(sip, -1);
1628 }
1629 
1630 /* Wake up a selecting thread, and set its priority. */
1631 void
1632 selwakeuppri(sip, pri)
1633 	struct selinfo *sip;
1634 	int pri;
1635 {
1636 	doselwakeup(sip, pri);
1637 }
1638 
1639 /*
1640  * Do a wakeup when a selectable event occurs.
1641  */
1642 static void
1643 doselwakeup(sip, pri)
1644 	struct selinfo *sip;
1645 	int pri;
1646 {
1647 	struct selfd *sfp;
1648 	struct selfd *sfn;
1649 	struct seltd *stp;
1650 
1651 	/* If it's not initialized there can't be any waiters. */
1652 	if (sip->si_mtx == NULL)
1653 		return;
1654 	/*
1655 	 * Locking the selinfo locks all selfds associated with it.
1656 	 */
1657 	mtx_lock(sip->si_mtx);
1658 	TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1659 		/*
1660 		 * Once we remove this sfp from the list and clear the
1661 		 * sf_si seltdclear will know to ignore this si.
1662 		 */
1663 		TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1664 		sfp->sf_si = NULL;
1665 		stp = sfp->sf_td;
1666 		mtx_lock(&stp->st_mtx);
1667 		stp->st_flags |= SELTD_PENDING;
1668 		cv_broadcastpri(&stp->st_wait, pri);
1669 		mtx_unlock(&stp->st_mtx);
1670 	}
1671 	mtx_unlock(sip->si_mtx);
1672 }
1673 
1674 static void
1675 seltdinit(struct thread *td)
1676 {
1677 	struct seltd *stp;
1678 
1679 	if ((stp = td->td_sel) != NULL)
1680 		goto out;
1681 	td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1682 	mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1683 	cv_init(&stp->st_wait, "select");
1684 out:
1685 	stp->st_flags = 0;
1686 	STAILQ_INIT(&stp->st_selq);
1687 }
1688 
1689 static int
1690 seltdwait(struct thread *td, int timo)
1691 {
1692 	struct seltd *stp;
1693 	int error;
1694 
1695 	stp = td->td_sel;
1696 	/*
1697 	 * An event of interest may occur while we do not hold the seltd
1698 	 * locked so check the pending flag before we sleep.
1699 	 */
1700 	mtx_lock(&stp->st_mtx);
1701 	/*
1702 	 * Any further calls to selrecord will be a rescan.
1703 	 */
1704 	stp->st_flags |= SELTD_RESCAN;
1705 	if (stp->st_flags & SELTD_PENDING) {
1706 		mtx_unlock(&stp->st_mtx);
1707 		return (0);
1708 	}
1709 	if (timo > 0)
1710 		error = cv_timedwait_sig(&stp->st_wait, &stp->st_mtx, timo);
1711 	else
1712 		error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1713 	mtx_unlock(&stp->st_mtx);
1714 
1715 	return (error);
1716 }
1717 
1718 void
1719 seltdfini(struct thread *td)
1720 {
1721 	struct seltd *stp;
1722 
1723 	stp = td->td_sel;
1724 	if (stp == NULL)
1725 		return;
1726 	if (stp->st_free1)
1727 		uma_zfree(selfd_zone, stp->st_free1);
1728 	if (stp->st_free2)
1729 		uma_zfree(selfd_zone, stp->st_free2);
1730 	td->td_sel = NULL;
1731 	free(stp, M_SELECT);
1732 }
1733 
1734 /*
1735  * Remove the references to the thread from all of the objects we were
1736  * polling.
1737  */
1738 static void
1739 seltdclear(struct thread *td)
1740 {
1741 	struct seltd *stp;
1742 	struct selfd *sfp;
1743 	struct selfd *sfn;
1744 
1745 	stp = td->td_sel;
1746 	STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1747 		selfdfree(stp, sfp);
1748 	stp->st_flags = 0;
1749 }
1750 
1751 static void selectinit(void *);
1752 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1753 static void
1754 selectinit(void *dummy __unused)
1755 {
1756 
1757 	selfd_zone = uma_zcreate("selfd", sizeof(struct selfd), NULL, NULL,
1758 	    NULL, NULL, UMA_ALIGN_PTR, 0);
1759 	mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);
1760 }
1761