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