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