xref: /dragonfly/sys/kern/sys_generic.c (revision 8a7bdfea)
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.48 2008/04/14 12:01:50 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/filedesc.h>
49 #include <sys/filio.h>
50 #include <sys/fcntl.h>
51 #include <sys/file.h>
52 #include <sys/proc.h>
53 #include <sys/signalvar.h>
54 #include <sys/socketvar.h>
55 #include <sys/uio.h>
56 #include <sys/kernel.h>
57 #include <sys/kern_syscall.h>
58 #include <sys/malloc.h>
59 #include <sys/mapped_ioctl.h>
60 #include <sys/poll.h>
61 #include <sys/queue.h>
62 #include <sys/resourcevar.h>
63 #include <sys/sysctl.h>
64 #include <sys/sysent.h>
65 #include <sys/buf.h>
66 #ifdef KTRACE
67 #include <sys/ktrace.h>
68 #endif
69 #include <vm/vm.h>
70 #include <vm/vm_page.h>
71 #include <sys/file2.h>
72 
73 #include <machine/limits.h>
74 
75 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
76 static MALLOC_DEFINE(M_IOCTLMAP, "ioctlmap", "mapped ioctl handler buffer");
77 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
78 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
79 
80 static int 	doselect(int nd, fd_set *in, fd_set *ou, fd_set *ex,
81 			struct timeval *tv, int *res);
82 static int	pollscan (struct proc *, struct pollfd *, u_int, int *);
83 static int	selscan (struct proc *, fd_mask **, fd_mask **,
84 			int, int *);
85 static int	dofileread(int, struct file *, struct uio *, int, int *);
86 static int	dofilewrite(int, struct file *, struct uio *, int, int *);
87 
88 /*
89  * Read system call.
90  *
91  * MPSAFE
92  */
93 int
94 sys_read(struct read_args *uap)
95 {
96 	struct thread *td = curthread;
97 	struct uio auio;
98 	struct iovec aiov;
99 	int error;
100 
101 	aiov.iov_base = uap->buf;
102 	aiov.iov_len = uap->nbyte;
103 	auio.uio_iov = &aiov;
104 	auio.uio_iovcnt = 1;
105 	auio.uio_offset = -1;
106 	auio.uio_resid = uap->nbyte;
107 	auio.uio_rw = UIO_READ;
108 	auio.uio_segflg = UIO_USERSPACE;
109 	auio.uio_td = td;
110 
111 	if (auio.uio_resid < 0)
112 		error = EINVAL;
113 	else
114 		error = kern_preadv(uap->fd, &auio, 0, &uap->sysmsg_result);
115 	return(error);
116 }
117 
118 /*
119  * Positioned (Pread) read system call
120  *
121  * MPSAFE
122  */
123 int
124 sys_extpread(struct extpread_args *uap)
125 {
126 	struct thread *td = curthread;
127 	struct uio auio;
128 	struct iovec aiov;
129 	int error;
130 	int flags;
131 
132 	aiov.iov_base = uap->buf;
133 	aiov.iov_len = uap->nbyte;
134 	auio.uio_iov = &aiov;
135 	auio.uio_iovcnt = 1;
136 	auio.uio_offset = uap->offset;
137 	auio.uio_resid = uap->nbyte;
138 	auio.uio_rw = UIO_READ;
139 	auio.uio_segflg = UIO_USERSPACE;
140 	auio.uio_td = td;
141 
142 	flags = uap->flags & O_FMASK;
143 	if (uap->offset != (off_t)-1)
144 		flags |= O_FOFFSET;
145 
146 	if (auio.uio_resid < 0)
147 		error = EINVAL;
148 	else
149 		error = kern_preadv(uap->fd, &auio, flags, &uap->sysmsg_result);
150 	return(error);
151 }
152 
153 /*
154  * Scatter read system call.
155  *
156  * MPSAFE
157  */
158 int
159 sys_readv(struct readv_args *uap)
160 {
161 	struct thread *td = curthread;
162 	struct uio auio;
163 	struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
164 	int error;
165 
166 	error = iovec_copyin(uap->iovp, &iov, aiov, uap->iovcnt,
167 			     &auio.uio_resid);
168 	if (error)
169 		return (error);
170 	auio.uio_iov = iov;
171 	auio.uio_iovcnt = uap->iovcnt;
172 	auio.uio_offset = -1;
173 	auio.uio_rw = UIO_READ;
174 	auio.uio_segflg = UIO_USERSPACE;
175 	auio.uio_td = td;
176 
177 	error = kern_preadv(uap->fd, &auio, 0, &uap->sysmsg_result);
178 
179 	iovec_free(&iov, aiov);
180 	return (error);
181 }
182 
183 
184 /*
185  * Scatter positioned read system call.
186  *
187  * MPSAFE
188  */
189 int
190 sys_extpreadv(struct extpreadv_args *uap)
191 {
192 	struct thread *td = curthread;
193 	struct uio auio;
194 	struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
195 	int error;
196 	int flags;
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 = uap->offset;
205 	auio.uio_rw = UIO_READ;
206 	auio.uio_segflg = UIO_USERSPACE;
207 	auio.uio_td = td;
208 
209 	flags = uap->flags & O_FMASK;
210 	if (uap->offset != (off_t)-1)
211 		flags |= O_FOFFSET;
212 
213 	error = kern_preadv(uap->fd, &auio, flags, &uap->sysmsg_result);
214 
215 	iovec_free(&iov, aiov);
216 	return(error);
217 }
218 
219 /*
220  * MPSAFE
221  */
222 int
223 kern_preadv(int fd, struct uio *auio, int flags, int *res)
224 {
225 	struct thread *td = curthread;
226 	struct proc *p = td->td_proc;
227 	struct file *fp;
228 	int error;
229 
230 	KKASSERT(p);
231 
232 	fp = holdfp(p->p_fd, fd, FREAD);
233 	if (fp == NULL)
234 		return (EBADF);
235 	if (flags & O_FOFFSET && fp->f_type != DTYPE_VNODE) {
236 		error = ESPIPE;
237 	} else if (auio->uio_resid < 0) {
238 		error = EINVAL;
239 	} else {
240 		error = dofileread(fd, fp, auio, flags, res);
241 	}
242 	fdrop(fp);
243 	return(error);
244 }
245 
246 /*
247  * Common code for readv and preadv that reads data in
248  * from a file using the passed in uio, offset, and flags.
249  *
250  * MPALMOSTSAFE - ktrace needs help
251  */
252 static int
253 dofileread(int fd, struct file *fp, struct uio *auio, int flags, int *res)
254 {
255 	struct thread *td = curthread;
256 	int error;
257 	int len;
258 #ifdef KTRACE
259 	struct iovec *ktriov = NULL;
260 	struct uio ktruio;
261 #endif
262 
263 #ifdef KTRACE
264 	/*
265 	 * if tracing, save a copy of iovec
266 	 */
267 	if (KTRPOINT(td, KTR_GENIO))  {
268 		int iovlen = auio->uio_iovcnt * sizeof(struct iovec);
269 
270 		MALLOC(ktriov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
271 		bcopy((caddr_t)auio->uio_iov, (caddr_t)ktriov, iovlen);
272 		ktruio = *auio;
273 	}
274 #endif
275 	len = auio->uio_resid;
276 	error = fo_read(fp, auio, fp->f_cred, flags);
277 	if (error) {
278 		if (auio->uio_resid != len && (error == ERESTART ||
279 		    error == EINTR || error == EWOULDBLOCK))
280 			error = 0;
281 	}
282 #ifdef KTRACE
283 	if (ktriov != NULL) {
284 		if (error == 0) {
285 			ktruio.uio_iov = ktriov;
286 			ktruio.uio_resid = len - auio->uio_resid;
287 			get_mplock();
288 			ktrgenio(td->td_lwp, fd, UIO_READ, &ktruio, error);
289 			rel_mplock();
290 		}
291 		FREE(ktriov, M_TEMP);
292 	}
293 #endif
294 	if (error == 0)
295 		*res = len - auio->uio_resid;
296 
297 	return(error);
298 }
299 
300 /*
301  * Write system call
302  *
303  * MPSAFE
304  */
305 int
306 sys_write(struct write_args *uap)
307 {
308 	struct thread *td = curthread;
309 	struct uio auio;
310 	struct iovec aiov;
311 	int error;
312 
313 	aiov.iov_base = (void *)(uintptr_t)uap->buf;
314 	aiov.iov_len = uap->nbyte;
315 	auio.uio_iov = &aiov;
316 	auio.uio_iovcnt = 1;
317 	auio.uio_offset = -1;
318 	auio.uio_resid = uap->nbyte;
319 	auio.uio_rw = UIO_WRITE;
320 	auio.uio_segflg = UIO_USERSPACE;
321 	auio.uio_td = td;
322 
323 	if (auio.uio_resid < 0)
324 		error = EINVAL;
325 	else
326 		error = kern_pwritev(uap->fd, &auio, 0, &uap->sysmsg_result);
327 
328 	return(error);
329 }
330 
331 /*
332  * Pwrite system call
333  *
334  * MPSAFE
335  */
336 int
337 sys_extpwrite(struct extpwrite_args *uap)
338 {
339 	struct thread *td = curthread;
340 	struct uio auio;
341 	struct iovec aiov;
342 	int error;
343 	int flags;
344 
345 	aiov.iov_base = (void *)(uintptr_t)uap->buf;
346 	aiov.iov_len = uap->nbyte;
347 	auio.uio_iov = &aiov;
348 	auio.uio_iovcnt = 1;
349 	auio.uio_offset = uap->offset;
350 	auio.uio_resid = uap->nbyte;
351 	auio.uio_rw = UIO_WRITE;
352 	auio.uio_segflg = UIO_USERSPACE;
353 	auio.uio_td = td;
354 
355 	flags = uap->flags & O_FMASK;
356 	if (uap->offset != (off_t)-1)
357 		flags |= O_FOFFSET;
358 
359 	if (auio.uio_resid < 0)
360 		error = EINVAL;
361 	else
362 		error = kern_pwritev(uap->fd, &auio, flags, &uap->sysmsg_result);
363 
364 	return(error);
365 }
366 
367 /*
368  * MPSAFE
369  */
370 int
371 sys_writev(struct writev_args *uap)
372 {
373 	struct thread *td = curthread;
374 	struct uio auio;
375 	struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
376 	int error;
377 
378 	error = iovec_copyin(uap->iovp, &iov, aiov, uap->iovcnt,
379 			     &auio.uio_resid);
380 	if (error)
381 		return (error);
382 	auio.uio_iov = iov;
383 	auio.uio_iovcnt = uap->iovcnt;
384 	auio.uio_offset = -1;
385 	auio.uio_rw = UIO_WRITE;
386 	auio.uio_segflg = UIO_USERSPACE;
387 	auio.uio_td = td;
388 
389 	error = kern_pwritev(uap->fd, &auio, 0, &uap->sysmsg_result);
390 
391 	iovec_free(&iov, aiov);
392 	return (error);
393 }
394 
395 
396 /*
397  * Gather positioned write system call
398  *
399  * MPSAFE
400  */
401 int
402 sys_extpwritev(struct extpwritev_args *uap)
403 {
404 	struct thread *td = curthread;
405 	struct uio auio;
406 	struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
407 	int error;
408 	int flags;
409 
410 	error = iovec_copyin(uap->iovp, &iov, aiov, uap->iovcnt,
411 			     &auio.uio_resid);
412 	if (error)
413 		return (error);
414 	auio.uio_iov = iov;
415 	auio.uio_iovcnt = uap->iovcnt;
416 	auio.uio_offset = uap->offset;
417 	auio.uio_rw = UIO_WRITE;
418 	auio.uio_segflg = UIO_USERSPACE;
419 	auio.uio_td = td;
420 
421 	flags = uap->flags & O_FMASK;
422 	if (uap->offset != (off_t)-1)
423 		flags |= O_FOFFSET;
424 
425 	error = kern_pwritev(uap->fd, &auio, flags, &uap->sysmsg_result);
426 
427 	iovec_free(&iov, aiov);
428 	return(error);
429 }
430 
431 /*
432  * MPSAFE
433  */
434 int
435 kern_pwritev(int fd, struct uio *auio, int flags, int *res)
436 {
437 	struct thread *td = curthread;
438 	struct proc *p = td->td_proc;
439 	struct file *fp;
440 	int error;
441 
442 	KKASSERT(p);
443 
444 	fp = holdfp(p->p_fd, fd, FWRITE);
445 	if (fp == NULL)
446 		return (EBADF);
447 	else if ((flags & O_FOFFSET) && fp->f_type != DTYPE_VNODE) {
448 		error = ESPIPE;
449 	} else {
450 		error = dofilewrite(fd, fp, auio, flags, res);
451 	}
452 
453 	fdrop(fp);
454 	return (error);
455 }
456 
457 /*
458  * Common code for writev and pwritev that writes data to
459  * a file using the passed in uio, offset, and flags.
460  *
461  * MPALMOSTSAFE - ktrace needs help
462  */
463 static int
464 dofilewrite(int fd, struct file *fp, struct uio *auio, int flags, int *res)
465 {
466 	struct thread *td = curthread;
467 	struct lwp *lp = td->td_lwp;
468 	int error;
469 	int len;
470 #ifdef KTRACE
471 	struct iovec *ktriov = NULL;
472 	struct uio ktruio;
473 #endif
474 
475 #ifdef KTRACE
476 	/*
477 	 * if tracing, save a copy of iovec and uio
478 	 */
479 	if (KTRPOINT(td, KTR_GENIO))  {
480 		int iovlen = auio->uio_iovcnt * sizeof(struct iovec);
481 
482 		MALLOC(ktriov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
483 		bcopy((caddr_t)auio->uio_iov, (caddr_t)ktriov, iovlen);
484 		ktruio = *auio;
485 	}
486 #endif
487 	len = auio->uio_resid;
488 	if (fp->f_type == DTYPE_VNODE)
489 		bwillwrite();
490 	error = fo_write(fp, auio, fp->f_cred, flags);
491 	if (error) {
492 		if (auio->uio_resid != len && (error == ERESTART ||
493 		    error == EINTR || error == EWOULDBLOCK))
494 			error = 0;
495 		/* Socket layer is responsible for issuing SIGPIPE. */
496 		if (error == EPIPE) {
497 			get_mplock();
498 			lwpsignal(lp->lwp_proc, lp, SIGPIPE);
499 			rel_mplock();
500 		}
501 	}
502 #ifdef KTRACE
503 	if (ktriov != NULL) {
504 		if (error == 0) {
505 			ktruio.uio_iov = ktriov;
506 			ktruio.uio_resid = len - auio->uio_resid;
507 			get_mplock();
508 			ktrgenio(lp, fd, UIO_WRITE, &ktruio, error);
509 			rel_mplock();
510 		}
511 		FREE(ktriov, M_TEMP);
512 	}
513 #endif
514 	if (error == 0)
515 		*res = len - auio->uio_resid;
516 
517 	return(error);
518 }
519 
520 /*
521  * Ioctl system call
522  */
523 /* ARGSUSED */
524 int
525 sys_ioctl(struct ioctl_args *uap)
526 {
527 	return(mapped_ioctl(uap->fd, uap->com, uap->data, NULL));
528 }
529 
530 struct ioctl_map_entry {
531 	const char *subsys;
532 	struct ioctl_map_range *cmd_ranges;
533 	LIST_ENTRY(ioctl_map_entry) entries;
534 };
535 
536 /*
537  * The true heart of all ioctl syscall handlers (native, emulation).
538  * If map != NULL, it will be searched for a matching entry for com,
539  * and appropriate conversions/conversion functions will be utilized.
540  */
541 int
542 mapped_ioctl(int fd, u_long com, caddr_t uspc_data, struct ioctl_map *map)
543 {
544 	struct thread *td = curthread;
545 	struct proc *p = td->td_proc;
546 	struct ucred *cred;
547 	struct file *fp;
548 	struct ioctl_map_range *iomc = NULL;
549 	int error;
550 	u_int size;
551 	u_long ocom = com;
552 	caddr_t data, memp;
553 	int tmp;
554 #define STK_PARAMS	128
555 	union {
556 	    char stkbuf[STK_PARAMS];
557 	    long align;
558 	} ubuf;
559 
560 	KKASSERT(p);
561 	cred = p->p_ucred;
562 
563 	fp = holdfp(p->p_fd, fd, FREAD|FWRITE);
564 	if (fp == NULL)
565 		return(EBADF);
566 
567 	if (map != NULL) {	/* obey translation map */
568 		u_long maskcmd;
569 		struct ioctl_map_entry *e;
570 
571 		maskcmd = com & map->mask;
572 
573 		LIST_FOREACH(e, &map->mapping, entries) {
574 			for (iomc = e->cmd_ranges; iomc->start != 0 ||
575 			     iomc->maptocmd != 0 || iomc->wrapfunc != NULL ||
576 			     iomc->mapfunc != NULL;
577 			     iomc++) {
578 				if (maskcmd >= iomc->start &&
579 				    maskcmd <= iomc->end)
580 					break;
581 			}
582 
583 			/* Did we find a match? */
584 			if (iomc->start != 0 || iomc->maptocmd != 0 ||
585 			    iomc->wrapfunc != NULL || iomc->mapfunc != NULL)
586 				break;
587 		}
588 
589 		if (iomc == NULL ||
590 		    (iomc->start == 0 && iomc->maptocmd == 0
591 		     && iomc->wrapfunc == NULL && iomc->mapfunc == NULL)) {
592 			kprintf("%s: 'ioctl' fd=%d, cmd=0x%lx ('%c',%d) not implemented\n",
593 			       map->sys, fd, maskcmd,
594 			       (int)((maskcmd >> 8) & 0xff),
595 			       (int)(maskcmd & 0xff));
596 			error = EINVAL;
597 			goto done;
598 		}
599 
600 		/*
601 		 * If it's a non-range one to one mapping, maptocmd should be
602 		 * correct. If it's a ranged one to one mapping, we pass the
603 		 * original value of com, and for a range mapped to a different
604 		 * range, we always need a mapping function to translate the
605 		 * ioctl to our native ioctl. Ex. 6500-65ff <-> 9500-95ff
606 		 */
607 		if (iomc->start == iomc->end && iomc->maptocmd == iomc->maptoend) {
608 			com = iomc->maptocmd;
609 		} else if (iomc->start == iomc->maptocmd && iomc->end == iomc->maptoend) {
610 			if (iomc->mapfunc != NULL)
611 				com = iomc->mapfunc(iomc->start, iomc->end,
612 						    iomc->start, iomc->end,
613 						    com, com);
614 		} else {
615 			if (iomc->mapfunc != NULL) {
616 				com = iomc->mapfunc(iomc->start, iomc->end,
617 						    iomc->maptocmd, iomc->maptoend,
618 						    com, ocom);
619 			} else {
620 				kprintf("%s: Invalid mapping for fd=%d, cmd=%#lx ('%c',%d)\n",
621 				       map->sys, fd, maskcmd,
622 				       (int)((maskcmd >> 8) & 0xff),
623 				       (int)(maskcmd & 0xff));
624 				error = EINVAL;
625 				goto done;
626 			}
627 		}
628 	}
629 
630 	switch (com) {
631 	case FIONCLEX:
632 		error = fclrfdflags(p->p_fd, fd, UF_EXCLOSE);
633 		goto done;
634 	case FIOCLEX:
635 		error = fsetfdflags(p->p_fd, fd, UF_EXCLOSE);
636 		goto done;
637 	}
638 
639 	/*
640 	 * Interpret high order word to find amount of data to be
641 	 * copied to/from the user's address space.
642 	 */
643 	size = IOCPARM_LEN(com);
644 	if (size > IOCPARM_MAX) {
645 		error = ENOTTY;
646 		goto done;
647 	}
648 
649 	memp = NULL;
650 	if (size > sizeof (ubuf.stkbuf)) {
651 		memp = kmalloc(size, M_IOCTLOPS, M_WAITOK);
652 		data = memp;
653 	} else {
654 		data = ubuf.stkbuf;
655 	}
656 	if ((com & IOC_IN) != 0) {
657 		if (size != 0) {
658 			error = copyin(uspc_data, data, (u_int)size);
659 			if (error) {
660 				if (memp != NULL)
661 					kfree(memp, M_IOCTLOPS);
662 				goto done;
663 			}
664 		} else {
665 			*(caddr_t *)data = uspc_data;
666 		}
667 	} else if ((com & IOC_OUT) != 0 && size) {
668 		/*
669 		 * Zero the buffer so the user always
670 		 * gets back something deterministic.
671 		 */
672 		bzero(data, size);
673 	} else if ((com & IOC_VOID) != 0) {
674 		*(caddr_t *)data = uspc_data;
675 	}
676 
677 	switch (com) {
678 	case FIONBIO:
679 		if ((tmp = *(int *)data))
680 			fp->f_flag |= FNONBLOCK;
681 		else
682 			fp->f_flag &= ~FNONBLOCK;
683 		error = 0;
684 		break;
685 
686 	case FIOASYNC:
687 		if ((tmp = *(int *)data))
688 			fp->f_flag |= FASYNC;
689 		else
690 			fp->f_flag &= ~FASYNC;
691 		error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp, cred);
692 		break;
693 
694 	default:
695 		/*
696 		 *  If there is a override function,
697 		 *  call it instead of directly routing the call
698 		 */
699 		if (map != NULL && iomc->wrapfunc != NULL)
700 			error = iomc->wrapfunc(fp, com, ocom, data, cred);
701 		else
702 			error = fo_ioctl(fp, com, data, cred);
703 		/*
704 		 * Copy any data to user, size was
705 		 * already set and checked above.
706 		 */
707 		if (error == 0 && (com & IOC_OUT) != 0 && size != 0)
708 			error = copyout(data, uspc_data, (u_int)size);
709 		break;
710 	}
711 	if (memp != NULL)
712 		kfree(memp, M_IOCTLOPS);
713 done:
714 	fdrop(fp);
715 	return(error);
716 }
717 
718 int
719 mapped_ioctl_register_handler(struct ioctl_map_handler *he)
720 {
721 	struct ioctl_map_entry *ne;
722 
723 	KKASSERT(he != NULL && he->map != NULL && he->cmd_ranges != NULL &&
724 		 he->subsys != NULL && *he->subsys != '\0');
725 
726 	ne = kmalloc(sizeof(struct ioctl_map_entry), M_IOCTLMAP, M_WAITOK);
727 
728 	ne->subsys = he->subsys;
729 	ne->cmd_ranges = he->cmd_ranges;
730 
731 	LIST_INSERT_HEAD(&he->map->mapping, ne, entries);
732 
733 	return(0);
734 }
735 
736 int
737 mapped_ioctl_unregister_handler(struct ioctl_map_handler *he)
738 {
739 	struct ioctl_map_entry *ne;
740 
741 	KKASSERT(he != NULL && he->map != NULL && he->cmd_ranges != NULL);
742 
743 	LIST_FOREACH(ne, &he->map->mapping, entries) {
744 		if (ne->cmd_ranges != he->cmd_ranges)
745 			continue;
746 		LIST_REMOVE(ne, entries);
747 		kfree(ne, M_IOCTLMAP);
748 		return(0);
749 	}
750 	return(EINVAL);
751 }
752 
753 static int	nselcoll;	/* Select collisions since boot */
754 int	selwait;
755 SYSCTL_INT(_kern, OID_AUTO, nselcoll, CTLFLAG_RD, &nselcoll, 0, "");
756 
757 /*
758  * Select system call.
759  */
760 int
761 sys_select(struct select_args *uap)
762 {
763 	struct timeval ktv;
764 	struct timeval *ktvp;
765 	int error;
766 
767 	/*
768 	 * Get timeout if any.
769 	 */
770 	if (uap->tv != NULL) {
771 		error = copyin(uap->tv, &ktv, sizeof (ktv));
772 		if (error)
773 			return (error);
774 		error = itimerfix(&ktv);
775 		if (error)
776 			return (error);
777 		ktvp = &ktv;
778 	} else {
779 		ktvp = NULL;
780 	}
781 
782 	/*
783 	 * Do real work.
784 	 */
785 	error = doselect(uap->nd, uap->in, uap->ou, uap->ex, ktvp,
786 			&uap->sysmsg_result);
787 
788 	return (error);
789 }
790 
791 
792 /*
793  * Pselect system call.
794  */
795 int
796 sys_pselect(struct pselect_args *uap)
797 {
798 	struct thread *td = curthread;
799 	struct lwp *lp = td->td_lwp;
800 	struct timespec kts;
801 	struct timeval ktv;
802 	struct timeval *ktvp;
803 	sigset_t sigmask;
804 	int error;
805 
806 	/*
807 	 * Get timeout if any and convert it.
808 	 * Round up during conversion to avoid timeout going off early.
809 	 */
810 	if (uap->ts != NULL) {
811 		error = copyin(uap->ts, &kts, sizeof (kts));
812 		if (error)
813 			return (error);
814 		ktv.tv_sec = kts.tv_sec;
815 		ktv.tv_usec = (kts.tv_nsec + 999) / 1000;
816 		error = itimerfix(&ktv);
817 		if (error)
818 			return (error);
819 		ktvp = &ktv;
820 	} else {
821 		ktvp = NULL;
822 	}
823 
824 	/*
825 	 * Install temporary signal mask if any provided.
826 	 */
827 	if (uap->sigmask != NULL) {
828 		error = copyin(uap->sigmask, &sigmask, sizeof(sigmask));
829 		if (error)
830 			return (error);
831 		lp->lwp_oldsigmask = lp->lwp_sigmask;
832 		SIG_CANTMASK(sigmask);
833 		lp->lwp_sigmask = sigmask;
834 	}
835 
836 	/*
837 	 * Do real job.
838 	 */
839 	error = doselect(uap->nd, uap->in, uap->ou, uap->ex, ktvp,
840 			&uap->sysmsg_result);
841 
842 	if (uap->sigmask != NULL) {
843 		/* doselect() responsible for turning ERESTART into EINTR */
844 		KKASSERT(error != ERESTART);
845 		if (error == EINTR) {
846 			/*
847 			 * We can't restore the previous signal mask now
848 			 * because it could block the signal that interrupted
849 			 * us.  So make a note to restore it after executing
850 			 * the handler.
851 			 */
852 			lp->lwp_flag |= LWP_OLDMASK;
853 		} else {
854 			/*
855 			 * No handler to run. Restore previous mask immediately.
856 			 */
857 			lp->lwp_sigmask = lp->lwp_oldsigmask;
858 		}
859 	}
860 
861 	return (error);
862 }
863 
864 /*
865  * Common code for sys_select() and sys_pselect().
866  *
867  * in, out and ex are userland pointers.  tv must point to validated
868  * kernel-side timeout value or NULL for infinite timeout.  res must
869  * point to syscall return value.
870  */
871 static int
872 doselect(int nd, fd_set *in, fd_set *ou, fd_set *ex, struct timeval *tv,
873 		int *res)
874 {
875 	struct lwp *lp = curthread->td_lwp;
876 	struct proc *p = curproc;
877 
878 	/*
879 	 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
880 	 * infds with the new FD_SETSIZE of 1024, and more than enough for
881 	 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
882 	 * of 256.
883 	 */
884 	fd_mask s_selbits[howmany(2048, NFDBITS)];
885 	fd_mask *ibits[3], *obits[3], *selbits, *sbp;
886 	struct timeval atv, rtv, ttv;
887 	int ncoll, error, timo;
888 	u_int nbufbytes, ncpbytes, nfdbits;
889 
890 	if (nd < 0)
891 		return (EINVAL);
892 	if (nd > p->p_fd->fd_nfiles)
893 		nd = p->p_fd->fd_nfiles;   /* forgiving; slightly wrong */
894 
895 	/*
896 	 * Allocate just enough bits for the non-null fd_sets.  Use the
897 	 * preallocated auto buffer if possible.
898 	 */
899 	nfdbits = roundup(nd, NFDBITS);
900 	ncpbytes = nfdbits / NBBY;
901 	nbufbytes = 0;
902 	if (in != NULL)
903 		nbufbytes += 2 * ncpbytes;
904 	if (ou != NULL)
905 		nbufbytes += 2 * ncpbytes;
906 	if (ex != NULL)
907 		nbufbytes += 2 * ncpbytes;
908 	if (nbufbytes <= sizeof s_selbits)
909 		selbits = &s_selbits[0];
910 	else
911 		selbits = kmalloc(nbufbytes, M_SELECT, M_WAITOK);
912 
913 	/*
914 	 * Assign pointers into the bit buffers and fetch the input bits.
915 	 * Put the output buffers together so that they can be bzeroed
916 	 * together.
917 	 */
918 	sbp = selbits;
919 #define	getbits(name, x) \
920 	do {								\
921 		if (name == NULL)					\
922 			ibits[x] = NULL;				\
923 		else {							\
924 			ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp;	\
925 			obits[x] = sbp;					\
926 			sbp += ncpbytes / sizeof *sbp;			\
927 			error = copyin(name, ibits[x], ncpbytes);	\
928 			if (error != 0)					\
929 				goto done;				\
930 		}							\
931 	} while (0)
932 	getbits(in, 0);
933 	getbits(ou, 1);
934 	getbits(ex, 2);
935 #undef	getbits
936 	if (nbufbytes != 0)
937 		bzero(selbits, nbufbytes / 2);
938 
939 	if (tv != NULL) {
940 		atv = *tv;
941 		getmicrouptime(&rtv);
942 		timevaladd(&atv, &rtv);
943 	} else {
944 		atv.tv_sec = 0;
945 		atv.tv_usec = 0;
946 	}
947 	timo = 0;
948 retry:
949 	ncoll = nselcoll;
950 	lp->lwp_flag |= LWP_SELECT;
951 	error = selscan(p, ibits, obits, nd, res);
952 	if (error || *res)
953 		goto done;
954 	if (atv.tv_sec || atv.tv_usec) {
955 		getmicrouptime(&rtv);
956 		if (timevalcmp(&rtv, &atv, >=))
957 			goto done;
958 		ttv = atv;
959 		timevalsub(&ttv, &rtv);
960 		timo = ttv.tv_sec > 24 * 60 * 60 ?
961 		    24 * 60 * 60 * hz : tvtohz_high(&ttv);
962 	}
963 	crit_enter();
964 	if ((lp->lwp_flag & LWP_SELECT) == 0 || nselcoll != ncoll) {
965 		crit_exit();
966 		goto retry;
967 	}
968 	lp->lwp_flag &= ~LWP_SELECT;
969 
970 	error = tsleep((caddr_t)&selwait, PCATCH, "select", timo);
971 
972 	crit_exit();
973 	if (error == 0)
974 		goto retry;
975 done:
976 	lp->lwp_flag &= ~LWP_SELECT;
977 	/* select is not restarted after signals... */
978 	if (error == ERESTART)
979 		error = EINTR;
980 	if (error == EWOULDBLOCK)
981 		error = 0;
982 #define	putbits(name, x) \
983 	if (name && (error2 = copyout(obits[x], name, ncpbytes))) \
984 		error = error2;
985 	if (error == 0) {
986 		int error2;
987 
988 		putbits(in, 0);
989 		putbits(ou, 1);
990 		putbits(ex, 2);
991 #undef putbits
992 	}
993 	if (selbits != &s_selbits[0])
994 		kfree(selbits, M_SELECT);
995 	return (error);
996 }
997 
998 static int
999 selscan(struct proc *p, fd_mask **ibits, fd_mask **obits, int nfd, int *res)
1000 {
1001 	int msk, i, fd;
1002 	fd_mask bits;
1003 	struct file *fp;
1004 	int n = 0;
1005 	/* Note: backend also returns POLLHUP/POLLERR if appropriate. */
1006 	static int flag[3] = { POLLRDNORM, POLLWRNORM, POLLRDBAND };
1007 
1008 	for (msk = 0; msk < 3; msk++) {
1009 		if (ibits[msk] == NULL)
1010 			continue;
1011 		for (i = 0; i < nfd; i += NFDBITS) {
1012 			bits = ibits[msk][i/NFDBITS];
1013 			/* ffs(int mask) not portable, fd_mask is long */
1014 			for (fd = i; bits && fd < nfd; fd++, bits >>= 1) {
1015 				if (!(bits & 1))
1016 					continue;
1017 				fp = holdfp(p->p_fd, fd, -1);
1018 				if (fp == NULL)
1019 					return (EBADF);
1020 				if (fo_poll(fp, flag[msk], fp->f_cred)) {
1021 					obits[msk][(fd)/NFDBITS] |=
1022 					    ((fd_mask)1 << ((fd) % NFDBITS));
1023 					n++;
1024 				}
1025 				fdrop(fp);
1026 			}
1027 		}
1028 	}
1029 	*res = n;
1030 	return (0);
1031 }
1032 
1033 /*
1034  * Poll system call.
1035  */
1036 int
1037 sys_poll(struct poll_args *uap)
1038 {
1039 	struct pollfd *bits;
1040 	struct pollfd smallbits[32];
1041 	struct timeval atv, rtv, ttv;
1042 	int ncoll, error = 0, timo;
1043 	u_int nfds;
1044 	size_t ni;
1045 	struct lwp *lp = curthread->td_lwp;
1046 	struct proc *p = curproc;
1047 
1048 	nfds = uap->nfds;
1049 	/*
1050 	 * This is kinda bogus.  We have fd limits, but that is not
1051 	 * really related to the size of the pollfd array.  Make sure
1052 	 * we let the process use at least FD_SETSIZE entries and at
1053 	 * least enough for the current limits.  We want to be reasonably
1054 	 * safe, but not overly restrictive.
1055 	 */
1056 	if (nfds > p->p_rlimit[RLIMIT_NOFILE].rlim_cur && nfds > FD_SETSIZE)
1057 		return (EINVAL);
1058 	ni = nfds * sizeof(struct pollfd);
1059 	if (ni > sizeof(smallbits))
1060 		bits = kmalloc(ni, M_TEMP, M_WAITOK);
1061 	else
1062 		bits = smallbits;
1063 	error = copyin(uap->fds, bits, ni);
1064 	if (error)
1065 		goto done;
1066 	if (uap->timeout != INFTIM) {
1067 		atv.tv_sec = uap->timeout / 1000;
1068 		atv.tv_usec = (uap->timeout % 1000) * 1000;
1069 		if (itimerfix(&atv)) {
1070 			error = EINVAL;
1071 			goto done;
1072 		}
1073 		getmicrouptime(&rtv);
1074 		timevaladd(&atv, &rtv);
1075 	} else {
1076 		atv.tv_sec = 0;
1077 		atv.tv_usec = 0;
1078 	}
1079 	timo = 0;
1080 retry:
1081 	ncoll = nselcoll;
1082 	lp->lwp_flag |= LWP_SELECT;
1083 	error = pollscan(p, bits, nfds, &uap->sysmsg_result);
1084 	if (error || uap->sysmsg_result)
1085 		goto done;
1086 	if (atv.tv_sec || atv.tv_usec) {
1087 		getmicrouptime(&rtv);
1088 		if (timevalcmp(&rtv, &atv, >=))
1089 			goto done;
1090 		ttv = atv;
1091 		timevalsub(&ttv, &rtv);
1092 		timo = ttv.tv_sec > 24 * 60 * 60 ?
1093 		    24 * 60 * 60 * hz : tvtohz_high(&ttv);
1094 	}
1095 	crit_enter();
1096 	if ((lp->lwp_flag & LWP_SELECT) == 0 || nselcoll != ncoll) {
1097 		crit_exit();
1098 		goto retry;
1099 	}
1100 	lp->lwp_flag &= ~LWP_SELECT;
1101 	error = tsleep((caddr_t)&selwait, PCATCH, "poll", timo);
1102 	crit_exit();
1103 	if (error == 0)
1104 		goto retry;
1105 done:
1106 	lp->lwp_flag &= ~LWP_SELECT;
1107 	/* poll is not restarted after signals... */
1108 	if (error == ERESTART)
1109 		error = EINTR;
1110 	if (error == EWOULDBLOCK)
1111 		error = 0;
1112 	if (error == 0) {
1113 		error = copyout(bits, uap->fds, ni);
1114 		if (error)
1115 			goto out;
1116 	}
1117 out:
1118 	if (ni > sizeof(smallbits))
1119 		kfree(bits, M_TEMP);
1120 	return (error);
1121 }
1122 
1123 static int
1124 pollscan(struct proc *p, struct pollfd *fds, u_int nfd, int *res)
1125 {
1126 	int i;
1127 	struct file *fp;
1128 	int n = 0;
1129 
1130 	for (i = 0; i < nfd; i++, fds++) {
1131 		if (fds->fd >= p->p_fd->fd_nfiles) {
1132 			fds->revents = POLLNVAL;
1133 			n++;
1134 		} else if (fds->fd < 0) {
1135 			fds->revents = 0;
1136 		} else {
1137 			fp = holdfp(p->p_fd, fds->fd, -1);
1138 			if (fp == NULL) {
1139 				fds->revents = POLLNVAL;
1140 				n++;
1141 			} else {
1142 				/*
1143 				 * Note: backend also returns POLLHUP and
1144 				 * POLLERR if appropriate.
1145 				 */
1146 				fds->revents = fo_poll(fp, fds->events,
1147 							fp->f_cred);
1148 				if (fds->revents != 0)
1149 					n++;
1150 				fdrop(fp);
1151 			}
1152 		}
1153 	}
1154 	*res = n;
1155 	return (0);
1156 }
1157 
1158 /*
1159  * OpenBSD poll system call.
1160  * XXX this isn't quite a true representation..  OpenBSD uses select ops.
1161  */
1162 int
1163 sys_openbsd_poll(struct openbsd_poll_args *uap)
1164 {
1165 	return (sys_poll((struct poll_args *)uap));
1166 }
1167 
1168 /*ARGSUSED*/
1169 int
1170 seltrue(cdev_t dev, int events)
1171 {
1172 	return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
1173 }
1174 
1175 /*
1176  * Record a select request.  A global wait must be used since a process/thread
1177  * might go away after recording its request.
1178  */
1179 void
1180 selrecord(struct thread *selector, struct selinfo *sip)
1181 {
1182 	struct proc *p;
1183 	struct lwp *lp = NULL;
1184 
1185 	if (selector->td_lwp == NULL)
1186 		panic("selrecord: thread needs a process");
1187 
1188 	if (sip->si_pid == selector->td_proc->p_pid &&
1189 	    sip->si_tid == selector->td_lwp->lwp_tid)
1190 		return;
1191 	if (sip->si_pid && (p = pfind(sip->si_pid)))
1192 		lp = lwp_rb_tree_RB_LOOKUP(&p->p_lwp_tree, sip->si_tid);
1193 	if (lp != NULL && lp->lwp_wchan == (caddr_t)&selwait) {
1194 		sip->si_flags |= SI_COLL;
1195 	} else {
1196 		sip->si_pid = selector->td_proc->p_pid;
1197 		sip->si_tid = selector->td_lwp->lwp_tid;
1198 	}
1199 }
1200 
1201 /*
1202  * Do a wakeup when a selectable event occurs.
1203  */
1204 void
1205 selwakeup(struct selinfo *sip)
1206 {
1207 	struct proc *p;
1208 	struct lwp *lp = NULL;
1209 
1210 	if (sip->si_pid == 0)
1211 		return;
1212 	if (sip->si_flags & SI_COLL) {
1213 		nselcoll++;
1214 		sip->si_flags &= ~SI_COLL;
1215 		wakeup((caddr_t)&selwait);	/* YYY fixable */
1216 	}
1217 	p = pfind(sip->si_pid);
1218 	sip->si_pid = 0;
1219 	if (p == NULL)
1220 		return;
1221 	lp = lwp_rb_tree_RB_LOOKUP(&p->p_lwp_tree, sip->si_tid);
1222 	if (lp == NULL)
1223 		return;
1224 
1225 	crit_enter();
1226 	if (lp->lwp_wchan == (caddr_t)&selwait) {
1227 		/*
1228 		 * Flag the process to break the tsleep when
1229 		 * setrunnable is called, but only call setrunnable
1230 		 * here if the process is not in a stopped state.
1231 		 */
1232 		lp->lwp_flag |= LWP_BREAKTSLEEP;
1233 		if (p->p_stat != SSTOP)
1234 			setrunnable(lp);
1235 	} else if (lp->lwp_flag & LWP_SELECT) {
1236 		lp->lwp_flag &= ~LWP_SELECT;
1237 	}
1238 	crit_exit();
1239 }
1240 
1241