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