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