xref: /dragonfly/sys/kern/sys_generic.c (revision bcb3e04d)
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  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)sys_generic.c	8.5 (Berkeley) 1/21/94
39  * $FreeBSD: src/sys/kern/sys_generic.c,v 1.55.2.10 2001/03/17 10:39:32 peter Exp $
40  * $DragonFly: src/sys/kern/sys_generic.c,v 1.49 2008/05/05 22:09:44 dillon Exp $
41  */
42 
43 #include "opt_ktrace.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/sysproto.h>
48 #include <sys/event.h>
49 #include <sys/filedesc.h>
50 #include <sys/filio.h>
51 #include <sys/fcntl.h>
52 #include <sys/file.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/kern_syscall.h>
59 #include <sys/malloc.h>
60 #include <sys/mapped_ioctl.h>
61 #include <sys/poll.h>
62 #include <sys/queue.h>
63 #include <sys/resourcevar.h>
64 #include <sys/socketops.h>
65 #include <sys/sysctl.h>
66 #include <sys/sysent.h>
67 #include <sys/buf.h>
68 #ifdef KTRACE
69 #include <sys/ktrace.h>
70 #endif
71 #include <vm/vm.h>
72 #include <vm/vm_page.h>
73 
74 #include <sys/file2.h>
75 #include <sys/mplock2.h>
76 #include <sys/spinlock2.h>
77 
78 #include <machine/limits.h>
79 
80 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
81 static MALLOC_DEFINE(M_IOCTLMAP, "ioctlmap", "mapped ioctl handler buffer");
82 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
83 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
84 
85 typedef struct kfd_set {
86         fd_mask	fds_bits[2];
87 } kfd_set;
88 
89 enum select_copyin_states {
90     COPYIN_READ, COPYIN_WRITE, COPYIN_EXCEPT, COPYIN_DONE };
91 
92 struct select_kevent_copyin_args {
93 	kfd_set		*read_set;
94 	kfd_set		*write_set;
95 	kfd_set		*except_set;
96 	int		active_set;	/* One of select_copyin_states */
97 	struct lwp	*lwp;		/* Pointer to our lwp */
98 	int		num_fds;	/* Number of file descriptors (syscall arg) */
99 	int		proc_fds;	/* Processed fd's (wraps) */
100 	int		error;		/* Returned to userland */
101 };
102 
103 struct poll_kevent_copyin_args {
104 	struct lwp	*lwp;
105 	struct pollfd	*fds;
106 	int		nfds;
107 	int		pfds;
108 	int		error;
109 };
110 
111 static struct lwkt_token mioctl_token = LWKT_TOKEN_MP_INITIALIZER(mioctl_token);
112 
113 static int 	doselect(int nd, fd_set *in, fd_set *ou, fd_set *ex,
114 			 struct timespec *ts, int *res);
115 static int	dopoll(int nfds, struct pollfd *fds, struct timespec *ts,
116 		       int *res);
117 static int	dofileread(int, struct file *, struct uio *, int, size_t *);
118 static int	dofilewrite(int, struct file *, struct uio *, int, size_t *);
119 
120 /*
121  * Read system call.
122  *
123  * MPSAFE
124  */
125 int
126 sys_read(struct read_args *uap)
127 {
128 	struct thread *td = curthread;
129 	struct uio auio;
130 	struct iovec aiov;
131 	int error;
132 
133 	if ((ssize_t)uap->nbyte < 0)
134 		error = EINVAL;
135 
136 	aiov.iov_base = uap->buf;
137 	aiov.iov_len = uap->nbyte;
138 	auio.uio_iov = &aiov;
139 	auio.uio_iovcnt = 1;
140 	auio.uio_offset = -1;
141 	auio.uio_resid = uap->nbyte;
142 	auio.uio_rw = UIO_READ;
143 	auio.uio_segflg = UIO_USERSPACE;
144 	auio.uio_td = td;
145 
146 	error = kern_preadv(uap->fd, &auio, 0, &uap->sysmsg_szresult);
147 	return(error);
148 }
149 
150 /*
151  * Positioned (Pread) read system call
152  *
153  * MPSAFE
154  */
155 int
156 sys_extpread(struct extpread_args *uap)
157 {
158 	struct thread *td = curthread;
159 	struct uio auio;
160 	struct iovec aiov;
161 	int error;
162 	int flags;
163 
164 	if ((ssize_t)uap->nbyte < 0)
165 		return(EINVAL);
166 
167 	aiov.iov_base = uap->buf;
168 	aiov.iov_len = uap->nbyte;
169 	auio.uio_iov = &aiov;
170 	auio.uio_iovcnt = 1;
171 	auio.uio_offset = uap->offset;
172 	auio.uio_resid = uap->nbyte;
173 	auio.uio_rw = UIO_READ;
174 	auio.uio_segflg = UIO_USERSPACE;
175 	auio.uio_td = td;
176 
177 	flags = uap->flags & O_FMASK;
178 	if (uap->offset != (off_t)-1)
179 		flags |= O_FOFFSET;
180 
181 	error = kern_preadv(uap->fd, &auio, flags, &uap->sysmsg_szresult);
182 	return(error);
183 }
184 
185 /*
186  * Scatter read system call.
187  *
188  * MPSAFE
189  */
190 int
191 sys_readv(struct readv_args *uap)
192 {
193 	struct thread *td = curthread;
194 	struct uio auio;
195 	struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
196 	int error;
197 
198 	error = iovec_copyin(uap->iovp, &iov, aiov, uap->iovcnt,
199 			     &auio.uio_resid);
200 	if (error)
201 		return (error);
202 	auio.uio_iov = iov;
203 	auio.uio_iovcnt = uap->iovcnt;
204 	auio.uio_offset = -1;
205 	auio.uio_rw = UIO_READ;
206 	auio.uio_segflg = UIO_USERSPACE;
207 	auio.uio_td = td;
208 
209 	error = kern_preadv(uap->fd, &auio, 0, &uap->sysmsg_szresult);
210 
211 	iovec_free(&iov, aiov);
212 	return (error);
213 }
214 
215 
216 /*
217  * Scatter positioned read system call.
218  *
219  * MPSAFE
220  */
221 int
222 sys_extpreadv(struct extpreadv_args *uap)
223 {
224 	struct thread *td = curthread;
225 	struct uio auio;
226 	struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
227 	int error;
228 	int flags;
229 
230 	error = iovec_copyin(uap->iovp, &iov, aiov, uap->iovcnt,
231 			     &auio.uio_resid);
232 	if (error)
233 		return (error);
234 	auio.uio_iov = iov;
235 	auio.uio_iovcnt = uap->iovcnt;
236 	auio.uio_offset = uap->offset;
237 	auio.uio_rw = UIO_READ;
238 	auio.uio_segflg = UIO_USERSPACE;
239 	auio.uio_td = td;
240 
241 	flags = uap->flags & O_FMASK;
242 	if (uap->offset != (off_t)-1)
243 		flags |= O_FOFFSET;
244 
245 	error = kern_preadv(uap->fd, &auio, flags, &uap->sysmsg_szresult);
246 
247 	iovec_free(&iov, aiov);
248 	return(error);
249 }
250 
251 /*
252  * MPSAFE
253  */
254 int
255 kern_preadv(int fd, struct uio *auio, int flags, size_t *res)
256 {
257 	struct thread *td = curthread;
258 	struct proc *p = td->td_proc;
259 	struct file *fp;
260 	int error;
261 
262 	KKASSERT(p);
263 
264 	fp = holdfp(p->p_fd, fd, FREAD);
265 	if (fp == NULL)
266 		return (EBADF);
267 	if (flags & O_FOFFSET && fp->f_type != DTYPE_VNODE) {
268 		error = ESPIPE;
269 	} else {
270 		error = dofileread(fd, fp, auio, flags, res);
271 	}
272 	fdrop(fp);
273 	return(error);
274 }
275 
276 /*
277  * Common code for readv and preadv that reads data in
278  * from a file using the passed in uio, offset, and flags.
279  *
280  * MPALMOSTSAFE - ktrace needs help
281  */
282 static int
283 dofileread(int fd, struct file *fp, struct uio *auio, int flags, size_t *res)
284 {
285 	int error;
286 	size_t len;
287 #ifdef KTRACE
288 	struct thread *td = curthread;
289 	struct iovec *ktriov = NULL;
290 	struct uio ktruio;
291 #endif
292 
293 #ifdef KTRACE
294 	/*
295 	 * if tracing, save a copy of iovec
296 	 */
297 	if (KTRPOINT(td, KTR_GENIO))  {
298 		int iovlen = auio->uio_iovcnt * sizeof(struct iovec);
299 
300 		MALLOC(ktriov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
301 		bcopy((caddr_t)auio->uio_iov, (caddr_t)ktriov, iovlen);
302 		ktruio = *auio;
303 	}
304 #endif
305 	len = auio->uio_resid;
306 	error = fo_read(fp, auio, fp->f_cred, flags);
307 	if (error) {
308 		if (auio->uio_resid != len && (error == ERESTART ||
309 		    error == EINTR || error == EWOULDBLOCK))
310 			error = 0;
311 	}
312 #ifdef KTRACE
313 	if (ktriov != NULL) {
314 		if (error == 0) {
315 			ktruio.uio_iov = ktriov;
316 			ktruio.uio_resid = len - auio->uio_resid;
317 			get_mplock();
318 			ktrgenio(td->td_lwp, fd, UIO_READ, &ktruio, error);
319 			rel_mplock();
320 		}
321 		FREE(ktriov, M_TEMP);
322 	}
323 #endif
324 	if (error == 0)
325 		*res = len - auio->uio_resid;
326 
327 	return(error);
328 }
329 
330 /*
331  * Write system call
332  *
333  * MPSAFE
334  */
335 int
336 sys_write(struct write_args *uap)
337 {
338 	struct thread *td = curthread;
339 	struct uio auio;
340 	struct iovec aiov;
341 	int error;
342 
343 	if ((ssize_t)uap->nbyte < 0)
344 		error = EINVAL;
345 
346 	aiov.iov_base = (void *)(uintptr_t)uap->buf;
347 	aiov.iov_len = uap->nbyte;
348 	auio.uio_iov = &aiov;
349 	auio.uio_iovcnt = 1;
350 	auio.uio_offset = -1;
351 	auio.uio_resid = uap->nbyte;
352 	auio.uio_rw = UIO_WRITE;
353 	auio.uio_segflg = UIO_USERSPACE;
354 	auio.uio_td = td;
355 
356 	error = kern_pwritev(uap->fd, &auio, 0, &uap->sysmsg_szresult);
357 
358 	return(error);
359 }
360 
361 /*
362  * Pwrite system call
363  *
364  * MPSAFE
365  */
366 int
367 sys_extpwrite(struct extpwrite_args *uap)
368 {
369 	struct thread *td = curthread;
370 	struct uio auio;
371 	struct iovec aiov;
372 	int error;
373 	int flags;
374 
375 	if ((ssize_t)uap->nbyte < 0)
376 		error = EINVAL;
377 
378 	aiov.iov_base = (void *)(uintptr_t)uap->buf;
379 	aiov.iov_len = uap->nbyte;
380 	auio.uio_iov = &aiov;
381 	auio.uio_iovcnt = 1;
382 	auio.uio_offset = uap->offset;
383 	auio.uio_resid = uap->nbyte;
384 	auio.uio_rw = UIO_WRITE;
385 	auio.uio_segflg = UIO_USERSPACE;
386 	auio.uio_td = td;
387 
388 	flags = uap->flags & O_FMASK;
389 	if (uap->offset != (off_t)-1)
390 		flags |= O_FOFFSET;
391 	error = kern_pwritev(uap->fd, &auio, flags, &uap->sysmsg_szresult);
392 	return(error);
393 }
394 
395 /*
396  * MPSAFE
397  */
398 int
399 sys_writev(struct writev_args *uap)
400 {
401 	struct thread *td = curthread;
402 	struct uio auio;
403 	struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
404 	int error;
405 
406 	error = iovec_copyin(uap->iovp, &iov, aiov, uap->iovcnt,
407 			     &auio.uio_resid);
408 	if (error)
409 		return (error);
410 	auio.uio_iov = iov;
411 	auio.uio_iovcnt = uap->iovcnt;
412 	auio.uio_offset = -1;
413 	auio.uio_rw = UIO_WRITE;
414 	auio.uio_segflg = UIO_USERSPACE;
415 	auio.uio_td = td;
416 
417 	error = kern_pwritev(uap->fd, &auio, 0, &uap->sysmsg_szresult);
418 
419 	iovec_free(&iov, aiov);
420 	return (error);
421 }
422 
423 
424 /*
425  * Gather positioned write system call
426  *
427  * MPSAFE
428  */
429 int
430 sys_extpwritev(struct extpwritev_args *uap)
431 {
432 	struct thread *td = curthread;
433 	struct uio auio;
434 	struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
435 	int error;
436 	int flags;
437 
438 	error = iovec_copyin(uap->iovp, &iov, aiov, uap->iovcnt,
439 			     &auio.uio_resid);
440 	if (error)
441 		return (error);
442 	auio.uio_iov = iov;
443 	auio.uio_iovcnt = uap->iovcnt;
444 	auio.uio_offset = uap->offset;
445 	auio.uio_rw = UIO_WRITE;
446 	auio.uio_segflg = UIO_USERSPACE;
447 	auio.uio_td = td;
448 
449 	flags = uap->flags & O_FMASK;
450 	if (uap->offset != (off_t)-1)
451 		flags |= O_FOFFSET;
452 
453 	error = kern_pwritev(uap->fd, &auio, flags, &uap->sysmsg_szresult);
454 
455 	iovec_free(&iov, aiov);
456 	return(error);
457 }
458 
459 /*
460  * MPSAFE
461  */
462 int
463 kern_pwritev(int fd, struct uio *auio, int flags, size_t *res)
464 {
465 	struct thread *td = curthread;
466 	struct proc *p = td->td_proc;
467 	struct file *fp;
468 	int error;
469 
470 	KKASSERT(p);
471 
472 	fp = holdfp(p->p_fd, fd, FWRITE);
473 	if (fp == NULL)
474 		return (EBADF);
475 	else if ((flags & O_FOFFSET) && fp->f_type != DTYPE_VNODE) {
476 		error = ESPIPE;
477 	} else {
478 		error = dofilewrite(fd, fp, auio, flags, res);
479 	}
480 
481 	fdrop(fp);
482 	return (error);
483 }
484 
485 /*
486  * Common code for writev and pwritev that writes data to
487  * a file using the passed in uio, offset, and flags.
488  *
489  * MPALMOSTSAFE - ktrace needs help
490  */
491 static int
492 dofilewrite(int fd, struct file *fp, struct uio *auio, int flags, size_t *res)
493 {
494 	struct thread *td = curthread;
495 	struct lwp *lp = td->td_lwp;
496 	int error;
497 	size_t len;
498 #ifdef KTRACE
499 	struct iovec *ktriov = NULL;
500 	struct uio ktruio;
501 #endif
502 
503 #ifdef KTRACE
504 	/*
505 	 * if tracing, save a copy of iovec and uio
506 	 */
507 	if (KTRPOINT(td, KTR_GENIO))  {
508 		int iovlen = auio->uio_iovcnt * sizeof(struct iovec);
509 
510 		MALLOC(ktriov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
511 		bcopy((caddr_t)auio->uio_iov, (caddr_t)ktriov, iovlen);
512 		ktruio = *auio;
513 	}
514 #endif
515 	len = auio->uio_resid;
516 	error = fo_write(fp, auio, fp->f_cred, flags);
517 	if (error) {
518 		if (auio->uio_resid != len && (error == ERESTART ||
519 		    error == EINTR || error == EWOULDBLOCK))
520 			error = 0;
521 		/* Socket layer is responsible for issuing SIGPIPE. */
522 		if (error == EPIPE) {
523 			get_mplock();
524 			lwpsignal(lp->lwp_proc, lp, SIGPIPE);
525 			rel_mplock();
526 		}
527 	}
528 #ifdef KTRACE
529 	if (ktriov != NULL) {
530 		if (error == 0) {
531 			ktruio.uio_iov = ktriov;
532 			ktruio.uio_resid = len - auio->uio_resid;
533 			get_mplock();
534 			ktrgenio(lp, fd, UIO_WRITE, &ktruio, error);
535 			rel_mplock();
536 		}
537 		FREE(ktriov, M_TEMP);
538 	}
539 #endif
540 	if (error == 0)
541 		*res = len - auio->uio_resid;
542 
543 	return(error);
544 }
545 
546 /*
547  * Ioctl system call
548  *
549  * MPSAFE
550  */
551 int
552 sys_ioctl(struct ioctl_args *uap)
553 {
554 	int error;
555 
556 	error = mapped_ioctl(uap->fd, uap->com, uap->data, NULL, &uap->sysmsg);
557 	return (error);
558 }
559 
560 struct ioctl_map_entry {
561 	const char *subsys;
562 	struct ioctl_map_range *cmd_ranges;
563 	LIST_ENTRY(ioctl_map_entry) entries;
564 };
565 
566 /*
567  * The true heart of all ioctl syscall handlers (native, emulation).
568  * If map != NULL, it will be searched for a matching entry for com,
569  * and appropriate conversions/conversion functions will be utilized.
570  *
571  * MPSAFE
572  */
573 int
574 mapped_ioctl(int fd, u_long com, caddr_t uspc_data, struct ioctl_map *map,
575 	     struct sysmsg *msg)
576 {
577 	struct thread *td = curthread;
578 	struct proc *p = td->td_proc;
579 	struct ucred *cred;
580 	struct file *fp;
581 	struct ioctl_map_range *iomc = NULL;
582 	int error;
583 	u_int size;
584 	u_long ocom = com;
585 	caddr_t data, memp;
586 	int tmp;
587 #define STK_PARAMS	128
588 	union {
589 	    char stkbuf[STK_PARAMS];
590 	    long align;
591 	} ubuf;
592 
593 	KKASSERT(p);
594 	cred = td->td_ucred;
595 
596 	fp = holdfp(p->p_fd, fd, FREAD|FWRITE);
597 	if (fp == NULL)
598 		return(EBADF);
599 
600 	if (map != NULL) {	/* obey translation map */
601 		u_long maskcmd;
602 		struct ioctl_map_entry *e;
603 
604 		maskcmd = com & map->mask;
605 
606 		lwkt_gettoken(&mioctl_token);
607 		LIST_FOREACH(e, &map->mapping, entries) {
608 			for (iomc = e->cmd_ranges; iomc->start != 0 ||
609 			     iomc->maptocmd != 0 || iomc->wrapfunc != NULL ||
610 			     iomc->mapfunc != NULL;
611 			     iomc++) {
612 				if (maskcmd >= iomc->start &&
613 				    maskcmd <= iomc->end)
614 					break;
615 			}
616 
617 			/* Did we find a match? */
618 			if (iomc->start != 0 || iomc->maptocmd != 0 ||
619 			    iomc->wrapfunc != NULL || iomc->mapfunc != NULL)
620 				break;
621 		}
622 		lwkt_reltoken(&mioctl_token);
623 
624 		if (iomc == NULL ||
625 		    (iomc->start == 0 && iomc->maptocmd == 0
626 		     && iomc->wrapfunc == NULL && iomc->mapfunc == NULL)) {
627 			kprintf("%s: 'ioctl' fd=%d, cmd=0x%lx ('%c',%d) not implemented\n",
628 			       map->sys, fd, maskcmd,
629 			       (int)((maskcmd >> 8) & 0xff),
630 			       (int)(maskcmd & 0xff));
631 			error = EINVAL;
632 			goto done;
633 		}
634 
635 		/*
636 		 * If it's a non-range one to one mapping, maptocmd should be
637 		 * correct. If it's a ranged one to one mapping, we pass the
638 		 * original value of com, and for a range mapped to a different
639 		 * range, we always need a mapping function to translate the
640 		 * ioctl to our native ioctl. Ex. 6500-65ff <-> 9500-95ff
641 		 */
642 		if (iomc->start == iomc->end && iomc->maptocmd == iomc->maptoend) {
643 			com = iomc->maptocmd;
644 		} else if (iomc->start == iomc->maptocmd && iomc->end == iomc->maptoend) {
645 			if (iomc->mapfunc != NULL)
646 				com = iomc->mapfunc(iomc->start, iomc->end,
647 						    iomc->start, iomc->end,
648 						    com, com);
649 		} else {
650 			if (iomc->mapfunc != NULL) {
651 				com = iomc->mapfunc(iomc->start, iomc->end,
652 						    iomc->maptocmd, iomc->maptoend,
653 						    com, ocom);
654 			} else {
655 				kprintf("%s: Invalid mapping for fd=%d, cmd=%#lx ('%c',%d)\n",
656 				       map->sys, fd, maskcmd,
657 				       (int)((maskcmd >> 8) & 0xff),
658 				       (int)(maskcmd & 0xff));
659 				error = EINVAL;
660 				goto done;
661 			}
662 		}
663 	}
664 
665 	switch (com) {
666 	case FIONCLEX:
667 		error = fclrfdflags(p->p_fd, fd, UF_EXCLOSE);
668 		goto done;
669 	case FIOCLEX:
670 		error = fsetfdflags(p->p_fd, fd, UF_EXCLOSE);
671 		goto done;
672 	}
673 
674 	/*
675 	 * Interpret high order word to find amount of data to be
676 	 * copied to/from the user's address space.
677 	 */
678 	size = IOCPARM_LEN(com);
679 	if (size > IOCPARM_MAX) {
680 		error = ENOTTY;
681 		goto done;
682 	}
683 
684 	if (size > sizeof (ubuf.stkbuf)) {
685 		memp = kmalloc(size, M_IOCTLOPS, M_WAITOK);
686 		data = memp;
687 	} else {
688 		memp = NULL;
689 		data = ubuf.stkbuf;
690 	}
691 	if ((com & IOC_IN) != 0) {
692 		if (size != 0) {
693 			error = copyin(uspc_data, data, (size_t)size);
694 			if (error) {
695 				if (memp != NULL)
696 					kfree(memp, M_IOCTLOPS);
697 				goto done;
698 			}
699 		} else {
700 			*(caddr_t *)data = uspc_data;
701 		}
702 	} else if ((com & IOC_OUT) != 0 && size) {
703 		/*
704 		 * Zero the buffer so the user always
705 		 * gets back something deterministic.
706 		 */
707 		bzero(data, (size_t)size);
708 	} else if ((com & IOC_VOID) != 0) {
709 		*(caddr_t *)data = uspc_data;
710 	}
711 
712 	switch (com) {
713 	case FIONBIO:
714 		if ((tmp = *(int *)data))
715 			atomic_set_int(&fp->f_flag, FNONBLOCK);
716 		else
717 			atomic_clear_int(&fp->f_flag, FNONBLOCK);
718 		error = 0;
719 		break;
720 
721 	case FIOASYNC:
722 		if ((tmp = *(int *)data))
723 			atomic_set_int(&fp->f_flag, FASYNC);
724 		else
725 			atomic_clear_int(&fp->f_flag, FASYNC);
726 		error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp, cred, msg);
727 		break;
728 
729 	default:
730 		/*
731 		 *  If there is a override function,
732 		 *  call it instead of directly routing the call
733 		 */
734 		if (map != NULL && iomc->wrapfunc != NULL)
735 			error = iomc->wrapfunc(fp, com, ocom, data, cred);
736 		else
737 			error = fo_ioctl(fp, com, data, cred, msg);
738 		/*
739 		 * Copy any data to user, size was
740 		 * already set and checked above.
741 		 */
742 		if (error == 0 && (com & IOC_OUT) != 0 && size != 0)
743 			error = copyout(data, uspc_data, (size_t)size);
744 		break;
745 	}
746 	if (memp != NULL)
747 		kfree(memp, M_IOCTLOPS);
748 done:
749 	fdrop(fp);
750 	return(error);
751 }
752 
753 /*
754  * MPSAFE
755  */
756 int
757 mapped_ioctl_register_handler(struct ioctl_map_handler *he)
758 {
759 	struct ioctl_map_entry *ne;
760 
761 	KKASSERT(he != NULL && he->map != NULL && he->cmd_ranges != NULL &&
762 		 he->subsys != NULL && *he->subsys != '\0');
763 
764 	ne = kmalloc(sizeof(struct ioctl_map_entry), M_IOCTLMAP,
765 		     M_WAITOK | M_ZERO);
766 
767 	ne->subsys = he->subsys;
768 	ne->cmd_ranges = he->cmd_ranges;
769 
770 	lwkt_gettoken(&mioctl_token);
771 	LIST_INSERT_HEAD(&he->map->mapping, ne, entries);
772 	lwkt_reltoken(&mioctl_token);
773 
774 	return(0);
775 }
776 
777 /*
778  * MPSAFE
779  */
780 int
781 mapped_ioctl_unregister_handler(struct ioctl_map_handler *he)
782 {
783 	struct ioctl_map_entry *ne;
784 	int error = EINVAL;
785 
786 	KKASSERT(he != NULL && he->map != NULL && he->cmd_ranges != NULL);
787 
788 	lwkt_gettoken(&mioctl_token);
789 	LIST_FOREACH(ne, &he->map->mapping, entries) {
790 		if (ne->cmd_ranges == he->cmd_ranges) {
791 			LIST_REMOVE(ne, entries);
792 			kfree(ne, M_IOCTLMAP);
793 			error = 0;
794 			break;
795 		}
796 	}
797 	lwkt_reltoken(&mioctl_token);
798 	return(error);
799 }
800 
801 static int	nselcoll;	/* Select collisions since boot */
802 int	selwait;
803 SYSCTL_INT(_kern, OID_AUTO, nselcoll, CTLFLAG_RD, &nselcoll, 0, "");
804 static int	nseldebug;
805 SYSCTL_INT(_kern, OID_AUTO, nseldebug, CTLFLAG_RW, &nseldebug, 0, "");
806 
807 /*
808  * Select system call.
809  *
810  * MPSAFE
811  */
812 int
813 sys_select(struct select_args *uap)
814 {
815 	struct timeval ktv;
816 	struct timespec *ktsp, kts;
817 	int error;
818 
819 	/*
820 	 * Get timeout if any.
821 	 */
822 	if (uap->tv != NULL) {
823 		error = copyin(uap->tv, &ktv, sizeof (ktv));
824 		if (error)
825 			return (error);
826 		TIMEVAL_TO_TIMESPEC(&ktv, &kts);
827 		ktsp = &kts;
828 	} else {
829 		ktsp = NULL;
830 	}
831 
832 	/*
833 	 * Do real work.
834 	 */
835 	error = doselect(uap->nd, uap->in, uap->ou, uap->ex, ktsp,
836 			 &uap->sysmsg_result);
837 
838 	return (error);
839 }
840 
841 
842 /*
843  * Pselect system call.
844  *
845  * MPALMOSTSAFE
846  */
847 int
848 sys_pselect(struct pselect_args *uap)
849 {
850 	struct thread *td = curthread;
851 	struct lwp *lp = td->td_lwp;
852 	struct timespec *ktsp, kts;
853 	sigset_t sigmask;
854 	int error;
855 
856 	/*
857 	 * Get timeout if any.
858 	 */
859 	if (uap->ts != NULL) {
860 		error = copyin(uap->ts, &kts, sizeof (kts));
861 		if (error)
862 			return (error);
863 		ktsp = &kts;
864 	} else {
865 		ktsp = NULL;
866 	}
867 
868 	/*
869 	 * Install temporary signal mask if any provided.
870 	 */
871 	if (uap->sigmask != NULL) {
872 		error = copyin(uap->sigmask, &sigmask, sizeof(sigmask));
873 		if (error)
874 			return (error);
875 		get_mplock();
876 		lp->lwp_oldsigmask = lp->lwp_sigmask;
877 		SIG_CANTMASK(sigmask);
878 		lp->lwp_sigmask = sigmask;
879 	} else {
880 		get_mplock();
881 	}
882 
883 	/*
884 	 * Do real job.
885 	 */
886 	error = doselect(uap->nd, uap->in, uap->ou, uap->ex, ktsp,
887 			 &uap->sysmsg_result);
888 
889 	if (uap->sigmask != NULL) {
890 		/* doselect() responsible for turning ERESTART into EINTR */
891 		KKASSERT(error != ERESTART);
892 		if (error == EINTR) {
893 			/*
894 			 * We can't restore the previous signal mask now
895 			 * because it could block the signal that interrupted
896 			 * us.  So make a note to restore it after executing
897 			 * the handler.
898 			 */
899 			lp->lwp_flag |= LWP_OLDMASK;
900 		} else {
901 			/*
902 			 * No handler to run. Restore previous mask immediately.
903 			 */
904 			lp->lwp_sigmask = lp->lwp_oldsigmask;
905 		}
906 	}
907 	rel_mplock();
908 
909 	return (error);
910 }
911 
912 static int
913 select_copyin(void *arg, struct kevent *kevp, int maxevents, int *events)
914 {
915 	struct select_kevent_copyin_args *skap = NULL;
916 	struct kevent *kev;
917 	int fd;
918 	kfd_set *fdp = NULL;
919 	short filter = 0;
920 	u_int fflags = 0;
921 
922 	skap = (struct select_kevent_copyin_args *)arg;
923 
924 	if (*events == maxevents)
925 		return (0);
926 
927 	while (skap->active_set < COPYIN_DONE) {
928 		switch (skap->active_set) {
929 		case COPYIN_READ:
930 			/*
931 			 * Register descriptors for the read filter
932 			 */
933 			fdp = skap->read_set;
934 			filter = EVFILT_READ;
935 			fflags = NOTE_OLDAPI;
936 			if (fdp)
937 				break;
938 			++skap->active_set;
939 			skap->proc_fds = 0;
940 			/* fall through */
941 		case COPYIN_WRITE:
942 			/*
943 			 * Register descriptors for the write filter
944 			 */
945 			fdp = skap->write_set;
946 			filter = EVFILT_WRITE;
947 			fflags = NOTE_OLDAPI;
948 			if (fdp)
949 				break;
950 			++skap->active_set;
951 			skap->proc_fds = 0;
952 			/* fall through */
953 		case COPYIN_EXCEPT:
954 			/*
955 			 * Register descriptors for the exception filter
956 			 */
957 			fdp = skap->except_set;
958 			filter = EVFILT_EXCEPT;
959 			fflags = NOTE_OLDAPI | NOTE_OOB;
960 			if (fdp)
961 				break;
962 			++skap->active_set;
963 			skap->proc_fds = 0;
964 			/* fall through */
965 		case COPYIN_DONE:
966 			/*
967 			 * Nothing left to register
968 			 */
969 			return(0);
970 			/* NOT REACHED */
971 		}
972 
973 		while (skap->proc_fds < skap->num_fds) {
974 			fd = skap->proc_fds;
975 			if (FD_ISSET(fd, fdp)) {
976 				kev = &kevp[*events];
977 				EV_SET(kev, fd, filter,
978 				       EV_ADD|EV_ENABLE,
979 				       fflags, 0,
980 				       (void *)(uintptr_t)
981 					skap->lwp->lwp_kqueue_serial);
982 				FD_CLR(fd, fdp);
983 				++*events;
984 
985 				if (nseldebug)
986 					kprintf("select fd %d filter %d serial %d\n",
987 						fd, filter, skap->lwp->lwp_kqueue_serial);
988 			}
989 			++skap->proc_fds;
990 			if (*events == maxevents)
991 				return (0);
992 		}
993 		skap->active_set++;
994 		skap->proc_fds = 0;
995 	}
996 
997 	return (0);
998 }
999 
1000 static int
1001 select_copyout(void *arg, struct kevent *kevp, int count, int *res)
1002 {
1003 	struct select_kevent_copyin_args *skap;
1004 	struct kevent kev;
1005 	int i = 0;
1006 
1007 	skap = (struct select_kevent_copyin_args *)arg;
1008 
1009 	for (i = 0; i < count; ++i) {
1010 		/*
1011 		 * Filter out and delete spurious events
1012 		 */
1013 		if ((u_int)(uintptr_t)kevp[i].udata !=
1014 		    skap->lwp->lwp_kqueue_serial) {
1015 			kev = kevp[i];
1016 			kev.flags = EV_DISABLE|EV_DELETE;
1017 			kqueue_register(&skap->lwp->lwp_kqueue, &kev);
1018 			if (nseldebug)
1019 				kprintf("select fd %ju mismatched serial %d\n",
1020 					(uintmax_t)kevp[i].ident,
1021 					skap->lwp->lwp_kqueue_serial);
1022 			continue;
1023 		}
1024 
1025 		/*
1026 		 * Handle errors
1027 		 */
1028 		if (kevp[i].flags & EV_ERROR) {
1029 			switch(kevp[i].data) {
1030 			case EBADF:
1031 				/*
1032 				 * A bad file descriptor is considered a
1033 				 * fatal error for select, bail out.
1034 				 */
1035 				skap->error = EBADF;
1036 				*res = 0;
1037 				return (1);
1038 				break;
1039 			default:
1040 				/*
1041 				 * Select silently swallows any unknown errors
1042 				 * for descriptors in the read or write sets.
1043 				 *
1044 				 * ALWAYS filter out EOPNOTSUPP errors from
1045 				 * filters (at least until all filters support
1046 				 * EVFILT_EXCEPT)
1047 				 */
1048 				if (kevp[i].filter != EVFILT_READ &&
1049 				    kevp[i].filter != EVFILT_WRITE &&
1050 				    kevp[i].data != EOPNOTSUPP) {
1051 					skap->error = kevp[i].data;
1052 					*res = 0;
1053 					return (1);
1054 				}
1055 				break;
1056 			}
1057 			if (nseldebug)
1058 				kprintf("select fd %ju filter %d error %jd\n",
1059 					(uintmax_t)kevp[i].ident,
1060 					kevp[i].filter,
1061 					(intmax_t)kevp[i].data);
1062 			continue;
1063 		}
1064 
1065 		switch (kevp[i].filter) {
1066 		case EVFILT_READ:
1067 			FD_SET(kevp[i].ident, skap->read_set);
1068 			break;
1069 		case EVFILT_WRITE:
1070 			FD_SET(kevp[i].ident, skap->write_set);
1071 			break;
1072 		case EVFILT_EXCEPT:
1073 			FD_SET(kevp[i].ident, skap->except_set);
1074 			break;
1075 		}
1076 
1077 		++*res;
1078 	}
1079 
1080 	return (0);
1081 }
1082 
1083 /*
1084  * Copy select bits in from userland.  Allocate kernel memory if the
1085  * set is large.
1086  */
1087 static int
1088 getbits(int bytes, fd_set *in_set, kfd_set **out_set, kfd_set *tmp_set)
1089 {
1090 	int error;
1091 
1092 	if (in_set) {
1093 		if (bytes < sizeof(*tmp_set))
1094 			*out_set = tmp_set;
1095 		else
1096 			*out_set = kmalloc(bytes, M_SELECT, M_WAITOK);
1097 		error = copyin(in_set, *out_set, bytes);
1098 	} else {
1099 		*out_set = NULL;
1100 		error = 0;
1101 	}
1102 	return (error);
1103 }
1104 
1105 /*
1106  * Copy returned select bits back out to userland.
1107  */
1108 static int
1109 putbits(int bytes, kfd_set *in_set, fd_set *out_set)
1110 {
1111 	int error;
1112 
1113 	if (in_set) {
1114 		error = copyout(in_set, out_set, bytes);
1115 	} else {
1116 		error = 0;
1117 	}
1118 	return (error);
1119 }
1120 
1121 /*
1122  * Common code for sys_select() and sys_pselect().
1123  *
1124  * in, out and ex are userland pointers.  ts must point to validated
1125  * kernel-side timeout value or NULL for infinite timeout.  res must
1126  * point to syscall return value.
1127  */
1128 static int
1129 doselect(int nd, fd_set *read, fd_set *write, fd_set *except,
1130 	 struct timespec *ts, int *res)
1131 {
1132 	struct proc *p = curproc;
1133 	struct select_kevent_copyin_args *kap, ka;
1134 	int bytes, error;
1135 	kfd_set read_tmp;
1136 	kfd_set write_tmp;
1137 	kfd_set except_tmp;
1138 
1139 	*res = 0;
1140 	if (nd < 0)
1141 		return (EINVAL);
1142 	if (nd > p->p_fd->fd_nfiles)		/* limit kmalloc */
1143 		nd = p->p_fd->fd_nfiles;
1144 
1145 	kap = &ka;
1146 	kap->lwp = curthread->td_lwp;
1147 	kap->num_fds = nd;
1148 	kap->proc_fds = 0;
1149 	kap->error = 0;
1150 	kap->active_set = COPYIN_READ;
1151 
1152 	/*
1153 	 * Calculate bytes based on the number of __fd_mask[] array entries
1154 	 * multiplied by the size of __fd_mask.
1155 	 */
1156 	bytes = howmany(nd, __NFDBITS) * sizeof(__fd_mask);
1157 
1158 	/* kap->read_set = NULL; not needed */
1159 	kap->write_set = NULL;
1160 	kap->except_set = NULL;
1161 
1162 	error = getbits(bytes, read, &kap->read_set, &read_tmp);
1163 	if (error == 0)
1164 		error = getbits(bytes, write, &kap->write_set, &write_tmp);
1165 	if (error == 0)
1166 		error = getbits(bytes, except, &kap->except_set, &except_tmp);
1167 	if (error)
1168 		goto done;
1169 
1170 	/*
1171 	 * NOTE: Make sure the max events passed to kern_kevent() is
1172 	 *	 effectively unlimited.  (nd * 3) accomplishes this.
1173 	 *
1174 	 *	 (*res) continues to increment as returned events are
1175 	 *	 loaded in.
1176 	 */
1177 	error = kern_kevent(&kap->lwp->lwp_kqueue, 0x7FFFFFFF, res, kap,
1178 			    select_copyin, select_copyout, ts);
1179 	if (error == 0)
1180 		error = putbits(bytes, kap->read_set, read);
1181 	if (error == 0)
1182 		error = putbits(bytes, kap->write_set, write);
1183 	if (error == 0)
1184 		error = putbits(bytes, kap->except_set, except);
1185 
1186 	/*
1187 	 * An error from an individual event that should be passed
1188 	 * back to userland (EBADF)
1189 	 */
1190 	if (kap->error)
1191 		error = kap->error;
1192 
1193 	/*
1194 	 * Clean up.
1195 	 */
1196 done:
1197 	if (kap->read_set && kap->read_set != &read_tmp)
1198 		kfree(kap->read_set, M_SELECT);
1199 	if (kap->write_set && kap->write_set != &write_tmp)
1200 		kfree(kap->write_set, M_SELECT);
1201 	if (kap->except_set && kap->except_set != &except_tmp)
1202 		kfree(kap->except_set, M_SELECT);
1203 
1204 	kap->lwp->lwp_kqueue_serial += kap->num_fds;
1205 
1206 	return (error);
1207 }
1208 
1209 /*
1210  * Poll system call.
1211  *
1212  * MPSAFE
1213  */
1214 int
1215 sys_poll(struct poll_args *uap)
1216 {
1217 	struct timespec ts, *tsp;
1218 	int error;
1219 
1220 	if (uap->timeout != INFTIM) {
1221 		ts.tv_sec = uap->timeout / 1000;
1222 		ts.tv_nsec = (uap->timeout % 1000) * 1000 * 1000;
1223 		tsp = &ts;
1224 	} else {
1225 		tsp = NULL;
1226 	}
1227 
1228 	error = dopoll(uap->nfds, uap->fds, tsp, &uap->sysmsg_result);
1229 
1230 	return (error);
1231 }
1232 
1233 static int
1234 poll_copyin(void *arg, struct kevent *kevp, int maxevents, int *events)
1235 {
1236 	struct poll_kevent_copyin_args *pkap;
1237 	struct pollfd *pfd;
1238 	struct kevent *kev;
1239 	int kev_count;
1240 
1241 	pkap = (struct poll_kevent_copyin_args *)arg;
1242 
1243 	while (pkap->pfds < pkap->nfds) {
1244 		pfd = &pkap->fds[pkap->pfds];
1245 
1246 		/* Clear return events */
1247 		pfd->revents = 0;
1248 
1249 		/* Do not check if fd is equal to -1 */
1250 		if (pfd->fd == -1) {
1251 			++pkap->pfds;
1252 			continue;
1253 		}
1254 
1255 		kev_count = 0;
1256 		if (pfd->events & (POLLIN | POLLRDNORM))
1257 			kev_count++;
1258 		if (pfd->events & (POLLOUT | POLLWRNORM))
1259 			kev_count++;
1260 		if (pfd->events & (POLLPRI | POLLRDBAND))
1261 			kev_count++;
1262 
1263 		if (*events + kev_count > maxevents)
1264 			return (0);
1265 
1266 		/*
1267 		 * NOTE: A combined serial number and poll array index is
1268 		 * stored in kev->udata.
1269 		 */
1270 		kev = &kevp[*events];
1271 		if (pfd->events & (POLLIN | POLLRDNORM)) {
1272 			EV_SET(kev++, pfd->fd, EVFILT_READ, EV_ADD|EV_ENABLE,
1273 			       NOTE_OLDAPI, 0, (void *)(uintptr_t)
1274 				(pkap->lwp->lwp_kqueue_serial + pkap->pfds));
1275 		}
1276 		if (pfd->events & (POLLOUT | POLLWRNORM)) {
1277 			EV_SET(kev++, pfd->fd, EVFILT_WRITE, EV_ADD|EV_ENABLE,
1278 			       NOTE_OLDAPI, 0, (void *)(uintptr_t)
1279 				(pkap->lwp->lwp_kqueue_serial + pkap->pfds));
1280 		}
1281 		if (pfd->events & (POLLPRI | POLLRDBAND)) {
1282 			EV_SET(kev++, pfd->fd, EVFILT_EXCEPT, EV_ADD|EV_ENABLE,
1283 			       NOTE_OLDAPI | NOTE_OOB, 0,
1284 			       (void *)(uintptr_t)
1285 				(pkap->lwp->lwp_kqueue_serial + pkap->pfds));
1286 		}
1287 
1288 		if (nseldebug) {
1289 			kprintf("poll index %d/%d fd %d events %08x serial %d\n",
1290 				pkap->pfds, pkap->nfds-1, pfd->fd, pfd->events,
1291 				pkap->lwp->lwp_kqueue_serial);
1292 		}
1293 
1294 		++pkap->pfds;
1295 		(*events) += kev_count;
1296 	}
1297 
1298 	return (0);
1299 }
1300 
1301 static int
1302 poll_copyout(void *arg, struct kevent *kevp, int count, int *res)
1303 {
1304 	struct poll_kevent_copyin_args *pkap;
1305 	struct pollfd *pfd;
1306 	struct kevent kev;
1307 	int count_res;
1308 	int i;
1309 	u_int pi;
1310 
1311 	pkap = (struct poll_kevent_copyin_args *)arg;
1312 
1313 	for (i = 0; i < count; ++i) {
1314 		/*
1315 		 * Extract the poll array index and delete spurious events.
1316 		 * We can easily tell if the serial number is incorrect
1317 		 * by checking whether the extracted index is out of range.
1318 		 */
1319 		pi = (u_int)(uintptr_t)kevp[i].udata -
1320 		     (u_int)pkap->lwp->lwp_kqueue_serial;
1321 
1322 		if (pi >= pkap->nfds) {
1323 			kev = kevp[i];
1324 			kev.flags = EV_DISABLE|EV_DELETE;
1325 			kqueue_register(&pkap->lwp->lwp_kqueue, &kev);
1326 			if (nseldebug)
1327 				kprintf("poll index %d out of range against serial %d\n",
1328 					pi, pkap->lwp->lwp_kqueue_serial);
1329 			continue;
1330 		}
1331 		pfd = &pkap->fds[pi];
1332 		if (kevp[i].ident == pfd->fd) {
1333 			/*
1334 			 * A single descriptor may generate an error against
1335 			 * more than one filter, make sure to set the
1336 			 * appropriate flags but do not increment (*res)
1337 			 * more than once.
1338 			 */
1339 			count_res = (pfd->revents == 0);
1340 			if (kevp[i].flags & EV_ERROR) {
1341 				switch(kevp[i].data) {
1342 				case EBADF:
1343 					/* Bad file descriptor */
1344 					if (count_res)
1345 						++*res;
1346 					pfd->revents |= POLLNVAL;
1347 					break;
1348 				default:
1349 					/*
1350 					 * Poll silently swallows any unknown
1351 					 * errors except in the case of POLLPRI
1352 					 * (OOB/urgent data).
1353 					 *
1354 					 * ALWAYS filter out EOPNOTSUPP errors
1355 					 * from filters, common applications
1356 					 * set POLLPRI|POLLRDBAND and most
1357 					 * filters do not support EVFILT_EXCEPT.
1358 					 */
1359 					if (kevp[i].filter != EVFILT_READ &&
1360 					    kevp[i].filter != EVFILT_WRITE &&
1361 					    kevp[i].data != EOPNOTSUPP) {
1362 						if (count_res == 0)
1363 							++*res;
1364 						pfd->revents |= POLLERR;
1365 					}
1366 					break;
1367 				}
1368 				if (nseldebug) {
1369 					kprintf("poll index %d fd %d "
1370 						"filter %d error %jd\n",
1371 						pi, pfd->fd,
1372 						kevp[i].filter,
1373 						(intmax_t)kevp[i].data);
1374 				}
1375 				continue;
1376 			}
1377 
1378 			switch (kevp[i].filter) {
1379 			case EVFILT_READ:
1380 #if 0
1381 				/*
1382 				 * EOF on the read side can indicate a
1383 				 * half-closed situation and not necessarily
1384 				 * a disconnect, so depend on the user
1385 				 * issuing a read() and getting 0 bytes back.
1386 				 */
1387 				if (kevp[i].flags & EV_EOF)
1388 					pfd->revents |= POLLHUP;
1389 #endif
1390 				if (pfd->events & POLLIN)
1391 					pfd->revents |= POLLIN;
1392 				if (pfd->events & POLLRDNORM)
1393 					pfd->revents |= POLLRDNORM;
1394 				break;
1395 			case EVFILT_WRITE:
1396 				/*
1397 				 * As per the OpenGroup POLLHUP is mutually
1398 				 * exclusive with the writability flags.  I
1399 				 * consider this a bit broken but...
1400 				 *
1401 				 * In this case a disconnect is implied even
1402 				 * for a half-closed (write side) situation.
1403 				 */
1404 				if (kevp[i].flags & EV_EOF) {
1405 					pfd->revents |= POLLHUP;
1406 				} else {
1407 					if (pfd->events & POLLOUT)
1408 						pfd->revents |= POLLOUT;
1409 					if (pfd->events & POLLWRNORM)
1410 						pfd->revents |= POLLWRNORM;
1411 				}
1412 				break;
1413 			case EVFILT_EXCEPT:
1414 				/*
1415 				 * EV_EOF should never be tagged for this
1416 				 * filter.
1417 				 */
1418 				if (pfd->events & POLLPRI)
1419 					pfd->revents |= POLLPRI;
1420 				if (pfd->events & POLLRDBAND)
1421 					pfd->revents |= POLLRDBAND;
1422 				break;
1423 			}
1424 
1425 			if (nseldebug) {
1426 				kprintf("poll index %d/%d fd %d revents %08x\n",
1427 					pi, pkap->nfds, pfd->fd, pfd->revents);
1428 			}
1429 
1430 			if (count_res && pfd->revents)
1431 				++*res;
1432 		} else {
1433 			if (nseldebug) {
1434 				kprintf("poll index %d mismatch %ju/%d\n",
1435 					pi, (uintmax_t)kevp[i].ident, pfd->fd);
1436 			}
1437 		}
1438 	}
1439 
1440 	return (0);
1441 }
1442 
1443 static int
1444 dopoll(int nfds, struct pollfd *fds, struct timespec *ts, int *res)
1445 {
1446 	struct poll_kevent_copyin_args ka;
1447 	struct pollfd sfds[64];
1448 	int bytes;
1449 	int error;
1450 
1451         *res = 0;
1452         if (nfds < 0)
1453                 return (EINVAL);
1454 
1455 	/*
1456 	 * This is a bit arbitrary but we need to limit internal kmallocs.
1457 	 */
1458         if (nfds > maxfilesperproc * 2)
1459                 nfds = maxfilesperproc * 2;
1460 	bytes = sizeof(struct pollfd) * nfds;
1461 
1462 	ka.lwp = curthread->td_lwp;
1463 	ka.nfds = nfds;
1464 	ka.pfds = 0;
1465 	ka.error = 0;
1466 
1467 	if (ka.nfds < 64)
1468 		ka.fds = sfds;
1469 	else
1470 		ka.fds = kmalloc(bytes, M_SELECT, M_WAITOK);
1471 
1472 	error = copyin(fds, ka.fds, bytes);
1473 	if (error == 0)
1474 		error = kern_kevent(&ka.lwp->lwp_kqueue, 0x7FFFFFFF, res, &ka,
1475 				    poll_copyin, poll_copyout, ts);
1476 
1477 	if (error == 0)
1478 		error = copyout(ka.fds, fds, bytes);
1479 
1480 	if (ka.fds != sfds)
1481 		kfree(ka.fds, M_SELECT);
1482 
1483 	ka.lwp->lwp_kqueue_serial += nfds;
1484 
1485 	return (error);
1486 }
1487 
1488 static int
1489 socket_wait_copyin(void *arg, struct kevent *kevp, int maxevents, int *events)
1490 {
1491 	return (0);
1492 }
1493 
1494 static int
1495 socket_wait_copyout(void *arg, struct kevent *kevp, int count, int *res)
1496 {
1497 	++*res;
1498 	return (0);
1499 }
1500 
1501 extern	struct fileops socketops;
1502 
1503 /*
1504  * NOTE: Callers of socket_wait() must already have a reference on the
1505  *	 socket.
1506  */
1507 int
1508 socket_wait(struct socket *so, struct timespec *ts, int *res)
1509 {
1510 	struct thread *td = curthread;
1511 	struct file *fp;
1512 	struct kqueue kq;
1513 	struct kevent kev;
1514 	int error, fd;
1515 
1516 	if ((error = falloc(td->td_lwp, &fp, &fd)) != 0)
1517 		return (error);
1518 
1519 	fp->f_type = DTYPE_SOCKET;
1520 	fp->f_flag = FREAD | FWRITE;
1521 	fp->f_ops = &socketops;
1522 	fp->f_data = so;
1523 	fsetfd(td->td_lwp->lwp_proc->p_fd, fp, fd);
1524 
1525 	kqueue_init(&kq, td->td_lwp->lwp_proc->p_fd);
1526 	EV_SET(&kev, fd, EVFILT_READ, EV_ADD|EV_ENABLE, 0, 0, NULL);
1527 	if ((error = kqueue_register(&kq, &kev)) != 0) {
1528 		fdrop(fp);
1529 		return (error);
1530 	}
1531 
1532 	error = kern_kevent(&kq, 1, res, NULL, socket_wait_copyin,
1533 			    socket_wait_copyout, ts);
1534 
1535 	EV_SET(&kev, fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1536 	kqueue_register(&kq, &kev);
1537 	fp->f_ops = &badfileops;
1538 	fdrop(fp);
1539 
1540 	return (error);
1541 }
1542 
1543 /*
1544  * OpenBSD poll system call.
1545  * XXX this isn't quite a true representation..  OpenBSD uses select ops.
1546  *
1547  * MPSAFE
1548  */
1549 int
1550 sys_openbsd_poll(struct openbsd_poll_args *uap)
1551 {
1552 	return (sys_poll((struct poll_args *)uap));
1553 }
1554 
1555 /*ARGSUSED*/
1556 int
1557 seltrue(cdev_t dev, int events)
1558 {
1559 	return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
1560 }
1561