sys_generic.c revision 177368
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: head/sys/kern/sys_generic.c 177368 2008-03-19 06:19:01Z jeff $");
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/ktr.h>
56#include <sys/limits.h>
57#include <sys/malloc.h>
58#include <sys/poll.h>
59#include <sys/resourcevar.h>
60#include <sys/selinfo.h>
61#include <sys/sleepqueue.h>
62#include <sys/syscallsubr.h>
63#include <sys/sysctl.h>
64#include <sys/sysent.h>
65#include <sys/vnode.h>
66#include <sys/bio.h>
67#include <sys/buf.h>
68#include <sys/condvar.h>
69#ifdef KTRACE
70#include <sys/ktrace.h>
71#endif
72
73#include <security/audit/audit.h>
74
75static MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
76static MALLOC_DEFINE(M_SELECT, "select", "select() buffer");
77MALLOC_DEFINE(M_IOV, "iov", "large iov's");
78
79static int	pollscan(struct thread *, struct pollfd *, u_int);
80static int	pollrescan(struct thread *);
81static int	selscan(struct thread *, fd_mask **, fd_mask **, int);
82static int	selrescan(struct thread *, fd_mask **, fd_mask **);
83static void	selfdalloc(struct thread *, void *);
84static void	selfdfree(struct seltd *, struct selfd *);
85static int	dofileread(struct thread *, int, struct file *, struct uio *,
86		    off_t, int);
87static int	dofilewrite(struct thread *, int, struct file *, struct uio *,
88		    off_t, int);
89static void	doselwakeup(struct selinfo *, int);
90static void	seltdinit(struct thread *);
91static int	seltdwait(struct thread *, int);
92static void	seltdclear(struct thread *);
93
94/*
95 * One seltd per-thread allocated on demand as needed.
96 *
97 *	t - protected by st_mtx
98 * 	k - Only accessed by curthread or read-only
99 */
100struct seltd {
101	STAILQ_HEAD(, selfd)	st_selq;	/* (k) List of selfds. */
102	struct selfd		*st_free1;	/* (k) free fd for read set. */
103	struct selfd		*st_free2;	/* (k) free fd for write set. */
104	struct mtx		st_mtx;		/* Protects struct seltd */
105	struct cv		st_wait;	/* (t) Wait channel. */
106	int			st_flags;	/* (t) SELTD_ flags. */
107};
108
109#define	SELTD_PENDING	0x0001			/* We have pending events. */
110#define	SELTD_RESCAN	0x0002			/* Doing a rescan. */
111
112/*
113 * One selfd allocated per-thread per-file-descriptor.
114 *	f - protected by sf_mtx
115 */
116struct selfd {
117	STAILQ_ENTRY(selfd)	sf_link;	/* (k) fds owned by this td. */
118	TAILQ_ENTRY(selfd)	sf_threads;	/* (f) fds on this selinfo. */
119	struct selinfo		*sf_si;		/* (f) selinfo when linked. */
120	struct mtx		*sf_mtx;	/* Pointer to selinfo mtx. */
121	struct seltd		*sf_td;		/* (k) owning seltd. */
122	void			*sf_cookie;	/* (k) fd or pollfd. */
123};
124
125static uma_zone_t selfd_zone;
126
127#ifndef _SYS_SYSPROTO_H_
128struct read_args {
129	int	fd;
130	void	*buf;
131	size_t	nbyte;
132};
133#endif
134int
135read(td, uap)
136	struct thread *td;
137	struct read_args *uap;
138{
139	struct uio auio;
140	struct iovec aiov;
141	int error;
142
143	if (uap->nbyte > INT_MAX)
144		return (EINVAL);
145	aiov.iov_base = uap->buf;
146	aiov.iov_len = uap->nbyte;
147	auio.uio_iov = &aiov;
148	auio.uio_iovcnt = 1;
149	auio.uio_resid = uap->nbyte;
150	auio.uio_segflg = UIO_USERSPACE;
151	error = kern_readv(td, uap->fd, &auio);
152	return(error);
153}
154
155/*
156 * Positioned read system call
157 */
158#ifndef _SYS_SYSPROTO_H_
159struct pread_args {
160	int	fd;
161	void	*buf;
162	size_t	nbyte;
163	int	pad;
164	off_t	offset;
165};
166#endif
167int
168pread(td, uap)
169	struct thread *td;
170	struct pread_args *uap;
171{
172	struct uio auio;
173	struct iovec aiov;
174	int error;
175
176	if (uap->nbyte > INT_MAX)
177		return (EINVAL);
178	aiov.iov_base = uap->buf;
179	aiov.iov_len = uap->nbyte;
180	auio.uio_iov = &aiov;
181	auio.uio_iovcnt = 1;
182	auio.uio_resid = uap->nbyte;
183	auio.uio_segflg = UIO_USERSPACE;
184	error = kern_preadv(td, uap->fd, &auio, uap->offset);
185	return(error);
186}
187
188int
189freebsd6_pread(td, uap)
190	struct thread *td;
191	struct freebsd6_pread_args *uap;
192{
193	struct pread_args oargs;
194
195	oargs.fd = uap->fd;
196	oargs.buf = uap->buf;
197	oargs.nbyte = uap->nbyte;
198	oargs.offset = uap->offset;
199	return (pread(td, &oargs));
200}
201
202/*
203 * Scatter read system call.
204 */
205#ifndef _SYS_SYSPROTO_H_
206struct readv_args {
207	int	fd;
208	struct	iovec *iovp;
209	u_int	iovcnt;
210};
211#endif
212int
213readv(struct thread *td, struct readv_args *uap)
214{
215	struct uio *auio;
216	int error;
217
218	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
219	if (error)
220		return (error);
221	error = kern_readv(td, uap->fd, auio);
222	free(auio, M_IOV);
223	return (error);
224}
225
226int
227kern_readv(struct thread *td, int fd, struct uio *auio)
228{
229	struct file *fp;
230	int error;
231
232	error = fget_read(td, fd, &fp);
233	if (error)
234		return (error);
235	error = dofileread(td, fd, fp, auio, (off_t)-1, 0);
236	fdrop(fp, td);
237	return (error);
238}
239
240/*
241 * Scatter positioned read system call.
242 */
243#ifndef _SYS_SYSPROTO_H_
244struct preadv_args {
245	int	fd;
246	struct	iovec *iovp;
247	u_int	iovcnt;
248	off_t	offset;
249};
250#endif
251int
252preadv(struct thread *td, struct preadv_args *uap)
253{
254	struct uio *auio;
255	int error;
256
257	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
258	if (error)
259		return (error);
260	error = kern_preadv(td, uap->fd, auio, uap->offset);
261	free(auio, M_IOV);
262	return (error);
263}
264
265int
266kern_preadv(td, fd, auio, offset)
267	struct thread *td;
268	int fd;
269	struct uio *auio;
270	off_t offset;
271{
272	struct file *fp;
273	int error;
274
275	error = fget_read(td, fd, &fp);
276	if (error)
277		return (error);
278	if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
279		error = ESPIPE;
280	else if (offset < 0 && fp->f_vnode->v_type != VCHR)
281		error = EINVAL;
282	else
283		error = dofileread(td, fd, fp, auio, offset, FOF_OFFSET);
284	fdrop(fp, td);
285	return (error);
286}
287
288/*
289 * Common code for readv and preadv that reads data in
290 * from a file using the passed in uio, offset, and flags.
291 */
292static int
293dofileread(td, fd, fp, auio, offset, flags)
294	struct thread *td;
295	int fd;
296	struct file *fp;
297	struct uio *auio;
298	off_t offset;
299	int flags;
300{
301	ssize_t cnt;
302	int error;
303#ifdef KTRACE
304	struct uio *ktruio = NULL;
305#endif
306
307	/* Finish zero length reads right here */
308	if (auio->uio_resid == 0) {
309		td->td_retval[0] = 0;
310		return(0);
311	}
312	auio->uio_rw = UIO_READ;
313	auio->uio_offset = offset;
314	auio->uio_td = td;
315#ifdef KTRACE
316	if (KTRPOINT(td, KTR_GENIO))
317		ktruio = cloneuio(auio);
318#endif
319	cnt = auio->uio_resid;
320	if ((error = fo_read(fp, auio, td->td_ucred, flags, td))) {
321		if (auio->uio_resid != cnt && (error == ERESTART ||
322		    error == EINTR || error == EWOULDBLOCK))
323			error = 0;
324	}
325	cnt -= auio->uio_resid;
326#ifdef KTRACE
327	if (ktruio != NULL) {
328		ktruio->uio_resid = cnt;
329		ktrgenio(fd, UIO_READ, ktruio, error);
330	}
331#endif
332	td->td_retval[0] = cnt;
333	return (error);
334}
335
336#ifndef _SYS_SYSPROTO_H_
337struct write_args {
338	int	fd;
339	const void *buf;
340	size_t	nbyte;
341};
342#endif
343int
344write(td, uap)
345	struct thread *td;
346	struct write_args *uap;
347{
348	struct uio auio;
349	struct iovec aiov;
350	int error;
351
352	if (uap->nbyte > INT_MAX)
353		return (EINVAL);
354	aiov.iov_base = (void *)(uintptr_t)uap->buf;
355	aiov.iov_len = uap->nbyte;
356	auio.uio_iov = &aiov;
357	auio.uio_iovcnt = 1;
358	auio.uio_resid = uap->nbyte;
359	auio.uio_segflg = UIO_USERSPACE;
360	error = kern_writev(td, uap->fd, &auio);
361	return(error);
362}
363
364/*
365 * Positioned write system call.
366 */
367#ifndef _SYS_SYSPROTO_H_
368struct pwrite_args {
369	int	fd;
370	const void *buf;
371	size_t	nbyte;
372	int	pad;
373	off_t	offset;
374};
375#endif
376int
377pwrite(td, uap)
378	struct thread *td;
379	struct pwrite_args *uap;
380{
381	struct uio auio;
382	struct iovec aiov;
383	int error;
384
385	if (uap->nbyte > INT_MAX)
386		return (EINVAL);
387	aiov.iov_base = (void *)(uintptr_t)uap->buf;
388	aiov.iov_len = uap->nbyte;
389	auio.uio_iov = &aiov;
390	auio.uio_iovcnt = 1;
391	auio.uio_resid = uap->nbyte;
392	auio.uio_segflg = UIO_USERSPACE;
393	error = kern_pwritev(td, uap->fd, &auio, uap->offset);
394	return(error);
395}
396
397int
398freebsd6_pwrite(td, uap)
399	struct thread *td;
400	struct freebsd6_pwrite_args *uap;
401{
402	struct pwrite_args oargs;
403
404	oargs.fd = uap->fd;
405	oargs.buf = uap->buf;
406	oargs.nbyte = uap->nbyte;
407	oargs.offset = uap->offset;
408	return (pwrite(td, &oargs));
409}
410
411/*
412 * Gather write system call.
413 */
414#ifndef _SYS_SYSPROTO_H_
415struct writev_args {
416	int	fd;
417	struct	iovec *iovp;
418	u_int	iovcnt;
419};
420#endif
421int
422writev(struct thread *td, struct writev_args *uap)
423{
424	struct uio *auio;
425	int error;
426
427	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
428	if (error)
429		return (error);
430	error = kern_writev(td, uap->fd, auio);
431	free(auio, M_IOV);
432	return (error);
433}
434
435int
436kern_writev(struct thread *td, int fd, struct uio *auio)
437{
438	struct file *fp;
439	int error;
440
441	error = fget_write(td, fd, &fp);
442	if (error)
443		return (error);
444	error = dofilewrite(td, fd, fp, auio, (off_t)-1, 0);
445	fdrop(fp, td);
446	return (error);
447}
448
449/*
450 * Gather positioned write system call.
451 */
452#ifndef _SYS_SYSPROTO_H_
453struct pwritev_args {
454	int	fd;
455	struct	iovec *iovp;
456	u_int	iovcnt;
457	off_t	offset;
458};
459#endif
460int
461pwritev(struct thread *td, struct pwritev_args *uap)
462{
463	struct uio *auio;
464	int error;
465
466	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
467	if (error)
468		return (error);
469	error = kern_pwritev(td, uap->fd, auio, uap->offset);
470	free(auio, M_IOV);
471	return (error);
472}
473
474int
475kern_pwritev(td, fd, auio, offset)
476	struct thread *td;
477	struct uio *auio;
478	int fd;
479	off_t offset;
480{
481	struct file *fp;
482	int error;
483
484	error = fget_write(td, fd, &fp);
485	if (error)
486		return (error);
487	if (!(fp->f_ops->fo_flags & DFLAG_SEEKABLE))
488		error = ESPIPE;
489	else if (offset < 0 && fp->f_vnode->v_type != VCHR)
490		error = EINVAL;
491	else
492		error = dofilewrite(td, fd, fp, auio, offset, FOF_OFFSET);
493	fdrop(fp, td);
494	return (error);
495}
496
497/*
498 * Common code for writev and pwritev that writes data to
499 * a file using the passed in uio, offset, and flags.
500 */
501static int
502dofilewrite(td, fd, fp, auio, offset, flags)
503	struct thread *td;
504	int fd;
505	struct file *fp;
506	struct uio *auio;
507	off_t offset;
508	int flags;
509{
510	ssize_t cnt;
511	int error;
512#ifdef KTRACE
513	struct uio *ktruio = NULL;
514#endif
515
516	auio->uio_rw = UIO_WRITE;
517	auio->uio_td = td;
518	auio->uio_offset = offset;
519#ifdef KTRACE
520	if (KTRPOINT(td, KTR_GENIO))
521		ktruio = cloneuio(auio);
522#endif
523	cnt = auio->uio_resid;
524	if (fp->f_type == DTYPE_VNODE)
525		bwillwrite();
526	if ((error = fo_write(fp, auio, td->td_ucred, flags, td))) {
527		if (auio->uio_resid != cnt && (error == ERESTART ||
528		    error == EINTR || error == EWOULDBLOCK))
529			error = 0;
530		/* Socket layer is responsible for issuing SIGPIPE. */
531		if (fp->f_type != DTYPE_SOCKET && error == EPIPE) {
532			PROC_LOCK(td->td_proc);
533			psignal(td->td_proc, SIGPIPE);
534			PROC_UNLOCK(td->td_proc);
535		}
536	}
537	cnt -= auio->uio_resid;
538#ifdef KTRACE
539	if (ktruio != NULL) {
540		ktruio->uio_resid = cnt;
541		ktrgenio(fd, UIO_WRITE, ktruio, error);
542	}
543#endif
544	td->td_retval[0] = cnt;
545	return (error);
546}
547
548/*
549 * Truncate a file given a file descriptor.
550 *
551 * Can't use fget_write() here, since must return EINVAL and not EBADF if the
552 * descriptor isn't writable.
553 */
554int
555kern_ftruncate(td, fd, length)
556	struct thread *td;
557	int fd;
558	off_t length;
559{
560	struct file *fp;
561	int error;
562
563	AUDIT_ARG(fd, fd);
564	if (length < 0)
565		return (EINVAL);
566	error = fget(td, fd, &fp);
567	if (error)
568		return (error);
569	AUDIT_ARG(file, td->td_proc, fp);
570	if (!(fp->f_flag & FWRITE)) {
571		fdrop(fp, td);
572		return (EINVAL);
573	}
574	error = fo_truncate(fp, length, td->td_ucred, td);
575	fdrop(fp, td);
576	return (error);
577}
578
579#ifndef _SYS_SYSPROTO_H_
580struct ftruncate_args {
581	int	fd;
582	int	pad;
583	off_t	length;
584};
585#endif
586int
587ftruncate(td, uap)
588	struct thread *td;
589	struct ftruncate_args *uap;
590{
591
592	return (kern_ftruncate(td, uap->fd, uap->length));
593}
594
595#if defined(COMPAT_43)
596#ifndef _SYS_SYSPROTO_H_
597struct oftruncate_args {
598	int	fd;
599	long	length;
600};
601#endif
602int
603oftruncate(td, uap)
604	struct thread *td;
605	struct oftruncate_args *uap;
606{
607
608	return (kern_ftruncate(td, uap->fd, uap->length));
609}
610#endif /* COMPAT_43 */
611
612#ifndef _SYS_SYSPROTO_H_
613struct ioctl_args {
614	int	fd;
615	u_long	com;
616	caddr_t	data;
617};
618#endif
619/* ARGSUSED */
620int
621ioctl(struct thread *td, struct ioctl_args *uap)
622{
623	u_long com;
624	int arg, error;
625	u_int size;
626	caddr_t data;
627
628	if (uap->com > 0xffffffff) {
629		printf(
630		    "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
631		    td->td_proc->p_pid, td->td_name, uap->com);
632		uap->com &= 0xffffffff;
633	}
634	com = uap->com;
635
636	/*
637	 * Interpret high order word to find amount of data to be
638	 * copied to/from the user's address space.
639	 */
640	size = IOCPARM_LEN(com);
641	if ((size > IOCPARM_MAX) ||
642	    ((com & (IOC_VOID  | IOC_IN | IOC_OUT)) == 0) ||
643#if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
644	    ((com & IOC_OUT) && size == 0) ||
645#else
646	    ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
647#endif
648	    ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
649		return (ENOTTY);
650
651	if (size > 0) {
652		if (!(com & IOC_VOID))
653			data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
654		else {
655			/* Integer argument. */
656			arg = (intptr_t)uap->data;
657			data = (void *)&arg;
658			size = 0;
659		}
660	} else
661		data = (void *)&uap->data;
662	if (com & IOC_IN) {
663		error = copyin(uap->data, data, (u_int)size);
664		if (error) {
665			if (size > 0)
666				free(data, M_IOCTLOPS);
667			return (error);
668		}
669	} else if (com & IOC_OUT) {
670		/*
671		 * Zero the buffer so the user always
672		 * gets back something deterministic.
673		 */
674		bzero(data, size);
675	}
676
677	error = kern_ioctl(td, uap->fd, com, data);
678
679	if (error == 0 && (com & IOC_OUT))
680		error = copyout(data, uap->data, (u_int)size);
681
682	if (size > 0)
683		free(data, M_IOCTLOPS);
684	return (error);
685}
686
687int
688kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
689{
690	struct file *fp;
691	struct filedesc *fdp;
692	int error;
693	int tmp;
694
695	if ((error = fget(td, fd, &fp)) != 0)
696		return (error);
697	if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
698		fdrop(fp, td);
699		return (EBADF);
700	}
701	fdp = td->td_proc->p_fd;
702	switch (com) {
703	case FIONCLEX:
704		FILEDESC_XLOCK(fdp);
705		fdp->fd_ofileflags[fd] &= ~UF_EXCLOSE;
706		FILEDESC_XUNLOCK(fdp);
707		goto out;
708	case FIOCLEX:
709		FILEDESC_XLOCK(fdp);
710		fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
711		FILEDESC_XUNLOCK(fdp);
712		goto out;
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		data = (void *)&tmp;
719		break;
720	case FIOASYNC:
721		if ((tmp = *(int *)data))
722			atomic_set_int(&fp->f_flag, FASYNC);
723		else
724			atomic_clear_int(&fp->f_flag, FASYNC);
725		data = (void *)&tmp;
726		break;
727	}
728
729	error = fo_ioctl(fp, com, data, td->td_ucred, td);
730out:
731	fdrop(fp, td);
732	return (error);
733}
734
735#ifndef _SYS_SYSPROTO_H_
736struct select_args {
737	int	nd;
738	fd_set	*in, *ou, *ex;
739	struct	timeval *tv;
740};
741#endif
742int
743select(td, uap)
744	register struct thread *td;
745	register struct select_args *uap;
746{
747	struct timeval tv, *tvp;
748	int error;
749
750	if (uap->tv != NULL) {
751		error = copyin(uap->tv, &tv, sizeof(tv));
752		if (error)
753			return (error);
754		tvp = &tv;
755	} else
756		tvp = NULL;
757
758	return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp));
759}
760
761int
762kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
763    fd_set *fd_ex, struct timeval *tvp)
764{
765	struct filedesc *fdp;
766	/*
767	 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
768	 * infds with the new FD_SETSIZE of 1024, and more than enough for
769	 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
770	 * of 256.
771	 */
772	fd_mask s_selbits[howmany(2048, NFDBITS)];
773	fd_mask *ibits[3], *obits[3], *selbits, *sbp;
774	struct timeval atv, rtv, ttv;
775	int error, timo;
776	u_int nbufbytes, ncpbytes, nfdbits;
777
778	if (nd < 0)
779		return (EINVAL);
780	fdp = td->td_proc->p_fd;
781
782	FILEDESC_SLOCK(fdp);
783	if (nd > td->td_proc->p_fd->fd_nfiles)
784		nd = td->td_proc->p_fd->fd_nfiles;   /* forgiving; slightly wrong */
785	FILEDESC_SUNLOCK(fdp);
786
787	/*
788	 * Allocate just enough bits for the non-null fd_sets.  Use the
789	 * preallocated auto buffer if possible.
790	 */
791	nfdbits = roundup(nd, NFDBITS);
792	ncpbytes = nfdbits / NBBY;
793	nbufbytes = 0;
794	if (fd_in != NULL)
795		nbufbytes += 2 * ncpbytes;
796	if (fd_ou != NULL)
797		nbufbytes += 2 * ncpbytes;
798	if (fd_ex != NULL)
799		nbufbytes += 2 * ncpbytes;
800	if (nbufbytes <= sizeof s_selbits)
801		selbits = &s_selbits[0];
802	else
803		selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
804
805	/*
806	 * Assign pointers into the bit buffers and fetch the input bits.
807	 * Put the output buffers together so that they can be bzeroed
808	 * together.
809	 */
810	sbp = selbits;
811#define	getbits(name, x) \
812	do {								\
813		if (name == NULL)					\
814			ibits[x] = NULL;				\
815		else {							\
816			ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp;	\
817			obits[x] = sbp;					\
818			sbp += ncpbytes / sizeof *sbp;			\
819			error = copyin(name, ibits[x], ncpbytes);	\
820			if (error != 0)					\
821				goto done;				\
822		}							\
823	} while (0)
824	getbits(fd_in, 0);
825	getbits(fd_ou, 1);
826	getbits(fd_ex, 2);
827#undef	getbits
828	if (nbufbytes != 0)
829		bzero(selbits, nbufbytes / 2);
830
831	if (tvp != NULL) {
832		atv = *tvp;
833		if (itimerfix(&atv)) {
834			error = EINVAL;
835			goto done;
836		}
837		getmicrouptime(&rtv);
838		timevaladd(&atv, &rtv);
839	} else {
840		atv.tv_sec = 0;
841		atv.tv_usec = 0;
842	}
843	timo = 0;
844	seltdinit(td);
845	/* Iterate until the timeout expires or descriptors become ready. */
846	for (;;) {
847		error = selscan(td, ibits, obits, nd);
848		if (error || td->td_retval[0] != 0)
849			break;
850		if (atv.tv_sec || atv.tv_usec) {
851			getmicrouptime(&rtv);
852			if (timevalcmp(&rtv, &atv, >=))
853				break;
854			ttv = atv;
855			timevalsub(&ttv, &rtv);
856			timo = ttv.tv_sec > 24 * 60 * 60 ?
857			    24 * 60 * 60 * hz : tvtohz(&ttv);
858		}
859		error = seltdwait(td, timo);
860		if (error)
861			break;
862		error = selrescan(td, ibits, obits);
863		if (error || td->td_retval[0] != 0)
864			break;
865	}
866	seltdclear(td);
867
868done:
869	/* select is not restarted after signals... */
870	if (error == ERESTART)
871		error = EINTR;
872	if (error == EWOULDBLOCK)
873		error = 0;
874#define	putbits(name, x) \
875	if (name && (error2 = copyout(obits[x], name, ncpbytes))) \
876		error = error2;
877	if (error == 0) {
878		int error2;
879
880		putbits(fd_in, 0);
881		putbits(fd_ou, 1);
882		putbits(fd_ex, 2);
883#undef putbits
884	}
885	if (selbits != &s_selbits[0])
886		free(selbits, M_SELECT);
887
888	return (error);
889}
890
891/*
892 * Traverse the list of fds attached to this thread's seltd and check for
893 * completion.
894 */
895static int
896selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
897{
898	struct seltd *stp;
899	struct selfd *sfp;
900	struct selfd *sfn;
901	struct selinfo *si;
902	struct file *fp;
903	int msk, fd;
904	int n = 0;
905	/* Note: backend also returns POLLHUP/POLLERR if appropriate. */
906	static int flag[3] = { POLLRDNORM, POLLWRNORM, POLLRDBAND };
907	struct filedesc *fdp = td->td_proc->p_fd;
908
909	stp = td->td_sel;
910	FILEDESC_SLOCK(fdp);
911	STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
912		fd = (int)(uintptr_t)sfp->sf_cookie;
913		si = sfp->sf_si;
914		selfdfree(stp, sfp);
915		/* If the selinfo wasn't cleared the event didn't fire. */
916		if (si != NULL)
917			continue;
918		if ((fp = fget_locked(fdp, fd)) == NULL) {
919			FILEDESC_SUNLOCK(fdp);
920			return (EBADF);
921		}
922		for (msk = 0; msk < 3; msk++) {
923			if (ibits[msk] == NULL)
924				continue;
925			if ((ibits[msk][fd/NFDBITS] &
926			    ((fd_mask) 1 << (fd % NFDBITS))) == 0)
927				continue;
928			if (fo_poll(fp, flag[msk], td->td_ucred, td)) {
929				obits[msk][(fd)/NFDBITS] |=
930				    ((fd_mask)1 << ((fd) % NFDBITS));
931				n++;
932			}
933		}
934	}
935	FILEDESC_SUNLOCK(fdp);
936	stp->st_flags = 0;
937	td->td_retval[0] = n;
938	return (0);
939}
940
941/*
942 * Perform the initial filedescriptor scan and register ourselves with
943 * each selinfo.
944 */
945static int
946selscan(td, ibits, obits, nfd)
947	struct thread *td;
948	fd_mask **ibits, **obits;
949	int nfd;
950{
951	int msk, i, fd;
952	fd_mask bits;
953	struct file *fp;
954	int n = 0;
955	/* Note: backend also returns POLLHUP/POLLERR if appropriate. */
956	static int flag[3] = { POLLRDNORM, POLLWRNORM, POLLRDBAND };
957	struct filedesc *fdp = td->td_proc->p_fd;
958
959	FILEDESC_SLOCK(fdp);
960	for (msk = 0; msk < 3; msk++) {
961		if (ibits[msk] == NULL)
962			continue;
963		for (i = 0; i < nfd; i += NFDBITS) {
964			bits = ibits[msk][i/NFDBITS];
965			/* ffs(int mask) not portable, fd_mask is long */
966			for (fd = i; bits && fd < nfd; fd++, bits >>= 1) {
967				if (!(bits & 1))
968					continue;
969				if ((fp = fget_locked(fdp, fd)) == NULL) {
970					FILEDESC_SUNLOCK(fdp);
971					return (EBADF);
972				}
973				selfdalloc(td, (void *)(uintptr_t)fd);
974				if (fo_poll(fp, flag[msk], td->td_ucred,
975				    td)) {
976					obits[msk][(fd)/NFDBITS] |=
977					    ((fd_mask)1 << ((fd) % NFDBITS));
978					n++;
979				}
980			}
981		}
982	}
983	FILEDESC_SUNLOCK(fdp);
984	td->td_retval[0] = n;
985	return (0);
986}
987
988#ifndef _SYS_SYSPROTO_H_
989struct poll_args {
990	struct pollfd *fds;
991	u_int	nfds;
992	int	timeout;
993};
994#endif
995int
996poll(td, uap)
997	struct thread *td;
998	struct poll_args *uap;
999{
1000	struct pollfd *bits;
1001	struct pollfd smallbits[32];
1002	struct timeval atv, rtv, ttv;
1003	int error = 0, timo;
1004	u_int nfds;
1005	size_t ni;
1006
1007	nfds = uap->nfds;
1008
1009	/*
1010	 * This is kinda bogus.  We have fd limits, but that is not
1011	 * really related to the size of the pollfd array.  Make sure
1012	 * we let the process use at least FD_SETSIZE entries and at
1013	 * least enough for the current limits.  We want to be reasonably
1014	 * safe, but not overly restrictive.
1015	 */
1016	if (nfds > maxfilesperproc && nfds > FD_SETSIZE)
1017		return (EINVAL);
1018	ni = nfds * sizeof(struct pollfd);
1019	if (ni > sizeof(smallbits))
1020		bits = malloc(ni, M_TEMP, M_WAITOK);
1021	else
1022		bits = smallbits;
1023	error = copyin(uap->fds, bits, ni);
1024	if (error)
1025		goto done;
1026	if (uap->timeout != INFTIM) {
1027		atv.tv_sec = uap->timeout / 1000;
1028		atv.tv_usec = (uap->timeout % 1000) * 1000;
1029		if (itimerfix(&atv)) {
1030			error = EINVAL;
1031			goto done;
1032		}
1033		getmicrouptime(&rtv);
1034		timevaladd(&atv, &rtv);
1035	} else {
1036		atv.tv_sec = 0;
1037		atv.tv_usec = 0;
1038	}
1039	timo = 0;
1040	seltdinit(td);
1041	/* Iterate until the timeout expires or descriptors become ready. */
1042	for (;;) {
1043		error = pollscan(td, bits, nfds);
1044		if (error || td->td_retval[0] != 0)
1045			break;
1046		if (atv.tv_sec || atv.tv_usec) {
1047			getmicrouptime(&rtv);
1048			if (timevalcmp(&rtv, &atv, >=))
1049				break;
1050			ttv = atv;
1051			timevalsub(&ttv, &rtv);
1052			timo = ttv.tv_sec > 24 * 60 * 60 ?
1053			    24 * 60 * 60 * hz : tvtohz(&ttv);
1054		}
1055		error = seltdwait(td, timo);
1056		if (error)
1057			break;
1058		error = pollrescan(td);
1059		if (error || td->td_retval[0] != 0)
1060			break;
1061	}
1062	seltdclear(td);
1063
1064done:
1065	/* poll is not restarted after signals... */
1066	if (error == ERESTART)
1067		error = EINTR;
1068	if (error == EWOULDBLOCK)
1069		error = 0;
1070	if (error == 0) {
1071		error = copyout(bits, uap->fds, ni);
1072		if (error)
1073			goto out;
1074	}
1075out:
1076	if (ni > sizeof(smallbits))
1077		free(bits, M_TEMP);
1078	return (error);
1079}
1080
1081static int
1082pollrescan(struct thread *td)
1083{
1084	struct seltd *stp;
1085	struct selfd *sfp;
1086	struct selfd *sfn;
1087	struct selinfo *si;
1088	struct filedesc *fdp;
1089	struct file *fp;
1090	struct pollfd *fd;
1091	int n;
1092
1093	n = 0;
1094	fdp = td->td_proc->p_fd;
1095	stp = td->td_sel;
1096	FILEDESC_SLOCK(fdp);
1097	STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1098		fd = (struct pollfd *)sfp->sf_cookie;
1099		si = sfp->sf_si;
1100		selfdfree(stp, sfp);
1101		/* If the selinfo wasn't cleared the event didn't fire. */
1102		if (si != NULL)
1103			continue;
1104		fp = fdp->fd_ofiles[fd->fd];
1105		if (fp == NULL) {
1106			fd->revents = POLLNVAL;
1107			n++;
1108			continue;
1109		}
1110		/*
1111		 * Note: backend also returns POLLHUP and
1112		 * POLLERR if appropriate.
1113		 */
1114		fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1115		if (fd->revents != 0)
1116			n++;
1117	}
1118	FILEDESC_SUNLOCK(fdp);
1119	stp->st_flags = 0;
1120	td->td_retval[0] = n;
1121	return (0);
1122}
1123
1124
1125static int
1126pollscan(td, fds, nfd)
1127	struct thread *td;
1128	struct pollfd *fds;
1129	u_int nfd;
1130{
1131	struct filedesc *fdp = td->td_proc->p_fd;
1132	int i;
1133	struct file *fp;
1134	int n = 0;
1135
1136	FILEDESC_SLOCK(fdp);
1137	for (i = 0; i < nfd; i++, fds++) {
1138		if (fds->fd >= fdp->fd_nfiles) {
1139			fds->revents = POLLNVAL;
1140			n++;
1141		} else if (fds->fd < 0) {
1142			fds->revents = 0;
1143		} else {
1144			fp = fdp->fd_ofiles[fds->fd];
1145			if (fp == NULL) {
1146				fds->revents = POLLNVAL;
1147				n++;
1148			} else {
1149				/*
1150				 * Note: backend also returns POLLHUP and
1151				 * POLLERR if appropriate.
1152				 */
1153				selfdalloc(td, fds);
1154				fds->revents = fo_poll(fp, fds->events,
1155				    td->td_ucred, td);
1156				if (fds->revents != 0)
1157					n++;
1158			}
1159		}
1160	}
1161	FILEDESC_SUNLOCK(fdp);
1162	td->td_retval[0] = n;
1163	return (0);
1164}
1165
1166/*
1167 * OpenBSD poll system call.
1168 *
1169 * XXX this isn't quite a true representation..  OpenBSD uses select ops.
1170 */
1171#ifndef _SYS_SYSPROTO_H_
1172struct openbsd_poll_args {
1173	struct pollfd *fds;
1174	u_int	nfds;
1175	int	timeout;
1176};
1177#endif
1178int
1179openbsd_poll(td, uap)
1180	register struct thread *td;
1181	register struct openbsd_poll_args *uap;
1182{
1183	return (poll(td, (struct poll_args *)uap));
1184}
1185
1186/*
1187 * XXX This was created specifically to support netncp and netsmb.  This
1188 * allows the caller to specify a socket to wait for events on.  It returns
1189 * 0 if any events matched and an error otherwise.  There is no way to
1190 * determine which events fired.
1191 */
1192int
1193selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1194{
1195	struct timeval atv, rtv, ttv;
1196	int error, timo;
1197
1198	if (tvp != NULL) {
1199		atv = *tvp;
1200		if (itimerfix(&atv))
1201			return (EINVAL);
1202		getmicrouptime(&rtv);
1203		timevaladd(&atv, &rtv);
1204	} else {
1205		atv.tv_sec = 0;
1206		atv.tv_usec = 0;
1207	}
1208
1209	timo = 0;
1210	seltdinit(td);
1211	/*
1212	 * Iterate until the timeout expires or the socket becomes ready.
1213	 */
1214	for (;;) {
1215		selfdalloc(td, NULL);
1216		error = sopoll(so, events, NULL, td);
1217		/* error here is actually the ready events. */
1218		if (error)
1219			return (0);
1220		if (atv.tv_sec || atv.tv_usec) {
1221			getmicrouptime(&rtv);
1222			if (timevalcmp(&rtv, &atv, >=)) {
1223				seltdclear(td);
1224				return (EWOULDBLOCK);
1225			}
1226			ttv = atv;
1227			timevalsub(&ttv, &rtv);
1228			timo = ttv.tv_sec > 24 * 60 * 60 ?
1229			    24 * 60 * 60 * hz : tvtohz(&ttv);
1230		}
1231		error = seltdwait(td, timo);
1232		seltdclear(td);
1233		if (error)
1234			break;
1235	}
1236	/* XXX Duplicates ncp/smb behavior. */
1237	if (error == ERESTART)
1238		error = 0;
1239	return (error);
1240}
1241
1242/*
1243 * Preallocate two selfds associated with 'cookie'.  Some fo_poll routines
1244 * have two select sets, one for read and another for write.
1245 */
1246static void
1247selfdalloc(struct thread *td, void *cookie)
1248{
1249	struct seltd *stp;
1250
1251	stp = td->td_sel;
1252	if (stp->st_free1 == NULL)
1253		stp->st_free1 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1254	stp->st_free1->sf_td = stp;
1255	stp->st_free1->sf_cookie = cookie;
1256	if (stp->st_free2 == NULL)
1257		stp->st_free2 = uma_zalloc(selfd_zone, M_WAITOK|M_ZERO);
1258	stp->st_free2->sf_td = stp;
1259	stp->st_free2->sf_cookie = cookie;
1260}
1261
1262static void
1263selfdfree(struct seltd *stp, struct selfd *sfp)
1264{
1265	STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1266	mtx_lock(sfp->sf_mtx);
1267	if (sfp->sf_si)
1268		TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1269	mtx_unlock(sfp->sf_mtx);
1270	uma_zfree(selfd_zone, sfp);
1271}
1272
1273/*
1274 * Record a select request.
1275 */
1276void
1277selrecord(selector, sip)
1278	struct thread *selector;
1279	struct selinfo *sip;
1280{
1281	struct selfd *sfp;
1282	struct seltd *stp;
1283	struct mtx *mtxp;
1284
1285	stp = selector->td_sel;
1286	/*
1287	 * Don't record when doing a rescan.
1288	 */
1289	if (stp->st_flags & SELTD_RESCAN)
1290		return;
1291	/*
1292	 * Grab one of the preallocated descriptors.
1293	 */
1294	sfp = NULL;
1295	if ((sfp = stp->st_free1) != NULL)
1296		stp->st_free1 = NULL;
1297	else if ((sfp = stp->st_free2) != NULL)
1298		stp->st_free2 = NULL;
1299	else
1300		panic("selrecord: No free selfd on selq");
1301	mtxp = mtx_pool_find(mtxpool_sleep, sip);
1302	/*
1303	 * Initialize the sfp and queue it in the thread.
1304	 */
1305	sfp->sf_si = sip;
1306	sfp->sf_mtx = mtxp;
1307	STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1308	/*
1309	 * Now that we've locked the sip, check for initialization.
1310	 */
1311	mtx_lock(mtxp);
1312	if (sip->si_mtx == NULL) {
1313		sip->si_mtx = mtxp;
1314		TAILQ_INIT(&sip->si_tdlist);
1315	}
1316	/*
1317	 * Add this thread to the list of selfds listening on this selinfo.
1318	 */
1319	TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1320	mtx_unlock(sip->si_mtx);
1321}
1322
1323/* Wake up a selecting thread. */
1324void
1325selwakeup(sip)
1326	struct selinfo *sip;
1327{
1328	doselwakeup(sip, -1);
1329}
1330
1331/* Wake up a selecting thread, and set its priority. */
1332void
1333selwakeuppri(sip, pri)
1334	struct selinfo *sip;
1335	int pri;
1336{
1337	doselwakeup(sip, pri);
1338}
1339
1340/*
1341 * Do a wakeup when a selectable event occurs.
1342 */
1343static void
1344doselwakeup(sip, pri)
1345	struct selinfo *sip;
1346	int pri;
1347{
1348	struct selfd *sfp;
1349	struct selfd *sfn;
1350	struct seltd *stp;
1351
1352	/* If it's not initialized there can't be any waiters. */
1353	if (sip->si_mtx == NULL)
1354		return;
1355	/*
1356	 * Locking the selinfo locks all selfds associated with it.
1357	 */
1358	mtx_lock(sip->si_mtx);
1359	TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1360		/*
1361		 * Once we remove this sfp from the list and clear the
1362		 * sf_si seltdclear will know to ignore this si.
1363		 */
1364		TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1365		sfp->sf_si = NULL;
1366		stp = sfp->sf_td;
1367		mtx_lock(&stp->st_mtx);
1368		stp->st_flags |= SELTD_PENDING;
1369		cv_broadcastpri(&stp->st_wait, pri);
1370		mtx_unlock(&stp->st_mtx);
1371	}
1372	mtx_unlock(sip->si_mtx);
1373}
1374
1375static void
1376seltdinit(struct thread *td)
1377{
1378	struct seltd *stp;
1379
1380	if ((stp = td->td_sel) != NULL)
1381		goto out;
1382	td->td_sel = stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1383	mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1384	cv_init(&stp->st_wait, "select");
1385out:
1386	stp->st_flags = 0;
1387	STAILQ_INIT(&stp->st_selq);
1388}
1389
1390static int
1391seltdwait(struct thread *td, int timo)
1392{
1393	struct seltd *stp;
1394	int error;
1395
1396	stp = td->td_sel;
1397	/*
1398	 * An event of interest may occur while we do not hold the seltd
1399	 * locked so check the pending flag before we sleep.
1400	 */
1401	mtx_lock(&stp->st_mtx);
1402	/*
1403	 * Any further calls to selrecord will be a rescan.
1404	 */
1405	stp->st_flags |= SELTD_RESCAN;
1406	if (stp->st_flags & SELTD_PENDING) {
1407		mtx_unlock(&stp->st_mtx);
1408		return (0);
1409	}
1410	if (timo > 0)
1411		error = cv_timedwait_sig(&stp->st_wait, &stp->st_mtx, timo);
1412	else
1413		error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
1414	mtx_unlock(&stp->st_mtx);
1415
1416	return (error);
1417}
1418
1419void
1420seltdfini(struct thread *td)
1421{
1422	struct seltd *stp;
1423
1424	stp = td->td_sel;
1425	if (stp == NULL)
1426		return;
1427	if (stp->st_free1)
1428		uma_zfree(selfd_zone, stp->st_free1);
1429	if (stp->st_free2)
1430		uma_zfree(selfd_zone, stp->st_free2);
1431	td->td_sel = NULL;
1432	free(stp, M_SELECT);
1433}
1434
1435/*
1436 * Remove the references to the thread from all of the objects we were
1437 * polling.
1438 */
1439static void
1440seltdclear(struct thread *td)
1441{
1442	struct seltd *stp;
1443	struct selfd *sfp;
1444	struct selfd *sfn;
1445
1446	stp = td->td_sel;
1447	STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
1448		selfdfree(stp, sfp);
1449	stp->st_flags = 0;
1450}
1451
1452static void selectinit(void *);
1453SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
1454static void
1455selectinit(void *dummy __unused)
1456{
1457	selfd_zone = uma_zcreate("selfd", sizeof(struct selfd), NULL, NULL,
1458	    NULL, NULL, UMA_ALIGN_PTR, 0);
1459}
1460