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