xref: /freebsd-14.2/sys/kern/sys_generic.c (revision 55e2bfab)
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 	error = fo_write(fp, auio, td->td_ucred, flags, td);
565 	/*
566 	 * Socket layer is responsible for special error handling,
567 	 * see sousrsend().
568 	 */
569 	if (error != 0 && fp->f_type != DTYPE_SOCKET) {
570 		if (auio->uio_resid != cnt && (error == ERESTART ||
571 		    error == EINTR || error == EWOULDBLOCK))
572 			error = 0;
573 		if (error == EPIPE) {
574 			PROC_LOCK(td->td_proc);
575 			tdsignal(td, SIGPIPE);
576 			PROC_UNLOCK(td->td_proc);
577 		}
578 	}
579 	cnt -= auio->uio_resid;
580 #ifdef KTRACE
581 	if (ktruio != NULL) {
582 		ktruio->uio_resid = cnt;
583 		ktrgenio(fd, UIO_WRITE, ktruio, error);
584 	}
585 #endif
586 	td->td_retval[0] = cnt;
587 	return (error);
588 }
589 
590 /*
591  * Truncate a file given a file descriptor.
592  *
593  * Can't use fget_write() here, since must return EINVAL and not EBADF if the
594  * descriptor isn't writable.
595  */
596 int
597 kern_ftruncate(struct thread *td, int fd, off_t length)
598 {
599 	struct file *fp;
600 	int error;
601 
602 	AUDIT_ARG_FD(fd);
603 	if (length < 0)
604 		return (EINVAL);
605 	error = fget(td, fd, &cap_ftruncate_rights, &fp);
606 	if (error)
607 		return (error);
608 	AUDIT_ARG_FILE(td->td_proc, fp);
609 	if (!(fp->f_flag & FWRITE)) {
610 		fdrop(fp, td);
611 		return (EINVAL);
612 	}
613 	error = fo_truncate(fp, length, td->td_ucred, td);
614 	fdrop(fp, td);
615 	return (error);
616 }
617 
618 #ifndef _SYS_SYSPROTO_H_
619 struct ftruncate_args {
620 	int	fd;
621 	int	pad;
622 	off_t	length;
623 };
624 #endif
625 int
626 sys_ftruncate(struct thread *td, struct ftruncate_args *uap)
627 {
628 
629 	return (kern_ftruncate(td, uap->fd, uap->length));
630 }
631 
632 #if defined(COMPAT_43)
633 #ifndef _SYS_SYSPROTO_H_
634 struct oftruncate_args {
635 	int	fd;
636 	long	length;
637 };
638 #endif
639 int
640 oftruncate(struct thread *td, struct oftruncate_args *uap)
641 {
642 
643 	return (kern_ftruncate(td, uap->fd, uap->length));
644 }
645 #endif /* COMPAT_43 */
646 
647 #ifndef _SYS_SYSPROTO_H_
648 struct ioctl_args {
649 	int	fd;
650 	u_long	com;
651 	caddr_t	data;
652 };
653 #endif
654 /* ARGSUSED */
655 int
656 sys_ioctl(struct thread *td, struct ioctl_args *uap)
657 {
658 	u_char smalldata[SYS_IOCTL_SMALL_SIZE] __aligned(SYS_IOCTL_SMALL_ALIGN);
659 	uint32_t com;
660 	int arg, error;
661 	u_int size;
662 	caddr_t data;
663 
664 #ifdef INVARIANTS
665 	if (uap->com > 0xffffffff) {
666 		printf(
667 		    "WARNING pid %d (%s): ioctl sign-extension ioctl %lx\n",
668 		    td->td_proc->p_pid, td->td_name, uap->com);
669 	}
670 #endif
671 	com = (uint32_t)uap->com;
672 
673 	/*
674 	 * Interpret high order word to find amount of data to be
675 	 * copied to/from the user's address space.
676 	 */
677 	size = IOCPARM_LEN(com);
678 	if ((size > IOCPARM_MAX) ||
679 	    ((com & (IOC_VOID  | IOC_IN | IOC_OUT)) == 0) ||
680 #if defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
681 	    ((com & IOC_OUT) && size == 0) ||
682 #else
683 	    ((com & (IOC_IN | IOC_OUT)) && size == 0) ||
684 #endif
685 	    ((com & IOC_VOID) && size > 0 && size != sizeof(int)))
686 		return (ENOTTY);
687 
688 	if (size > 0) {
689 		if (com & IOC_VOID) {
690 			/* Integer argument. */
691 			arg = (intptr_t)uap->data;
692 			data = (void *)&arg;
693 			size = 0;
694 		} else {
695 			if (size > SYS_IOCTL_SMALL_SIZE)
696 				data = malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
697 			else
698 				data = smalldata;
699 		}
700 	} else
701 		data = (void *)&uap->data;
702 	if (com & IOC_IN) {
703 		error = copyin(uap->data, data, (u_int)size);
704 		if (error != 0)
705 			goto out;
706 	} else if (com & IOC_OUT) {
707 		/*
708 		 * Zero the buffer so the user always
709 		 * gets back something deterministic.
710 		 */
711 		bzero(data, size);
712 	}
713 
714 	error = kern_ioctl(td, uap->fd, com, data);
715 
716 	if (error == 0 && (com & IOC_OUT))
717 		error = copyout(data, uap->data, (u_int)size);
718 
719 out:
720 	if (size > SYS_IOCTL_SMALL_SIZE)
721 		free(data, M_IOCTLOPS);
722 	return (error);
723 }
724 
725 int
726 kern_ioctl(struct thread *td, int fd, u_long com, caddr_t data)
727 {
728 	struct file *fp;
729 	struct filedesc *fdp;
730 	int error, tmp, locked;
731 
732 	AUDIT_ARG_FD(fd);
733 	AUDIT_ARG_CMD(com);
734 
735 	fdp = td->td_proc->p_fd;
736 
737 	switch (com) {
738 	case FIONCLEX:
739 	case FIOCLEX:
740 		FILEDESC_XLOCK(fdp);
741 		locked = LA_XLOCKED;
742 		break;
743 	default:
744 #ifdef CAPABILITIES
745 		FILEDESC_SLOCK(fdp);
746 		locked = LA_SLOCKED;
747 #else
748 		locked = LA_UNLOCKED;
749 #endif
750 		break;
751 	}
752 
753 #ifdef CAPABILITIES
754 	if ((fp = fget_noref(fdp, fd)) == NULL) {
755 		error = EBADF;
756 		goto out;
757 	}
758 	if ((error = cap_ioctl_check(fdp, fd, com)) != 0) {
759 		fp = NULL;	/* fhold() was not called yet */
760 		goto out;
761 	}
762 	if (!fhold(fp)) {
763 		error = EBADF;
764 		fp = NULL;
765 		goto out;
766 	}
767 	if (locked == LA_SLOCKED) {
768 		FILEDESC_SUNLOCK(fdp);
769 		locked = LA_UNLOCKED;
770 	}
771 #else
772 	error = fget(td, fd, &cap_ioctl_rights, &fp);
773 	if (error != 0) {
774 		fp = NULL;
775 		goto out;
776 	}
777 #endif
778 	if ((fp->f_flag & (FREAD | FWRITE)) == 0) {
779 		error = EBADF;
780 		goto out;
781 	}
782 
783 	switch (com) {
784 	case FIONCLEX:
785 		fdp->fd_ofiles[fd].fde_flags &= ~UF_EXCLOSE;
786 		goto out;
787 	case FIOCLEX:
788 		fdp->fd_ofiles[fd].fde_flags |= UF_EXCLOSE;
789 		goto out;
790 	case FIONBIO:
791 		if ((tmp = *(int *)data))
792 			atomic_set_int(&fp->f_flag, FNONBLOCK);
793 		else
794 			atomic_clear_int(&fp->f_flag, FNONBLOCK);
795 		data = (void *)&tmp;
796 		break;
797 	case FIOASYNC:
798 		if ((tmp = *(int *)data))
799 			atomic_set_int(&fp->f_flag, FASYNC);
800 		else
801 			atomic_clear_int(&fp->f_flag, FASYNC);
802 		data = (void *)&tmp;
803 		break;
804 	}
805 
806 	error = fo_ioctl(fp, com, data, td->td_ucred, td);
807 out:
808 	switch (locked) {
809 	case LA_XLOCKED:
810 		FILEDESC_XUNLOCK(fdp);
811 		break;
812 #ifdef CAPABILITIES
813 	case LA_SLOCKED:
814 		FILEDESC_SUNLOCK(fdp);
815 		break;
816 #endif
817 	default:
818 		FILEDESC_UNLOCK_ASSERT(fdp);
819 		break;
820 	}
821 	if (fp != NULL)
822 		fdrop(fp, td);
823 	return (error);
824 }
825 
826 int
827 sys_posix_fallocate(struct thread *td, struct posix_fallocate_args *uap)
828 {
829 	int error;
830 
831 	error = kern_posix_fallocate(td, uap->fd, uap->offset, uap->len);
832 	return (kern_posix_error(td, error));
833 }
834 
835 int
836 kern_posix_fallocate(struct thread *td, int fd, off_t offset, off_t len)
837 {
838 	struct file *fp;
839 	int error;
840 
841 	AUDIT_ARG_FD(fd);
842 	if (offset < 0 || len <= 0)
843 		return (EINVAL);
844 	/* Check for wrap. */
845 	if (offset > OFF_MAX - len)
846 		return (EFBIG);
847 	AUDIT_ARG_FD(fd);
848 	error = fget(td, fd, &cap_pwrite_rights, &fp);
849 	if (error != 0)
850 		return (error);
851 	AUDIT_ARG_FILE(td->td_proc, fp);
852 	if ((fp->f_ops->fo_flags & DFLAG_SEEKABLE) == 0) {
853 		error = ESPIPE;
854 		goto out;
855 	}
856 	if ((fp->f_flag & FWRITE) == 0) {
857 		error = EBADF;
858 		goto out;
859 	}
860 
861 	error = fo_fallocate(fp, offset, len, td);
862  out:
863 	fdrop(fp, td);
864 	return (error);
865 }
866 
867 int
868 sys_fspacectl(struct thread *td, struct fspacectl_args *uap)
869 {
870 	struct spacectl_range rqsr, rmsr;
871 	int error, cerror;
872 
873 	error = copyin(uap->rqsr, &rqsr, sizeof(rqsr));
874 	if (error != 0)
875 		return (error);
876 
877 	error = kern_fspacectl(td, uap->fd, uap->cmd, &rqsr, uap->flags,
878 	    &rmsr);
879 	if (uap->rmsr != NULL) {
880 		cerror = copyout(&rmsr, uap->rmsr, sizeof(rmsr));
881 		if (error == 0)
882 			error = cerror;
883 	}
884 	return (error);
885 }
886 
887 int
888 kern_fspacectl(struct thread *td, int fd, int cmd,
889     const struct spacectl_range *rqsr, int flags, struct spacectl_range *rmsrp)
890 {
891 	struct file *fp;
892 	struct spacectl_range rmsr;
893 	int error;
894 
895 	AUDIT_ARG_FD(fd);
896 	AUDIT_ARG_CMD(cmd);
897 	AUDIT_ARG_FFLAGS(flags);
898 
899 	if (rqsr == NULL)
900 		return (EINVAL);
901 	rmsr = *rqsr;
902 	if (rmsrp != NULL)
903 		*rmsrp = rmsr;
904 
905 	if (cmd != SPACECTL_DEALLOC ||
906 	    rqsr->r_offset < 0 || rqsr->r_len <= 0 ||
907 	    rqsr->r_offset > OFF_MAX - rqsr->r_len ||
908 	    (flags & ~SPACECTL_F_SUPPORTED) != 0)
909 		return (EINVAL);
910 
911 	error = fget_write(td, fd, &cap_pwrite_rights, &fp);
912 	if (error != 0)
913 		return (error);
914 	AUDIT_ARG_FILE(td->td_proc, fp);
915 	if ((fp->f_ops->fo_flags & DFLAG_SEEKABLE) == 0) {
916 		error = ESPIPE;
917 		goto out;
918 	}
919 	if ((fp->f_flag & FWRITE) == 0) {
920 		error = EBADF;
921 		goto out;
922 	}
923 
924 	error = fo_fspacectl(fp, cmd, &rmsr.r_offset, &rmsr.r_len, flags,
925 	    td->td_ucred, td);
926 	/* fspacectl is not restarted after signals if the file is modified. */
927 	if (rmsr.r_len != rqsr->r_len && (error == ERESTART ||
928 	    error == EINTR || error == EWOULDBLOCK))
929 		error = 0;
930 	if (rmsrp != NULL)
931 		*rmsrp = rmsr;
932 out:
933 	fdrop(fp, td);
934 	return (error);
935 }
936 
937 int
938 kern_specialfd(struct thread *td, int type, void *arg)
939 {
940 	struct file *fp;
941 	struct specialfd_eventfd *ae;
942 	int error, fd, fflags;
943 
944 	fflags = 0;
945 	error = falloc_noinstall(td, &fp);
946 	if (error != 0)
947 		return (error);
948 
949 	switch (type) {
950 	case SPECIALFD_EVENTFD:
951 		ae = arg;
952 		if ((ae->flags & EFD_CLOEXEC) != 0)
953 			fflags |= O_CLOEXEC;
954 		error = eventfd_create_file(td, fp, ae->initval, ae->flags);
955 		break;
956 	default:
957 		error = EINVAL;
958 		break;
959 	}
960 
961 	if (error == 0)
962 		error = finstall(td, fp, &fd, fflags, NULL);
963 	fdrop(fp, td);
964 	if (error == 0)
965 		td->td_retval[0] = fd;
966 	return (error);
967 }
968 
969 int
970 sys___specialfd(struct thread *td, struct __specialfd_args *args)
971 {
972 	struct specialfd_eventfd ae;
973 	int error;
974 
975 	switch (args->type) {
976 	case SPECIALFD_EVENTFD:
977 		if (args->len != sizeof(struct specialfd_eventfd)) {
978 			error = EINVAL;
979 			break;
980 		}
981 		error = copyin(args->req, &ae, sizeof(ae));
982 		if (error != 0)
983 			break;
984 		if ((ae.flags & ~(EFD_CLOEXEC | EFD_NONBLOCK |
985 		    EFD_SEMAPHORE)) != 0) {
986 			error = EINVAL;
987 			break;
988 		}
989 		error = kern_specialfd(td, args->type, &ae);
990 		break;
991 	default:
992 		error = EINVAL;
993 		break;
994 	}
995 	return (error);
996 }
997 
998 int
999 poll_no_poll(int events)
1000 {
1001 	/*
1002 	 * Return true for read/write.  If the user asked for something
1003 	 * special, return POLLNVAL, so that clients have a way of
1004 	 * determining reliably whether or not the extended
1005 	 * functionality is present without hard-coding knowledge
1006 	 * of specific filesystem implementations.
1007 	 */
1008 	if (events & ~POLLSTANDARD)
1009 		return (POLLNVAL);
1010 
1011 	return (events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
1012 }
1013 
1014 int
1015 sys_pselect(struct thread *td, struct pselect_args *uap)
1016 {
1017 	struct timespec ts;
1018 	struct timeval tv, *tvp;
1019 	sigset_t set, *uset;
1020 	int error;
1021 
1022 	if (uap->ts != NULL) {
1023 		error = copyin(uap->ts, &ts, sizeof(ts));
1024 		if (error != 0)
1025 		    return (error);
1026 		TIMESPEC_TO_TIMEVAL(&tv, &ts);
1027 		tvp = &tv;
1028 	} else
1029 		tvp = NULL;
1030 	if (uap->sm != NULL) {
1031 		error = copyin(uap->sm, &set, sizeof(set));
1032 		if (error != 0)
1033 			return (error);
1034 		uset = &set;
1035 	} else
1036 		uset = NULL;
1037 	return (kern_pselect(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
1038 	    uset, NFDBITS));
1039 }
1040 
1041 int
1042 kern_pselect(struct thread *td, int nd, fd_set *in, fd_set *ou, fd_set *ex,
1043     struct timeval *tvp, sigset_t *uset, int abi_nfdbits)
1044 {
1045 	int error;
1046 
1047 	if (uset != NULL) {
1048 		error = kern_sigprocmask(td, SIG_SETMASK, uset,
1049 		    &td->td_oldsigmask, 0);
1050 		if (error != 0)
1051 			return (error);
1052 		td->td_pflags |= TDP_OLDMASK;
1053 		/*
1054 		 * Make sure that ast() is called on return to
1055 		 * usermode and TDP_OLDMASK is cleared, restoring old
1056 		 * sigmask.
1057 		 */
1058 		ast_sched(td, TDA_SIGSUSPEND);
1059 	}
1060 	error = kern_select(td, nd, in, ou, ex, tvp, abi_nfdbits);
1061 	return (error);
1062 }
1063 
1064 #ifndef _SYS_SYSPROTO_H_
1065 struct select_args {
1066 	int	nd;
1067 	fd_set	*in, *ou, *ex;
1068 	struct	timeval *tv;
1069 };
1070 #endif
1071 int
1072 sys_select(struct thread *td, struct select_args *uap)
1073 {
1074 	struct timeval tv, *tvp;
1075 	int error;
1076 
1077 	if (uap->tv != NULL) {
1078 		error = copyin(uap->tv, &tv, sizeof(tv));
1079 		if (error)
1080 			return (error);
1081 		tvp = &tv;
1082 	} else
1083 		tvp = NULL;
1084 
1085 	return (kern_select(td, uap->nd, uap->in, uap->ou, uap->ex, tvp,
1086 	    NFDBITS));
1087 }
1088 
1089 /*
1090  * In the unlikely case when user specified n greater then the last
1091  * open file descriptor, check that no bits are set after the last
1092  * valid fd.  We must return EBADF if any is set.
1093  *
1094  * There are applications that rely on the behaviour.
1095  *
1096  * nd is fd_nfiles.
1097  */
1098 static int
1099 select_check_badfd(fd_set *fd_in, int nd, int ndu, int abi_nfdbits)
1100 {
1101 	char *addr, *oaddr;
1102 	int b, i, res;
1103 	uint8_t bits;
1104 
1105 	if (nd >= ndu || fd_in == NULL)
1106 		return (0);
1107 
1108 	oaddr = NULL;
1109 	bits = 0; /* silence gcc */
1110 	for (i = nd; i < ndu; i++) {
1111 		b = i / NBBY;
1112 #if BYTE_ORDER == LITTLE_ENDIAN
1113 		addr = (char *)fd_in + b;
1114 #else
1115 		addr = (char *)fd_in;
1116 		if (abi_nfdbits == NFDBITS) {
1117 			addr += rounddown(b, sizeof(fd_mask)) +
1118 			    sizeof(fd_mask) - 1 - b % sizeof(fd_mask);
1119 		} else {
1120 			addr += rounddown(b, sizeof(uint32_t)) +
1121 			    sizeof(uint32_t) - 1 - b % sizeof(uint32_t);
1122 		}
1123 #endif
1124 		if (addr != oaddr) {
1125 			res = fubyte(addr);
1126 			if (res == -1)
1127 				return (EFAULT);
1128 			oaddr = addr;
1129 			bits = res;
1130 		}
1131 		if ((bits & (1 << (i % NBBY))) != 0)
1132 			return (EBADF);
1133 	}
1134 	return (0);
1135 }
1136 
1137 int
1138 kern_select(struct thread *td, int nd, fd_set *fd_in, fd_set *fd_ou,
1139     fd_set *fd_ex, struct timeval *tvp, int abi_nfdbits)
1140 {
1141 	struct filedesc *fdp;
1142 	/*
1143 	 * The magic 2048 here is chosen to be just enough for FD_SETSIZE
1144 	 * infds with the new FD_SETSIZE of 1024, and more than enough for
1145 	 * FD_SETSIZE infds, outfds and exceptfds with the old FD_SETSIZE
1146 	 * of 256.
1147 	 */
1148 	fd_mask s_selbits[howmany(2048, NFDBITS)];
1149 	fd_mask *ibits[3], *obits[3], *selbits, *sbp;
1150 	struct timeval rtv;
1151 	sbintime_t asbt, precision, rsbt;
1152 	u_int nbufbytes, ncpbytes, ncpubytes, nfdbits;
1153 	int error, lf, ndu;
1154 
1155 	if (nd < 0)
1156 		return (EINVAL);
1157 	fdp = td->td_proc->p_fd;
1158 	ndu = nd;
1159 	lf = fdp->fd_nfiles;
1160 	if (nd > lf)
1161 		nd = lf;
1162 
1163 	error = select_check_badfd(fd_in, nd, ndu, abi_nfdbits);
1164 	if (error != 0)
1165 		return (error);
1166 	error = select_check_badfd(fd_ou, nd, ndu, abi_nfdbits);
1167 	if (error != 0)
1168 		return (error);
1169 	error = select_check_badfd(fd_ex, nd, ndu, abi_nfdbits);
1170 	if (error != 0)
1171 		return (error);
1172 
1173 	/*
1174 	 * Allocate just enough bits for the non-null fd_sets.  Use the
1175 	 * preallocated auto buffer if possible.
1176 	 */
1177 	nfdbits = roundup(nd, NFDBITS);
1178 	ncpbytes = nfdbits / NBBY;
1179 	ncpubytes = roundup(nd, abi_nfdbits) / NBBY;
1180 	nbufbytes = 0;
1181 	if (fd_in != NULL)
1182 		nbufbytes += 2 * ncpbytes;
1183 	if (fd_ou != NULL)
1184 		nbufbytes += 2 * ncpbytes;
1185 	if (fd_ex != NULL)
1186 		nbufbytes += 2 * ncpbytes;
1187 	if (nbufbytes <= sizeof s_selbits)
1188 		selbits = &s_selbits[0];
1189 	else
1190 		selbits = malloc(nbufbytes, M_SELECT, M_WAITOK);
1191 
1192 	/*
1193 	 * Assign pointers into the bit buffers and fetch the input bits.
1194 	 * Put the output buffers together so that they can be bzeroed
1195 	 * together.
1196 	 */
1197 	sbp = selbits;
1198 #define	getbits(name, x) \
1199 	do {								\
1200 		if (name == NULL) {					\
1201 			ibits[x] = NULL;				\
1202 			obits[x] = NULL;				\
1203 		} else {						\
1204 			ibits[x] = sbp + nbufbytes / 2 / sizeof *sbp;	\
1205 			obits[x] = sbp;					\
1206 			sbp += ncpbytes / sizeof *sbp;			\
1207 			error = copyin(name, ibits[x], ncpubytes);	\
1208 			if (error != 0)					\
1209 				goto done;				\
1210 			if (ncpbytes != ncpubytes)			\
1211 				bzero((char *)ibits[x] + ncpubytes,	\
1212 				    ncpbytes - ncpubytes);		\
1213 		}							\
1214 	} while (0)
1215 	getbits(fd_in, 0);
1216 	getbits(fd_ou, 1);
1217 	getbits(fd_ex, 2);
1218 #undef	getbits
1219 
1220 #if BYTE_ORDER == BIG_ENDIAN && defined(__LP64__)
1221 	/*
1222 	 * XXX: swizzle_fdset assumes that if abi_nfdbits != NFDBITS,
1223 	 * we are running under 32-bit emulation. This should be more
1224 	 * generic.
1225 	 */
1226 #define swizzle_fdset(bits)						\
1227 	if (abi_nfdbits != NFDBITS && bits != NULL) {			\
1228 		int i;							\
1229 		for (i = 0; i < ncpbytes / sizeof *sbp; i++)		\
1230 			bits[i] = (bits[i] >> 32) | (bits[i] << 32);	\
1231 	}
1232 #else
1233 #define swizzle_fdset(bits)
1234 #endif
1235 
1236 	/* Make sure the bit order makes it through an ABI transition */
1237 	swizzle_fdset(ibits[0]);
1238 	swizzle_fdset(ibits[1]);
1239 	swizzle_fdset(ibits[2]);
1240 
1241 	if (nbufbytes != 0)
1242 		bzero(selbits, nbufbytes / 2);
1243 
1244 	precision = 0;
1245 	if (tvp != NULL) {
1246 		rtv = *tvp;
1247 		if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1248 		    rtv.tv_usec >= 1000000) {
1249 			error = EINVAL;
1250 			goto done;
1251 		}
1252 		if (!timevalisset(&rtv))
1253 			asbt = 0;
1254 		else if (rtv.tv_sec <= INT32_MAX) {
1255 			rsbt = tvtosbt(rtv);
1256 			precision = rsbt;
1257 			precision >>= tc_precexp;
1258 			if (TIMESEL(&asbt, rsbt))
1259 				asbt += tc_tick_sbt;
1260 			if (asbt <= SBT_MAX - rsbt)
1261 				asbt += rsbt;
1262 			else
1263 				asbt = -1;
1264 		} else
1265 			asbt = -1;
1266 	} else
1267 		asbt = -1;
1268 	seltdinit(td);
1269 	/* Iterate until the timeout expires or descriptors become ready. */
1270 	for (;;) {
1271 		error = selscan(td, ibits, obits, nd);
1272 		if (error || td->td_retval[0] != 0)
1273 			break;
1274 		error = seltdwait(td, asbt, precision);
1275 		if (error)
1276 			break;
1277 		error = selrescan(td, ibits, obits);
1278 		if (error || td->td_retval[0] != 0)
1279 			break;
1280 	}
1281 	seltdclear(td);
1282 
1283 done:
1284 	/* select is not restarted after signals... */
1285 	if (error == ERESTART)
1286 		error = EINTR;
1287 	if (error == EWOULDBLOCK)
1288 		error = 0;
1289 
1290 	/* swizzle bit order back, if necessary */
1291 	swizzle_fdset(obits[0]);
1292 	swizzle_fdset(obits[1]);
1293 	swizzle_fdset(obits[2]);
1294 #undef swizzle_fdset
1295 
1296 #define	putbits(name, x) \
1297 	if (name && (error2 = copyout(obits[x], name, ncpubytes))) \
1298 		error = error2;
1299 	if (error == 0) {
1300 		int error2;
1301 
1302 		putbits(fd_in, 0);
1303 		putbits(fd_ou, 1);
1304 		putbits(fd_ex, 2);
1305 #undef putbits
1306 	}
1307 	if (selbits != &s_selbits[0])
1308 		free(selbits, M_SELECT);
1309 
1310 	return (error);
1311 }
1312 /*
1313  * Convert a select bit set to poll flags.
1314  *
1315  * The backend always returns POLLHUP/POLLERR if appropriate and we
1316  * return this as a set bit in any set.
1317  */
1318 static const int select_flags[3] = {
1319     POLLRDNORM | POLLHUP | POLLERR,
1320     POLLWRNORM | POLLHUP | POLLERR,
1321     POLLRDBAND | POLLERR
1322 };
1323 
1324 /*
1325  * Compute the fo_poll flags required for a fd given by the index and
1326  * bit position in the fd_mask array.
1327  */
1328 static __inline int
1329 selflags(fd_mask **ibits, int idx, fd_mask bit)
1330 {
1331 	int flags;
1332 	int msk;
1333 
1334 	flags = 0;
1335 	for (msk = 0; msk < 3; msk++) {
1336 		if (ibits[msk] == NULL)
1337 			continue;
1338 		if ((ibits[msk][idx] & bit) == 0)
1339 			continue;
1340 		flags |= select_flags[msk];
1341 	}
1342 	return (flags);
1343 }
1344 
1345 /*
1346  * Set the appropriate output bits given a mask of fired events and the
1347  * input bits originally requested.
1348  */
1349 static __inline int
1350 selsetbits(fd_mask **ibits, fd_mask **obits, int idx, fd_mask bit, int events)
1351 {
1352 	int msk;
1353 	int n;
1354 
1355 	n = 0;
1356 	for (msk = 0; msk < 3; msk++) {
1357 		if ((events & select_flags[msk]) == 0)
1358 			continue;
1359 		if (ibits[msk] == NULL)
1360 			continue;
1361 		if ((ibits[msk][idx] & bit) == 0)
1362 			continue;
1363 		/*
1364 		 * XXX Check for a duplicate set.  This can occur because a
1365 		 * socket calls selrecord() twice for each poll() call
1366 		 * resulting in two selfds per real fd.  selrescan() will
1367 		 * call selsetbits twice as a result.
1368 		 */
1369 		if ((obits[msk][idx] & bit) != 0)
1370 			continue;
1371 		obits[msk][idx] |= bit;
1372 		n++;
1373 	}
1374 
1375 	return (n);
1376 }
1377 
1378 /*
1379  * Traverse the list of fds attached to this thread's seltd and check for
1380  * completion.
1381  */
1382 static int
1383 selrescan(struct thread *td, fd_mask **ibits, fd_mask **obits)
1384 {
1385 	struct filedesc *fdp;
1386 	struct selinfo *si;
1387 	struct seltd *stp;
1388 	struct selfd *sfp;
1389 	struct selfd *sfn;
1390 	struct file *fp;
1391 	fd_mask bit;
1392 	int fd, ev, n, idx;
1393 	int error;
1394 	bool only_user;
1395 
1396 	fdp = td->td_proc->p_fd;
1397 	stp = td->td_sel;
1398 	n = 0;
1399 	only_user = FILEDESC_IS_ONLY_USER(fdp);
1400 	STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1401 		fd = (int)(uintptr_t)sfp->sf_cookie;
1402 		si = sfp->sf_si;
1403 		selfdfree(stp, sfp);
1404 		/* If the selinfo wasn't cleared the event didn't fire. */
1405 		if (si != NULL)
1406 			continue;
1407 		if (only_user)
1408 			error = fget_only_user(fdp, fd, &cap_event_rights, &fp);
1409 		else
1410 			error = fget_unlocked(td, fd, &cap_event_rights, &fp);
1411 		if (__predict_false(error != 0))
1412 			return (error);
1413 		idx = fd / NFDBITS;
1414 		bit = (fd_mask)1 << (fd % NFDBITS);
1415 		ev = fo_poll(fp, selflags(ibits, idx, bit), td->td_ucred, td);
1416 		if (only_user)
1417 			fput_only_user(fdp, fp);
1418 		else
1419 			fdrop(fp, td);
1420 		if (ev != 0)
1421 			n += selsetbits(ibits, obits, idx, bit, ev);
1422 	}
1423 	stp->st_flags = 0;
1424 	td->td_retval[0] = n;
1425 	return (0);
1426 }
1427 
1428 /*
1429  * Perform the initial filedescriptor scan and register ourselves with
1430  * each selinfo.
1431  */
1432 static int
1433 selscan(struct thread *td, fd_mask **ibits, fd_mask **obits, int nfd)
1434 {
1435 	struct filedesc *fdp;
1436 	struct file *fp;
1437 	fd_mask bit;
1438 	int ev, flags, end, fd;
1439 	int n, idx;
1440 	int error;
1441 	bool only_user;
1442 
1443 	fdp = td->td_proc->p_fd;
1444 	n = 0;
1445 	only_user = FILEDESC_IS_ONLY_USER(fdp);
1446 	for (idx = 0, fd = 0; fd < nfd; idx++) {
1447 		end = imin(fd + NFDBITS, nfd);
1448 		for (bit = 1; fd < end; bit <<= 1, fd++) {
1449 			/* Compute the list of events we're interested in. */
1450 			flags = selflags(ibits, idx, bit);
1451 			if (flags == 0)
1452 				continue;
1453 			if (only_user)
1454 				error = fget_only_user(fdp, fd, &cap_event_rights, &fp);
1455 			else
1456 				error = fget_unlocked(td, fd, &cap_event_rights, &fp);
1457 			if (__predict_false(error != 0))
1458 				return (error);
1459 			selfdalloc(td, (void *)(uintptr_t)fd);
1460 			ev = fo_poll(fp, flags, td->td_ucred, td);
1461 			if (only_user)
1462 				fput_only_user(fdp, fp);
1463 			else
1464 				fdrop(fp, td);
1465 			if (ev != 0)
1466 				n += selsetbits(ibits, obits, idx, bit, ev);
1467 		}
1468 	}
1469 
1470 	td->td_retval[0] = n;
1471 	return (0);
1472 }
1473 
1474 int
1475 sys_poll(struct thread *td, struct poll_args *uap)
1476 {
1477 	struct timespec ts, *tsp;
1478 
1479 	if (uap->timeout != INFTIM) {
1480 		if (uap->timeout < 0)
1481 			return (EINVAL);
1482 		ts.tv_sec = uap->timeout / 1000;
1483 		ts.tv_nsec = (uap->timeout % 1000) * 1000000;
1484 		tsp = &ts;
1485 	} else
1486 		tsp = NULL;
1487 
1488 	return (kern_poll(td, uap->fds, uap->nfds, tsp, NULL));
1489 }
1490 
1491 /*
1492  * kfds points to an array in the kernel.
1493  */
1494 int
1495 kern_poll_kfds(struct thread *td, struct pollfd *kfds, u_int nfds,
1496     struct timespec *tsp, sigset_t *uset)
1497 {
1498 	sbintime_t sbt, precision, tmp;
1499 	time_t over;
1500 	struct timespec ts;
1501 	int error;
1502 
1503 	precision = 0;
1504 	if (tsp != NULL) {
1505 		if (!timespecvalid_interval(tsp))
1506 			return (EINVAL);
1507 		if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
1508 			sbt = 0;
1509 		else {
1510 			ts = *tsp;
1511 			if (ts.tv_sec > INT32_MAX / 2) {
1512 				over = ts.tv_sec - INT32_MAX / 2;
1513 				ts.tv_sec -= over;
1514 			} else
1515 				over = 0;
1516 			tmp = tstosbt(ts);
1517 			precision = tmp;
1518 			precision >>= tc_precexp;
1519 			if (TIMESEL(&sbt, tmp))
1520 				sbt += tc_tick_sbt;
1521 			sbt += tmp;
1522 		}
1523 	} else
1524 		sbt = -1;
1525 
1526 	if (uset != NULL) {
1527 		error = kern_sigprocmask(td, SIG_SETMASK, uset,
1528 		    &td->td_oldsigmask, 0);
1529 		if (error)
1530 			return (error);
1531 		td->td_pflags |= TDP_OLDMASK;
1532 		/*
1533 		 * Make sure that ast() is called on return to
1534 		 * usermode and TDP_OLDMASK is cleared, restoring old
1535 		 * sigmask.
1536 		 */
1537 		ast_sched(td, TDA_SIGSUSPEND);
1538 	}
1539 
1540 	seltdinit(td);
1541 	/* Iterate until the timeout expires or descriptors become ready. */
1542 	for (;;) {
1543 		error = pollscan(td, kfds, nfds);
1544 		if (error || td->td_retval[0] != 0)
1545 			break;
1546 		error = seltdwait(td, sbt, precision);
1547 		if (error)
1548 			break;
1549 		error = pollrescan(td);
1550 		if (error || td->td_retval[0] != 0)
1551 			break;
1552 	}
1553 	seltdclear(td);
1554 
1555 	/* poll is not restarted after signals... */
1556 	if (error == ERESTART)
1557 		error = EINTR;
1558 	if (error == EWOULDBLOCK)
1559 		error = 0;
1560 	return (error);
1561 }
1562 
1563 int
1564 sys_ppoll(struct thread *td, struct ppoll_args *uap)
1565 {
1566 	struct timespec ts, *tsp;
1567 	sigset_t set, *ssp;
1568 	int error;
1569 
1570 	if (uap->ts != NULL) {
1571 		error = copyin(uap->ts, &ts, sizeof(ts));
1572 		if (error)
1573 			return (error);
1574 		tsp = &ts;
1575 	} else
1576 		tsp = NULL;
1577 	if (uap->set != NULL) {
1578 		error = copyin(uap->set, &set, sizeof(set));
1579 		if (error)
1580 			return (error);
1581 		ssp = &set;
1582 	} else
1583 		ssp = NULL;
1584 	return (kern_poll(td, uap->fds, uap->nfds, tsp, ssp));
1585 }
1586 
1587 /*
1588  * ufds points to an array in user space.
1589  */
1590 int
1591 kern_poll(struct thread *td, struct pollfd *ufds, u_int nfds,
1592     struct timespec *tsp, sigset_t *set)
1593 {
1594 	struct pollfd *kfds;
1595 	struct pollfd stackfds[32];
1596 	int error;
1597 
1598 	if (kern_poll_maxfds(nfds))
1599 		return (EINVAL);
1600 	if (nfds > nitems(stackfds))
1601 		kfds = mallocarray(nfds, sizeof(*kfds), M_TEMP, M_WAITOK);
1602 	else
1603 		kfds = stackfds;
1604 	error = copyin(ufds, kfds, nfds * sizeof(*kfds));
1605 	if (error != 0)
1606 		goto out;
1607 
1608 	error = kern_poll_kfds(td, kfds, nfds, tsp, set);
1609 	if (error == 0)
1610 		error = pollout(td, kfds, ufds, nfds);
1611 
1612 out:
1613 	if (nfds > nitems(stackfds))
1614 		free(kfds, M_TEMP);
1615 	return (error);
1616 }
1617 
1618 bool
1619 kern_poll_maxfds(u_int nfds)
1620 {
1621 
1622 	/*
1623 	 * This is kinda bogus.  We have fd limits, but that is not
1624 	 * really related to the size of the pollfd array.  Make sure
1625 	 * we let the process use at least FD_SETSIZE entries and at
1626 	 * least enough for the system-wide limits.  We want to be reasonably
1627 	 * safe, but not overly restrictive.
1628 	 */
1629 	return (nfds > maxfilesperproc && nfds > FD_SETSIZE);
1630 }
1631 
1632 static int
1633 pollrescan(struct thread *td)
1634 {
1635 	struct seltd *stp;
1636 	struct selfd *sfp;
1637 	struct selfd *sfn;
1638 	struct selinfo *si;
1639 	struct filedesc *fdp;
1640 	struct file *fp;
1641 	struct pollfd *fd;
1642 	int n, error;
1643 	bool only_user;
1644 
1645 	n = 0;
1646 	fdp = td->td_proc->p_fd;
1647 	stp = td->td_sel;
1648 	only_user = FILEDESC_IS_ONLY_USER(fdp);
1649 	STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn) {
1650 		fd = (struct pollfd *)sfp->sf_cookie;
1651 		si = sfp->sf_si;
1652 		selfdfree(stp, sfp);
1653 		/* If the selinfo wasn't cleared the event didn't fire. */
1654 		if (si != NULL)
1655 			continue;
1656 		if (only_user)
1657 			error = fget_only_user(fdp, fd->fd, &cap_event_rights, &fp);
1658 		else
1659 			error = fget_unlocked(td, fd->fd, &cap_event_rights, &fp);
1660 		if (__predict_false(error != 0)) {
1661 			fd->revents = POLLNVAL;
1662 			n++;
1663 			continue;
1664 		}
1665 		/*
1666 		 * Note: backend also returns POLLHUP and
1667 		 * POLLERR if appropriate.
1668 		 */
1669 		fd->revents = fo_poll(fp, fd->events, td->td_ucred, td);
1670 		if (only_user)
1671 			fput_only_user(fdp, fp);
1672 		else
1673 			fdrop(fp, td);
1674 		if (fd->revents != 0)
1675 			n++;
1676 	}
1677 	stp->st_flags = 0;
1678 	td->td_retval[0] = n;
1679 	return (0);
1680 }
1681 
1682 static int
1683 pollout(struct thread *td, struct pollfd *fds, struct pollfd *ufds, u_int nfd)
1684 {
1685 	int error = 0;
1686 	u_int i = 0;
1687 	u_int n = 0;
1688 
1689 	for (i = 0; i < nfd; i++) {
1690 		error = copyout(&fds->revents, &ufds->revents,
1691 		    sizeof(ufds->revents));
1692 		if (error)
1693 			return (error);
1694 		if (fds->revents != 0)
1695 			n++;
1696 		fds++;
1697 		ufds++;
1698 	}
1699 	td->td_retval[0] = n;
1700 	return (0);
1701 }
1702 
1703 static int
1704 pollscan(struct thread *td, struct pollfd *fds, u_int nfd)
1705 {
1706 	struct filedesc *fdp;
1707 	struct file *fp;
1708 	int i, n, error;
1709 	bool only_user;
1710 
1711 	n = 0;
1712 	fdp = td->td_proc->p_fd;
1713 	only_user = FILEDESC_IS_ONLY_USER(fdp);
1714 	for (i = 0; i < nfd; i++, fds++) {
1715 		if (fds->fd < 0) {
1716 			fds->revents = 0;
1717 			continue;
1718 		}
1719 		if (only_user)
1720 			error = fget_only_user(fdp, fds->fd, &cap_event_rights, &fp);
1721 		else
1722 			error = fget_unlocked(td, fds->fd, &cap_event_rights, &fp);
1723 		if (__predict_false(error != 0)) {
1724 			fds->revents = POLLNVAL;
1725 			n++;
1726 			continue;
1727 		}
1728 		/*
1729 		 * Note: backend also returns POLLHUP and
1730 		 * POLLERR if appropriate.
1731 		 */
1732 		selfdalloc(td, fds);
1733 		fds->revents = fo_poll(fp, fds->events,
1734 		    td->td_ucred, td);
1735 		if (only_user)
1736 			fput_only_user(fdp, fp);
1737 		else
1738 			fdrop(fp, td);
1739 		/*
1740 		 * POSIX requires POLLOUT to be never
1741 		 * set simultaneously with POLLHUP.
1742 		 */
1743 		if ((fds->revents & POLLHUP) != 0)
1744 			fds->revents &= ~POLLOUT;
1745 
1746 		if (fds->revents != 0)
1747 			n++;
1748 	}
1749 	td->td_retval[0] = n;
1750 	return (0);
1751 }
1752 
1753 /*
1754  * XXX This was created specifically to support netncp and netsmb.  This
1755  * allows the caller to specify a socket to wait for events on.  It returns
1756  * 0 if any events matched and an error otherwise.  There is no way to
1757  * determine which events fired.
1758  */
1759 int
1760 selsocket(struct socket *so, int events, struct timeval *tvp, struct thread *td)
1761 {
1762 	struct timeval rtv;
1763 	sbintime_t asbt, precision, rsbt;
1764 	int error;
1765 
1766 	precision = 0;	/* stupid gcc! */
1767 	if (tvp != NULL) {
1768 		rtv = *tvp;
1769 		if (rtv.tv_sec < 0 || rtv.tv_usec < 0 ||
1770 		    rtv.tv_usec >= 1000000)
1771 			return (EINVAL);
1772 		if (!timevalisset(&rtv))
1773 			asbt = 0;
1774 		else if (rtv.tv_sec <= INT32_MAX) {
1775 			rsbt = tvtosbt(rtv);
1776 			precision = rsbt;
1777 			precision >>= tc_precexp;
1778 			if (TIMESEL(&asbt, rsbt))
1779 				asbt += tc_tick_sbt;
1780 			if (asbt <= SBT_MAX - rsbt)
1781 				asbt += rsbt;
1782 			else
1783 				asbt = -1;
1784 		} else
1785 			asbt = -1;
1786 	} else
1787 		asbt = -1;
1788 	seltdinit(td);
1789 	/*
1790 	 * Iterate until the timeout expires or the socket becomes ready.
1791 	 */
1792 	for (;;) {
1793 		selfdalloc(td, NULL);
1794 		if (sopoll(so, events, NULL, td) != 0) {
1795 			error = 0;
1796 			break;
1797 		}
1798 		error = seltdwait(td, asbt, precision);
1799 		if (error)
1800 			break;
1801 	}
1802 	seltdclear(td);
1803 	/* XXX Duplicates ncp/smb behavior. */
1804 	if (error == ERESTART)
1805 		error = 0;
1806 	return (error);
1807 }
1808 
1809 /*
1810  * Preallocate two selfds associated with 'cookie'.  Some fo_poll routines
1811  * have two select sets, one for read and another for write.
1812  */
1813 static void
1814 selfdalloc(struct thread *td, void *cookie)
1815 {
1816 	struct seltd *stp;
1817 
1818 	stp = td->td_sel;
1819 	if (stp->st_free1 == NULL)
1820 		stp->st_free1 = malloc(sizeof(*stp->st_free1), M_SELFD, M_WAITOK|M_ZERO);
1821 	stp->st_free1->sf_td = stp;
1822 	stp->st_free1->sf_cookie = cookie;
1823 	if (stp->st_free2 == NULL)
1824 		stp->st_free2 = malloc(sizeof(*stp->st_free2), M_SELFD, M_WAITOK|M_ZERO);
1825 	stp->st_free2->sf_td = stp;
1826 	stp->st_free2->sf_cookie = cookie;
1827 }
1828 
1829 static void
1830 selfdfree(struct seltd *stp, struct selfd *sfp)
1831 {
1832 	STAILQ_REMOVE(&stp->st_selq, sfp, selfd, sf_link);
1833 	/*
1834 	 * Paired with doselwakeup.
1835 	 */
1836 	if (atomic_load_acq_ptr((uintptr_t *)&sfp->sf_si) != (uintptr_t)NULL) {
1837 		mtx_lock(sfp->sf_mtx);
1838 		if (sfp->sf_si != NULL) {
1839 			TAILQ_REMOVE(&sfp->sf_si->si_tdlist, sfp, sf_threads);
1840 		}
1841 		mtx_unlock(sfp->sf_mtx);
1842 	}
1843 	free(sfp, M_SELFD);
1844 }
1845 
1846 /* Drain the waiters tied to all the selfd belonging the specified selinfo. */
1847 void
1848 seldrain(struct selinfo *sip)
1849 {
1850 
1851 	/*
1852 	 * This feature is already provided by doselwakeup(), thus it is
1853 	 * enough to go for it.
1854 	 * Eventually, the context, should take care to avoid races
1855 	 * between thread calling select()/poll() and file descriptor
1856 	 * detaching, but, again, the races are just the same as
1857 	 * selwakeup().
1858 	 */
1859         doselwakeup(sip, -1);
1860 }
1861 
1862 /*
1863  * Record a select request.
1864  */
1865 void
1866 selrecord(struct thread *selector, struct selinfo *sip)
1867 {
1868 	struct selfd *sfp;
1869 	struct seltd *stp;
1870 	struct mtx *mtxp;
1871 
1872 	stp = selector->td_sel;
1873 	/*
1874 	 * Don't record when doing a rescan.
1875 	 */
1876 	if (stp->st_flags & SELTD_RESCAN)
1877 		return;
1878 	/*
1879 	 * Grab one of the preallocated descriptors.
1880 	 */
1881 	sfp = NULL;
1882 	if ((sfp = stp->st_free1) != NULL)
1883 		stp->st_free1 = NULL;
1884 	else if ((sfp = stp->st_free2) != NULL)
1885 		stp->st_free2 = NULL;
1886 	else
1887 		panic("selrecord: No free selfd on selq");
1888 	mtxp = sip->si_mtx;
1889 	if (mtxp == NULL)
1890 		mtxp = mtx_pool_find(mtxpool_select, sip);
1891 	/*
1892 	 * Initialize the sfp and queue it in the thread.
1893 	 */
1894 	sfp->sf_si = sip;
1895 	sfp->sf_mtx = mtxp;
1896 	STAILQ_INSERT_TAIL(&stp->st_selq, sfp, sf_link);
1897 	/*
1898 	 * Now that we've locked the sip, check for initialization.
1899 	 */
1900 	mtx_lock(mtxp);
1901 	if (sip->si_mtx == NULL) {
1902 		sip->si_mtx = mtxp;
1903 		TAILQ_INIT(&sip->si_tdlist);
1904 	}
1905 	/*
1906 	 * Add this thread to the list of selfds listening on this selinfo.
1907 	 */
1908 	TAILQ_INSERT_TAIL(&sip->si_tdlist, sfp, sf_threads);
1909 	mtx_unlock(sip->si_mtx);
1910 }
1911 
1912 /* Wake up a selecting thread. */
1913 void
1914 selwakeup(struct selinfo *sip)
1915 {
1916 	doselwakeup(sip, -1);
1917 }
1918 
1919 /* Wake up a selecting thread, and set its priority. */
1920 void
1921 selwakeuppri(struct selinfo *sip, int pri)
1922 {
1923 	doselwakeup(sip, pri);
1924 }
1925 
1926 /*
1927  * Do a wakeup when a selectable event occurs.
1928  */
1929 static void
1930 doselwakeup(struct selinfo *sip, int pri)
1931 {
1932 	struct selfd *sfp;
1933 	struct selfd *sfn;
1934 	struct seltd *stp;
1935 
1936 	/* If it's not initialized there can't be any waiters. */
1937 	if (sip->si_mtx == NULL)
1938 		return;
1939 	/*
1940 	 * Locking the selinfo locks all selfds associated with it.
1941 	 */
1942 	mtx_lock(sip->si_mtx);
1943 	TAILQ_FOREACH_SAFE(sfp, &sip->si_tdlist, sf_threads, sfn) {
1944 		/*
1945 		 * Once we remove this sfp from the list and clear the
1946 		 * sf_si seltdclear will know to ignore this si.
1947 		 */
1948 		TAILQ_REMOVE(&sip->si_tdlist, sfp, sf_threads);
1949 		stp = sfp->sf_td;
1950 		mtx_lock(&stp->st_mtx);
1951 		stp->st_flags |= SELTD_PENDING;
1952 		cv_broadcastpri(&stp->st_wait, pri);
1953 		mtx_unlock(&stp->st_mtx);
1954 		/*
1955 		 * Paired with selfdfree.
1956 		 *
1957 		 * Storing this only after the wakeup provides an invariant that
1958 		 * stp is not used after selfdfree returns.
1959 		 */
1960 		atomic_store_rel_ptr((uintptr_t *)&sfp->sf_si, (uintptr_t)NULL);
1961 	}
1962 	mtx_unlock(sip->si_mtx);
1963 }
1964 
1965 static void
1966 seltdinit(struct thread *td)
1967 {
1968 	struct seltd *stp;
1969 
1970 	stp = td->td_sel;
1971 	if (stp != NULL) {
1972 		MPASS(stp->st_flags == 0);
1973 		MPASS(STAILQ_EMPTY(&stp->st_selq));
1974 		return;
1975 	}
1976 	stp = malloc(sizeof(*stp), M_SELECT, M_WAITOK|M_ZERO);
1977 	mtx_init(&stp->st_mtx, "sellck", NULL, MTX_DEF);
1978 	cv_init(&stp->st_wait, "select");
1979 	stp->st_flags = 0;
1980 	STAILQ_INIT(&stp->st_selq);
1981 	td->td_sel = stp;
1982 }
1983 
1984 static int
1985 seltdwait(struct thread *td, sbintime_t sbt, sbintime_t precision)
1986 {
1987 	struct seltd *stp;
1988 	int error;
1989 
1990 	stp = td->td_sel;
1991 	/*
1992 	 * An event of interest may occur while we do not hold the seltd
1993 	 * locked so check the pending flag before we sleep.
1994 	 */
1995 	mtx_lock(&stp->st_mtx);
1996 	/*
1997 	 * Any further calls to selrecord will be a rescan.
1998 	 */
1999 	stp->st_flags |= SELTD_RESCAN;
2000 	if (stp->st_flags & SELTD_PENDING) {
2001 		mtx_unlock(&stp->st_mtx);
2002 		return (0);
2003 	}
2004 	if (sbt == 0)
2005 		error = EWOULDBLOCK;
2006 	else if (sbt != -1)
2007 		error = cv_timedwait_sig_sbt(&stp->st_wait, &stp->st_mtx,
2008 		    sbt, precision, C_ABSOLUTE);
2009 	else
2010 		error = cv_wait_sig(&stp->st_wait, &stp->st_mtx);
2011 	mtx_unlock(&stp->st_mtx);
2012 
2013 	return (error);
2014 }
2015 
2016 void
2017 seltdfini(struct thread *td)
2018 {
2019 	struct seltd *stp;
2020 
2021 	stp = td->td_sel;
2022 	if (stp == NULL)
2023 		return;
2024 	MPASS(stp->st_flags == 0);
2025 	MPASS(STAILQ_EMPTY(&stp->st_selq));
2026 	if (stp->st_free1)
2027 		free(stp->st_free1, M_SELFD);
2028 	if (stp->st_free2)
2029 		free(stp->st_free2, M_SELFD);
2030 	td->td_sel = NULL;
2031 	cv_destroy(&stp->st_wait);
2032 	mtx_destroy(&stp->st_mtx);
2033 	free(stp, M_SELECT);
2034 }
2035 
2036 /*
2037  * Remove the references to the thread from all of the objects we were
2038  * polling.
2039  */
2040 static void
2041 seltdclear(struct thread *td)
2042 {
2043 	struct seltd *stp;
2044 	struct selfd *sfp;
2045 	struct selfd *sfn;
2046 
2047 	stp = td->td_sel;
2048 	STAILQ_FOREACH_SAFE(sfp, &stp->st_selq, sf_link, sfn)
2049 		selfdfree(stp, sfp);
2050 	stp->st_flags = 0;
2051 }
2052 
2053 static void selectinit(void *);
2054 SYSINIT(select, SI_SUB_SYSCALLS, SI_ORDER_ANY, selectinit, NULL);
2055 static void
2056 selectinit(void *dummy __unused)
2057 {
2058 
2059 	mtxpool_select = mtx_pool_create("select mtxpool", 128, MTX_DEF);
2060 }
2061 
2062 /*
2063  * Set up a syscall return value that follows the convention specified for
2064  * posix_* functions.
2065  */
2066 int
2067 kern_posix_error(struct thread *td, int error)
2068 {
2069 
2070 	if (error <= 0)
2071 		return (error);
2072 	td->td_errno = error;
2073 	td->td_pflags |= TDP_NERRNO;
2074 	td->td_retval[0] = error;
2075 	return (0);
2076 }
2077 
2078 int
2079 kcmp_cmp(uintptr_t a, uintptr_t b)
2080 {
2081 	if (a == b)
2082 		return (0);
2083 	else if (a < b)
2084 		return (1);
2085 	return (2);
2086 }
2087 
2088 static int
2089 kcmp_pget(struct thread *td, pid_t pid, struct proc **pp)
2090 {
2091 	if (pid == td->td_proc->p_pid) {
2092 		*pp = td->td_proc;
2093 		return (0);
2094 	}
2095 	return (pget(pid, PGET_CANDEBUG | PGET_NOTWEXIT | PGET_HOLD, pp));
2096 }
2097 
2098 int
2099 kern_kcmp(struct thread *td, pid_t pid1, pid_t pid2, int type,
2100     uintptr_t idx1, uintptr_t idx2)
2101 {
2102 	struct proc *p1, *p2;
2103 	struct file *fp1, *fp2;
2104 	int error, res;
2105 
2106 	res = -1;
2107 	p1 = p2 = NULL;
2108 	error = kcmp_pget(td, pid1, &p1);
2109 	if (error == 0)
2110 		error = kcmp_pget(td, pid2, &p2);
2111 	if (error != 0)
2112 		goto out;
2113 
2114 	switch (type) {
2115 	case KCMP_FILE:
2116 	case KCMP_FILEOBJ:
2117 		error = fget_remote(td, p1, idx1, &fp1);
2118 		if (error == 0) {
2119 			error = fget_remote(td, p2, idx2, &fp2);
2120 			if (error == 0) {
2121 				if (type == KCMP_FILEOBJ)
2122 					res = fo_cmp(fp1, fp2, td);
2123 				else
2124 					res = kcmp_cmp((uintptr_t)fp1,
2125 					    (uintptr_t)fp2);
2126 				fdrop(fp2, td);
2127 			}
2128 			fdrop(fp1, td);
2129 		}
2130 		break;
2131 	case KCMP_FILES:
2132 		res = kcmp_cmp((uintptr_t)p1->p_fd, (uintptr_t)p2->p_fd);
2133 		break;
2134 	case KCMP_SIGHAND:
2135 		res = kcmp_cmp((uintptr_t)p1->p_sigacts,
2136 		    (uintptr_t)p2->p_sigacts);
2137 		break;
2138 	case KCMP_VM:
2139 		res = kcmp_cmp((uintptr_t)p1->p_vmspace,
2140 		    (uintptr_t)p2->p_vmspace);
2141 		break;
2142 	default:
2143 		error = EINVAL;
2144 		break;
2145 	}
2146 
2147 out:
2148 	if (p1 != NULL && p1 != td->td_proc)
2149 		PRELE(p1);
2150 	if (p2 != NULL && p2 != td->td_proc)
2151 		PRELE(p2);
2152 
2153 	td->td_retval[0] = res;
2154 	return (error);
2155 }
2156 
2157 int
2158 sys_kcmp(struct thread *td, struct kcmp_args *uap)
2159 {
2160 	return (kern_kcmp(td, uap->pid1, uap->pid2, uap->type,
2161 	    uap->idx1, uap->idx2));
2162 }
2163 
2164 int
2165 file_kcmp_generic(struct file *fp1, struct file *fp2, struct thread *td)
2166 {
2167 	if (fp1->f_type != fp2->f_type)
2168 		return (3);
2169 	return (kcmp_cmp((uintptr_t)fp1->f_data, (uintptr_t)fp2->f_data));
2170 }
2171