xref: /freebsd/sys/kern/sys_generic.c (revision f0a75d274af375d15b97b830966b99a02b7db911)
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_compat.h"
41 #include "opt_ktrace.h"
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/sysproto.h>
46 #include <sys/filedesc.h>
47 #include <sys/filio.h>
48 #include <sys/fcntl.h>
49 #include <sys/file.h>
50 #include <sys/proc.h>
51 #include <sys/signalvar.h>
52 #include <sys/socketvar.h>
53 #include <sys/uio.h>
54 #include <sys/kernel.h>
55 #include <sys/limits.h>
56 #include <sys/malloc.h>
57 #include <sys/poll.h>
58 #include <sys/resourcevar.h>
59 #include <sys/selinfo.h>
60 #include <sys/sleepqueue.h>
61 #include <sys/syscallsubr.h>
62 #include <sys/sysctl.h>
63 #include <sys/sysent.h>
64 #include <sys/vnode.h>
65 #include <sys/bio.h>
66 #include <sys/buf.h>
67 #include <sys/condvar.h>
68 #ifdef KTRACE
69 #include <sys/ktrace.h>
70 #endif
71 #include <vm/vm.h>
72 #include <vm/vm_page.h>
73 
74 static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
75 static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
76 MALLOC_DEFINE(M_IOV, "iov", "large iov's");
77 
78 static int	pollscan(struct thread *, struct pollfd *, u_int);
79 static int	selscan(struct thread *, fd_mask **, fd_mask **, int);
80 static int	dofileread(struct thread *, int, struct file *, struct uio *,
81 		    off_t, int);
82 static int	dofilewrite(struct thread *, int, struct file *, struct uio *,
83 		    off_t, int);
84 static void	doselwakeup(struct selinfo *, int);
85 
86 #ifndef _SYS_SYSPROTO_H_
87 struct read_args {
88 	int	fd;
89 	void	*buf;
90 	size_t	nbyte;
91 };
92 #endif
93 int
94 read(td, uap)
95 	struct thread *td;
96 	struct read_args *uap;
97 {
98 	struct uio auio;
99 	struct iovec aiov;
100 	int error;
101 
102 	if (uap->nbyte > INT_MAX)
103 		return (EINVAL);
104 	aiov.iov_base = uap->buf;
105 	aiov.iov_len = uap->nbyte;
106 	auio.uio_iov = &aiov;
107 	auio.uio_iovcnt = 1;
108 	auio.uio_resid = uap->nbyte;
109 	auio.uio_segflg = UIO_USERSPACE;
110 	error = kern_readv(td, uap->fd, &auio);
111 	return(error);
112 }
113 
114 /*
115  * Positioned read system call
116  */
117 #ifndef _SYS_SYSPROTO_H_
118 struct pread_args {
119 	int	fd;
120 	void	*buf;
121 	size_t	nbyte;
122 	int	pad;
123 	off_t	offset;
124 };
125 #endif
126 int
127 pread(td, uap)
128 	struct thread *td;
129 	struct pread_args *uap;
130 {
131 	struct uio auio;
132 	struct iovec aiov;
133 	int error;
134 
135 	if (uap->nbyte > INT_MAX)
136 		return (EINVAL);
137 	aiov.iov_base = uap->buf;
138 	aiov.iov_len = uap->nbyte;
139 	auio.uio_iov = &aiov;
140 	auio.uio_iovcnt = 1;
141 	auio.uio_resid = uap->nbyte;
142 	auio.uio_segflg = UIO_USERSPACE;
143 	error = kern_preadv(td, uap->fd, &auio, uap->offset);
144 	return(error);
145 }
146 
147 /*
148  * Scatter read system call.
149  */
150 #ifndef _SYS_SYSPROTO_H_
151 struct readv_args {
152 	int	fd;
153 	struct	iovec *iovp;
154 	u_int	iovcnt;
155 };
156 #endif
157 int
158 readv(struct thread *td, struct readv_args *uap)
159 {
160 	struct uio *auio;
161 	int error;
162 
163 	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
164 	if (error)
165 		return (error);
166 	error = kern_readv(td, uap->fd, auio);
167 	free(auio, M_IOV);
168 	return (error);
169 }
170 
171 int
172 kern_readv(struct thread *td, int fd, struct uio *auio)
173 {
174 	struct file *fp;
175 	int error;
176 
177 	error = fget_read(td, fd, &fp);
178 	if (error)
179 		return (error);
180 	error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
181 	fdrop(fp, td);
182 	return (error);
183 }
184 
185 /*
186  * Scatter positioned read system call.
187  */
188 #ifndef _SYS_SYSPROTO_H_
189 struct preadv_args {
190 	int	fd;
191 	struct	iovec *iovp;
192 	u_int	iovcnt;
193 	off_t	offset;
194 };
195 #endif
196 int
197 preadv(struct thread *td, struct preadv_args *uap)
198 {
199 	struct uio *auio;
200 	int error;
201 
202 	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
203 	if (error)
204 		return (error);
205 	error = kern_preadv(td, uap->fd, auio, uap->offset);
206 	free(auio, M_IOV);
207 	return (error);
208 }
209 
210 int
211 kern_preadv(td, fd, auio, offset)
212 	struct thread *td;
213 	int fd;
214 	struct uio *auio;
215 	off_t offset;
216 {
217 	struct file *fp;
218 	int error;
219 
220 	error = fget_read(td, fd, &fp);
221 	if (error)
222 		return (error);
223 	if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
224 		error = ESPIPE;
225 	else if (offset < 0 && fp->f_vnode->v_type != VCHR)
226 		error = EINVAL;
227 	else
228 		error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
229 	fdrop(fp, td);
230 	return (error);
231 }
232 
233 /*
234  * Common code for readv and preadv that reads data in
235  * from a file using the passed in uio, offset, and flags.
236  */
237 static int
238 dofileread(td, fd, fp, auio, offset, flags)
239 	struct thread *td;
240 	int fd;
241 	struct file *fp;
242 	struct uio *auio;
243 	off_t offset;
244 	int flags;
245 {
246 	ssize_t cnt;
247 	int error;
248 #ifdef KTRACE
249 	struct uio *ktruio = NULL;
250 #endif
251 
252 	/* Finish zero length reads right here */
253 	if (auio->uio_resid == 0) {
254 		td->td_retval[0] = 0;
255 		return(0);
256 	}
257 	auio->uio_rw = UIO_READ;
258 	auio->uio_offset = offset;
259 	auio->uio_td = td;
260 #ifdef KTRACE
261 	if (KTRPOINT(td, KTR_GENIO))
262 		ktruio = cloneuio(auio);
263 #endif
264 	cnt = auio->uio_resid;
265 	if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
266 		if (auio->uio_resid != cnt && (error == ERESTART ||
267 		    error == EINTR || error == EWOULDBLOCK))
268 			error = 0;
269 	}
270 	cnt -= auio->uio_resid;
271 #ifdef KTRACE
272 	if (ktruio != NULL) {
273 		ktruio->uio_resid = cnt;
274 		ktrgenio(fd, UIO_READ, ktruio, error);
275 	}
276 #endif
277 	td->td_retval[0] = cnt;
278 	return (error);
279 }
280 
281 #ifndef _SYS_SYSPROTO_H_
282 struct write_args {
283 	int	fd;
284 	const void *buf;
285 	size_t	nbyte;
286 };
287 #endif
288 int
289 write(td, uap)
290 	struct thread *td;
291 	struct write_args *uap;
292 {
293 	struct uio auio;
294 	struct iovec aiov;
295 	int error;
296 
297 	if (uap->nbyte > INT_MAX)
298 		return (EINVAL);
299 	aiov.iov_base = (void *)(uintptr_t)uap->buf;
300 	aiov.iov_len = uap->nbyte;
301 	auio.uio_iov = &aiov;
302 	auio.uio_iovcnt = 1;
303 	auio.uio_resid = uap->nbyte;
304 	auio.uio_segflg = UIO_USERSPACE;
305 	error = kern_writev(td, uap->fd, &auio);
306 	return(error);
307 }
308 
309 /*
310  * Positioned write system call.
311  */
312 #ifndef _SYS_SYSPROTO_H_
313 struct pwrite_args {
314 	int	fd;
315 	const void *buf;
316 	size_t	nbyte;
317 	int	pad;
318 	off_t	offset;
319 };
320 #endif
321 int
322 pwrite(td, uap)
323 	struct thread *td;
324 	struct pwrite_args *uap;
325 {
326 	struct uio auio;
327 	struct iovec aiov;
328 	int error;
329 
330 	if (uap->nbyte > INT_MAX)
331 		return (EINVAL);
332 	aiov.iov_base = (void *)(uintptr_t)uap->buf;
333 	aiov.iov_len = uap->nbyte;
334 	auio.uio_iov = &aiov;
335 	auio.uio_iovcnt = 1;
336 	auio.uio_resid = uap->nbyte;
337 	auio.uio_segflg = UIO_USERSPACE;
338 	error = kern_pwritev(td, uap->fd, &auio, uap->offset);
339 	return(error);
340 }
341 
342 /*
343  * Gather write system call.
344  */
345 #ifndef _SYS_SYSPROTO_H_
346 struct writev_args {
347 	int	fd;
348 	struct	iovec *iovp;
349 	u_int	iovcnt;
350 };
351 #endif
352 int
353 writev(struct thread *td, struct writev_args *uap)
354 {
355 	struct uio *auio;
356 	int error;
357 
358 	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
359 	if (error)
360 		return (error);
361 	error = kern_writev(td, uap->fd, auio);
362 	free(auio, M_IOV);
363 	return (error);
364 }
365 
366 int
367 kern_writev(struct thread *td, int fd, struct uio *auio)
368 {
369 	struct file *fp;
370 	int error;
371 
372 	error = fget_write(td, fd, &fp);
373 	if (error)
374 		return (error);
375 	error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
376 	fdrop(fp, td);
377 	return (error);
378 }
379 
380 /*
381  * Gather positioned write system call.
382  */
383 #ifndef _SYS_SYSPROTO_H_
384 struct pwritev_args {
385 	int	fd;
386 	struct	iovec *iovp;
387 	u_int	iovcnt;
388 	off_t	offset;
389 };
390 #endif
391 int
392 pwritev(struct thread *td, struct pwritev_args *uap)
393 {
394 	struct uio *auio;
395 	int error;
396 
397 	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
398 	if (error)
399 		return (error);
400 	error = kern_pwritev(td, uap->fd, auio, uap->offset);
401 	free(auio, M_IOV);
402 	return (error);
403 }
404 
405 int
406 kern_pwritev(td, fd, auio, offset)
407 	struct thread *td;
408 	struct uio *auio;
409 	int fd;
410 	off_t offset;
411 {
412 	struct file *fp;
413 	int error;
414 
415 	error = fget_write(td, fd, &fp);
416 	if (error)
417 		return (error);
418 	if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
419 		error = ESPIPE;
420 	else if (offset < 0 && fp->f_vnode->v_type != VCHR)
421 		error = EINVAL;
422 	else
423 		error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
424 	fdrop(fp, td);
425 	return (error);
426 }
427 
428 /*
429  * Common code for writev and pwritev that writes data to
430  * a file using the passed in uio, offset, and flags.
431  */
432 static int
433 dofilewrite(td, fd, fp, auio, offset, flags)
434 	struct thread *td;
435 	int fd;
436 	struct file *fp;
437 	struct uio *auio;
438 	off_t offset;
439 	int flags;
440 {
441 	ssize_t cnt;
442 	int error;
443 #ifdef KTRACE
444 	struct uio *ktruio = NULL;
445 #endif
446 
447 	auio->uio_rw = UIO_WRITE;
448 	auio->uio_td = td;
449 	auio->uio_offset = offset;
450 #ifdef KTRACE
451 	if (KTRPOINT(td, KTR_GENIO))
452 		ktruio = cloneuio(auio);
453 #endif
454 	cnt = auio->uio_resid;
455 	if (fp->f_type == DTYPE_VNODE)
456 		bwillwrite();
457 	if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
458 		if (auio->uio_resid != cnt && (error == ERESTART ||
459 		    error == EINTR || error == EWOULDBLOCK))
460 			error = 0;
461 		/* Socket layer is responsible for issuing SIGPIPE. */
462 		if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
463 			PROC_LOCK(td->td_proc);
464 			psignal(td->td_proc, SIGPIPE);
465 			PROC_UNLOCK(td->td_proc);
466 		}
467 	}
468 	cnt -= auio->uio_resid;
469 #ifdef KTRACE
470 	if (ktruio != NULL) {
471 		ktruio->uio_resid = cnt;
472 		ktrgenio(fd, UIO_WRITE, ktruio, error);
473 	}
474 #endif
475 	td->td_retval[0] = cnt;
476 	return (error);
477 }
478 
479 #ifndef _SYS_SYSPROTO_H_
480 struct ioctl_args {
481 	int	fd;
482 	u_long	com;
483 	caddr_t	data;
484 };
485 #endif
486 /* ARGSUSED */
487 int
488 ioctl(struct thread *td, struct ioctl_args *uap)
489 {
490 	u_long com;
491 	int arg, error;
492 	u_int size;
493 	caddr_t data;
494 
495 	if (uap->com > 0xffffffff) {
496 		printf(
497 		    "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
498 		    td->td_proc->p_pid, td->td_proc->p_comm, uap->com);
499 		uap->com &= 0xffffffff;
500 	}
501 	com = uap->com;
502 
503 	/*
504 	 * Interpret high order word to find amount of data to be
505 	 * copied to/from the user's address space.
506 	 */
507 	size = IOCPARM_LEN(com);
508 	if ((size > IOCPARM_MAX) ||
509 	    ((com & (IOC_VOID  | IOC_IN | IOC_OUT)) == 0) ||
510 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
511 	    ((com & IOC_OUT) && size == 0) ||
512 #else
513 	    ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
514 #endif
515 	    ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
516 		return (ENOTTY);
517 
518 	if (size > 0) {
519 		if (!(com & IOC_VOID))
520 			data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
521 		else {
522 			/* Integer argument. */
523 			arg = (intptr_t)uap->data;
524 			data = (void *)&arg;
525 			size = 0;
526 		}
527 	} else
528 		data = (void *)&uap->data;
529 	if (com & IOC_IN) {
530 		error = copyin(uap->data, data, (u_int)size);
531 		if (error) {
532 			if (size > 0)
533 				free(data, M_IOCTLOPS);
534 			return (error);
535 		}
536 	} else if (com & IOC_OUT) {
537 		/*
538 		 * Zero the buffer so the user always
539 		 * gets back something deterministic.
540 		 */
541 		bzero(data, size);
542 	}
543 
544 	error = kern_ioctl(td, uap->fd, com, data);
545 
546 	if (error == 0 && (com & IOC_OUT))
547 		error = copyout(data, uap->data, (u_int)size);
548 
549 	if (size > 0)
550 		free(data, M_IOCTLOPS);
551 	return (error);
552 }
553 
554 int
555 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
556 {
557 	struct file *fp;
558 	struct filedesc *fdp;
559 	int error;
560 	int tmp;
561 
562 	if ((error = fget(td, fd, &fp)) != 0)
563 		return (error);
564 	if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
565 		fdrop(fp, td);
566 		return (EBADF);
567 	}
568 	fdp = td->td_proc->p_fd;
569 	switch (com) {
570 	case FIONCLEX:
571 		FILEDESC_XLOCK(fdp);
572 		fdp->fd_ofileflags[fd] &= ~UF_EXCLOSE;
573 		FILEDESC_XUNLOCK(fdp);
574 		goto out;
575 	case FIOCLEX:
576 		FILEDESC_XLOCK(fdp);
577 		fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
578 		FILEDESC_XUNLOCK(fdp);
579 		goto out;
580 	case FIONBIO:
581 		FILE_LOCK(fp);
582 		if ((tmp = *(int *)data))
583 			fp->f_flag |= FNONBLOCK;
584 		else
585 			fp->f_flag &= ~FNONBLOCK;
586 		FILE_UNLOCK(fp);
587 		data = (void *)&tmp;
588 		break;
589 	case FIOASYNC:
590 		FILE_LOCK(fp);
591 		if ((tmp = *(int *)data))
592 			fp->f_flag |= FASYNC;
593 		else
594 			fp->f_flag &= ~FASYNC;
595 		FILE_UNLOCK(fp);
596 		data = (void *)&tmp;
597 		break;
598 	}
599 
600 	error = fo_ioctl(fp, com, data, td->td_ucred, td);
601 out:
602 	fdrop(fp, td);
603 	return (error);
604 }
605 
606 /*
607  * sellock and selwait are initialized in selectinit() via SYSINIT.
608  */
609 struct mtx	sellock;
610 struct cv	selwait;
611 u_int		nselcoll;	/* Select collisions since boot */
612 SYSCTL_UINT(_kern, OID_AUTO, nselcoll, CTLFLAG_RD, &nselcoll, 0, "");
613 
614 #ifndef _SYS_SYSPROTO_H_
615 struct select_args {
616 	int	nd;
617 	fd_set	*in, *ou, *ex;
618 	struct	timeval *tv;
619 };
620 #endif
621 int
622 select(td, uap)
623 	register struct thread *td;
624 	register struct select_args *uap;
625 {
626 	struct timeval tv, *tvp;
627 	int error;
628 
629 	if (uap->tv != NULL) {
630 		error = copyin(uap->tv, &tv, sizeof(tv));
631 		if (error)
632 			return (error);
633 		tvp = &tv;
634 	} else
635 		tvp = NULL;
636 
637 	return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp));
638 }
639 
640 int
641 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
642     fd_set *fd_ex, struct timeval *tvp)
643 {
644 	struct filedesc *fdp;
645 	/*
646 	 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
647 	 * infds with the new FD_SETSIZE of 1024, and more than enough for
648 	 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
649 	 * of 256.
650 	 */
651 	fd_mask s_selbits[howmany(2048, NFDBITS)];
652 	fd_mask *ibits[3], *obits[3], *selbits, *sbp;
653 	struct timeval atv, rtv, ttv;
654 	int error, timo;
655 	u_int ncoll, nbufbytes, ncpbytes, nfdbits;
656 
657 	if (nd < 0)
658 		return (EINVAL);
659 	fdp = td->td_proc->p_fd;
660 
661 	FILEDESC_SLOCK(fdp);
662 	if (nd > td->td_proc->p_fd->fd_nfiles)
663 		nd = td->td_proc->p_fd->fd_nfiles;   /* forgiving; slightly wrong */
664 	FILEDESC_SUNLOCK(fdp);
665 
666 	/*
667 	 * Allocate just enough bits for the non-null fd_sets.  Use the
668 	 * preallocated auto buffer if possible.
669 	 */
670 	nfdbits = roundup(nd, NFDBITS);
671 	ncpbytes = nfdbits / NBBY;
672 	nbufbytes = 0;
673 	if (fd_in != NULL)
674 		nbufbytes += 2 * ncpbytes;
675 	if (fd_ou != NULL)
676 		nbufbytes += 2 * ncpbytes;
677 	if (fd_ex != NULL)
678 		nbufbytes += 2 * ncpbytes;
679 	if (nbufbytes <= sizeof s_selbits)
680 		selbits = &s_selbits[0];
681 	else
682 		selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
683 
684 	/*
685 	 * Assign pointers into the bit buffers and fetch the input bits.
686 	 * Put the output buffers together so that they can be bzeroed
687 	 * together.
688 	 */
689 	sbp = selbits;
690 #define	getbits(name, x) \
691 	do {								\
692 		if (name == NULL)					\
693 			ibits[x] = NULL;				\
694 		else {							\
695 			ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp;	\
696 			obits[x] = sbp;					\
697 			sbp += ncpbytes / sizeof *sbp;			\
698 			error = copyin(name, ibits[x], ncpbytes);	\
699 			if (error != 0)					\
700 				goto done_nosellock;			\
701 		}							\
702 	} while (0)
703 	getbits(fd_in, 0);
704 	getbits(fd_ou, 1);
705 	getbits(fd_ex, 2);
706 #undef	getbits
707 	if (nbufbytes != 0)
708 		bzero(selbits, nbufbytes / 2);
709 
710 	if (tvp != NULL) {
711 		atv = *tvp;
712 		if (itimerfix(&atv)) {
713 			error = EINVAL;
714 			goto done_nosellock;
715 		}
716 		getmicrouptime(&rtv);
717 		timevaladd(&atv, &rtv);
718 	} else {
719 		atv.tv_sec = 0;
720 		atv.tv_usec = 0;
721 	}
722 	timo = 0;
723 	TAILQ_INIT(&td->td_selq);
724 	mtx_lock(&sellock);
725 retry:
726 	ncoll = nselcoll;
727 	mtx_lock_spin(&sched_lock);
728 	td->td_flags |= TDF_SELECT;
729 	mtx_unlock_spin(&sched_lock);
730 	mtx_unlock(&sellock);
731 
732 	error = selscan(td, ibits, obits, nd);
733 	mtx_lock(&sellock);
734 	if (error || td->td_retval[0])
735 		goto done;
736 	if (atv.tv_sec || atv.tv_usec) {
737 		getmicrouptime(&rtv);
738 		if (timevalcmp(&rtv, &atv, >=))
739 			goto done;
740 		ttv = atv;
741 		timevalsub(&ttv, &rtv);
742 		timo = ttv.tv_sec > 24 * 60 * 60 ?
743 		    24 * 60 * 60 * hz : tvtohz(&ttv);
744 	}
745 
746 	/*
747 	 * An event of interest may occur while we do not hold
748 	 * sellock, so check TDF_SELECT and the number of
749 	 * collisions and rescan the file descriptors if
750 	 * necessary.
751 	 */
752 	mtx_lock_spin(&sched_lock);
753 	if ((td->td_flags & TDF_SELECT) == 0 || nselcoll != ncoll) {
754 		mtx_unlock_spin(&sched_lock);
755 		goto retry;
756 	}
757 	mtx_unlock_spin(&sched_lock);
758 
759 	if (timo > 0)
760 		error = cv_timedwait_sig(&selwait, &sellock, timo);
761 	else
762 		error = cv_wait_sig(&selwait, &sellock);
763 
764 	if (error == 0)
765 		goto retry;
766 
767 done:
768 	clear_selinfo_list(td);
769 	mtx_lock_spin(&sched_lock);
770 	td->td_flags &= ~TDF_SELECT;
771 	mtx_unlock_spin(&sched_lock);
772 	mtx_unlock(&sellock);
773 
774 done_nosellock:
775 	/* select is not restarted after signals... */
776 	if (error == ERESTART)
777 		error = EINTR;
778 	if (error == EWOULDBLOCK)
779 		error = 0;
780 #define	putbits(name, x) \
781 	if (name && (error2 = copyout(obits[x], name, ncpbytes))) \
782 		error = error2;
783 	if (error == 0) {
784 		int error2;
785 
786 		putbits(fd_in, 0);
787 		putbits(fd_ou, 1);
788 		putbits(fd_ex, 2);
789 #undef putbits
790 	}
791 	if (selbits != &s_selbits[0])
792 		free(selbits, M_SELECT);
793 
794 	return (error);
795 }
796 
797 static int
798 selscan(td, ibits, obits, nfd)
799 	struct thread *td;
800 	fd_mask **ibits, **obits;
801 	int nfd;
802 {
803 	int msk, i, fd;
804 	fd_mask bits;
805 	struct file *fp;
806 	int n = 0;
807 	/* Note: backend also returns POLLHUP/POLLERR if appropriate. */
808 	static int flag[3] = { POLLRDNORM, POLLWRNORM, POLLRDBAND };
809 	struct filedesc *fdp = td->td_proc->p_fd;
810 
811 	FILEDESC_SLOCK(fdp);
812 	for (msk = 0; msk < 3; msk++) {
813 		if (ibits[msk] == NULL)
814 			continue;
815 		for (i = 0; i < nfd; i += NFDBITS) {
816 			bits = ibits[msk][i/NFDBITS];
817 			/* ffs(int mask) not portable, fd_mask is long */
818 			for (fd = i; bits && fd < nfd; fd++, bits >>= 1) {
819 				if (!(bits & 1))
820 					continue;
821 				if ((fp = fget_locked(fdp, fd)) == NULL) {
822 					FILEDESC_SUNLOCK(fdp);
823 					return (EBADF);
824 				}
825 				if (fo_poll(fp, flag[msk], td->td_ucred,
826 				    td)) {
827 					obits[msk][(fd)/NFDBITS] |=
828 					    ((fd_mask)1 << ((fd) % NFDBITS));
829 					n++;
830 				}
831 			}
832 		}
833 	}
834 	FILEDESC_SUNLOCK(fdp);
835 	td->td_retval[0] = n;
836 	return (0);
837 }
838 
839 #ifndef _SYS_SYSPROTO_H_
840 struct poll_args {
841 	struct pollfd *fds;
842 	u_int	nfds;
843 	int	timeout;
844 };
845 #endif
846 int
847 poll(td, uap)
848 	struct thread *td;
849 	struct poll_args *uap;
850 {
851 	struct pollfd *bits;
852 	struct pollfd smallbits[32];
853 	struct timeval atv, rtv, ttv;
854 	int error = 0, timo;
855 	u_int ncoll, nfds;
856 	size_t ni;
857 
858 	nfds = uap->nfds;
859 
860 	/*
861 	 * This is kinda bogus.  We have fd limits, but that is not
862 	 * really related to the size of the pollfd array.  Make sure
863 	 * we let the process use at least FD_SETSIZE entries and at
864 	 * least enough for the current limits.  We want to be reasonably
865 	 * safe, but not overly restrictive.
866 	 */
867 	PROC_LOCK(td->td_proc);
868 	if ((nfds > lim_cur(td->td_proc, RLIMIT_NOFILE)) &&
869 	    (nfds > FD_SETSIZE)) {
870 		PROC_UNLOCK(td->td_proc);
871 		error = EINVAL;
872 		goto done2;
873 	}
874 	PROC_UNLOCK(td->td_proc);
875 	ni = nfds * sizeof(struct pollfd);
876 	if (ni > sizeof(smallbits))
877 		bits = malloc(ni, M_TEMP, M_WAITOK);
878 	else
879 		bits = smallbits;
880 	error = copyin(uap->fds, bits, ni);
881 	if (error)
882 		goto done_nosellock;
883 	if (uap->timeout != INFTIM) {
884 		atv.tv_sec = uap->timeout / 1000;
885 		atv.tv_usec = (uap->timeout % 1000) * 1000;
886 		if (itimerfix(&atv)) {
887 			error = EINVAL;
888 			goto done_nosellock;
889 		}
890 		getmicrouptime(&rtv);
891 		timevaladd(&atv, &rtv);
892 	} else {
893 		atv.tv_sec = 0;
894 		atv.tv_usec = 0;
895 	}
896 	timo = 0;
897 	TAILQ_INIT(&td->td_selq);
898 	mtx_lock(&sellock);
899 retry:
900 	ncoll = nselcoll;
901 	mtx_lock_spin(&sched_lock);
902 	td->td_flags |= TDF_SELECT;
903 	mtx_unlock_spin(&sched_lock);
904 	mtx_unlock(&sellock);
905 
906 	error = pollscan(td, bits, nfds);
907 	mtx_lock(&sellock);
908 	if (error || td->td_retval[0])
909 		goto done;
910 	if (atv.tv_sec || atv.tv_usec) {
911 		getmicrouptime(&rtv);
912 		if (timevalcmp(&rtv, &atv, >=))
913 			goto done;
914 		ttv = atv;
915 		timevalsub(&ttv, &rtv);
916 		timo = ttv.tv_sec > 24 * 60 * 60 ?
917 		    24 * 60 * 60 * hz : tvtohz(&ttv);
918 	}
919 	/*
920 	 * An event of interest may occur while we do not hold
921 	 * sellock, so check TDF_SELECT and the number of collisions
922 	 * and rescan the file descriptors if necessary.
923 	 */
924 	mtx_lock_spin(&sched_lock);
925 	if ((td->td_flags & TDF_SELECT) == 0 || nselcoll != ncoll) {
926 		mtx_unlock_spin(&sched_lock);
927 		goto retry;
928 	}
929 	mtx_unlock_spin(&sched_lock);
930 
931 	if (timo > 0)
932 		error = cv_timedwait_sig(&selwait, &sellock, timo);
933 	else
934 		error = cv_wait_sig(&selwait, &sellock);
935 
936 	if (error == 0)
937 		goto retry;
938 
939 done:
940 	clear_selinfo_list(td);
941 	mtx_lock_spin(&sched_lock);
942 	td->td_flags &= ~TDF_SELECT;
943 	mtx_unlock_spin(&sched_lock);
944 	mtx_unlock(&sellock);
945 
946 done_nosellock:
947 	/* poll is not restarted after signals... */
948 	if (error == ERESTART)
949 		error = EINTR;
950 	if (error == EWOULDBLOCK)
951 		error = 0;
952 	if (error == 0) {
953 		error = copyout(bits, uap->fds, ni);
954 		if (error)
955 			goto out;
956 	}
957 out:
958 	if (ni > sizeof(smallbits))
959 		free(bits, M_TEMP);
960 done2:
961 	return (error);
962 }
963 
964 static int
965 pollscan(td, fds, nfd)
966 	struct thread *td;
967 	struct pollfd *fds;
968 	u_int nfd;
969 {
970 	register struct filedesc *fdp = td->td_proc->p_fd;
971 	int i;
972 	struct file *fp;
973 	int n = 0;
974 
975 	FILEDESC_SLOCK(fdp);
976 	for (i = 0; i < nfd; i++, fds++) {
977 		if (fds->fd >= fdp->fd_nfiles) {
978 			fds->revents = POLLNVAL;
979 			n++;
980 		} else if (fds->fd < 0) {
981 			fds->revents = 0;
982 		} else {
983 			fp = fdp->fd_ofiles[fds->fd];
984 			if (fp == NULL) {
985 				fds->revents = POLLNVAL;
986 				n++;
987 			} else {
988 				/*
989 				 * Note: backend also returns POLLHUP and
990 				 * POLLERR if appropriate.
991 				 */
992 				fds->revents = fo_poll(fp, fds->events,
993 				    td->td_ucred, td);
994 				if (fds->revents != 0)
995 					n++;
996 			}
997 		}
998 	}
999 	FILEDESC_SUNLOCK(fdp);
1000 	td->td_retval[0] = n;
1001 	return (0);
1002 }
1003 
1004 /*
1005  * OpenBSD poll system call.
1006  *
1007  * XXX this isn't quite a true representation..  OpenBSD uses select ops.
1008  */
1009 #ifndef _SYS_SYSPROTO_H_
1010 struct openbsd_poll_args {
1011 	struct pollfd *fds;
1012 	u_int	nfds;
1013 	int	timeout;
1014 };
1015 #endif
1016 int
1017 openbsd_poll(td, uap)
1018 	register struct thread *td;
1019 	register struct openbsd_poll_args *uap;
1020 {
1021 	return (poll(td, (struct poll_args *)uap));
1022 }
1023 
1024 /*
1025  * Remove the references to the thread from all of the objects we were
1026  * polling.
1027  *
1028  * This code assumes that the underlying owner of the selinfo structure will
1029  * hold sellock before it changes it, and that it will unlink itself from our
1030  * list if it goes away.
1031  */
1032 void
1033 clear_selinfo_list(td)
1034 	struct thread *td;
1035 {
1036 	struct selinfo *si;
1037 
1038 	mtx_assert(&sellock, MA_OWNED);
1039 	TAILQ_FOREACH(si, &td->td_selq, si_thrlist)
1040 		si->si_thread = NULL;
1041 	TAILQ_INIT(&td->td_selq);
1042 }
1043 
1044 /*
1045  * Record a select request.
1046  */
1047 void
1048 selrecord(selector, sip)
1049 	struct thread *selector;
1050 	struct selinfo *sip;
1051 {
1052 
1053 	mtx_lock(&sellock);
1054 	/*
1055 	 * If the selinfo's thread pointer is NULL then take ownership of it.
1056 	 *
1057 	 * If the thread pointer is not NULL and it points to another
1058 	 * thread, then we have a collision.
1059 	 *
1060 	 * If the thread pointer is not NULL and points back to us then leave
1061 	 * it alone as we've already added pointed it at us and added it to
1062 	 * our list.
1063 	 */
1064 	if (sip->si_thread == NULL) {
1065 		sip->si_thread = selector;
1066 		TAILQ_INSERT_TAIL(&selector->td_selq, sip, si_thrlist);
1067 	} else if (sip->si_thread != selector) {
1068 		sip->si_flags |= SI_COLL;
1069 	}
1070 
1071 	mtx_unlock(&sellock);
1072 }
1073 
1074 /* Wake up a selecting thread. */
1075 void
1076 selwakeup(sip)
1077 	struct selinfo *sip;
1078 {
1079 	doselwakeup(sip, -1);
1080 }
1081 
1082 /* Wake up a selecting thread, and set its priority. */
1083 void
1084 selwakeuppri(sip, pri)
1085 	struct selinfo *sip;
1086 	int pri;
1087 {
1088 	doselwakeup(sip, pri);
1089 }
1090 
1091 /*
1092  * Do a wakeup when a selectable event occurs.
1093  */
1094 static void
1095 doselwakeup(sip, pri)
1096 	struct selinfo *sip;
1097 	int pri;
1098 {
1099 	struct thread *td;
1100 
1101 	mtx_lock(&sellock);
1102 	td = sip->si_thread;
1103 	if ((sip->si_flags & SI_COLL) != 0) {
1104 		nselcoll++;
1105 		sip->si_flags &= ~SI_COLL;
1106 		cv_broadcastpri(&selwait, pri);
1107 	}
1108 	if (td == NULL) {
1109 		mtx_unlock(&sellock);
1110 		return;
1111 	}
1112 	TAILQ_REMOVE(&td->td_selq, sip, si_thrlist);
1113 	sip->si_thread = NULL;
1114 	mtx_lock_spin(&sched_lock);
1115 	td->td_flags &= ~TDF_SELECT;
1116 	mtx_unlock_spin(&sched_lock);
1117 	sleepq_remove(td, &selwait);
1118 	mtx_unlock(&sellock);
1119 }
1120 
1121 static void selectinit(void *);
1122 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, selectinit, NULL)
1123 
1124 /* ARGSUSED*/
1125 static void
1126 selectinit(dummy)
1127 	void *dummy;
1128 {
1129 	cv_init(&selwait, "select");
1130 	mtx_init(&sellock, "sellck", NULL, MTX_DEF);
1131 }
1132