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