xref: /freebsd-14.2/sys/kern/kern_descrip.c (revision e05087ee)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1991, 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  *	@(#)kern_descrip.c	8.6 (Berkeley) 4/19/94
37  */
38 
39 #include <sys/cdefs.h>
40 #include "opt_capsicum.h"
41 #include "opt_ddb.h"
42 #include "opt_ktrace.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 
47 #include <sys/capsicum.h>
48 #include <sys/conf.h>
49 #include <sys/fcntl.h>
50 #include <sys/file.h>
51 #include <sys/filedesc.h>
52 #include <sys/filio.h>
53 #include <sys/jail.h>
54 #include <sys/kernel.h>
55 #include <sys/limits.h>
56 #include <sys/lock.h>
57 #include <sys/malloc.h>
58 #include <sys/mount.h>
59 #include <sys/mutex.h>
60 #include <sys/namei.h>
61 #include <sys/selinfo.h>
62 #include <sys/poll.h>
63 #include <sys/priv.h>
64 #include <sys/proc.h>
65 #include <sys/protosw.h>
66 #include <sys/racct.h>
67 #include <sys/resourcevar.h>
68 #include <sys/sbuf.h>
69 #include <sys/signalvar.h>
70 #include <sys/kdb.h>
71 #include <sys/smr.h>
72 #include <sys/stat.h>
73 #include <sys/sx.h>
74 #include <sys/syscallsubr.h>
75 #include <sys/sysctl.h>
76 #include <sys/sysproto.h>
77 #include <sys/unistd.h>
78 #include <sys/user.h>
79 #include <sys/vnode.h>
80 #include <sys/ktrace.h>
81 
82 #include <net/vnet.h>
83 
84 #include <security/audit/audit.h>
85 
86 #include <vm/uma.h>
87 #include <vm/vm.h>
88 
89 #include <ddb/ddb.h>
90 
91 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
92 static MALLOC_DEFINE(M_PWD, "pwd", "Descriptor table vnodes");
93 static MALLOC_DEFINE(M_PWDDESC, "pwddesc", "Pwd descriptors");
94 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
95     "file desc to leader structures");
96 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
97 MALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities");
98 
99 MALLOC_DECLARE(M_FADVISE);
100 
101 static __read_mostly uma_zone_t file_zone;
102 static __read_mostly uma_zone_t filedesc0_zone;
103 __read_mostly uma_zone_t pwd_zone;
104 VFS_SMR_DECLARE;
105 
106 static int	closefp(struct filedesc *fdp, int fd, struct file *fp,
107 		    struct thread *td, bool holdleaders, bool audit);
108 static void	export_file_to_kinfo(struct file *fp, int fd,
109 		    cap_rights_t *rightsp, struct kinfo_file *kif,
110 		    struct filedesc *fdp, int flags);
111 static int	fd_first_free(struct filedesc *fdp, int low, int size);
112 static void	fdgrowtable(struct filedesc *fdp, int nfd);
113 static void	fdgrowtable_exp(struct filedesc *fdp, int nfd);
114 static void	fdunused(struct filedesc *fdp, int fd);
115 static void	fdused(struct filedesc *fdp, int fd);
116 static int	fget_unlocked_seq(struct thread *td, int fd,
117 		    cap_rights_t *needrightsp, struct file **fpp, seqc_t *seqp);
118 static int	getmaxfd(struct thread *td);
119 static u_long	*filecaps_copy_prep(const struct filecaps *src);
120 static void	filecaps_copy_finish(const struct filecaps *src,
121 		    struct filecaps *dst, u_long *ioctls);
122 static u_long 	*filecaps_free_prep(struct filecaps *fcaps);
123 static void	filecaps_free_finish(u_long *ioctls);
124 
125 static struct pwd *pwd_alloc(void);
126 
127 /*
128  * Each process has:
129  *
130  * - An array of open file descriptors (fd_ofiles)
131  * - An array of file flags (fd_ofileflags)
132  * - A bitmap recording which descriptors are in use (fd_map)
133  *
134  * A process starts out with NDFILE descriptors.  The value of NDFILE has
135  * been selected based the historical limit of 20 open files, and an
136  * assumption that the majority of processes, especially short-lived
137  * processes like shells, will never need more.
138  *
139  * If this initial allocation is exhausted, a larger descriptor table and
140  * map are allocated dynamically, and the pointers in the process's struct
141  * filedesc are updated to point to those.  This is repeated every time
142  * the process runs out of file descriptors (provided it hasn't hit its
143  * resource limit).
144  *
145  * Since threads may hold references to individual descriptor table
146  * entries, the tables are never freed.  Instead, they are placed on a
147  * linked list and freed only when the struct filedesc is released.
148  */
149 #define NDFILE		20
150 #define NDSLOTSIZE	sizeof(NDSLOTTYPE)
151 #define	NDENTRIES	(NDSLOTSIZE * __CHAR_BIT)
152 #define NDSLOT(x)	((x) / NDENTRIES)
153 #define NDBIT(x)	((NDSLOTTYPE)1 << ((x) % NDENTRIES))
154 #define	NDSLOTS(x)	(((x) + NDENTRIES - 1) / NDENTRIES)
155 
156 #define	FILEDESC_FOREACH_FDE(fdp, _iterator, _fde)				\
157 	struct filedesc *_fdp = (fdp);						\
158 	int _lastfile = fdlastfile_single(_fdp);				\
159 	for (_iterator = 0; _iterator <= _lastfile; _iterator++)		\
160 		if ((_fde = &_fdp->fd_ofiles[_iterator])->fde_file != NULL)
161 
162 #define	FILEDESC_FOREACH_FP(fdp, _iterator, _fp)				\
163 	struct filedesc *_fdp = (fdp);						\
164 	int _lastfile = fdlastfile_single(_fdp);				\
165 	for (_iterator = 0; _iterator <= _lastfile; _iterator++)		\
166 		if ((_fp = _fdp->fd_ofiles[_iterator].fde_file) != NULL)
167 
168 /*
169  * SLIST entry used to keep track of ofiles which must be reclaimed when
170  * the process exits.
171  */
172 struct freetable {
173 	struct fdescenttbl *ft_table;
174 	SLIST_ENTRY(freetable) ft_next;
175 };
176 
177 /*
178  * Initial allocation: a filedesc structure + the head of SLIST used to
179  * keep track of old ofiles + enough space for NDFILE descriptors.
180  */
181 
182 struct fdescenttbl0 {
183 	int	fdt_nfiles;
184 	struct	filedescent fdt_ofiles[NDFILE];
185 };
186 
187 struct filedesc0 {
188 	struct filedesc fd_fd;
189 	SLIST_HEAD(, freetable) fd_free;
190 	struct	fdescenttbl0 fd_dfiles;
191 	NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
192 };
193 
194 /*
195  * Descriptor management.
196  */
197 static int __exclusive_cache_line openfiles; /* actual number of open files */
198 struct mtx sigio_lock;		/* mtx to protect pointers to sigio */
199 void __read_mostly (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
200 
201 /*
202  * If low >= size, just return low. Otherwise find the first zero bit in the
203  * given bitmap, starting at low and not exceeding size - 1. Return size if
204  * not found.
205  */
206 static int
fd_first_free(struct filedesc * fdp,int low,int size)207 fd_first_free(struct filedesc *fdp, int low, int size)
208 {
209 	NDSLOTTYPE *map = fdp->fd_map;
210 	NDSLOTTYPE mask;
211 	int off, maxoff;
212 
213 	if (low >= size)
214 		return (low);
215 
216 	off = NDSLOT(low);
217 	if (low % NDENTRIES) {
218 		mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
219 		if ((mask &= ~map[off]) != 0UL)
220 			return (off * NDENTRIES + ffsl(mask) - 1);
221 		++off;
222 	}
223 	for (maxoff = NDSLOTS(size); off < maxoff; ++off)
224 		if (map[off] != ~0UL)
225 			return (off * NDENTRIES + ffsl(~map[off]) - 1);
226 	return (size);
227 }
228 
229 /*
230  * Find the last used fd.
231  *
232  * Call this variant if fdp can't be modified by anyone else (e.g, during exec).
233  * Otherwise use fdlastfile.
234  */
235 int
fdlastfile_single(struct filedesc * fdp)236 fdlastfile_single(struct filedesc *fdp)
237 {
238 	NDSLOTTYPE *map = fdp->fd_map;
239 	int off, minoff;
240 
241 	off = NDSLOT(fdp->fd_nfiles - 1);
242 	for (minoff = NDSLOT(0); off >= minoff; --off)
243 		if (map[off] != 0)
244 			return (off * NDENTRIES + flsl(map[off]) - 1);
245 	return (-1);
246 }
247 
248 int
fdlastfile(struct filedesc * fdp)249 fdlastfile(struct filedesc *fdp)
250 {
251 
252 	FILEDESC_LOCK_ASSERT(fdp);
253 	return (fdlastfile_single(fdp));
254 }
255 
256 static int
fdisused(struct filedesc * fdp,int fd)257 fdisused(struct filedesc *fdp, int fd)
258 {
259 
260 	KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
261 	    ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
262 
263 	return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
264 }
265 
266 /*
267  * Mark a file descriptor as used.
268  */
269 static void
fdused_init(struct filedesc * fdp,int fd)270 fdused_init(struct filedesc *fdp, int fd)
271 {
272 
273 	KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
274 
275 	fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
276 }
277 
278 static void
fdused(struct filedesc * fdp,int fd)279 fdused(struct filedesc *fdp, int fd)
280 {
281 
282 	FILEDESC_XLOCK_ASSERT(fdp);
283 
284 	fdused_init(fdp, fd);
285 	if (fd == fdp->fd_freefile)
286 		fdp->fd_freefile++;
287 }
288 
289 /*
290  * Mark a file descriptor as unused.
291  */
292 static void
fdunused(struct filedesc * fdp,int fd)293 fdunused(struct filedesc *fdp, int fd)
294 {
295 
296 	FILEDESC_XLOCK_ASSERT(fdp);
297 
298 	KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
299 	KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
300 	    ("fd=%d is still in use", fd));
301 
302 	fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
303 	if (fd < fdp->fd_freefile)
304 		fdp->fd_freefile = fd;
305 }
306 
307 /*
308  * Free a file descriptor.
309  *
310  * Avoid some work if fdp is about to be destroyed.
311  */
312 static inline void
fdefree_last(struct filedescent * fde)313 fdefree_last(struct filedescent *fde)
314 {
315 
316 	filecaps_free(&fde->fde_caps);
317 }
318 
319 static inline void
fdfree(struct filedesc * fdp,int fd)320 fdfree(struct filedesc *fdp, int fd)
321 {
322 	struct filedescent *fde;
323 
324 	FILEDESC_XLOCK_ASSERT(fdp);
325 	fde = &fdp->fd_ofiles[fd];
326 #ifdef CAPABILITIES
327 	seqc_write_begin(&fde->fde_seqc);
328 #endif
329 	fde->fde_file = NULL;
330 #ifdef CAPABILITIES
331 	seqc_write_end(&fde->fde_seqc);
332 #endif
333 	fdefree_last(fde);
334 	fdunused(fdp, fd);
335 }
336 
337 /*
338  * System calls on descriptors.
339  */
340 #ifndef _SYS_SYSPROTO_H_
341 struct getdtablesize_args {
342 	int	dummy;
343 };
344 #endif
345 /* ARGSUSED */
346 int
sys_getdtablesize(struct thread * td,struct getdtablesize_args * uap)347 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
348 {
349 #ifdef	RACCT
350 	uint64_t lim;
351 #endif
352 
353 	td->td_retval[0] = getmaxfd(td);
354 #ifdef	RACCT
355 	PROC_LOCK(td->td_proc);
356 	lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
357 	PROC_UNLOCK(td->td_proc);
358 	if (lim < td->td_retval[0])
359 		td->td_retval[0] = lim;
360 #endif
361 	return (0);
362 }
363 
364 /*
365  * Duplicate a file descriptor to a particular value.
366  *
367  * Note: keep in mind that a potential race condition exists when closing
368  * descriptors from a shared descriptor table (via rfork).
369  */
370 #ifndef _SYS_SYSPROTO_H_
371 struct dup2_args {
372 	u_int	from;
373 	u_int	to;
374 };
375 #endif
376 /* ARGSUSED */
377 int
sys_dup2(struct thread * td,struct dup2_args * uap)378 sys_dup2(struct thread *td, struct dup2_args *uap)
379 {
380 
381 	return (kern_dup(td, FDDUP_FIXED, 0, (int)uap->from, (int)uap->to));
382 }
383 
384 /*
385  * Duplicate a file descriptor.
386  */
387 #ifndef _SYS_SYSPROTO_H_
388 struct dup_args {
389 	u_int	fd;
390 };
391 #endif
392 /* ARGSUSED */
393 int
sys_dup(struct thread * td,struct dup_args * uap)394 sys_dup(struct thread *td, struct dup_args *uap)
395 {
396 
397 	return (kern_dup(td, FDDUP_NORMAL, 0, (int)uap->fd, 0));
398 }
399 
400 /*
401  * The file control system call.
402  */
403 #ifndef _SYS_SYSPROTO_H_
404 struct fcntl_args {
405 	int	fd;
406 	int	cmd;
407 	long	arg;
408 };
409 #endif
410 /* ARGSUSED */
411 int
sys_fcntl(struct thread * td,struct fcntl_args * uap)412 sys_fcntl(struct thread *td, struct fcntl_args *uap)
413 {
414 
415 	return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg));
416 }
417 
418 int
kern_fcntl_freebsd(struct thread * td,int fd,int cmd,long arg)419 kern_fcntl_freebsd(struct thread *td, int fd, int cmd, long arg)
420 {
421 	struct flock fl;
422 	struct __oflock ofl;
423 	intptr_t arg1;
424 	int error, newcmd;
425 
426 	error = 0;
427 	newcmd = cmd;
428 	switch (cmd) {
429 	case F_OGETLK:
430 	case F_OSETLK:
431 	case F_OSETLKW:
432 		/*
433 		 * Convert old flock structure to new.
434 		 */
435 		error = copyin((void *)(intptr_t)arg, &ofl, sizeof(ofl));
436 		fl.l_start = ofl.l_start;
437 		fl.l_len = ofl.l_len;
438 		fl.l_pid = ofl.l_pid;
439 		fl.l_type = ofl.l_type;
440 		fl.l_whence = ofl.l_whence;
441 		fl.l_sysid = 0;
442 
443 		switch (cmd) {
444 		case F_OGETLK:
445 			newcmd = F_GETLK;
446 			break;
447 		case F_OSETLK:
448 			newcmd = F_SETLK;
449 			break;
450 		case F_OSETLKW:
451 			newcmd = F_SETLKW;
452 			break;
453 		}
454 		arg1 = (intptr_t)&fl;
455 		break;
456 	case F_GETLK:
457 	case F_SETLK:
458 	case F_SETLKW:
459 	case F_SETLK_REMOTE:
460 		error = copyin((void *)(intptr_t)arg, &fl, sizeof(fl));
461 		arg1 = (intptr_t)&fl;
462 		break;
463 	default:
464 		arg1 = arg;
465 		break;
466 	}
467 	if (error)
468 		return (error);
469 	error = kern_fcntl(td, fd, newcmd, arg1);
470 	if (error)
471 		return (error);
472 	if (cmd == F_OGETLK) {
473 		ofl.l_start = fl.l_start;
474 		ofl.l_len = fl.l_len;
475 		ofl.l_pid = fl.l_pid;
476 		ofl.l_type = fl.l_type;
477 		ofl.l_whence = fl.l_whence;
478 		error = copyout(&ofl, (void *)(intptr_t)arg, sizeof(ofl));
479 	} else if (cmd == F_GETLK) {
480 		error = copyout(&fl, (void *)(intptr_t)arg, sizeof(fl));
481 	}
482 	return (error);
483 }
484 
485 int
kern_fcntl(struct thread * td,int fd,int cmd,intptr_t arg)486 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
487 {
488 	struct filedesc *fdp;
489 	struct flock *flp;
490 	struct file *fp, *fp2;
491 	struct filedescent *fde;
492 	struct proc *p;
493 	struct vnode *vp;
494 	struct mount *mp;
495 	struct kinfo_file *kif;
496 	int error, flg, kif_sz, seals, tmp, got_set, got_cleared;
497 	uint64_t bsize;
498 	off_t foffset;
499 
500 	error = 0;
501 	flg = F_POSIX;
502 	p = td->td_proc;
503 	fdp = p->p_fd;
504 
505 	AUDIT_ARG_FD(cmd);
506 	AUDIT_ARG_CMD(cmd);
507 	switch (cmd) {
508 	case F_DUPFD:
509 		tmp = arg;
510 		error = kern_dup(td, FDDUP_FCNTL, 0, fd, tmp);
511 		break;
512 
513 	case F_DUPFD_CLOEXEC:
514 		tmp = arg;
515 		error = kern_dup(td, FDDUP_FCNTL, FDDUP_FLAG_CLOEXEC, fd, tmp);
516 		break;
517 
518 	case F_DUP2FD:
519 		tmp = arg;
520 		error = kern_dup(td, FDDUP_FIXED, 0, fd, tmp);
521 		break;
522 
523 	case F_DUP2FD_CLOEXEC:
524 		tmp = arg;
525 		error = kern_dup(td, FDDUP_FIXED, FDDUP_FLAG_CLOEXEC, fd, tmp);
526 		break;
527 
528 	case F_GETFD:
529 		error = EBADF;
530 		FILEDESC_SLOCK(fdp);
531 		fde = fdeget_noref(fdp, fd);
532 		if (fde != NULL) {
533 			td->td_retval[0] =
534 			    (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
535 			error = 0;
536 		}
537 		FILEDESC_SUNLOCK(fdp);
538 		break;
539 
540 	case F_SETFD:
541 		error = EBADF;
542 		FILEDESC_XLOCK(fdp);
543 		fde = fdeget_noref(fdp, fd);
544 		if (fde != NULL) {
545 			fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
546 			    (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
547 			error = 0;
548 		}
549 		FILEDESC_XUNLOCK(fdp);
550 		break;
551 
552 	case F_GETFL:
553 		error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETFL, &fp);
554 		if (error != 0)
555 			break;
556 		td->td_retval[0] = OFLAGS(fp->f_flag);
557 		fdrop(fp, td);
558 		break;
559 
560 	case F_SETFL:
561 		error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETFL, &fp);
562 		if (error != 0)
563 			break;
564 		if (fp->f_ops == &path_fileops) {
565 			fdrop(fp, td);
566 			error = EBADF;
567 			break;
568 		}
569 		do {
570 			tmp = flg = fp->f_flag;
571 			tmp &= ~FCNTLFLAGS;
572 			tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
573 		} while (atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
574 		got_set = tmp & ~flg;
575 		got_cleared = flg & ~tmp;
576 		tmp = fp->f_flag & FNONBLOCK;
577 		error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
578 		if (error != 0)
579 			goto revert_f_setfl;
580 		tmp = fp->f_flag & FASYNC;
581 		error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
582 		if (error == 0) {
583 			fdrop(fp, td);
584 			break;
585 		}
586 		atomic_clear_int(&fp->f_flag, FNONBLOCK);
587 		tmp = 0;
588 		(void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
589 revert_f_setfl:
590 		do {
591 			tmp = flg = fp->f_flag;
592 			tmp &= ~FCNTLFLAGS;
593 			tmp |= got_cleared;
594 			tmp &= ~got_set;
595 		} while (atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
596 		fdrop(fp, td);
597 		break;
598 
599 	case F_GETOWN:
600 		error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETOWN, &fp);
601 		if (error != 0)
602 			break;
603 		error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
604 		if (error == 0)
605 			td->td_retval[0] = tmp;
606 		fdrop(fp, td);
607 		break;
608 
609 	case F_SETOWN:
610 		error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETOWN, &fp);
611 		if (error != 0)
612 			break;
613 		tmp = arg;
614 		error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
615 		fdrop(fp, td);
616 		break;
617 
618 	case F_SETLK_REMOTE:
619 		error = priv_check(td, PRIV_NFS_LOCKD);
620 		if (error != 0)
621 			return (error);
622 		flg = F_REMOTE;
623 		goto do_setlk;
624 
625 	case F_SETLKW:
626 		flg |= F_WAIT;
627 		/* FALLTHROUGH F_SETLK */
628 
629 	case F_SETLK:
630 	do_setlk:
631 		flp = (struct flock *)arg;
632 		if ((flg & F_REMOTE) != 0 && flp->l_sysid == 0) {
633 			error = EINVAL;
634 			break;
635 		}
636 
637 		error = fget_unlocked(td, fd, &cap_flock_rights, &fp);
638 		if (error != 0)
639 			break;
640 		if (fp->f_type != DTYPE_VNODE || fp->f_ops == &path_fileops) {
641 			error = EBADF;
642 			fdrop(fp, td);
643 			break;
644 		}
645 
646 		if (flp->l_whence == SEEK_CUR) {
647 			foffset = foffset_get(fp);
648 			if (foffset < 0 ||
649 			    (flp->l_start > 0 &&
650 			     foffset > OFF_MAX - flp->l_start)) {
651 				error = EOVERFLOW;
652 				fdrop(fp, td);
653 				break;
654 			}
655 			flp->l_start += foffset;
656 		}
657 
658 		vp = fp->f_vnode;
659 		switch (flp->l_type) {
660 		case F_RDLCK:
661 			if ((fp->f_flag & FREAD) == 0) {
662 				error = EBADF;
663 				break;
664 			}
665 			if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
666 				PROC_LOCK(p->p_leader);
667 				p->p_leader->p_flag |= P_ADVLOCK;
668 				PROC_UNLOCK(p->p_leader);
669 			}
670 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
671 			    flp, flg);
672 			break;
673 		case F_WRLCK:
674 			if ((fp->f_flag & FWRITE) == 0) {
675 				error = EBADF;
676 				break;
677 			}
678 			if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
679 				PROC_LOCK(p->p_leader);
680 				p->p_leader->p_flag |= P_ADVLOCK;
681 				PROC_UNLOCK(p->p_leader);
682 			}
683 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
684 			    flp, flg);
685 			break;
686 		case F_UNLCK:
687 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
688 			    flp, flg);
689 			break;
690 		case F_UNLCKSYS:
691 			if (flg != F_REMOTE) {
692 				error = EINVAL;
693 				break;
694 			}
695 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
696 			    F_UNLCKSYS, flp, flg);
697 			break;
698 		default:
699 			error = EINVAL;
700 			break;
701 		}
702 		if (error != 0 || flp->l_type == F_UNLCK ||
703 		    flp->l_type == F_UNLCKSYS) {
704 			fdrop(fp, td);
705 			break;
706 		}
707 
708 		/*
709 		 * Check for a race with close.
710 		 *
711 		 * The vnode is now advisory locked (or unlocked, but this case
712 		 * is not really important) as the caller requested.
713 		 * We had to drop the filedesc lock, so we need to recheck if
714 		 * the descriptor is still valid, because if it was closed
715 		 * in the meantime we need to remove advisory lock from the
716 		 * vnode - close on any descriptor leading to an advisory
717 		 * locked vnode, removes that lock.
718 		 * We will return 0 on purpose in that case, as the result of
719 		 * successful advisory lock might have been externally visible
720 		 * already. This is fine - effectively we pretend to the caller
721 		 * that the closing thread was a bit slower and that the
722 		 * advisory lock succeeded before the close.
723 		 */
724 		error = fget_unlocked(td, fd, &cap_no_rights, &fp2);
725 		if (error != 0) {
726 			fdrop(fp, td);
727 			break;
728 		}
729 		if (fp != fp2) {
730 			flp->l_whence = SEEK_SET;
731 			flp->l_start = 0;
732 			flp->l_len = 0;
733 			flp->l_type = F_UNLCK;
734 			(void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
735 			    F_UNLCK, flp, F_POSIX);
736 		}
737 		fdrop(fp, td);
738 		fdrop(fp2, td);
739 		break;
740 
741 	case F_GETLK:
742 		error = fget_unlocked(td, fd, &cap_flock_rights, &fp);
743 		if (error != 0)
744 			break;
745 		if (fp->f_type != DTYPE_VNODE || fp->f_ops == &path_fileops) {
746 			error = EBADF;
747 			fdrop(fp, td);
748 			break;
749 		}
750 		flp = (struct flock *)arg;
751 		if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
752 		    flp->l_type != F_UNLCK) {
753 			error = EINVAL;
754 			fdrop(fp, td);
755 			break;
756 		}
757 		if (flp->l_whence == SEEK_CUR) {
758 			foffset = foffset_get(fp);
759 			if ((flp->l_start > 0 &&
760 			    foffset > OFF_MAX - flp->l_start) ||
761 			    (flp->l_start < 0 &&
762 			    foffset < OFF_MIN - flp->l_start)) {
763 				error = EOVERFLOW;
764 				fdrop(fp, td);
765 				break;
766 			}
767 			flp->l_start += foffset;
768 		}
769 		vp = fp->f_vnode;
770 		error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
771 		    F_POSIX);
772 		fdrop(fp, td);
773 		break;
774 
775 	case F_ADD_SEALS:
776 		error = fget_unlocked(td, fd, &cap_no_rights, &fp);
777 		if (error != 0)
778 			break;
779 		error = fo_add_seals(fp, arg);
780 		fdrop(fp, td);
781 		break;
782 
783 	case F_GET_SEALS:
784 		error = fget_unlocked(td, fd, &cap_no_rights, &fp);
785 		if (error != 0)
786 			break;
787 		if (fo_get_seals(fp, &seals) == 0)
788 			td->td_retval[0] = seals;
789 		else
790 			error = EINVAL;
791 		fdrop(fp, td);
792 		break;
793 
794 	case F_RDAHEAD:
795 		arg = arg ? 128 * 1024: 0;
796 		/* FALLTHROUGH */
797 	case F_READAHEAD:
798 		error = fget_unlocked(td, fd, &cap_no_rights, &fp);
799 		if (error != 0)
800 			break;
801 		if (fp->f_type != DTYPE_VNODE || fp->f_ops == &path_fileops) {
802 			fdrop(fp, td);
803 			error = EBADF;
804 			break;
805 		}
806 		vp = fp->f_vnode;
807 		if (vp->v_type != VREG) {
808 			fdrop(fp, td);
809 			error = ENOTTY;
810 			break;
811 		}
812 
813 		/*
814 		 * Exclusive lock synchronizes against f_seqcount reads and
815 		 * writes in sequential_heuristic().
816 		 */
817 		error = vn_lock(vp, LK_EXCLUSIVE);
818 		if (error != 0) {
819 			fdrop(fp, td);
820 			break;
821 		}
822 		if (arg >= 0) {
823 			bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
824 			arg = MIN(arg, INT_MAX - bsize + 1);
825 			fp->f_seqcount[UIO_READ] = MIN(IO_SEQMAX,
826 			    (arg + bsize - 1) / bsize);
827 			atomic_set_int(&fp->f_flag, FRDAHEAD);
828 		} else {
829 			atomic_clear_int(&fp->f_flag, FRDAHEAD);
830 		}
831 		VOP_UNLOCK(vp);
832 		fdrop(fp, td);
833 		break;
834 
835 	case F_ISUNIONSTACK:
836 		/*
837 		 * Check if the vnode is part of a union stack (either the
838 		 * "union" flag from mount(2) or unionfs).
839 		 *
840 		 * Prior to introduction of this op libc's readdir would call
841 		 * fstatfs(2), in effect unnecessarily copying kilobytes of
842 		 * data just to check fs name and a mount flag.
843 		 *
844 		 * Fixing the code to handle everything in the kernel instead
845 		 * is a non-trivial endeavor and has low priority, thus this
846 		 * horrible kludge facilitates the current behavior in a much
847 		 * cheaper manner until someone(tm) sorts this out.
848 		 */
849 		error = fget_unlocked(td, fd, &cap_no_rights, &fp);
850 		if (error != 0)
851 			break;
852 		if (fp->f_type != DTYPE_VNODE) {
853 			fdrop(fp, td);
854 			error = EBADF;
855 			break;
856 		}
857 		vp = fp->f_vnode;
858 		/*
859 		 * Since we don't prevent dooming the vnode even non-null mp
860 		 * found can become immediately stale. This is tolerable since
861 		 * mount points are type-stable (providing safe memory access)
862 		 * and any vfs op on this vnode going forward will return an
863 		 * error (meaning return value in this case is meaningless).
864 		 */
865 		mp = atomic_load_ptr(&vp->v_mount);
866 		if (__predict_false(mp == NULL)) {
867 			fdrop(fp, td);
868 			error = EBADF;
869 			break;
870 		}
871 		td->td_retval[0] = 0;
872 		if (mp->mnt_kern_flag & MNTK_UNIONFS ||
873 		    mp->mnt_flag & MNT_UNION)
874 			td->td_retval[0] = 1;
875 		fdrop(fp, td);
876 		break;
877 
878 	case F_KINFO:
879 #ifdef CAPABILITY_MODE
880 		if (CAP_TRACING(td))
881 			ktrcapfail(CAPFAIL_SYSCALL, &cmd);
882 		if (IN_CAPABILITY_MODE(td)) {
883 			error = ECAPMODE;
884 			break;
885 		}
886 #endif
887 		error = copyin((void *)arg, &kif_sz, sizeof(kif_sz));
888 		if (error != 0)
889 			break;
890 		if (kif_sz != sizeof(*kif)) {
891 			error = EINVAL;
892 			break;
893 		}
894 		kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK | M_ZERO);
895 		FILEDESC_SLOCK(fdp);
896 		error = fget_cap_noref(fdp, fd, &cap_fcntl_rights, &fp, NULL);
897 		if (error == 0 && fhold(fp)) {
898 			export_file_to_kinfo(fp, fd, NULL, kif, fdp, 0);
899 			FILEDESC_SUNLOCK(fdp);
900 			fdrop(fp, td);
901 			if ((kif->kf_status & KF_ATTR_VALID) != 0) {
902 				kif->kf_structsize = sizeof(*kif);
903 				error = copyout(kif, (void *)arg, sizeof(*kif));
904 			} else {
905 				error = EBADF;
906 			}
907 		} else {
908 			FILEDESC_SUNLOCK(fdp);
909 			if (error == 0)
910 				error = EBADF;
911 		}
912 		free(kif, M_TEMP);
913 		break;
914 
915 	default:
916 		error = EINVAL;
917 		break;
918 	}
919 	return (error);
920 }
921 
922 static int
getmaxfd(struct thread * td)923 getmaxfd(struct thread *td)
924 {
925 
926 	return (min((int)lim_cur(td, RLIMIT_NOFILE), maxfilesperproc));
927 }
928 
929 /*
930  * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
931  */
932 int
kern_dup(struct thread * td,u_int mode,int flags,int old,int new)933 kern_dup(struct thread *td, u_int mode, int flags, int old, int new)
934 {
935 	struct filedesc *fdp;
936 	struct filedescent *oldfde, *newfde;
937 	struct proc *p;
938 	struct file *delfp, *oldfp;
939 	u_long *oioctls, *nioctls;
940 	int error, maxfd;
941 
942 	p = td->td_proc;
943 	fdp = p->p_fd;
944 	oioctls = NULL;
945 
946 	MPASS((flags & ~(FDDUP_FLAG_CLOEXEC)) == 0);
947 	MPASS(mode < FDDUP_LASTMODE);
948 
949 	AUDIT_ARG_FD(old);
950 	/* XXXRW: if (flags & FDDUP_FIXED) AUDIT_ARG_FD2(new); */
951 
952 	/*
953 	 * Verify we have a valid descriptor to dup from and possibly to
954 	 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
955 	 * return EINVAL when the new descriptor is out of bounds.
956 	 */
957 	if (old < 0)
958 		return (EBADF);
959 	if (new < 0)
960 		return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
961 	maxfd = getmaxfd(td);
962 	if (new >= maxfd)
963 		return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
964 
965 	error = EBADF;
966 	FILEDESC_XLOCK(fdp);
967 	if (fget_noref(fdp, old) == NULL)
968 		goto unlock;
969 	if (mode == FDDUP_FIXED && old == new) {
970 		td->td_retval[0] = new;
971 		if (flags & FDDUP_FLAG_CLOEXEC)
972 			fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
973 		error = 0;
974 		goto unlock;
975 	}
976 
977 	oldfde = &fdp->fd_ofiles[old];
978 	oldfp = oldfde->fde_file;
979 	if (!fhold(oldfp))
980 		goto unlock;
981 
982 	/*
983 	 * If the caller specified a file descriptor, make sure the file
984 	 * table is large enough to hold it, and grab it.  Otherwise, just
985 	 * allocate a new descriptor the usual way.
986 	 */
987 	switch (mode) {
988 	case FDDUP_NORMAL:
989 	case FDDUP_FCNTL:
990 		if ((error = fdalloc(td, new, &new)) != 0) {
991 			fdrop(oldfp, td);
992 			goto unlock;
993 		}
994 		break;
995 	case FDDUP_FIXED:
996 		if (new >= fdp->fd_nfiles) {
997 			/*
998 			 * The resource limits are here instead of e.g.
999 			 * fdalloc(), because the file descriptor table may be
1000 			 * shared between processes, so we can't really use
1001 			 * racct_add()/racct_sub().  Instead of counting the
1002 			 * number of actually allocated descriptors, just put
1003 			 * the limit on the size of the file descriptor table.
1004 			 */
1005 #ifdef RACCT
1006 			if (RACCT_ENABLED()) {
1007 				error = racct_set_unlocked(p, RACCT_NOFILE, new + 1);
1008 				if (error != 0) {
1009 					error = EMFILE;
1010 					fdrop(oldfp, td);
1011 					goto unlock;
1012 				}
1013 			}
1014 #endif
1015 			fdgrowtable_exp(fdp, new + 1);
1016 		}
1017 		if (!fdisused(fdp, new))
1018 			fdused(fdp, new);
1019 		break;
1020 	default:
1021 		KASSERT(0, ("%s unsupported mode %d", __func__, mode));
1022 	}
1023 
1024 	KASSERT(old != new, ("new fd is same as old"));
1025 
1026 	/* Refetch oldfde because the table may have grown and old one freed. */
1027 	oldfde = &fdp->fd_ofiles[old];
1028 	KASSERT(oldfp == oldfde->fde_file,
1029 	    ("fdt_ofiles shift from growth observed at fd %d",
1030 	    old));
1031 
1032 	newfde = &fdp->fd_ofiles[new];
1033 	delfp = newfde->fde_file;
1034 
1035 	nioctls = filecaps_copy_prep(&oldfde->fde_caps);
1036 
1037 	/*
1038 	 * Duplicate the source descriptor.
1039 	 */
1040 #ifdef CAPABILITIES
1041 	seqc_write_begin(&newfde->fde_seqc);
1042 #endif
1043 	oioctls = filecaps_free_prep(&newfde->fde_caps);
1044 	fde_copy(oldfde, newfde);
1045 	filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
1046 	    nioctls);
1047 	if ((flags & FDDUP_FLAG_CLOEXEC) != 0)
1048 		newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
1049 	else
1050 		newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
1051 #ifdef CAPABILITIES
1052 	seqc_write_end(&newfde->fde_seqc);
1053 #endif
1054 	td->td_retval[0] = new;
1055 
1056 	error = 0;
1057 
1058 	if (delfp != NULL) {
1059 		(void) closefp(fdp, new, delfp, td, true, false);
1060 		FILEDESC_UNLOCK_ASSERT(fdp);
1061 	} else {
1062 unlock:
1063 		FILEDESC_XUNLOCK(fdp);
1064 	}
1065 
1066 	filecaps_free_finish(oioctls);
1067 	return (error);
1068 }
1069 
1070 static void
sigiofree(struct sigio * sigio)1071 sigiofree(struct sigio *sigio)
1072 {
1073 	crfree(sigio->sio_ucred);
1074 	free(sigio, M_SIGIO);
1075 }
1076 
1077 static struct sigio *
funsetown_locked(struct sigio * sigio)1078 funsetown_locked(struct sigio *sigio)
1079 {
1080 	struct proc *p;
1081 	struct pgrp *pg;
1082 
1083 	SIGIO_ASSERT_LOCKED();
1084 
1085 	if (sigio == NULL)
1086 		return (NULL);
1087 	*sigio->sio_myref = NULL;
1088 	if (sigio->sio_pgid < 0) {
1089 		pg = sigio->sio_pgrp;
1090 		PGRP_LOCK(pg);
1091 		SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio, sio_pgsigio);
1092 		PGRP_UNLOCK(pg);
1093 	} else {
1094 		p = sigio->sio_proc;
1095 		PROC_LOCK(p);
1096 		SLIST_REMOVE(&p->p_sigiolst, sigio, sigio, sio_pgsigio);
1097 		PROC_UNLOCK(p);
1098 	}
1099 	return (sigio);
1100 }
1101 
1102 /*
1103  * If sigio is on the list associated with a process or process group,
1104  * disable signalling from the device, remove sigio from the list and
1105  * free sigio.
1106  */
1107 void
funsetown(struct sigio ** sigiop)1108 funsetown(struct sigio **sigiop)
1109 {
1110 	struct sigio *sigio;
1111 
1112 	/* Racy check, consumers must provide synchronization. */
1113 	if (*sigiop == NULL)
1114 		return;
1115 
1116 	SIGIO_LOCK();
1117 	sigio = funsetown_locked(*sigiop);
1118 	SIGIO_UNLOCK();
1119 	if (sigio != NULL)
1120 		sigiofree(sigio);
1121 }
1122 
1123 /*
1124  * Free a list of sigio structures.  The caller must ensure that new sigio
1125  * structures cannot be added after this point.  For process groups this is
1126  * guaranteed using the proctree lock; for processes, the P_WEXIT flag serves
1127  * as an interlock.
1128  */
1129 void
funsetownlst(struct sigiolst * sigiolst)1130 funsetownlst(struct sigiolst *sigiolst)
1131 {
1132 	struct proc *p;
1133 	struct pgrp *pg;
1134 	struct sigio *sigio, *tmp;
1135 
1136 	/* Racy check. */
1137 	sigio = SLIST_FIRST(sigiolst);
1138 	if (sigio == NULL)
1139 		return;
1140 
1141 	p = NULL;
1142 	pg = NULL;
1143 
1144 	SIGIO_LOCK();
1145 	sigio = SLIST_FIRST(sigiolst);
1146 	if (sigio == NULL) {
1147 		SIGIO_UNLOCK();
1148 		return;
1149 	}
1150 
1151 	/*
1152 	 * Every entry of the list should belong to a single proc or pgrp.
1153 	 */
1154 	if (sigio->sio_pgid < 0) {
1155 		pg = sigio->sio_pgrp;
1156 		sx_assert(&proctree_lock, SX_XLOCKED);
1157 		PGRP_LOCK(pg);
1158 	} else /* if (sigio->sio_pgid > 0) */ {
1159 		p = sigio->sio_proc;
1160 		PROC_LOCK(p);
1161 		KASSERT((p->p_flag & P_WEXIT) != 0,
1162 		    ("%s: process %p is not exiting", __func__, p));
1163 	}
1164 
1165 	SLIST_FOREACH(sigio, sigiolst, sio_pgsigio) {
1166 		*sigio->sio_myref = NULL;
1167 		if (pg != NULL) {
1168 			KASSERT(sigio->sio_pgid < 0,
1169 			    ("Proc sigio in pgrp sigio list"));
1170 			KASSERT(sigio->sio_pgrp == pg,
1171 			    ("Bogus pgrp in sigio list"));
1172 		} else /* if (p != NULL) */ {
1173 			KASSERT(sigio->sio_pgid > 0,
1174 			    ("Pgrp sigio in proc sigio list"));
1175 			KASSERT(sigio->sio_proc == p,
1176 			    ("Bogus proc in sigio list"));
1177 		}
1178 	}
1179 
1180 	if (pg != NULL)
1181 		PGRP_UNLOCK(pg);
1182 	else
1183 		PROC_UNLOCK(p);
1184 	SIGIO_UNLOCK();
1185 
1186 	SLIST_FOREACH_SAFE(sigio, sigiolst, sio_pgsigio, tmp)
1187 		sigiofree(sigio);
1188 }
1189 
1190 /*
1191  * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1192  *
1193  * After permission checking, add a sigio structure to the sigio list for
1194  * the process or process group.
1195  */
1196 int
fsetown(pid_t pgid,struct sigio ** sigiop)1197 fsetown(pid_t pgid, struct sigio **sigiop)
1198 {
1199 	struct proc *proc;
1200 	struct pgrp *pgrp;
1201 	struct sigio *osigio, *sigio;
1202 	int ret;
1203 
1204 	if (pgid == 0) {
1205 		funsetown(sigiop);
1206 		return (0);
1207 	}
1208 
1209 	sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1210 	sigio->sio_pgid = pgid;
1211 	sigio->sio_ucred = crhold(curthread->td_ucred);
1212 	sigio->sio_myref = sigiop;
1213 
1214 	ret = 0;
1215 	if (pgid > 0) {
1216 		ret = pget(pgid, PGET_NOTWEXIT | PGET_NOTID | PGET_HOLD, &proc);
1217 		SIGIO_LOCK();
1218 		osigio = funsetown_locked(*sigiop);
1219 		if (ret == 0) {
1220 			PROC_LOCK(proc);
1221 			_PRELE(proc);
1222 			if ((proc->p_flag & P_WEXIT) != 0) {
1223 				ret = ESRCH;
1224 			} else if (proc->p_session !=
1225 			    curthread->td_proc->p_session) {
1226 				/*
1227 				 * Policy - Don't allow a process to FSETOWN a
1228 				 * process in another session.
1229 				 *
1230 				 * Remove this test to allow maximum flexibility
1231 				 * or restrict FSETOWN to the current process or
1232 				 * process group for maximum safety.
1233 				 */
1234 				ret = EPERM;
1235 			} else {
1236 				sigio->sio_proc = proc;
1237 				SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio,
1238 				    sio_pgsigio);
1239 			}
1240 			PROC_UNLOCK(proc);
1241 		}
1242 	} else /* if (pgid < 0) */ {
1243 		sx_slock(&proctree_lock);
1244 		SIGIO_LOCK();
1245 		osigio = funsetown_locked(*sigiop);
1246 		pgrp = pgfind(-pgid);
1247 		if (pgrp == NULL) {
1248 			ret = ESRCH;
1249 		} else {
1250 			if (pgrp->pg_session != curthread->td_proc->p_session) {
1251 				/*
1252 				 * Policy - Don't allow a process to FSETOWN a
1253 				 * process in another session.
1254 				 *
1255 				 * Remove this test to allow maximum flexibility
1256 				 * or restrict FSETOWN to the current process or
1257 				 * process group for maximum safety.
1258 				 */
1259 				ret = EPERM;
1260 			} else {
1261 				sigio->sio_pgrp = pgrp;
1262 				SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio,
1263 				    sio_pgsigio);
1264 			}
1265 			PGRP_UNLOCK(pgrp);
1266 		}
1267 		sx_sunlock(&proctree_lock);
1268 	}
1269 	if (ret == 0)
1270 		*sigiop = sigio;
1271 	SIGIO_UNLOCK();
1272 	if (osigio != NULL)
1273 		sigiofree(osigio);
1274 	return (ret);
1275 }
1276 
1277 /*
1278  * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1279  */
1280 pid_t
fgetown(struct sigio ** sigiop)1281 fgetown(struct sigio **sigiop)
1282 {
1283 	pid_t pgid;
1284 
1285 	SIGIO_LOCK();
1286 	pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1287 	SIGIO_UNLOCK();
1288 	return (pgid);
1289 }
1290 
1291 static int
closefp_impl(struct filedesc * fdp,int fd,struct file * fp,struct thread * td,bool audit)1292 closefp_impl(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1293     bool audit)
1294 {
1295 	int error;
1296 
1297 	FILEDESC_XLOCK_ASSERT(fdp);
1298 
1299 	/*
1300 	 * We now hold the fp reference that used to be owned by the
1301 	 * descriptor array.  We have to unlock the FILEDESC *AFTER*
1302 	 * knote_fdclose to prevent a race of the fd getting opened, a knote
1303 	 * added, and deleteing a knote for the new fd.
1304 	 */
1305 	if (__predict_false(!TAILQ_EMPTY(&fdp->fd_kqlist)))
1306 		knote_fdclose(td, fd);
1307 
1308 	/*
1309 	 * We need to notify mqueue if the object is of type mqueue.
1310 	 */
1311 	if (__predict_false(fp->f_type == DTYPE_MQUEUE))
1312 		mq_fdclose(td, fd, fp);
1313 	FILEDESC_XUNLOCK(fdp);
1314 
1315 #ifdef AUDIT
1316 	if (AUDITING_TD(td) && audit)
1317 		audit_sysclose(td, fd, fp);
1318 #endif
1319 	error = closef(fp, td);
1320 
1321 	/*
1322 	 * All paths leading up to closefp() will have already removed or
1323 	 * replaced the fd in the filedesc table, so a restart would not
1324 	 * operate on the same file.
1325 	 */
1326 	if (error == ERESTART)
1327 		error = EINTR;
1328 
1329 	return (error);
1330 }
1331 
1332 static int
closefp_hl(struct filedesc * fdp,int fd,struct file * fp,struct thread * td,bool holdleaders,bool audit)1333 closefp_hl(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1334     bool holdleaders, bool audit)
1335 {
1336 	int error;
1337 
1338 	FILEDESC_XLOCK_ASSERT(fdp);
1339 
1340 	if (holdleaders) {
1341 		if (td->td_proc->p_fdtol != NULL) {
1342 			/*
1343 			 * Ask fdfree() to sleep to ensure that all relevant
1344 			 * process leaders can be traversed in closef().
1345 			 */
1346 			fdp->fd_holdleaderscount++;
1347 		} else {
1348 			holdleaders = false;
1349 		}
1350 	}
1351 
1352 	error = closefp_impl(fdp, fd, fp, td, audit);
1353 	if (holdleaders) {
1354 		FILEDESC_XLOCK(fdp);
1355 		fdp->fd_holdleaderscount--;
1356 		if (fdp->fd_holdleaderscount == 0 &&
1357 		    fdp->fd_holdleaderswakeup != 0) {
1358 			fdp->fd_holdleaderswakeup = 0;
1359 			wakeup(&fdp->fd_holdleaderscount);
1360 		}
1361 		FILEDESC_XUNLOCK(fdp);
1362 	}
1363 	return (error);
1364 }
1365 
1366 static int
closefp(struct filedesc * fdp,int fd,struct file * fp,struct thread * td,bool holdleaders,bool audit)1367 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1368     bool holdleaders, bool audit)
1369 {
1370 
1371 	FILEDESC_XLOCK_ASSERT(fdp);
1372 
1373 	if (__predict_false(td->td_proc->p_fdtol != NULL)) {
1374 		return (closefp_hl(fdp, fd, fp, td, holdleaders, audit));
1375 	} else {
1376 		return (closefp_impl(fdp, fd, fp, td, audit));
1377 	}
1378 }
1379 
1380 /*
1381  * Close a file descriptor.
1382  */
1383 #ifndef _SYS_SYSPROTO_H_
1384 struct close_args {
1385 	int     fd;
1386 };
1387 #endif
1388 /* ARGSUSED */
1389 int
sys_close(struct thread * td,struct close_args * uap)1390 sys_close(struct thread *td, struct close_args *uap)
1391 {
1392 
1393 	return (kern_close(td, uap->fd));
1394 }
1395 
1396 int
kern_close(struct thread * td,int fd)1397 kern_close(struct thread *td, int fd)
1398 {
1399 	struct filedesc *fdp;
1400 	struct file *fp;
1401 
1402 	fdp = td->td_proc->p_fd;
1403 
1404 	FILEDESC_XLOCK(fdp);
1405 	if ((fp = fget_noref(fdp, fd)) == NULL) {
1406 		FILEDESC_XUNLOCK(fdp);
1407 		return (EBADF);
1408 	}
1409 	fdfree(fdp, fd);
1410 
1411 	/* closefp() drops the FILEDESC lock for us. */
1412 	return (closefp(fdp, fd, fp, td, true, true));
1413 }
1414 
1415 static int
close_range_cloexec(struct thread * td,u_int lowfd,u_int highfd)1416 close_range_cloexec(struct thread *td, u_int lowfd, u_int highfd)
1417 {
1418 	struct filedesc *fdp;
1419 	struct fdescenttbl *fdt;
1420 	struct filedescent *fde;
1421 	int fd;
1422 
1423 	fdp = td->td_proc->p_fd;
1424 	FILEDESC_XLOCK(fdp);
1425 	fdt = atomic_load_ptr(&fdp->fd_files);
1426 	highfd = MIN(highfd, fdt->fdt_nfiles - 1);
1427 	fd = lowfd;
1428 	if (__predict_false(fd > highfd)) {
1429 		goto out_locked;
1430 	}
1431 	for (; fd <= highfd; fd++) {
1432 		fde = &fdt->fdt_ofiles[fd];
1433 		if (fde->fde_file != NULL)
1434 			fde->fde_flags |= UF_EXCLOSE;
1435 	}
1436 out_locked:
1437 	FILEDESC_XUNLOCK(fdp);
1438 	return (0);
1439 }
1440 
1441 static int
close_range_impl(struct thread * td,u_int lowfd,u_int highfd)1442 close_range_impl(struct thread *td, u_int lowfd, u_int highfd)
1443 {
1444 	struct filedesc *fdp;
1445 	const struct fdescenttbl *fdt;
1446 	struct file *fp;
1447 	int fd;
1448 
1449 	fdp = td->td_proc->p_fd;
1450 	FILEDESC_XLOCK(fdp);
1451 	fdt = atomic_load_ptr(&fdp->fd_files);
1452 	highfd = MIN(highfd, fdt->fdt_nfiles - 1);
1453 	fd = lowfd;
1454 	if (__predict_false(fd > highfd)) {
1455 		goto out_locked;
1456 	}
1457 	for (;;) {
1458 		fp = fdt->fdt_ofiles[fd].fde_file;
1459 		if (fp == NULL) {
1460 			if (fd == highfd)
1461 				goto out_locked;
1462 		} else {
1463 			fdfree(fdp, fd);
1464 			(void) closefp(fdp, fd, fp, td, true, true);
1465 			if (fd == highfd)
1466 				goto out_unlocked;
1467 			FILEDESC_XLOCK(fdp);
1468 			fdt = atomic_load_ptr(&fdp->fd_files);
1469 		}
1470 		fd++;
1471 	}
1472 out_locked:
1473 	FILEDESC_XUNLOCK(fdp);
1474 out_unlocked:
1475 	return (0);
1476 }
1477 
1478 int
kern_close_range(struct thread * td,int flags,u_int lowfd,u_int highfd)1479 kern_close_range(struct thread *td, int flags, u_int lowfd, u_int highfd)
1480 {
1481 
1482 	/*
1483 	 * Check this prior to clamping; closefrom(3) with only fd 0, 1, and 2
1484 	 * open should not be a usage error.  From a close_range() perspective,
1485 	 * close_range(3, ~0U, 0) in the same scenario should also likely not
1486 	 * be a usage error as all fd above 3 are in-fact already closed.
1487 	 */
1488 	if (highfd < lowfd) {
1489 		return (EINVAL);
1490 	}
1491 
1492 	if ((flags & CLOSE_RANGE_CLOEXEC) != 0)
1493 		return (close_range_cloexec(td, lowfd, highfd));
1494 
1495 	return (close_range_impl(td, lowfd, highfd));
1496 }
1497 
1498 #ifndef _SYS_SYSPROTO_H_
1499 struct close_range_args {
1500 	u_int	lowfd;
1501 	u_int	highfd;
1502 	int	flags;
1503 };
1504 #endif
1505 int
sys_close_range(struct thread * td,struct close_range_args * uap)1506 sys_close_range(struct thread *td, struct close_range_args *uap)
1507 {
1508 
1509 	AUDIT_ARG_FD(uap->lowfd);
1510 	AUDIT_ARG_CMD(uap->highfd);
1511 	AUDIT_ARG_FFLAGS(uap->flags);
1512 
1513 	if ((uap->flags & ~(CLOSE_RANGE_CLOEXEC)) != 0)
1514 		return (EINVAL);
1515 	return (kern_close_range(td, uap->flags, uap->lowfd, uap->highfd));
1516 }
1517 
1518 #ifdef COMPAT_FREEBSD12
1519 /*
1520  * Close open file descriptors.
1521  */
1522 #ifndef _SYS_SYSPROTO_H_
1523 struct freebsd12_closefrom_args {
1524 	int	lowfd;
1525 };
1526 #endif
1527 /* ARGSUSED */
1528 int
freebsd12_closefrom(struct thread * td,struct freebsd12_closefrom_args * uap)1529 freebsd12_closefrom(struct thread *td, struct freebsd12_closefrom_args *uap)
1530 {
1531 	u_int lowfd;
1532 
1533 	AUDIT_ARG_FD(uap->lowfd);
1534 
1535 	/*
1536 	 * Treat negative starting file descriptor values identical to
1537 	 * closefrom(0) which closes all files.
1538 	 */
1539 	lowfd = MAX(0, uap->lowfd);
1540 	return (kern_close_range(td, 0, lowfd, ~0U));
1541 }
1542 #endif	/* COMPAT_FREEBSD12 */
1543 
1544 #if defined(COMPAT_43)
1545 /*
1546  * Return status information about a file descriptor.
1547  */
1548 #ifndef _SYS_SYSPROTO_H_
1549 struct ofstat_args {
1550 	int	fd;
1551 	struct	ostat *sb;
1552 };
1553 #endif
1554 /* ARGSUSED */
1555 int
ofstat(struct thread * td,struct ofstat_args * uap)1556 ofstat(struct thread *td, struct ofstat_args *uap)
1557 {
1558 	struct ostat oub;
1559 	struct stat ub;
1560 	int error;
1561 
1562 	error = kern_fstat(td, uap->fd, &ub);
1563 	if (error == 0) {
1564 		cvtstat(&ub, &oub);
1565 		error = copyout(&oub, uap->sb, sizeof(oub));
1566 	}
1567 	return (error);
1568 }
1569 #endif /* COMPAT_43 */
1570 
1571 #if defined(COMPAT_FREEBSD11)
1572 int
freebsd11_fstat(struct thread * td,struct freebsd11_fstat_args * uap)1573 freebsd11_fstat(struct thread *td, struct freebsd11_fstat_args *uap)
1574 {
1575 	struct stat sb;
1576 	struct freebsd11_stat osb;
1577 	int error;
1578 
1579 	error = kern_fstat(td, uap->fd, &sb);
1580 	if (error != 0)
1581 		return (error);
1582 	error = freebsd11_cvtstat(&sb, &osb);
1583 	if (error == 0)
1584 		error = copyout(&osb, uap->sb, sizeof(osb));
1585 	return (error);
1586 }
1587 #endif	/* COMPAT_FREEBSD11 */
1588 
1589 /*
1590  * Return status information about a file descriptor.
1591  */
1592 #ifndef _SYS_SYSPROTO_H_
1593 struct fstat_args {
1594 	int	fd;
1595 	struct	stat *sb;
1596 };
1597 #endif
1598 /* ARGSUSED */
1599 int
sys_fstat(struct thread * td,struct fstat_args * uap)1600 sys_fstat(struct thread *td, struct fstat_args *uap)
1601 {
1602 	struct stat ub;
1603 	int error;
1604 
1605 	error = kern_fstat(td, uap->fd, &ub);
1606 	if (error == 0)
1607 		error = copyout(&ub, uap->sb, sizeof(ub));
1608 	return (error);
1609 }
1610 
1611 int
kern_fstat(struct thread * td,int fd,struct stat * sbp)1612 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1613 {
1614 	struct file *fp;
1615 	int error;
1616 
1617 	AUDIT_ARG_FD(fd);
1618 
1619 	error = fget(td, fd, &cap_fstat_rights, &fp);
1620 	if (__predict_false(error != 0))
1621 		return (error);
1622 
1623 	AUDIT_ARG_FILE(td->td_proc, fp);
1624 
1625 	error = fo_stat(fp, sbp, td->td_ucred);
1626 	fdrop(fp, td);
1627 #ifdef __STAT_TIME_T_EXT
1628 	sbp->st_atim_ext = 0;
1629 	sbp->st_mtim_ext = 0;
1630 	sbp->st_ctim_ext = 0;
1631 	sbp->st_btim_ext = 0;
1632 #endif
1633 #ifdef KTRACE
1634 	if (KTRPOINT(td, KTR_STRUCT))
1635 		ktrstat_error(sbp, error);
1636 #endif
1637 	return (error);
1638 }
1639 
1640 #if defined(COMPAT_FREEBSD11)
1641 /*
1642  * Return status information about a file descriptor.
1643  */
1644 #ifndef _SYS_SYSPROTO_H_
1645 struct freebsd11_nfstat_args {
1646 	int	fd;
1647 	struct	nstat *sb;
1648 };
1649 #endif
1650 /* ARGSUSED */
1651 int
freebsd11_nfstat(struct thread * td,struct freebsd11_nfstat_args * uap)1652 freebsd11_nfstat(struct thread *td, struct freebsd11_nfstat_args *uap)
1653 {
1654 	struct nstat nub;
1655 	struct stat ub;
1656 	int error;
1657 
1658 	error = kern_fstat(td, uap->fd, &ub);
1659 	if (error != 0)
1660 		return (error);
1661 	error = freebsd11_cvtnstat(&ub, &nub);
1662 	if (error != 0)
1663 		error = copyout(&nub, uap->sb, sizeof(nub));
1664 	return (error);
1665 }
1666 #endif /* COMPAT_FREEBSD11 */
1667 
1668 /*
1669  * Return pathconf information about a file descriptor.
1670  */
1671 #ifndef _SYS_SYSPROTO_H_
1672 struct fpathconf_args {
1673 	int	fd;
1674 	int	name;
1675 };
1676 #endif
1677 /* ARGSUSED */
1678 int
sys_fpathconf(struct thread * td,struct fpathconf_args * uap)1679 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1680 {
1681 	long value;
1682 	int error;
1683 
1684 	error = kern_fpathconf(td, uap->fd, uap->name, &value);
1685 	if (error == 0)
1686 		td->td_retval[0] = value;
1687 	return (error);
1688 }
1689 
1690 int
kern_fpathconf(struct thread * td,int fd,int name,long * valuep)1691 kern_fpathconf(struct thread *td, int fd, int name, long *valuep)
1692 {
1693 	struct file *fp;
1694 	struct vnode *vp;
1695 	int error;
1696 
1697 	error = fget(td, fd, &cap_fpathconf_rights, &fp);
1698 	if (error != 0)
1699 		return (error);
1700 
1701 	if (name == _PC_ASYNC_IO) {
1702 		*valuep = _POSIX_ASYNCHRONOUS_IO;
1703 		goto out;
1704 	}
1705 	vp = fp->f_vnode;
1706 	if (vp != NULL) {
1707 		vn_lock(vp, LK_SHARED | LK_RETRY);
1708 		error = VOP_PATHCONF(vp, name, valuep);
1709 		VOP_UNLOCK(vp);
1710 	} else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1711 		if (name != _PC_PIPE_BUF) {
1712 			error = EINVAL;
1713 		} else {
1714 			*valuep = PIPE_BUF;
1715 			error = 0;
1716 		}
1717 	} else {
1718 		error = EOPNOTSUPP;
1719 	}
1720 out:
1721 	fdrop(fp, td);
1722 	return (error);
1723 }
1724 
1725 /*
1726  * Copy filecaps structure allocating memory for ioctls array if needed.
1727  *
1728  * The last parameter indicates whether the fdtable is locked. If it is not and
1729  * ioctls are encountered, copying fails and the caller must lock the table.
1730  *
1731  * Note that if the table was not locked, the caller has to check the relevant
1732  * sequence counter to determine whether the operation was successful.
1733  */
1734 bool
filecaps_copy(const struct filecaps * src,struct filecaps * dst,bool locked)1735 filecaps_copy(const struct filecaps *src, struct filecaps *dst, bool locked)
1736 {
1737 	size_t size;
1738 
1739 	if (src->fc_ioctls != NULL && !locked)
1740 		return (false);
1741 	memcpy(dst, src, sizeof(*src));
1742 	if (src->fc_ioctls == NULL)
1743 		return (true);
1744 
1745 	KASSERT(src->fc_nioctls > 0,
1746 	    ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1747 
1748 	size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1749 	dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1750 	memcpy(dst->fc_ioctls, src->fc_ioctls, size);
1751 	return (true);
1752 }
1753 
1754 static u_long *
filecaps_copy_prep(const struct filecaps * src)1755 filecaps_copy_prep(const struct filecaps *src)
1756 {
1757 	u_long *ioctls;
1758 	size_t size;
1759 
1760 	if (__predict_true(src->fc_ioctls == NULL))
1761 		return (NULL);
1762 
1763 	KASSERT(src->fc_nioctls > 0,
1764 	    ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1765 
1766 	size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1767 	ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1768 	return (ioctls);
1769 }
1770 
1771 static void
filecaps_copy_finish(const struct filecaps * src,struct filecaps * dst,u_long * ioctls)1772 filecaps_copy_finish(const struct filecaps *src, struct filecaps *dst,
1773     u_long *ioctls)
1774 {
1775 	size_t size;
1776 
1777 	*dst = *src;
1778 	if (__predict_true(src->fc_ioctls == NULL)) {
1779 		MPASS(ioctls == NULL);
1780 		return;
1781 	}
1782 
1783 	size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1784 	dst->fc_ioctls = ioctls;
1785 	bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1786 }
1787 
1788 /*
1789  * Move filecaps structure to the new place and clear the old place.
1790  */
1791 void
filecaps_move(struct filecaps * src,struct filecaps * dst)1792 filecaps_move(struct filecaps *src, struct filecaps *dst)
1793 {
1794 
1795 	*dst = *src;
1796 	bzero(src, sizeof(*src));
1797 }
1798 
1799 /*
1800  * Fill the given filecaps structure with full rights.
1801  */
1802 static void
filecaps_fill(struct filecaps * fcaps)1803 filecaps_fill(struct filecaps *fcaps)
1804 {
1805 
1806 	CAP_ALL(&fcaps->fc_rights);
1807 	fcaps->fc_ioctls = NULL;
1808 	fcaps->fc_nioctls = -1;
1809 	fcaps->fc_fcntls = CAP_FCNTL_ALL;
1810 }
1811 
1812 /*
1813  * Free memory allocated within filecaps structure.
1814  */
1815 static void
filecaps_free_ioctl(struct filecaps * fcaps)1816 filecaps_free_ioctl(struct filecaps *fcaps)
1817 {
1818 
1819 	free(fcaps->fc_ioctls, M_FILECAPS);
1820 	fcaps->fc_ioctls = NULL;
1821 }
1822 
1823 void
filecaps_free(struct filecaps * fcaps)1824 filecaps_free(struct filecaps *fcaps)
1825 {
1826 
1827 	filecaps_free_ioctl(fcaps);
1828 	bzero(fcaps, sizeof(*fcaps));
1829 }
1830 
1831 static u_long *
filecaps_free_prep(struct filecaps * fcaps)1832 filecaps_free_prep(struct filecaps *fcaps)
1833 {
1834 	u_long *ioctls;
1835 
1836 	ioctls = fcaps->fc_ioctls;
1837 	bzero(fcaps, sizeof(*fcaps));
1838 	return (ioctls);
1839 }
1840 
1841 static void
filecaps_free_finish(u_long * ioctls)1842 filecaps_free_finish(u_long *ioctls)
1843 {
1844 
1845 	free(ioctls, M_FILECAPS);
1846 }
1847 
1848 /*
1849  * Validate the given filecaps structure.
1850  */
1851 static void
filecaps_validate(const struct filecaps * fcaps,const char * func)1852 filecaps_validate(const struct filecaps *fcaps, const char *func)
1853 {
1854 
1855 	KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1856 	    ("%s: invalid rights", func));
1857 	KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1858 	    ("%s: invalid fcntls", func));
1859 	KASSERT(fcaps->fc_fcntls == 0 ||
1860 	    cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1861 	    ("%s: fcntls without CAP_FCNTL", func));
1862 	/*
1863 	 * open calls without WANTIOCTLCAPS free caps but leave the counter
1864 	 */
1865 #if 0
1866 	KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1867 	    (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1868 	    ("%s: invalid ioctls", func));
1869 #endif
1870 	KASSERT(fcaps->fc_nioctls == 0 ||
1871 	    cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1872 	    ("%s: ioctls without CAP_IOCTL", func));
1873 }
1874 
1875 static void
fdgrowtable_exp(struct filedesc * fdp,int nfd)1876 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1877 {
1878 	int nfd1;
1879 
1880 	FILEDESC_XLOCK_ASSERT(fdp);
1881 
1882 	nfd1 = fdp->fd_nfiles * 2;
1883 	if (nfd1 < nfd)
1884 		nfd1 = nfd;
1885 	fdgrowtable(fdp, nfd1);
1886 }
1887 
1888 /*
1889  * Grow the file table to accommodate (at least) nfd descriptors.
1890  */
1891 static void
fdgrowtable(struct filedesc * fdp,int nfd)1892 fdgrowtable(struct filedesc *fdp, int nfd)
1893 {
1894 	struct filedesc0 *fdp0;
1895 	struct freetable *ft;
1896 	struct fdescenttbl *ntable;
1897 	struct fdescenttbl *otable;
1898 	int nnfiles, onfiles;
1899 	NDSLOTTYPE *nmap, *omap;
1900 
1901 	KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1902 
1903 	/* save old values */
1904 	onfiles = fdp->fd_nfiles;
1905 	otable = fdp->fd_files;
1906 	omap = fdp->fd_map;
1907 
1908 	/* compute the size of the new table */
1909 	nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1910 	if (nnfiles <= onfiles)
1911 		/* the table is already large enough */
1912 		return;
1913 
1914 	/*
1915 	 * Allocate a new table.  We need enough space for the number of
1916 	 * entries, file entries themselves and the struct freetable we will use
1917 	 * when we decommission the table and place it on the freelist.
1918 	 * We place the struct freetable in the middle so we don't have
1919 	 * to worry about padding.
1920 	 */
1921 	ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1922 	    nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1923 	    sizeof(struct freetable),
1924 	    M_FILEDESC, M_ZERO | M_WAITOK);
1925 	/* copy the old data */
1926 	ntable->fdt_nfiles = nnfiles;
1927 	memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1928 	    onfiles * sizeof(ntable->fdt_ofiles[0]));
1929 
1930 	/*
1931 	 * Allocate a new map only if the old is not large enough.  It will
1932 	 * grow at a slower rate than the table as it can map more
1933 	 * entries than the table can hold.
1934 	 */
1935 	if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1936 		nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1937 		    M_ZERO | M_WAITOK);
1938 		/* copy over the old data and update the pointer */
1939 		memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1940 		fdp->fd_map = nmap;
1941 	}
1942 
1943 	/*
1944 	 * Make sure that ntable is correctly initialized before we replace
1945 	 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1946 	 * data.
1947 	 */
1948 	atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1949 
1950 	/*
1951 	 * Free the old file table when not shared by other threads or processes.
1952 	 * The old file table is considered to be shared when either are true:
1953 	 * - The process has more than one thread.
1954 	 * - The file descriptor table has been shared via fdshare().
1955 	 *
1956 	 * When shared, the old file table will be placed on a freelist
1957 	 * which will be processed when the struct filedesc is released.
1958 	 *
1959 	 * Note that if onfiles == NDFILE, we're dealing with the original
1960 	 * static allocation contained within (struct filedesc0 *)fdp,
1961 	 * which must not be freed.
1962 	 */
1963 	if (onfiles > NDFILE) {
1964 		/*
1965 		 * Note we may be called here from fdinit while allocating a
1966 		 * table for a new process in which case ->p_fd points
1967 		 * elsewhere.
1968 		 */
1969 		if (curproc->p_fd != fdp || FILEDESC_IS_ONLY_USER(fdp)) {
1970 			free(otable, M_FILEDESC);
1971 		} else {
1972 			ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1973 			fdp0 = (struct filedesc0 *)fdp;
1974 			ft->ft_table = otable;
1975 			SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1976 		}
1977 	}
1978 	/*
1979 	 * The map does not have the same possibility of threads still
1980 	 * holding references to it.  So always free it as long as it
1981 	 * does not reference the original static allocation.
1982 	 */
1983 	if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1984 		free(omap, M_FILEDESC);
1985 }
1986 
1987 /*
1988  * Allocate a file descriptor for the process.
1989  */
1990 int
fdalloc(struct thread * td,int minfd,int * result)1991 fdalloc(struct thread *td, int minfd, int *result)
1992 {
1993 	struct proc *p = td->td_proc;
1994 	struct filedesc *fdp = p->p_fd;
1995 	int fd, maxfd, allocfd;
1996 #ifdef RACCT
1997 	int error;
1998 #endif
1999 
2000 	FILEDESC_XLOCK_ASSERT(fdp);
2001 
2002 	if (fdp->fd_freefile > minfd)
2003 		minfd = fdp->fd_freefile;
2004 
2005 	maxfd = getmaxfd(td);
2006 
2007 	/*
2008 	 * Search the bitmap for a free descriptor starting at minfd.
2009 	 * If none is found, grow the file table.
2010 	 */
2011 	fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
2012 	if (__predict_false(fd >= maxfd))
2013 		return (EMFILE);
2014 	if (__predict_false(fd >= fdp->fd_nfiles)) {
2015 		allocfd = min(fd * 2, maxfd);
2016 #ifdef RACCT
2017 		if (RACCT_ENABLED()) {
2018 			error = racct_set_unlocked(p, RACCT_NOFILE, allocfd);
2019 			if (error != 0)
2020 				return (EMFILE);
2021 		}
2022 #endif
2023 		/*
2024 		 * fd is already equal to first free descriptor >= minfd, so
2025 		 * we only need to grow the table and we are done.
2026 		 */
2027 		fdgrowtable_exp(fdp, allocfd);
2028 	}
2029 
2030 	/*
2031 	 * Perform some sanity checks, then mark the file descriptor as
2032 	 * used and return it to the caller.
2033 	 */
2034 	KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
2035 	    ("invalid descriptor %d", fd));
2036 	KASSERT(!fdisused(fdp, fd),
2037 	    ("fd_first_free() returned non-free descriptor"));
2038 	KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
2039 	    ("file descriptor isn't free"));
2040 	fdused(fdp, fd);
2041 	*result = fd;
2042 	return (0);
2043 }
2044 
2045 /*
2046  * Allocate n file descriptors for the process.
2047  */
2048 int
fdallocn(struct thread * td,int minfd,int * fds,int n)2049 fdallocn(struct thread *td, int minfd, int *fds, int n)
2050 {
2051 	struct proc *p = td->td_proc;
2052 	struct filedesc *fdp = p->p_fd;
2053 	int i;
2054 
2055 	FILEDESC_XLOCK_ASSERT(fdp);
2056 
2057 	for (i = 0; i < n; i++)
2058 		if (fdalloc(td, 0, &fds[i]) != 0)
2059 			break;
2060 
2061 	if (i < n) {
2062 		for (i--; i >= 0; i--)
2063 			fdunused(fdp, fds[i]);
2064 		return (EMFILE);
2065 	}
2066 
2067 	return (0);
2068 }
2069 
2070 /*
2071  * Create a new open file structure and allocate a file descriptor for the
2072  * process that refers to it.  We add one reference to the file for the
2073  * descriptor table and one reference for resultfp. This is to prevent us
2074  * being preempted and the entry in the descriptor table closed after we
2075  * release the FILEDESC lock.
2076  */
2077 int
falloc_caps(struct thread * td,struct file ** resultfp,int * resultfd,int flags,struct filecaps * fcaps)2078 falloc_caps(struct thread *td, struct file **resultfp, int *resultfd, int flags,
2079     struct filecaps *fcaps)
2080 {
2081 	struct file *fp;
2082 	int error, fd;
2083 
2084 	MPASS(resultfp != NULL);
2085 	MPASS(resultfd != NULL);
2086 
2087 	error = _falloc_noinstall(td, &fp, 2);
2088 	if (__predict_false(error != 0)) {
2089 		return (error);
2090 	}
2091 
2092 	error = finstall_refed(td, fp, &fd, flags, fcaps);
2093 	if (__predict_false(error != 0)) {
2094 		falloc_abort(td, fp);
2095 		return (error);
2096 	}
2097 
2098 	*resultfp = fp;
2099 	*resultfd = fd;
2100 
2101 	return (0);
2102 }
2103 
2104 /*
2105  * Create a new open file structure without allocating a file descriptor.
2106  */
2107 int
_falloc_noinstall(struct thread * td,struct file ** resultfp,u_int n)2108 _falloc_noinstall(struct thread *td, struct file **resultfp, u_int n)
2109 {
2110 	struct file *fp;
2111 	int maxuserfiles = maxfiles - (maxfiles / 20);
2112 	int openfiles_new;
2113 	static struct timeval lastfail;
2114 	static int curfail;
2115 
2116 	KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
2117 	MPASS(n > 0);
2118 
2119 	openfiles_new = atomic_fetchadd_int(&openfiles, 1) + 1;
2120 	if ((openfiles_new >= maxuserfiles &&
2121 	    priv_check(td, PRIV_MAXFILES) != 0) ||
2122 	    openfiles_new >= maxfiles) {
2123 		atomic_subtract_int(&openfiles, 1);
2124 		if (ppsratecheck(&lastfail, &curfail, 1)) {
2125 			printf("kern.maxfiles limit exceeded by uid %i, (%s) "
2126 			    "please see tuning(7).\n", td->td_ucred->cr_ruid, td->td_proc->p_comm);
2127 		}
2128 		return (ENFILE);
2129 	}
2130 	fp = uma_zalloc(file_zone, M_WAITOK);
2131 	bzero(fp, sizeof(*fp));
2132 	refcount_init(&fp->f_count, n);
2133 	fp->f_cred = crhold(td->td_ucred);
2134 	fp->f_ops = &badfileops;
2135 	*resultfp = fp;
2136 	return (0);
2137 }
2138 
2139 void
falloc_abort(struct thread * td,struct file * fp)2140 falloc_abort(struct thread *td, struct file *fp)
2141 {
2142 
2143 	/*
2144 	 * For assertion purposes.
2145 	 */
2146 	refcount_init(&fp->f_count, 0);
2147 	_fdrop(fp, td);
2148 }
2149 
2150 /*
2151  * Install a file in a file descriptor table.
2152  */
2153 void
_finstall(struct filedesc * fdp,struct file * fp,int fd,int flags,struct filecaps * fcaps)2154 _finstall(struct filedesc *fdp, struct file *fp, int fd, int flags,
2155     struct filecaps *fcaps)
2156 {
2157 	struct filedescent *fde;
2158 
2159 	MPASS(fp != NULL);
2160 	if (fcaps != NULL)
2161 		filecaps_validate(fcaps, __func__);
2162 	FILEDESC_XLOCK_ASSERT(fdp);
2163 
2164 	fde = &fdp->fd_ofiles[fd];
2165 #ifdef CAPABILITIES
2166 	seqc_write_begin(&fde->fde_seqc);
2167 #endif
2168 	fde->fde_file = fp;
2169 	fde->fde_flags = (flags & O_CLOEXEC) != 0 ? UF_EXCLOSE : 0;
2170 	if (fcaps != NULL)
2171 		filecaps_move(fcaps, &fde->fde_caps);
2172 	else
2173 		filecaps_fill(&fde->fde_caps);
2174 #ifdef CAPABILITIES
2175 	seqc_write_end(&fde->fde_seqc);
2176 #endif
2177 }
2178 
2179 int
finstall_refed(struct thread * td,struct file * fp,int * fd,int flags,struct filecaps * fcaps)2180 finstall_refed(struct thread *td, struct file *fp, int *fd, int flags,
2181     struct filecaps *fcaps)
2182 {
2183 	struct filedesc *fdp = td->td_proc->p_fd;
2184 	int error;
2185 
2186 	MPASS(fd != NULL);
2187 
2188 	FILEDESC_XLOCK(fdp);
2189 	error = fdalloc(td, 0, fd);
2190 	if (__predict_true(error == 0)) {
2191 		_finstall(fdp, fp, *fd, flags, fcaps);
2192 	}
2193 	FILEDESC_XUNLOCK(fdp);
2194 	return (error);
2195 }
2196 
2197 int
finstall(struct thread * td,struct file * fp,int * fd,int flags,struct filecaps * fcaps)2198 finstall(struct thread *td, struct file *fp, int *fd, int flags,
2199     struct filecaps *fcaps)
2200 {
2201 	int error;
2202 
2203 	MPASS(fd != NULL);
2204 
2205 	if (!fhold(fp))
2206 		return (EBADF);
2207 	error = finstall_refed(td, fp, fd, flags, fcaps);
2208 	if (__predict_false(error != 0)) {
2209 		fdrop(fp, td);
2210 	}
2211 	return (error);
2212 }
2213 
2214 /*
2215  * Build a new filedesc structure from another.
2216  *
2217  * If fdp is not NULL, return with it shared locked.
2218  */
2219 struct filedesc *
fdinit(void)2220 fdinit(void)
2221 {
2222 	struct filedesc0 *newfdp0;
2223 	struct filedesc *newfdp;
2224 
2225 	newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO);
2226 	newfdp = &newfdp0->fd_fd;
2227 
2228 	/* Create the file descriptor table. */
2229 	FILEDESC_LOCK_INIT(newfdp);
2230 	refcount_init(&newfdp->fd_refcnt, 1);
2231 	refcount_init(&newfdp->fd_holdcnt, 1);
2232 	newfdp->fd_map = newfdp0->fd_dmap;
2233 	newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles;
2234 	newfdp->fd_files->fdt_nfiles = NDFILE;
2235 
2236 	return (newfdp);
2237 }
2238 
2239 /*
2240  * Build a pwddesc structure from another.
2241  * Copy the current, root, and jail root vnode references.
2242  *
2243  * If pdp is not NULL, return with it shared locked.
2244  */
2245 struct pwddesc *
pdinit(struct pwddesc * pdp,bool keeplock)2246 pdinit(struct pwddesc *pdp, bool keeplock)
2247 {
2248 	struct pwddesc *newpdp;
2249 	struct pwd *newpwd;
2250 
2251 	newpdp = malloc(sizeof(*newpdp), M_PWDDESC, M_WAITOK | M_ZERO);
2252 
2253 	PWDDESC_LOCK_INIT(newpdp);
2254 	refcount_init(&newpdp->pd_refcount, 1);
2255 	newpdp->pd_cmask = CMASK;
2256 
2257 	if (pdp == NULL) {
2258 		newpwd = pwd_alloc();
2259 		smr_serialized_store(&newpdp->pd_pwd, newpwd, true);
2260 		return (newpdp);
2261 	}
2262 
2263 	PWDDESC_XLOCK(pdp);
2264 	newpwd = pwd_hold_pwddesc(pdp);
2265 	smr_serialized_store(&newpdp->pd_pwd, newpwd, true);
2266 	if (!keeplock)
2267 		PWDDESC_XUNLOCK(pdp);
2268 	return (newpdp);
2269 }
2270 
2271 /*
2272  * Hold either filedesc or pwddesc of the passed process.
2273  *
2274  * The process lock is used to synchronize against the target exiting and
2275  * freeing the data.
2276  *
2277  * Clearing can be ilustrated in 3 steps:
2278  * 1. set the pointer to NULL. Either routine can race against it, hence
2279  *   atomic_load_ptr.
2280  * 2. observe the process lock as not taken. Until then fdhold/pdhold can
2281  *   race to either still see the pointer or find NULL. It is still safe to
2282  *   grab a reference as clearing is stalled.
2283  * 3. after the lock is observed as not taken, any fdhold/pdhold calls are
2284  *   guaranteed to see NULL, making it safe to finish clearing
2285  */
2286 static struct filedesc *
fdhold(struct proc * p)2287 fdhold(struct proc *p)
2288 {
2289 	struct filedesc *fdp;
2290 
2291 	PROC_LOCK_ASSERT(p, MA_OWNED);
2292 	fdp = atomic_load_ptr(&p->p_fd);
2293 	if (fdp != NULL)
2294 		refcount_acquire(&fdp->fd_holdcnt);
2295 	return (fdp);
2296 }
2297 
2298 static struct pwddesc *
pdhold(struct proc * p)2299 pdhold(struct proc *p)
2300 {
2301 	struct pwddesc *pdp;
2302 
2303 	PROC_LOCK_ASSERT(p, MA_OWNED);
2304 	pdp = atomic_load_ptr(&p->p_pd);
2305 	if (pdp != NULL)
2306 		refcount_acquire(&pdp->pd_refcount);
2307 	return (pdp);
2308 }
2309 
2310 static void
fddrop(struct filedesc * fdp)2311 fddrop(struct filedesc *fdp)
2312 {
2313 
2314 	if (refcount_load(&fdp->fd_holdcnt) > 1) {
2315 		if (refcount_release(&fdp->fd_holdcnt) == 0)
2316 			return;
2317 	}
2318 
2319 	FILEDESC_LOCK_DESTROY(fdp);
2320 	uma_zfree(filedesc0_zone, fdp);
2321 }
2322 
2323 static void
pddrop(struct pwddesc * pdp)2324 pddrop(struct pwddesc *pdp)
2325 {
2326 	struct pwd *pwd;
2327 
2328 	if (refcount_release_if_not_last(&pdp->pd_refcount))
2329 		return;
2330 
2331 	PWDDESC_XLOCK(pdp);
2332 	if (refcount_release(&pdp->pd_refcount) == 0) {
2333 		PWDDESC_XUNLOCK(pdp);
2334 		return;
2335 	}
2336 	pwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
2337 	pwd_set(pdp, NULL);
2338 	PWDDESC_XUNLOCK(pdp);
2339 	pwd_drop(pwd);
2340 
2341 	PWDDESC_LOCK_DESTROY(pdp);
2342 	free(pdp, M_PWDDESC);
2343 }
2344 
2345 /*
2346  * Share a filedesc structure.
2347  */
2348 struct filedesc *
fdshare(struct filedesc * fdp)2349 fdshare(struct filedesc *fdp)
2350 {
2351 
2352 	refcount_acquire(&fdp->fd_refcnt);
2353 	return (fdp);
2354 }
2355 
2356 /*
2357  * Share a pwddesc structure.
2358  */
2359 struct pwddesc *
pdshare(struct pwddesc * pdp)2360 pdshare(struct pwddesc *pdp)
2361 {
2362 	refcount_acquire(&pdp->pd_refcount);
2363 	return (pdp);
2364 }
2365 
2366 /*
2367  * Unshare a filedesc structure, if necessary by making a copy
2368  */
2369 void
fdunshare(struct thread * td)2370 fdunshare(struct thread *td)
2371 {
2372 	struct filedesc *tmp;
2373 	struct proc *p = td->td_proc;
2374 
2375 	if (refcount_load(&p->p_fd->fd_refcnt) == 1)
2376 		return;
2377 
2378 	tmp = fdcopy(p->p_fd);
2379 	fdescfree(td);
2380 	p->p_fd = tmp;
2381 }
2382 
2383 /*
2384  * Unshare a pwddesc structure.
2385  */
2386 void
pdunshare(struct thread * td)2387 pdunshare(struct thread *td)
2388 {
2389 	struct pwddesc *pdp;
2390 	struct proc *p;
2391 
2392 	p = td->td_proc;
2393 	/* Not shared. */
2394 	if (refcount_load(&p->p_pd->pd_refcount) == 1)
2395 		return;
2396 
2397 	pdp = pdcopy(p->p_pd);
2398 	pdescfree(td);
2399 	p->p_pd = pdp;
2400 }
2401 
2402 /*
2403  * Copy a filedesc structure.  A NULL pointer in returns a NULL reference,
2404  * this is to ease callers, not catch errors.
2405  */
2406 struct filedesc *
fdcopy(struct filedesc * fdp)2407 fdcopy(struct filedesc *fdp)
2408 {
2409 	struct filedesc *newfdp;
2410 	struct filedescent *nfde, *ofde;
2411 	int i, lastfile;
2412 
2413 	MPASS(fdp != NULL);
2414 
2415 	newfdp = fdinit();
2416 	FILEDESC_SLOCK(fdp);
2417 	for (;;) {
2418 		lastfile = fdlastfile(fdp);
2419 		if (lastfile < newfdp->fd_nfiles)
2420 			break;
2421 		FILEDESC_SUNLOCK(fdp);
2422 		fdgrowtable(newfdp, lastfile + 1);
2423 		FILEDESC_SLOCK(fdp);
2424 	}
2425 	/* copy all passable descriptors (i.e. not kqueue) */
2426 	newfdp->fd_freefile = fdp->fd_freefile;
2427 	FILEDESC_FOREACH_FDE(fdp, i, ofde) {
2428 		if ((ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0 ||
2429 		    !fhold(ofde->fde_file)) {
2430 			if (newfdp->fd_freefile == fdp->fd_freefile)
2431 				newfdp->fd_freefile = i;
2432 			continue;
2433 		}
2434 		nfde = &newfdp->fd_ofiles[i];
2435 		*nfde = *ofde;
2436 		filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2437 		fdused_init(newfdp, i);
2438 	}
2439 	MPASS(newfdp->fd_freefile != -1);
2440 	FILEDESC_SUNLOCK(fdp);
2441 	return (newfdp);
2442 }
2443 
2444 /*
2445  * Copy a pwddesc structure.
2446  */
2447 struct pwddesc *
pdcopy(struct pwddesc * pdp)2448 pdcopy(struct pwddesc *pdp)
2449 {
2450 	struct pwddesc *newpdp;
2451 
2452 	MPASS(pdp != NULL);
2453 
2454 	newpdp = pdinit(pdp, true);
2455 	newpdp->pd_cmask = pdp->pd_cmask;
2456 	PWDDESC_XUNLOCK(pdp);
2457 	return (newpdp);
2458 }
2459 
2460 /*
2461  * Clear POSIX style locks. This is only used when fdp looses a reference (i.e.
2462  * one of processes using it exits) and the table used to be shared.
2463  */
2464 static void
fdclearlocks(struct thread * td)2465 fdclearlocks(struct thread *td)
2466 {
2467 	struct filedesc *fdp;
2468 	struct filedesc_to_leader *fdtol;
2469 	struct flock lf;
2470 	struct file *fp;
2471 	struct proc *p;
2472 	struct vnode *vp;
2473 	int i;
2474 
2475 	p = td->td_proc;
2476 	fdp = p->p_fd;
2477 	fdtol = p->p_fdtol;
2478 	MPASS(fdtol != NULL);
2479 
2480 	FILEDESC_XLOCK(fdp);
2481 	KASSERT(fdtol->fdl_refcount > 0,
2482 	    ("filedesc_to_refcount botch: fdl_refcount=%d",
2483 	    fdtol->fdl_refcount));
2484 	if (fdtol->fdl_refcount == 1 &&
2485 	    (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2486 		FILEDESC_FOREACH_FP(fdp, i, fp) {
2487 			if (fp->f_type != DTYPE_VNODE ||
2488 			    !fhold(fp))
2489 				continue;
2490 			FILEDESC_XUNLOCK(fdp);
2491 			lf.l_whence = SEEK_SET;
2492 			lf.l_start = 0;
2493 			lf.l_len = 0;
2494 			lf.l_type = F_UNLCK;
2495 			vp = fp->f_vnode;
2496 			(void) VOP_ADVLOCK(vp,
2497 			    (caddr_t)p->p_leader, F_UNLCK,
2498 			    &lf, F_POSIX);
2499 			FILEDESC_XLOCK(fdp);
2500 			fdrop(fp, td);
2501 		}
2502 	}
2503 retry:
2504 	if (fdtol->fdl_refcount == 1) {
2505 		if (fdp->fd_holdleaderscount > 0 &&
2506 		    (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2507 			/*
2508 			 * close() or kern_dup() has cleared a reference
2509 			 * in a shared file descriptor table.
2510 			 */
2511 			fdp->fd_holdleaderswakeup = 1;
2512 			sx_sleep(&fdp->fd_holdleaderscount,
2513 			    FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2514 			goto retry;
2515 		}
2516 		if (fdtol->fdl_holdcount > 0) {
2517 			/*
2518 			 * Ensure that fdtol->fdl_leader remains
2519 			 * valid in closef().
2520 			 */
2521 			fdtol->fdl_wakeup = 1;
2522 			sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2523 			    "fdlhold", 0);
2524 			goto retry;
2525 		}
2526 	}
2527 	fdtol->fdl_refcount--;
2528 	if (fdtol->fdl_refcount == 0 &&
2529 	    fdtol->fdl_holdcount == 0) {
2530 		fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2531 		fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2532 	} else
2533 		fdtol = NULL;
2534 	p->p_fdtol = NULL;
2535 	FILEDESC_XUNLOCK(fdp);
2536 	if (fdtol != NULL)
2537 		free(fdtol, M_FILEDESC_TO_LEADER);
2538 }
2539 
2540 /*
2541  * Release a filedesc structure.
2542  */
2543 static void
fdescfree_fds(struct thread * td,struct filedesc * fdp)2544 fdescfree_fds(struct thread *td, struct filedesc *fdp)
2545 {
2546 	struct filedesc0 *fdp0;
2547 	struct freetable *ft, *tft;
2548 	struct filedescent *fde;
2549 	struct file *fp;
2550 	int i;
2551 
2552 	KASSERT(refcount_load(&fdp->fd_refcnt) == 0,
2553 	    ("%s: fd table %p carries references", __func__, fdp));
2554 
2555 	/*
2556 	 * Serialize with threads iterating over the table, if any.
2557 	 */
2558 	if (refcount_load(&fdp->fd_holdcnt) > 1) {
2559 		FILEDESC_XLOCK(fdp);
2560 		FILEDESC_XUNLOCK(fdp);
2561 	}
2562 
2563 	FILEDESC_FOREACH_FDE(fdp, i, fde) {
2564 		fp = fde->fde_file;
2565 		fdefree_last(fde);
2566 		(void) closef(fp, td);
2567 	}
2568 
2569 	if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2570 		free(fdp->fd_map, M_FILEDESC);
2571 	if (fdp->fd_nfiles > NDFILE)
2572 		free(fdp->fd_files, M_FILEDESC);
2573 
2574 	fdp0 = (struct filedesc0 *)fdp;
2575 	SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft)
2576 		free(ft->ft_table, M_FILEDESC);
2577 
2578 	fddrop(fdp);
2579 }
2580 
2581 void
fdescfree(struct thread * td)2582 fdescfree(struct thread *td)
2583 {
2584 	struct proc *p;
2585 	struct filedesc *fdp;
2586 
2587 	p = td->td_proc;
2588 	fdp = p->p_fd;
2589 	MPASS(fdp != NULL);
2590 
2591 #ifdef RACCT
2592 	if (RACCT_ENABLED())
2593 		racct_set_unlocked(p, RACCT_NOFILE, 0);
2594 #endif
2595 
2596 	if (p->p_fdtol != NULL)
2597 		fdclearlocks(td);
2598 
2599 	/*
2600 	 * Check fdhold for an explanation.
2601 	 */
2602 	atomic_store_ptr(&p->p_fd, NULL);
2603 	atomic_thread_fence_seq_cst();
2604 	PROC_WAIT_UNLOCKED(p);
2605 
2606 	if (refcount_release(&fdp->fd_refcnt) == 0)
2607 		return;
2608 
2609 	fdescfree_fds(td, fdp);
2610 }
2611 
2612 void
pdescfree(struct thread * td)2613 pdescfree(struct thread *td)
2614 {
2615 	struct proc *p;
2616 	struct pwddesc *pdp;
2617 
2618 	p = td->td_proc;
2619 	pdp = p->p_pd;
2620 	MPASS(pdp != NULL);
2621 
2622 	/*
2623 	 * Check pdhold for an explanation.
2624 	 */
2625 	atomic_store_ptr(&p->p_pd, NULL);
2626 	atomic_thread_fence_seq_cst();
2627 	PROC_WAIT_UNLOCKED(p);
2628 
2629 	pddrop(pdp);
2630 }
2631 
2632 /*
2633  * For setugid programs, we don't want to people to use that setugidness
2634  * to generate error messages which write to a file which otherwise would
2635  * otherwise be off-limits to the process.  We check for filesystems where
2636  * the vnode can change out from under us after execve (like [lin]procfs).
2637  *
2638  * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is
2639  * sufficient.  We also don't check for setugidness since we know we are.
2640  */
2641 static bool
is_unsafe(struct file * fp)2642 is_unsafe(struct file *fp)
2643 {
2644 	struct vnode *vp;
2645 
2646 	if (fp->f_type != DTYPE_VNODE)
2647 		return (false);
2648 
2649 	vp = fp->f_vnode;
2650 	return ((vp->v_vflag & VV_PROCDEP) != 0);
2651 }
2652 
2653 /*
2654  * Make this setguid thing safe, if at all possible.
2655  */
2656 void
fdsetugidsafety(struct thread * td)2657 fdsetugidsafety(struct thread *td)
2658 {
2659 	struct filedesc *fdp;
2660 	struct file *fp;
2661 	int i;
2662 
2663 	fdp = td->td_proc->p_fd;
2664 	KASSERT(refcount_load(&fdp->fd_refcnt) == 1,
2665 	    ("the fdtable should not be shared"));
2666 	MPASS(fdp->fd_nfiles >= 3);
2667 	for (i = 0; i <= 2; i++) {
2668 		fp = fdp->fd_ofiles[i].fde_file;
2669 		if (fp != NULL && is_unsafe(fp)) {
2670 			FILEDESC_XLOCK(fdp);
2671 			knote_fdclose(td, i);
2672 			/*
2673 			 * NULL-out descriptor prior to close to avoid
2674 			 * a race while close blocks.
2675 			 */
2676 			fdfree(fdp, i);
2677 			FILEDESC_XUNLOCK(fdp);
2678 			(void) closef(fp, td);
2679 		}
2680 	}
2681 }
2682 
2683 /*
2684  * If a specific file object occupies a specific file descriptor, close the
2685  * file descriptor entry and drop a reference on the file object.  This is a
2686  * convenience function to handle a subsequent error in a function that calls
2687  * falloc() that handles the race that another thread might have closed the
2688  * file descriptor out from under the thread creating the file object.
2689  */
2690 void
fdclose(struct thread * td,struct file * fp,int idx)2691 fdclose(struct thread *td, struct file *fp, int idx)
2692 {
2693 	struct filedesc *fdp = td->td_proc->p_fd;
2694 
2695 	FILEDESC_XLOCK(fdp);
2696 	if (fdp->fd_ofiles[idx].fde_file == fp) {
2697 		fdfree(fdp, idx);
2698 		FILEDESC_XUNLOCK(fdp);
2699 		fdrop(fp, td);
2700 	} else
2701 		FILEDESC_XUNLOCK(fdp);
2702 }
2703 
2704 /*
2705  * Close any files on exec?
2706  */
2707 void
fdcloseexec(struct thread * td)2708 fdcloseexec(struct thread *td)
2709 {
2710 	struct filedesc *fdp;
2711 	struct filedescent *fde;
2712 	struct file *fp;
2713 	int i;
2714 
2715 	fdp = td->td_proc->p_fd;
2716 	KASSERT(refcount_load(&fdp->fd_refcnt) == 1,
2717 	    ("the fdtable should not be shared"));
2718 	FILEDESC_FOREACH_FDE(fdp, i, fde) {
2719 		fp = fde->fde_file;
2720 		if (fp->f_type == DTYPE_MQUEUE ||
2721 		    (fde->fde_flags & UF_EXCLOSE)) {
2722 			FILEDESC_XLOCK(fdp);
2723 			fdfree(fdp, i);
2724 			(void) closefp(fdp, i, fp, td, false, false);
2725 			FILEDESC_UNLOCK_ASSERT(fdp);
2726 		}
2727 	}
2728 }
2729 
2730 /*
2731  * It is unsafe for set[ug]id processes to be started with file
2732  * descriptors 0..2 closed, as these descriptors are given implicit
2733  * significance in the Standard C library.  fdcheckstd() will create a
2734  * descriptor referencing /dev/null for each of stdin, stdout, and
2735  * stderr that is not already open.
2736  */
2737 int
fdcheckstd(struct thread * td)2738 fdcheckstd(struct thread *td)
2739 {
2740 	struct filedesc *fdp;
2741 	register_t save;
2742 	int i, error, devnull;
2743 
2744 	fdp = td->td_proc->p_fd;
2745 	KASSERT(refcount_load(&fdp->fd_refcnt) == 1,
2746 	    ("the fdtable should not be shared"));
2747 	MPASS(fdp->fd_nfiles >= 3);
2748 	devnull = -1;
2749 	for (i = 0; i <= 2; i++) {
2750 		if (fdp->fd_ofiles[i].fde_file != NULL)
2751 			continue;
2752 
2753 		save = td->td_retval[0];
2754 		if (devnull != -1) {
2755 			error = kern_dup(td, FDDUP_FIXED, 0, devnull, i);
2756 		} else {
2757 			error = kern_openat(td, AT_FDCWD, "/dev/null",
2758 			    UIO_SYSSPACE, O_RDWR, 0);
2759 			if (error == 0) {
2760 				devnull = td->td_retval[0];
2761 				KASSERT(devnull == i, ("we didn't get our fd"));
2762 			}
2763 		}
2764 		td->td_retval[0] = save;
2765 		if (error != 0)
2766 			return (error);
2767 	}
2768 	return (0);
2769 }
2770 
2771 /*
2772  * Internal form of close.  Decrement reference count on file structure.
2773  * Note: td may be NULL when closing a file that was being passed in a
2774  * message.
2775  */
2776 int
closef(struct file * fp,struct thread * td)2777 closef(struct file *fp, struct thread *td)
2778 {
2779 	struct vnode *vp;
2780 	struct flock lf;
2781 	struct filedesc_to_leader *fdtol;
2782 	struct filedesc *fdp;
2783 
2784 	MPASS(td != NULL);
2785 
2786 	/*
2787 	 * POSIX record locking dictates that any close releases ALL
2788 	 * locks owned by this process.  This is handled by setting
2789 	 * a flag in the unlock to free ONLY locks obeying POSIX
2790 	 * semantics, and not to free BSD-style file locks.
2791 	 * If the descriptor was in a message, POSIX-style locks
2792 	 * aren't passed with the descriptor, and the thread pointer
2793 	 * will be NULL.  Callers should be careful only to pass a
2794 	 * NULL thread pointer when there really is no owning
2795 	 * context that might have locks, or the locks will be
2796 	 * leaked.
2797 	 */
2798 	if (fp->f_type == DTYPE_VNODE) {
2799 		vp = fp->f_vnode;
2800 		if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2801 			lf.l_whence = SEEK_SET;
2802 			lf.l_start = 0;
2803 			lf.l_len = 0;
2804 			lf.l_type = F_UNLCK;
2805 			(void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2806 			    F_UNLCK, &lf, F_POSIX);
2807 		}
2808 		fdtol = td->td_proc->p_fdtol;
2809 		if (fdtol != NULL) {
2810 			/*
2811 			 * Handle special case where file descriptor table is
2812 			 * shared between multiple process leaders.
2813 			 */
2814 			fdp = td->td_proc->p_fd;
2815 			FILEDESC_XLOCK(fdp);
2816 			for (fdtol = fdtol->fdl_next;
2817 			    fdtol != td->td_proc->p_fdtol;
2818 			    fdtol = fdtol->fdl_next) {
2819 				if ((fdtol->fdl_leader->p_flag &
2820 				    P_ADVLOCK) == 0)
2821 					continue;
2822 				fdtol->fdl_holdcount++;
2823 				FILEDESC_XUNLOCK(fdp);
2824 				lf.l_whence = SEEK_SET;
2825 				lf.l_start = 0;
2826 				lf.l_len = 0;
2827 				lf.l_type = F_UNLCK;
2828 				vp = fp->f_vnode;
2829 				(void) VOP_ADVLOCK(vp,
2830 				    (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2831 				    F_POSIX);
2832 				FILEDESC_XLOCK(fdp);
2833 				fdtol->fdl_holdcount--;
2834 				if (fdtol->fdl_holdcount == 0 &&
2835 				    fdtol->fdl_wakeup != 0) {
2836 					fdtol->fdl_wakeup = 0;
2837 					wakeup(fdtol);
2838 				}
2839 			}
2840 			FILEDESC_XUNLOCK(fdp);
2841 		}
2842 	}
2843 	return (fdrop_close(fp, td));
2844 }
2845 
2846 /*
2847  * Hack for file descriptor passing code.
2848  */
2849 void
closef_nothread(struct file * fp)2850 closef_nothread(struct file *fp)
2851 {
2852 
2853 	fdrop(fp, NULL);
2854 }
2855 
2856 /*
2857  * Initialize the file pointer with the specified properties.
2858  *
2859  * The ops are set with release semantics to be certain that the flags, type,
2860  * and data are visible when ops is.  This is to prevent ops methods from being
2861  * called with bad data.
2862  */
2863 void
finit(struct file * fp,u_int flag,short type,void * data,struct fileops * ops)2864 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2865 {
2866 	fp->f_data = data;
2867 	fp->f_flag = flag;
2868 	fp->f_type = type;
2869 	atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2870 }
2871 
2872 void
finit_vnode(struct file * fp,u_int flag,void * data,struct fileops * ops)2873 finit_vnode(struct file *fp, u_int flag, void *data, struct fileops *ops)
2874 {
2875 	fp->f_seqcount[UIO_READ] = 1;
2876 	fp->f_seqcount[UIO_WRITE] = 1;
2877 	finit(fp, (flag & FMASK) | (fp->f_flag & FHASLOCK), DTYPE_VNODE,
2878 	    data, ops);
2879 }
2880 
2881 int
fget_cap_noref(struct filedesc * fdp,int fd,cap_rights_t * needrightsp,struct file ** fpp,struct filecaps * havecapsp)2882 fget_cap_noref(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2883     struct file **fpp, struct filecaps *havecapsp)
2884 {
2885 	struct filedescent *fde;
2886 	int error;
2887 
2888 	FILEDESC_LOCK_ASSERT(fdp);
2889 
2890 	*fpp = NULL;
2891 	fde = fdeget_noref(fdp, fd);
2892 	if (fde == NULL) {
2893 		error = EBADF;
2894 		goto out;
2895 	}
2896 
2897 #ifdef CAPABILITIES
2898 	error = cap_check(cap_rights_fde_inline(fde), needrightsp);
2899 	if (error != 0)
2900 		goto out;
2901 #endif
2902 
2903 	if (havecapsp != NULL)
2904 		filecaps_copy(&fde->fde_caps, havecapsp, true);
2905 
2906 	*fpp = fde->fde_file;
2907 
2908 	error = 0;
2909 out:
2910 	return (error);
2911 }
2912 
2913 #ifdef CAPABILITIES
2914 int
fget_cap(struct thread * td,int fd,cap_rights_t * needrightsp,struct file ** fpp,struct filecaps * havecapsp)2915 fget_cap(struct thread *td, int fd, cap_rights_t *needrightsp,
2916     struct file **fpp, struct filecaps *havecapsp)
2917 {
2918 	struct filedesc *fdp = td->td_proc->p_fd;
2919 	int error;
2920 	struct file *fp;
2921 	seqc_t seq;
2922 
2923 	*fpp = NULL;
2924 	for (;;) {
2925 		error = fget_unlocked_seq(td, fd, needrightsp, &fp, &seq);
2926 		if (error != 0)
2927 			return (error);
2928 
2929 		if (havecapsp != NULL) {
2930 			if (!filecaps_copy(&fdp->fd_ofiles[fd].fde_caps,
2931 			    havecapsp, false)) {
2932 				fdrop(fp, td);
2933 				goto get_locked;
2934 			}
2935 		}
2936 
2937 		if (!fd_modified(fdp, fd, seq))
2938 			break;
2939 		fdrop(fp, td);
2940 	}
2941 
2942 	*fpp = fp;
2943 	return (0);
2944 
2945 get_locked:
2946 	FILEDESC_SLOCK(fdp);
2947 	error = fget_cap_noref(fdp, fd, needrightsp, fpp, havecapsp);
2948 	if (error == 0 && !fhold(*fpp))
2949 		error = EBADF;
2950 	FILEDESC_SUNLOCK(fdp);
2951 	return (error);
2952 }
2953 #else
2954 int
fget_cap(struct thread * td,int fd,cap_rights_t * needrightsp,struct file ** fpp,struct filecaps * havecapsp)2955 fget_cap(struct thread *td, int fd, cap_rights_t *needrightsp,
2956     struct file **fpp, struct filecaps *havecapsp)
2957 {
2958 	int error;
2959 	error = fget_unlocked(td, fd, needrightsp, fpp);
2960 	if (havecapsp != NULL && error == 0)
2961 		filecaps_fill(havecapsp);
2962 
2963 	return (error);
2964 }
2965 #endif
2966 
2967 int
fget_remote(struct thread * td,struct proc * p,int fd,struct file ** fpp)2968 fget_remote(struct thread *td, struct proc *p, int fd, struct file **fpp)
2969 {
2970 	struct filedesc *fdp;
2971 	struct file *fp;
2972 	int error;
2973 
2974 	if (p == td->td_proc)	/* curproc */
2975 		return (fget_unlocked(td, fd, &cap_no_rights, fpp));
2976 
2977 	PROC_LOCK(p);
2978 	fdp = fdhold(p);
2979 	PROC_UNLOCK(p);
2980 	if (fdp == NULL)
2981 		return (ENOENT);
2982 	FILEDESC_SLOCK(fdp);
2983 	if (refcount_load(&fdp->fd_refcnt) != 0) {
2984 		fp = fget_noref(fdp, fd);
2985 		if (fp != NULL && fhold(fp)) {
2986 			*fpp = fp;
2987 			error = 0;
2988 		} else {
2989 			error = EBADF;
2990 		}
2991 	} else {
2992 		error = ENOENT;
2993 	}
2994 	FILEDESC_SUNLOCK(fdp);
2995 	fddrop(fdp);
2996 	return (error);
2997 }
2998 
2999 #ifdef CAPABILITIES
3000 int
fgetvp_lookup_smr(struct nameidata * ndp,struct vnode ** vpp,bool * fsearch)3001 fgetvp_lookup_smr(struct nameidata *ndp, struct vnode **vpp, bool *fsearch)
3002 {
3003 	const struct filedescent *fde;
3004 	const struct fdescenttbl *fdt;
3005 	struct filedesc *fdp;
3006 	struct file *fp;
3007 	struct vnode *vp;
3008 	const cap_rights_t *haverights;
3009 	cap_rights_t rights;
3010 	seqc_t seq;
3011 	int fd;
3012 
3013 	VFS_SMR_ASSERT_ENTERED();
3014 
3015 	fd = ndp->ni_dirfd;
3016 	rights = *ndp->ni_rightsneeded;
3017 	cap_rights_set_one(&rights, CAP_LOOKUP);
3018 
3019 	fdp = curproc->p_fd;
3020 	fdt = fdp->fd_files;
3021 	if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
3022 		return (EBADF);
3023 	seq = seqc_read_notmodify(fd_seqc(fdt, fd));
3024 	fde = &fdt->fdt_ofiles[fd];
3025 	haverights = cap_rights_fde_inline(fde);
3026 	fp = fde->fde_file;
3027 	if (__predict_false(fp == NULL))
3028 		return (EAGAIN);
3029 	if (__predict_false(cap_check_inline_transient(haverights, &rights)))
3030 		return (EAGAIN);
3031 	*fsearch = ((fp->f_flag & FSEARCH) != 0);
3032 	vp = fp->f_vnode;
3033 	if (__predict_false(vp == NULL)) {
3034 		return (EAGAIN);
3035 	}
3036 	if (!filecaps_copy(&fde->fde_caps, &ndp->ni_filecaps, false)) {
3037 		return (EAGAIN);
3038 	}
3039 	/*
3040 	 * Use an acquire barrier to force re-reading of fdt so it is
3041 	 * refreshed for verification.
3042 	 */
3043 	atomic_thread_fence_acq();
3044 	fdt = fdp->fd_files;
3045 	if (__predict_false(!seqc_consistent_no_fence(fd_seqc(fdt, fd), seq)))
3046 		return (EAGAIN);
3047 	/*
3048 	 * If file descriptor doesn't have all rights,
3049 	 * all lookups relative to it must also be
3050 	 * strictly relative.
3051 	 *
3052 	 * Not yet supported by fast path.
3053 	 */
3054 	CAP_ALL(&rights);
3055 	if (!cap_rights_contains(&ndp->ni_filecaps.fc_rights, &rights) ||
3056 	    ndp->ni_filecaps.fc_fcntls != CAP_FCNTL_ALL ||
3057 	    ndp->ni_filecaps.fc_nioctls != -1) {
3058 #ifdef notyet
3059 		ndp->ni_lcf |= NI_LCF_STRICTREL;
3060 #else
3061 		return (EAGAIN);
3062 #endif
3063 	}
3064 	*vpp = vp;
3065 	return (0);
3066 }
3067 #else
3068 int
fgetvp_lookup_smr(struct nameidata * ndp,struct vnode ** vpp,bool * fsearch)3069 fgetvp_lookup_smr(struct nameidata *ndp, struct vnode **vpp, bool *fsearch)
3070 {
3071 	const struct fdescenttbl *fdt;
3072 	struct filedesc *fdp;
3073 	struct file *fp;
3074 	struct vnode *vp;
3075 	int fd;
3076 
3077 	VFS_SMR_ASSERT_ENTERED();
3078 
3079 	fd = ndp->ni_dirfd;
3080 	fdp = curproc->p_fd;
3081 	fdt = fdp->fd_files;
3082 	if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
3083 		return (EBADF);
3084 	fp = fdt->fdt_ofiles[fd].fde_file;
3085 	if (__predict_false(fp == NULL))
3086 		return (EAGAIN);
3087 	*fsearch = ((fp->f_flag & FSEARCH) != 0);
3088 	vp = fp->f_vnode;
3089 	if (__predict_false(vp == NULL || vp->v_type != VDIR)) {
3090 		return (EAGAIN);
3091 	}
3092 	/*
3093 	 * Use an acquire barrier to force re-reading of fdt so it is
3094 	 * refreshed for verification.
3095 	 */
3096 	atomic_thread_fence_acq();
3097 	fdt = fdp->fd_files;
3098 	if (__predict_false(fp != fdt->fdt_ofiles[fd].fde_file))
3099 		return (EAGAIN);
3100 	filecaps_fill(&ndp->ni_filecaps);
3101 	*vpp = vp;
3102 	return (0);
3103 }
3104 #endif
3105 
3106 int
fgetvp_lookup(struct nameidata * ndp,struct vnode ** vpp)3107 fgetvp_lookup(struct nameidata *ndp, struct vnode **vpp)
3108 {
3109 	struct thread *td;
3110 	struct file *fp;
3111 	struct vnode *vp;
3112 	struct componentname *cnp;
3113 	cap_rights_t rights;
3114 	int error;
3115 
3116 	td = curthread;
3117 	rights = *ndp->ni_rightsneeded;
3118 	cap_rights_set_one(&rights, CAP_LOOKUP);
3119 	cnp = &ndp->ni_cnd;
3120 
3121 	error = fget_cap(td, ndp->ni_dirfd, &rights, &fp, &ndp->ni_filecaps);
3122 	if (__predict_false(error != 0))
3123 		return (error);
3124 	if (__predict_false(fp->f_ops == &badfileops)) {
3125 		error = EBADF;
3126 		goto out_free;
3127 	}
3128 	vp = fp->f_vnode;
3129 	if (__predict_false(vp == NULL)) {
3130 		error = ENOTDIR;
3131 		goto out_free;
3132 	}
3133 	vrefact(vp);
3134 	/*
3135 	 * XXX does not check for VDIR, handled by namei_setup
3136 	 */
3137 	if ((fp->f_flag & FSEARCH) != 0)
3138 		cnp->cn_flags |= NOEXECCHECK;
3139 	fdrop(fp, td);
3140 
3141 #ifdef CAPABILITIES
3142 	/*
3143 	 * If file descriptor doesn't have all rights,
3144 	 * all lookups relative to it must also be
3145 	 * strictly relative.
3146 	 */
3147 	CAP_ALL(&rights);
3148 	if (!cap_rights_contains(&ndp->ni_filecaps.fc_rights, &rights) ||
3149 	    ndp->ni_filecaps.fc_fcntls != CAP_FCNTL_ALL ||
3150 	    ndp->ni_filecaps.fc_nioctls != -1) {
3151 		ndp->ni_lcf |= NI_LCF_STRICTREL;
3152 		ndp->ni_resflags |= NIRES_STRICTREL;
3153 	}
3154 #endif
3155 
3156 	/*
3157 	 * TODO: avoid copying ioctl caps if it can be helped to begin with
3158 	 */
3159 	if ((cnp->cn_flags & WANTIOCTLCAPS) == 0)
3160 		filecaps_free_ioctl(&ndp->ni_filecaps);
3161 
3162 	*vpp = vp;
3163 	return (0);
3164 
3165 out_free:
3166 	filecaps_free(&ndp->ni_filecaps);
3167 	fdrop(fp, td);
3168 	return (error);
3169 }
3170 
3171 /*
3172  * Fetch the descriptor locklessly.
3173  *
3174  * We avoid fdrop() races by never raising a refcount above 0.  To accomplish
3175  * this we have to use a cmpset loop rather than an atomic_add.  The descriptor
3176  * must be re-verified once we acquire a reference to be certain that the
3177  * identity is still correct and we did not lose a race due to preemption.
3178  *
3179  * Force a reload of fdt when looping. Another thread could reallocate
3180  * the table before this fd was closed, so it is possible that there is
3181  * a stale fp pointer in cached version.
3182  */
3183 #ifdef CAPABILITIES
3184 static int
fget_unlocked_seq(struct thread * td,int fd,cap_rights_t * needrightsp,struct file ** fpp,seqc_t * seqp)3185 fget_unlocked_seq(struct thread *td, int fd, cap_rights_t *needrightsp,
3186     struct file **fpp, seqc_t *seqp)
3187 {
3188 	struct filedesc *fdp;
3189 	const struct filedescent *fde;
3190 	const struct fdescenttbl *fdt;
3191 	struct file *fp;
3192 	seqc_t seq;
3193 	cap_rights_t haverights;
3194 	int error;
3195 
3196 	fdp = td->td_proc->p_fd;
3197 	fdt = fdp->fd_files;
3198 	if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
3199 		return (EBADF);
3200 
3201 	for (;;) {
3202 		seq = seqc_read_notmodify(fd_seqc(fdt, fd));
3203 		fde = &fdt->fdt_ofiles[fd];
3204 		haverights = *cap_rights_fde_inline(fde);
3205 		fp = fde->fde_file;
3206 		if (__predict_false(fp == NULL)) {
3207 			if (seqc_consistent(fd_seqc(fdt, fd), seq))
3208 				return (EBADF);
3209 			fdt = atomic_load_ptr(&fdp->fd_files);
3210 			continue;
3211 		}
3212 		error = cap_check_inline(&haverights, needrightsp);
3213 		if (__predict_false(error != 0)) {
3214 			if (seqc_consistent(fd_seqc(fdt, fd), seq))
3215 				return (error);
3216 			fdt = atomic_load_ptr(&fdp->fd_files);
3217 			continue;
3218 		}
3219 		if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count))) {
3220 			fdt = atomic_load_ptr(&fdp->fd_files);
3221 			continue;
3222 		}
3223 		/*
3224 		 * Use an acquire barrier to force re-reading of fdt so it is
3225 		 * refreshed for verification.
3226 		 */
3227 		atomic_thread_fence_acq();
3228 		fdt = fdp->fd_files;
3229 		if (seqc_consistent_no_fence(fd_seqc(fdt, fd), seq))
3230 			break;
3231 		fdrop(fp, td);
3232 	}
3233 	*fpp = fp;
3234 	if (seqp != NULL) {
3235 		*seqp = seq;
3236 	}
3237 	return (0);
3238 }
3239 #else
3240 static int
fget_unlocked_seq(struct thread * td,int fd,cap_rights_t * needrightsp,struct file ** fpp,seqc_t * seqp __unused)3241 fget_unlocked_seq(struct thread *td, int fd, cap_rights_t *needrightsp,
3242     struct file **fpp, seqc_t *seqp __unused)
3243 {
3244 	struct filedesc *fdp;
3245 	const struct fdescenttbl *fdt;
3246 	struct file *fp;
3247 
3248 	fdp = td->td_proc->p_fd;
3249 	fdt = fdp->fd_files;
3250 	if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
3251 		return (EBADF);
3252 
3253 	for (;;) {
3254 		fp = fdt->fdt_ofiles[fd].fde_file;
3255 		if (__predict_false(fp == NULL))
3256 			return (EBADF);
3257 		if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count))) {
3258 			fdt = atomic_load_ptr(&fdp->fd_files);
3259 			continue;
3260 		}
3261 		/*
3262 		 * Use an acquire barrier to force re-reading of fdt so it is
3263 		 * refreshed for verification.
3264 		 */
3265 		atomic_thread_fence_acq();
3266 		fdt = fdp->fd_files;
3267 		if (__predict_true(fp == fdt->fdt_ofiles[fd].fde_file))
3268 			break;
3269 		fdrop(fp, td);
3270 	}
3271 	*fpp = fp;
3272 	return (0);
3273 }
3274 #endif
3275 
3276 /*
3277  * See the comments in fget_unlocked_seq for an explanation of how this works.
3278  *
3279  * This is a simplified variant which bails out to the aforementioned routine
3280  * if anything goes wrong. In practice this only happens when userspace is
3281  * racing with itself.
3282  */
3283 int
fget_unlocked(struct thread * td,int fd,cap_rights_t * needrightsp,struct file ** fpp)3284 fget_unlocked(struct thread *td, int fd, cap_rights_t *needrightsp,
3285     struct file **fpp)
3286 {
3287 	struct filedesc *fdp;
3288 #ifdef CAPABILITIES
3289 	const struct filedescent *fde;
3290 #endif
3291 	const struct fdescenttbl *fdt;
3292 	struct file *fp;
3293 #ifdef CAPABILITIES
3294 	seqc_t seq;
3295 	const cap_rights_t *haverights;
3296 #endif
3297 
3298 	fdp = td->td_proc->p_fd;
3299 	fdt = fdp->fd_files;
3300 	if (__predict_false((u_int)fd >= fdt->fdt_nfiles)) {
3301 		*fpp = NULL;
3302 		return (EBADF);
3303 	}
3304 #ifdef CAPABILITIES
3305 	seq = seqc_read_notmodify(fd_seqc(fdt, fd));
3306 	fde = &fdt->fdt_ofiles[fd];
3307 	haverights = cap_rights_fde_inline(fde);
3308 	fp = fde->fde_file;
3309 #else
3310 	fp = fdt->fdt_ofiles[fd].fde_file;
3311 #endif
3312 	if (__predict_false(fp == NULL))
3313 		goto out_fallback;
3314 #ifdef CAPABILITIES
3315 	if (__predict_false(cap_check_inline_transient(haverights, needrightsp)))
3316 		goto out_fallback;
3317 #endif
3318 	if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count)))
3319 		goto out_fallback;
3320 
3321 	/*
3322 	 * Use an acquire barrier to force re-reading of fdt so it is
3323 	 * refreshed for verification.
3324 	 */
3325 	atomic_thread_fence_acq();
3326 	fdt = fdp->fd_files;
3327 #ifdef	CAPABILITIES
3328 	if (__predict_false(!seqc_consistent_no_fence(fd_seqc(fdt, fd), seq)))
3329 #else
3330 	if (__predict_false(fp != fdt->fdt_ofiles[fd].fde_file))
3331 #endif
3332 		goto out_fdrop;
3333 	*fpp = fp;
3334 	return (0);
3335 out_fdrop:
3336 	fdrop(fp, td);
3337 out_fallback:
3338 	*fpp = NULL;
3339 	return (fget_unlocked_seq(td, fd, needrightsp, fpp, NULL));
3340 }
3341 
3342 /*
3343  * Translate fd -> file when the caller guarantees the file descriptor table
3344  * can't be changed by others.
3345  *
3346  * Note this does not mean the file object itself is only visible to the caller,
3347  * merely that it wont disappear without having to be referenced.
3348  *
3349  * Must be paired with fput_only_user.
3350  */
3351 #ifdef	CAPABILITIES
3352 int
fget_only_user(struct filedesc * fdp,int fd,cap_rights_t * needrightsp,struct file ** fpp)3353 fget_only_user(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
3354     struct file **fpp)
3355 {
3356 	const struct filedescent *fde;
3357 	const struct fdescenttbl *fdt;
3358 	const cap_rights_t *haverights;
3359 	struct file *fp;
3360 	int error;
3361 
3362 	MPASS(FILEDESC_IS_ONLY_USER(fdp));
3363 
3364 	*fpp = NULL;
3365 	if (__predict_false(fd >= fdp->fd_nfiles))
3366 		return (EBADF);
3367 
3368 	fdt = fdp->fd_files;
3369 	fde = &fdt->fdt_ofiles[fd];
3370 	fp = fde->fde_file;
3371 	if (__predict_false(fp == NULL))
3372 		return (EBADF);
3373 	MPASS(refcount_load(&fp->f_count) > 0);
3374 	haverights = cap_rights_fde_inline(fde);
3375 	error = cap_check_inline(haverights, needrightsp);
3376 	if (__predict_false(error != 0))
3377 		return (error);
3378 	*fpp = fp;
3379 	return (0);
3380 }
3381 #else
3382 int
fget_only_user(struct filedesc * fdp,int fd,cap_rights_t * needrightsp,struct file ** fpp)3383 fget_only_user(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
3384     struct file **fpp)
3385 {
3386 	struct file *fp;
3387 
3388 	MPASS(FILEDESC_IS_ONLY_USER(fdp));
3389 
3390 	*fpp = NULL;
3391 	if (__predict_false(fd >= fdp->fd_nfiles))
3392 		return (EBADF);
3393 
3394 	fp = fdp->fd_ofiles[fd].fde_file;
3395 	if (__predict_false(fp == NULL))
3396 		return (EBADF);
3397 
3398 	MPASS(refcount_load(&fp->f_count) > 0);
3399 	*fpp = fp;
3400 	return (0);
3401 }
3402 #endif
3403 
3404 /*
3405  * Extract the file pointer associated with the specified descriptor for the
3406  * current user process.
3407  *
3408  * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
3409  * returned.
3410  *
3411  * File's rights will be checked against the capability rights mask.
3412  *
3413  * If an error occurred the non-zero error is returned and *fpp is set to
3414  * NULL.  Otherwise *fpp is held and set and zero is returned.  Caller is
3415  * responsible for fdrop().
3416  */
3417 static __inline int
_fget(struct thread * td,int fd,struct file ** fpp,int flags,cap_rights_t * needrightsp)3418 _fget(struct thread *td, int fd, struct file **fpp, int flags,
3419     cap_rights_t *needrightsp)
3420 {
3421 	struct file *fp;
3422 	int error;
3423 
3424 	*fpp = NULL;
3425 	error = fget_unlocked(td, fd, needrightsp, &fp);
3426 	if (__predict_false(error != 0))
3427 		return (error);
3428 	if (__predict_false(fp->f_ops == &badfileops)) {
3429 		fdrop(fp, td);
3430 		return (EBADF);
3431 	}
3432 
3433 	/*
3434 	 * FREAD and FWRITE failure return EBADF as per POSIX.
3435 	 */
3436 	error = 0;
3437 	switch (flags) {
3438 	case FREAD:
3439 	case FWRITE:
3440 		if ((fp->f_flag & flags) == 0)
3441 			error = EBADF;
3442 		break;
3443 	case FEXEC:
3444 		if (fp->f_ops != &path_fileops &&
3445 		    ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
3446 		    (fp->f_flag & FWRITE) != 0))
3447 			error = EBADF;
3448 		break;
3449 	case 0:
3450 		break;
3451 	default:
3452 		KASSERT(0, ("wrong flags"));
3453 	}
3454 
3455 	if (error != 0) {
3456 		fdrop(fp, td);
3457 		return (error);
3458 	}
3459 
3460 	*fpp = fp;
3461 	return (0);
3462 }
3463 
3464 int
fget(struct thread * td,int fd,cap_rights_t * rightsp,struct file ** fpp)3465 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
3466 {
3467 
3468 	return (_fget(td, fd, fpp, 0, rightsp));
3469 }
3470 
3471 int
fget_mmap(struct thread * td,int fd,cap_rights_t * rightsp,vm_prot_t * maxprotp,struct file ** fpp)3472 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, vm_prot_t *maxprotp,
3473     struct file **fpp)
3474 {
3475 	int error;
3476 #ifndef CAPABILITIES
3477 	error = _fget(td, fd, fpp, 0, rightsp);
3478 	if (maxprotp != NULL)
3479 		*maxprotp = VM_PROT_ALL;
3480 	return (error);
3481 #else
3482 	cap_rights_t fdrights;
3483 	struct filedesc *fdp;
3484 	struct file *fp;
3485 	seqc_t seq;
3486 
3487 	*fpp = NULL;
3488 	fdp = td->td_proc->p_fd;
3489 	MPASS(cap_rights_is_set(rightsp, CAP_MMAP));
3490 	for (;;) {
3491 		error = fget_unlocked_seq(td, fd, rightsp, &fp, &seq);
3492 		if (__predict_false(error != 0))
3493 			return (error);
3494 		if (__predict_false(fp->f_ops == &badfileops)) {
3495 			fdrop(fp, td);
3496 			return (EBADF);
3497 		}
3498 		if (maxprotp != NULL)
3499 			fdrights = *cap_rights(fdp, fd);
3500 		if (!fd_modified(fdp, fd, seq))
3501 			break;
3502 		fdrop(fp, td);
3503 	}
3504 
3505 	/*
3506 	 * If requested, convert capability rights to access flags.
3507 	 */
3508 	if (maxprotp != NULL)
3509 		*maxprotp = cap_rights_to_vmprot(&fdrights);
3510 	*fpp = fp;
3511 	return (0);
3512 #endif
3513 }
3514 
3515 int
fget_read(struct thread * td,int fd,cap_rights_t * rightsp,struct file ** fpp)3516 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
3517 {
3518 
3519 	return (_fget(td, fd, fpp, FREAD, rightsp));
3520 }
3521 
3522 int
fget_write(struct thread * td,int fd,cap_rights_t * rightsp,struct file ** fpp)3523 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
3524 {
3525 
3526 	return (_fget(td, fd, fpp, FWRITE, rightsp));
3527 }
3528 
3529 int
fget_fcntl(struct thread * td,int fd,cap_rights_t * rightsp,int needfcntl,struct file ** fpp)3530 fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp, int needfcntl,
3531     struct file **fpp)
3532 {
3533 #ifndef CAPABILITIES
3534 	return (fget_unlocked(td, fd, rightsp, fpp));
3535 #else
3536 	struct filedesc *fdp = td->td_proc->p_fd;
3537 	struct file *fp;
3538 	int error;
3539 	seqc_t seq;
3540 
3541 	*fpp = NULL;
3542 	MPASS(cap_rights_is_set(rightsp, CAP_FCNTL));
3543 	for (;;) {
3544 		error = fget_unlocked_seq(td, fd, rightsp, &fp, &seq);
3545 		if (error != 0)
3546 			return (error);
3547 		error = cap_fcntl_check(fdp, fd, needfcntl);
3548 		if (!fd_modified(fdp, fd, seq))
3549 			break;
3550 		fdrop(fp, td);
3551 	}
3552 	if (error != 0) {
3553 		fdrop(fp, td);
3554 		return (error);
3555 	}
3556 	*fpp = fp;
3557 	return (0);
3558 #endif
3559 }
3560 
3561 /*
3562  * Like fget() but loads the underlying vnode, or returns an error if the
3563  * descriptor does not represent a vnode.  Note that pipes use vnodes but
3564  * never have VM objects.  The returned vnode will be vref()'d.
3565  *
3566  * XXX: what about the unused flags ?
3567  */
3568 static __inline int
_fgetvp(struct thread * td,int fd,int flags,cap_rights_t * needrightsp,struct vnode ** vpp)3569 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
3570     struct vnode **vpp)
3571 {
3572 	struct file *fp;
3573 	int error;
3574 
3575 	*vpp = NULL;
3576 	error = _fget(td, fd, &fp, flags, needrightsp);
3577 	if (error != 0)
3578 		return (error);
3579 	if (fp->f_vnode == NULL) {
3580 		error = EINVAL;
3581 	} else {
3582 		*vpp = fp->f_vnode;
3583 		vrefact(*vpp);
3584 	}
3585 	fdrop(fp, td);
3586 
3587 	return (error);
3588 }
3589 
3590 int
fgetvp(struct thread * td,int fd,cap_rights_t * rightsp,struct vnode ** vpp)3591 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3592 {
3593 
3594 	return (_fgetvp(td, fd, 0, rightsp, vpp));
3595 }
3596 
3597 int
fgetvp_rights(struct thread * td,int fd,cap_rights_t * needrightsp,struct filecaps * havecaps,struct vnode ** vpp)3598 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
3599     struct filecaps *havecaps, struct vnode **vpp)
3600 {
3601 	struct filecaps caps;
3602 	struct file *fp;
3603 	int error;
3604 
3605 	error = fget_cap(td, fd, needrightsp, &fp, &caps);
3606 	if (error != 0)
3607 		return (error);
3608 	if (fp->f_ops == &badfileops) {
3609 		error = EBADF;
3610 		goto out;
3611 	}
3612 	if (fp->f_vnode == NULL) {
3613 		error = EINVAL;
3614 		goto out;
3615 	}
3616 
3617 	*havecaps = caps;
3618 	*vpp = fp->f_vnode;
3619 	vrefact(*vpp);
3620 	fdrop(fp, td);
3621 
3622 	return (0);
3623 out:
3624 	filecaps_free(&caps);
3625 	fdrop(fp, td);
3626 	return (error);
3627 }
3628 
3629 int
fgetvp_read(struct thread * td,int fd,cap_rights_t * rightsp,struct vnode ** vpp)3630 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3631 {
3632 
3633 	return (_fgetvp(td, fd, FREAD, rightsp, vpp));
3634 }
3635 
3636 int
fgetvp_exec(struct thread * td,int fd,cap_rights_t * rightsp,struct vnode ** vpp)3637 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3638 {
3639 
3640 	return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
3641 }
3642 
3643 #ifdef notyet
3644 int
fgetvp_write(struct thread * td,int fd,cap_rights_t * rightsp,struct vnode ** vpp)3645 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
3646     struct vnode **vpp)
3647 {
3648 
3649 	return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
3650 }
3651 #endif
3652 
3653 /*
3654  * Handle the last reference to a file being closed.
3655  *
3656  * Without the noinline attribute clang keeps inlining the func thorough this
3657  * file when fdrop is used.
3658  */
3659 int __noinline
_fdrop(struct file * fp,struct thread * td)3660 _fdrop(struct file *fp, struct thread *td)
3661 {
3662 	int error;
3663 #ifdef INVARIANTS
3664 	int count;
3665 
3666 	count = refcount_load(&fp->f_count);
3667 	if (count != 0)
3668 		panic("fdrop: fp %p count %d", fp, count);
3669 #endif
3670 	error = fo_close(fp, td);
3671 	atomic_subtract_int(&openfiles, 1);
3672 	crfree(fp->f_cred);
3673 	free(fp->f_advice, M_FADVISE);
3674 	uma_zfree(file_zone, fp);
3675 
3676 	return (error);
3677 }
3678 
3679 /*
3680  * Apply an advisory lock on a file descriptor.
3681  *
3682  * Just attempt to get a record lock of the requested type on the entire file
3683  * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
3684  */
3685 #ifndef _SYS_SYSPROTO_H_
3686 struct flock_args {
3687 	int	fd;
3688 	int	how;
3689 };
3690 #endif
3691 /* ARGSUSED */
3692 int
sys_flock(struct thread * td,struct flock_args * uap)3693 sys_flock(struct thread *td, struct flock_args *uap)
3694 {
3695 	struct file *fp;
3696 	struct vnode *vp;
3697 	struct flock lf;
3698 	int error;
3699 
3700 	error = fget(td, uap->fd, &cap_flock_rights, &fp);
3701 	if (error != 0)
3702 		return (error);
3703 	error = EOPNOTSUPP;
3704 	if (fp->f_type != DTYPE_VNODE && fp->f_type != DTYPE_FIFO) {
3705 		goto done;
3706 	}
3707 	if (fp->f_ops == &path_fileops) {
3708 		goto done;
3709 	}
3710 
3711 	error = 0;
3712 	vp = fp->f_vnode;
3713 	lf.l_whence = SEEK_SET;
3714 	lf.l_start = 0;
3715 	lf.l_len = 0;
3716 	if (uap->how & LOCK_UN) {
3717 		lf.l_type = F_UNLCK;
3718 		atomic_clear_int(&fp->f_flag, FHASLOCK);
3719 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
3720 		goto done;
3721 	}
3722 	if (uap->how & LOCK_EX)
3723 		lf.l_type = F_WRLCK;
3724 	else if (uap->how & LOCK_SH)
3725 		lf.l_type = F_RDLCK;
3726 	else {
3727 		error = EBADF;
3728 		goto done;
3729 	}
3730 	atomic_set_int(&fp->f_flag, FHASLOCK);
3731 	error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
3732 	    (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
3733 done:
3734 	fdrop(fp, td);
3735 	return (error);
3736 }
3737 /*
3738  * Duplicate the specified descriptor to a free descriptor.
3739  */
3740 int
dupfdopen(struct thread * td,struct filedesc * fdp,int dfd,int mode,int openerror,int * indxp)3741 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
3742     int openerror, int *indxp)
3743 {
3744 	struct filedescent *newfde, *oldfde;
3745 	struct file *fp;
3746 	u_long *ioctls;
3747 	int error, indx;
3748 
3749 	KASSERT(openerror == ENODEV || openerror == ENXIO,
3750 	    ("unexpected error %d in %s", openerror, __func__));
3751 
3752 	/*
3753 	 * If the to-be-dup'd fd number is greater than the allowed number
3754 	 * of file descriptors, or the fd to be dup'd has already been
3755 	 * closed, then reject.
3756 	 */
3757 	FILEDESC_XLOCK(fdp);
3758 	if ((fp = fget_noref(fdp, dfd)) == NULL) {
3759 		FILEDESC_XUNLOCK(fdp);
3760 		return (EBADF);
3761 	}
3762 
3763 	error = fdalloc(td, 0, &indx);
3764 	if (error != 0) {
3765 		FILEDESC_XUNLOCK(fdp);
3766 		return (error);
3767 	}
3768 
3769 	/*
3770 	 * There are two cases of interest here.
3771 	 *
3772 	 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
3773 	 *
3774 	 * For ENXIO steal away the file structure from (dfd) and store it in
3775 	 * (indx).  (dfd) is effectively closed by this operation.
3776 	 */
3777 	switch (openerror) {
3778 	case ENODEV:
3779 		/*
3780 		 * Check that the mode the file is being opened for is a
3781 		 * subset of the mode of the existing descriptor.
3782 		 */
3783 		if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
3784 			fdunused(fdp, indx);
3785 			FILEDESC_XUNLOCK(fdp);
3786 			return (EACCES);
3787 		}
3788 		if (!fhold(fp)) {
3789 			fdunused(fdp, indx);
3790 			FILEDESC_XUNLOCK(fdp);
3791 			return (EBADF);
3792 		}
3793 		newfde = &fdp->fd_ofiles[indx];
3794 		oldfde = &fdp->fd_ofiles[dfd];
3795 		ioctls = filecaps_copy_prep(&oldfde->fde_caps);
3796 #ifdef CAPABILITIES
3797 		seqc_write_begin(&newfde->fde_seqc);
3798 #endif
3799 		fde_copy(oldfde, newfde);
3800 		filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
3801 		    ioctls);
3802 #ifdef CAPABILITIES
3803 		seqc_write_end(&newfde->fde_seqc);
3804 #endif
3805 		break;
3806 	case ENXIO:
3807 		/*
3808 		 * Steal away the file pointer from dfd and stuff it into indx.
3809 		 */
3810 		newfde = &fdp->fd_ofiles[indx];
3811 		oldfde = &fdp->fd_ofiles[dfd];
3812 #ifdef CAPABILITIES
3813 		seqc_write_begin(&oldfde->fde_seqc);
3814 		seqc_write_begin(&newfde->fde_seqc);
3815 #endif
3816 		fde_copy(oldfde, newfde);
3817 		oldfde->fde_file = NULL;
3818 		fdunused(fdp, dfd);
3819 #ifdef CAPABILITIES
3820 		seqc_write_end(&newfde->fde_seqc);
3821 		seqc_write_end(&oldfde->fde_seqc);
3822 #endif
3823 		break;
3824 	}
3825 	FILEDESC_XUNLOCK(fdp);
3826 	*indxp = indx;
3827 	return (0);
3828 }
3829 
3830 /*
3831  * This sysctl determines if we will allow a process to chroot(2) if it
3832  * has a directory open:
3833  *	0: disallowed for all processes.
3834  *	1: allowed for processes that were not already chroot(2)'ed.
3835  *	2: allowed for all processes.
3836  */
3837 
3838 static int chroot_allow_open_directories = 1;
3839 
3840 SYSCTL_INT(_kern, OID_AUTO, chroot_allow_open_directories, CTLFLAG_RW,
3841     &chroot_allow_open_directories, 0,
3842     "Allow a process to chroot(2) if it has a directory open");
3843 
3844 /*
3845  * Helper function for raised chroot(2) security function:  Refuse if
3846  * any filedescriptors are open directories.
3847  */
3848 static int
chroot_refuse_vdir_fds(struct filedesc * fdp)3849 chroot_refuse_vdir_fds(struct filedesc *fdp)
3850 {
3851 	struct vnode *vp;
3852 	struct file *fp;
3853 	int i;
3854 
3855 	FILEDESC_LOCK_ASSERT(fdp);
3856 
3857 	FILEDESC_FOREACH_FP(fdp, i, fp) {
3858 		if (fp->f_type == DTYPE_VNODE) {
3859 			vp = fp->f_vnode;
3860 			if (vp->v_type == VDIR)
3861 				return (EPERM);
3862 		}
3863 	}
3864 	return (0);
3865 }
3866 
3867 static void
pwd_fill(struct pwd * oldpwd,struct pwd * newpwd)3868 pwd_fill(struct pwd *oldpwd, struct pwd *newpwd)
3869 {
3870 
3871 	if (newpwd->pwd_cdir == NULL && oldpwd->pwd_cdir != NULL) {
3872 		vrefact(oldpwd->pwd_cdir);
3873 		newpwd->pwd_cdir = oldpwd->pwd_cdir;
3874 	}
3875 
3876 	if (newpwd->pwd_rdir == NULL && oldpwd->pwd_rdir != NULL) {
3877 		vrefact(oldpwd->pwd_rdir);
3878 		newpwd->pwd_rdir = oldpwd->pwd_rdir;
3879 	}
3880 
3881 	if (newpwd->pwd_jdir == NULL && oldpwd->pwd_jdir != NULL) {
3882 		vrefact(oldpwd->pwd_jdir);
3883 		newpwd->pwd_jdir = oldpwd->pwd_jdir;
3884 	}
3885 
3886 	if (newpwd->pwd_adir == NULL && oldpwd->pwd_adir != NULL) {
3887 		vrefact(oldpwd->pwd_adir);
3888 		newpwd->pwd_adir = oldpwd->pwd_adir;
3889 	}
3890 }
3891 
3892 struct pwd *
pwd_hold_pwddesc(struct pwddesc * pdp)3893 pwd_hold_pwddesc(struct pwddesc *pdp)
3894 {
3895 	struct pwd *pwd;
3896 
3897 	PWDDESC_ASSERT_XLOCKED(pdp);
3898 	pwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
3899 	if (pwd != NULL)
3900 		refcount_acquire(&pwd->pwd_refcount);
3901 	return (pwd);
3902 }
3903 
3904 bool
pwd_hold_smr(struct pwd * pwd)3905 pwd_hold_smr(struct pwd *pwd)
3906 {
3907 
3908 	MPASS(pwd != NULL);
3909 	if (__predict_true(refcount_acquire_if_not_zero(&pwd->pwd_refcount))) {
3910 		return (true);
3911 	}
3912 	return (false);
3913 }
3914 
3915 struct pwd *
pwd_hold(struct thread * td)3916 pwd_hold(struct thread *td)
3917 {
3918 	struct pwddesc *pdp;
3919 	struct pwd *pwd;
3920 
3921 	pdp = td->td_proc->p_pd;
3922 
3923 	vfs_smr_enter();
3924 	pwd = vfs_smr_entered_load(&pdp->pd_pwd);
3925 	if (pwd_hold_smr(pwd)) {
3926 		vfs_smr_exit();
3927 		return (pwd);
3928 	}
3929 	vfs_smr_exit();
3930 	PWDDESC_XLOCK(pdp);
3931 	pwd = pwd_hold_pwddesc(pdp);
3932 	MPASS(pwd != NULL);
3933 	PWDDESC_XUNLOCK(pdp);
3934 	return (pwd);
3935 }
3936 
3937 struct pwd *
pwd_hold_proc(struct proc * p)3938 pwd_hold_proc(struct proc *p)
3939 {
3940 	struct pwddesc *pdp;
3941 	struct pwd *pwd;
3942 
3943 	PROC_ASSERT_HELD(p);
3944 	PROC_LOCK(p);
3945 	pdp = pdhold(p);
3946 	MPASS(pdp != NULL);
3947 	PROC_UNLOCK(p);
3948 
3949 	PWDDESC_XLOCK(pdp);
3950 	pwd = pwd_hold_pwddesc(pdp);
3951 	MPASS(pwd != NULL);
3952 	PWDDESC_XUNLOCK(pdp);
3953 	pddrop(pdp);
3954 	return (pwd);
3955 }
3956 
3957 static struct pwd *
pwd_alloc(void)3958 pwd_alloc(void)
3959 {
3960 	struct pwd *pwd;
3961 
3962 	pwd = uma_zalloc_smr(pwd_zone, M_WAITOK);
3963 	bzero(pwd, sizeof(*pwd));
3964 	refcount_init(&pwd->pwd_refcount, 1);
3965 	return (pwd);
3966 }
3967 
3968 void
pwd_drop(struct pwd * pwd)3969 pwd_drop(struct pwd *pwd)
3970 {
3971 
3972 	if (!refcount_release(&pwd->pwd_refcount))
3973 		return;
3974 
3975 	if (pwd->pwd_cdir != NULL)
3976 		vrele(pwd->pwd_cdir);
3977 	if (pwd->pwd_rdir != NULL)
3978 		vrele(pwd->pwd_rdir);
3979 	if (pwd->pwd_jdir != NULL)
3980 		vrele(pwd->pwd_jdir);
3981 	if (pwd->pwd_adir != NULL)
3982 		vrele(pwd->pwd_adir);
3983 	uma_zfree_smr(pwd_zone, pwd);
3984 }
3985 
3986 /*
3987 * The caller is responsible for invoking priv_check() and
3988 * mac_vnode_check_chroot() to authorize this operation.
3989 */
3990 int
pwd_chroot(struct thread * td,struct vnode * vp)3991 pwd_chroot(struct thread *td, struct vnode *vp)
3992 {
3993 	struct pwddesc *pdp;
3994 	struct filedesc *fdp;
3995 	struct pwd *newpwd, *oldpwd;
3996 	int error;
3997 
3998 	fdp = td->td_proc->p_fd;
3999 	pdp = td->td_proc->p_pd;
4000 	newpwd = pwd_alloc();
4001 	FILEDESC_SLOCK(fdp);
4002 	PWDDESC_XLOCK(pdp);
4003 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4004 	if (chroot_allow_open_directories == 0 ||
4005 	    (chroot_allow_open_directories == 1 &&
4006 	    oldpwd->pwd_rdir != rootvnode)) {
4007 		error = chroot_refuse_vdir_fds(fdp);
4008 		FILEDESC_SUNLOCK(fdp);
4009 		if (error != 0) {
4010 			PWDDESC_XUNLOCK(pdp);
4011 			pwd_drop(newpwd);
4012 			return (error);
4013 		}
4014 	} else {
4015 		FILEDESC_SUNLOCK(fdp);
4016 	}
4017 
4018 	vrefact(vp);
4019 	newpwd->pwd_rdir = vp;
4020 	vrefact(vp);
4021 	newpwd->pwd_adir = vp;
4022 	if (oldpwd->pwd_jdir == NULL) {
4023 		vrefact(vp);
4024 		newpwd->pwd_jdir = vp;
4025 	}
4026 	pwd_fill(oldpwd, newpwd);
4027 	pwd_set(pdp, newpwd);
4028 	PWDDESC_XUNLOCK(pdp);
4029 	pwd_drop(oldpwd);
4030 	return (0);
4031 }
4032 
4033 void
pwd_chdir(struct thread * td,struct vnode * vp)4034 pwd_chdir(struct thread *td, struct vnode *vp)
4035 {
4036 	struct pwddesc *pdp;
4037 	struct pwd *newpwd, *oldpwd;
4038 
4039 	VNPASS(vp->v_usecount > 0, vp);
4040 
4041 	newpwd = pwd_alloc();
4042 	pdp = td->td_proc->p_pd;
4043 	PWDDESC_XLOCK(pdp);
4044 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4045 	newpwd->pwd_cdir = vp;
4046 	pwd_fill(oldpwd, newpwd);
4047 	pwd_set(pdp, newpwd);
4048 	PWDDESC_XUNLOCK(pdp);
4049 	pwd_drop(oldpwd);
4050 }
4051 
4052 /*
4053  * Process is transitioning to/from a non-native ABI.
4054  */
4055 void
pwd_altroot(struct thread * td,struct vnode * altroot_vp)4056 pwd_altroot(struct thread *td, struct vnode *altroot_vp)
4057 {
4058 	struct pwddesc *pdp;
4059 	struct pwd *newpwd, *oldpwd;
4060 
4061 	newpwd = pwd_alloc();
4062 	pdp = td->td_proc->p_pd;
4063 	PWDDESC_XLOCK(pdp);
4064 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4065 	if (altroot_vp != NULL) {
4066 		/*
4067 		 * Native process to a non-native ABI.
4068 		 */
4069 
4070 		vrefact(altroot_vp);
4071 		newpwd->pwd_adir = altroot_vp;
4072 	} else {
4073 		/*
4074 		 * Non-native process to the native ABI.
4075 		 */
4076 
4077 		vrefact(oldpwd->pwd_rdir);
4078 		newpwd->pwd_adir = oldpwd->pwd_rdir;
4079 	}
4080 	pwd_fill(oldpwd, newpwd);
4081 	pwd_set(pdp, newpwd);
4082 	PWDDESC_XUNLOCK(pdp);
4083 	pwd_drop(oldpwd);
4084 }
4085 
4086 /*
4087  * jail_attach(2) changes both root and working directories.
4088  */
4089 int
pwd_chroot_chdir(struct thread * td,struct vnode * vp)4090 pwd_chroot_chdir(struct thread *td, struct vnode *vp)
4091 {
4092 	struct pwddesc *pdp;
4093 	struct filedesc *fdp;
4094 	struct pwd *newpwd, *oldpwd;
4095 	int error;
4096 
4097 	fdp = td->td_proc->p_fd;
4098 	pdp = td->td_proc->p_pd;
4099 	newpwd = pwd_alloc();
4100 	FILEDESC_SLOCK(fdp);
4101 	PWDDESC_XLOCK(pdp);
4102 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4103 	error = chroot_refuse_vdir_fds(fdp);
4104 	FILEDESC_SUNLOCK(fdp);
4105 	if (error != 0) {
4106 		PWDDESC_XUNLOCK(pdp);
4107 		pwd_drop(newpwd);
4108 		return (error);
4109 	}
4110 
4111 	vrefact(vp);
4112 	newpwd->pwd_rdir = vp;
4113 	vrefact(vp);
4114 	newpwd->pwd_cdir = vp;
4115 	if (oldpwd->pwd_jdir == NULL) {
4116 		vrefact(vp);
4117 		newpwd->pwd_jdir = vp;
4118 	}
4119 	vrefact(vp);
4120 	newpwd->pwd_adir = vp;
4121 	pwd_fill(oldpwd, newpwd);
4122 	pwd_set(pdp, newpwd);
4123 	PWDDESC_XUNLOCK(pdp);
4124 	pwd_drop(oldpwd);
4125 	return (0);
4126 }
4127 
4128 void
pwd_ensure_dirs(void)4129 pwd_ensure_dirs(void)
4130 {
4131 	struct pwddesc *pdp;
4132 	struct pwd *oldpwd, *newpwd;
4133 
4134 	pdp = curproc->p_pd;
4135 	PWDDESC_XLOCK(pdp);
4136 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4137 	if (oldpwd->pwd_cdir != NULL && oldpwd->pwd_rdir != NULL &&
4138 	    oldpwd->pwd_adir != NULL) {
4139 		PWDDESC_XUNLOCK(pdp);
4140 		return;
4141 	}
4142 	PWDDESC_XUNLOCK(pdp);
4143 
4144 	newpwd = pwd_alloc();
4145 	PWDDESC_XLOCK(pdp);
4146 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4147 	pwd_fill(oldpwd, newpwd);
4148 	if (newpwd->pwd_cdir == NULL) {
4149 		vrefact(rootvnode);
4150 		newpwd->pwd_cdir = rootvnode;
4151 	}
4152 	if (newpwd->pwd_rdir == NULL) {
4153 		vrefact(rootvnode);
4154 		newpwd->pwd_rdir = rootvnode;
4155 	}
4156 	if (newpwd->pwd_adir == NULL) {
4157 		vrefact(rootvnode);
4158 		newpwd->pwd_adir = rootvnode;
4159 	}
4160 	pwd_set(pdp, newpwd);
4161 	PWDDESC_XUNLOCK(pdp);
4162 	pwd_drop(oldpwd);
4163 }
4164 
4165 void
pwd_set_rootvnode(void)4166 pwd_set_rootvnode(void)
4167 {
4168 	struct pwddesc *pdp;
4169 	struct pwd *oldpwd, *newpwd;
4170 
4171 	pdp = curproc->p_pd;
4172 
4173 	newpwd = pwd_alloc();
4174 	PWDDESC_XLOCK(pdp);
4175 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4176 	vrefact(rootvnode);
4177 	newpwd->pwd_cdir = rootvnode;
4178 	vrefact(rootvnode);
4179 	newpwd->pwd_rdir = rootvnode;
4180 	vrefact(rootvnode);
4181 	newpwd->pwd_adir = rootvnode;
4182 	pwd_fill(oldpwd, newpwd);
4183 	pwd_set(pdp, newpwd);
4184 	PWDDESC_XUNLOCK(pdp);
4185 	pwd_drop(oldpwd);
4186 }
4187 
4188 /*
4189  * Scan all active processes and prisons to see if any of them have a current
4190  * or root directory of `olddp'. If so, replace them with the new mount point.
4191  */
4192 void
mountcheckdirs(struct vnode * olddp,struct vnode * newdp)4193 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
4194 {
4195 	struct pwddesc *pdp;
4196 	struct pwd *newpwd, *oldpwd;
4197 	struct prison *pr;
4198 	struct proc *p;
4199 	int nrele;
4200 
4201 	if (vrefcnt(olddp) == 1)
4202 		return;
4203 	nrele = 0;
4204 	newpwd = pwd_alloc();
4205 	sx_slock(&allproc_lock);
4206 	FOREACH_PROC_IN_SYSTEM(p) {
4207 		PROC_LOCK(p);
4208 		pdp = pdhold(p);
4209 		PROC_UNLOCK(p);
4210 		if (pdp == NULL)
4211 			continue;
4212 		PWDDESC_XLOCK(pdp);
4213 		oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4214 		if (oldpwd == NULL ||
4215 		    (oldpwd->pwd_cdir != olddp &&
4216 		    oldpwd->pwd_rdir != olddp &&
4217 		    oldpwd->pwd_jdir != olddp &&
4218 		    oldpwd->pwd_adir != olddp)) {
4219 			PWDDESC_XUNLOCK(pdp);
4220 			pddrop(pdp);
4221 			continue;
4222 		}
4223 		if (oldpwd->pwd_cdir == olddp) {
4224 			vrefact(newdp);
4225 			newpwd->pwd_cdir = newdp;
4226 		}
4227 		if (oldpwd->pwd_rdir == olddp) {
4228 			vrefact(newdp);
4229 			newpwd->pwd_rdir = newdp;
4230 		}
4231 		if (oldpwd->pwd_jdir == olddp) {
4232 			vrefact(newdp);
4233 			newpwd->pwd_jdir = newdp;
4234 		}
4235 		if (oldpwd->pwd_adir == olddp) {
4236 			vrefact(newdp);
4237 			newpwd->pwd_adir = newdp;
4238 		}
4239 		pwd_fill(oldpwd, newpwd);
4240 		pwd_set(pdp, newpwd);
4241 		PWDDESC_XUNLOCK(pdp);
4242 		pwd_drop(oldpwd);
4243 		pddrop(pdp);
4244 		newpwd = pwd_alloc();
4245 	}
4246 	sx_sunlock(&allproc_lock);
4247 	pwd_drop(newpwd);
4248 	if (rootvnode == olddp) {
4249 		vrefact(newdp);
4250 		rootvnode = newdp;
4251 		nrele++;
4252 	}
4253 	mtx_lock(&prison0.pr_mtx);
4254 	if (prison0.pr_root == olddp) {
4255 		vrefact(newdp);
4256 		prison0.pr_root = newdp;
4257 		nrele++;
4258 	}
4259 	mtx_unlock(&prison0.pr_mtx);
4260 	sx_slock(&allprison_lock);
4261 	TAILQ_FOREACH(pr, &allprison, pr_list) {
4262 		mtx_lock(&pr->pr_mtx);
4263 		if (pr->pr_root == olddp) {
4264 			vrefact(newdp);
4265 			pr->pr_root = newdp;
4266 			nrele++;
4267 		}
4268 		mtx_unlock(&pr->pr_mtx);
4269 	}
4270 	sx_sunlock(&allprison_lock);
4271 	while (nrele--)
4272 		vrele(olddp);
4273 }
4274 
4275 int
descrip_check_write_mp(struct filedesc * fdp,struct mount * mp)4276 descrip_check_write_mp(struct filedesc *fdp, struct mount *mp)
4277 {
4278 	struct file *fp;
4279 	struct vnode *vp;
4280 	int error, i;
4281 
4282 	error = 0;
4283 	FILEDESC_SLOCK(fdp);
4284 	FILEDESC_FOREACH_FP(fdp, i, fp) {
4285 		if (fp->f_type != DTYPE_VNODE ||
4286 		    (atomic_load_int(&fp->f_flag) & FWRITE) == 0)
4287 			continue;
4288 		vp = fp->f_vnode;
4289 		if (vp->v_mount == mp) {
4290 			error = EDEADLK;
4291 			break;
4292 		}
4293 	}
4294 	FILEDESC_SUNLOCK(fdp);
4295 	return (error);
4296 }
4297 
4298 struct filedesc_to_leader *
filedesc_to_leader_alloc(struct filedesc_to_leader * old,struct filedesc * fdp,struct proc * leader)4299 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp,
4300     struct proc *leader)
4301 {
4302 	struct filedesc_to_leader *fdtol;
4303 
4304 	fdtol = malloc(sizeof(struct filedesc_to_leader),
4305 	    M_FILEDESC_TO_LEADER, M_WAITOK);
4306 	fdtol->fdl_refcount = 1;
4307 	fdtol->fdl_holdcount = 0;
4308 	fdtol->fdl_wakeup = 0;
4309 	fdtol->fdl_leader = leader;
4310 	if (old != NULL) {
4311 		FILEDESC_XLOCK(fdp);
4312 		fdtol->fdl_next = old->fdl_next;
4313 		fdtol->fdl_prev = old;
4314 		old->fdl_next = fdtol;
4315 		fdtol->fdl_next->fdl_prev = fdtol;
4316 		FILEDESC_XUNLOCK(fdp);
4317 	} else {
4318 		fdtol->fdl_next = fdtol;
4319 		fdtol->fdl_prev = fdtol;
4320 	}
4321 	return (fdtol);
4322 }
4323 
4324 struct filedesc_to_leader *
filedesc_to_leader_share(struct filedesc_to_leader * fdtol,struct filedesc * fdp)4325 filedesc_to_leader_share(struct filedesc_to_leader *fdtol, struct filedesc *fdp)
4326 {
4327 	FILEDESC_XLOCK(fdp);
4328 	fdtol->fdl_refcount++;
4329 	FILEDESC_XUNLOCK(fdp);
4330 	return (fdtol);
4331 }
4332 
4333 static int
filedesc_nfiles(struct filedesc * fdp)4334 filedesc_nfiles(struct filedesc *fdp)
4335 {
4336 	NDSLOTTYPE *map;
4337 	int count, off, minoff;
4338 
4339 	if (fdp == NULL)
4340 		return (0);
4341 	count = 0;
4342 	FILEDESC_SLOCK(fdp);
4343 	map = fdp->fd_map;
4344 	off = NDSLOT(fdp->fd_nfiles - 1);
4345 	for (minoff = NDSLOT(0); off >= minoff; --off)
4346 		count += bitcountl(map[off]);
4347 	FILEDESC_SUNLOCK(fdp);
4348 	return (count);
4349 }
4350 
4351 int
proc_nfiles(struct proc * p)4352 proc_nfiles(struct proc *p)
4353 {
4354 	struct filedesc *fdp;
4355 	int res;
4356 
4357 	PROC_LOCK(p);
4358 	fdp = fdhold(p);
4359 	PROC_UNLOCK(p);
4360 	res = filedesc_nfiles(fdp);
4361 	fddrop(fdp);
4362 	return (res);
4363 }
4364 
4365 static int
sysctl_kern_proc_nfds(SYSCTL_HANDLER_ARGS)4366 sysctl_kern_proc_nfds(SYSCTL_HANDLER_ARGS)
4367 {
4368 	u_int namelen;
4369 	int count;
4370 
4371 	namelen = arg2;
4372 	if (namelen != 1)
4373 		return (EINVAL);
4374 
4375 	if (*(int *)arg1 != 0)
4376 		return (EINVAL);
4377 
4378 	count = filedesc_nfiles(curproc->p_fd);
4379 	return (SYSCTL_OUT(req, &count, sizeof(count)));
4380 }
4381 
4382 static SYSCTL_NODE(_kern_proc, KERN_PROC_NFDS, nfds,
4383     CTLFLAG_RD|CTLFLAG_CAPRD|CTLFLAG_MPSAFE, sysctl_kern_proc_nfds,
4384     "Number of open file descriptors");
4385 
4386 /*
4387  * Get file structures globally.
4388  */
4389 static int
sysctl_kern_file(SYSCTL_HANDLER_ARGS)4390 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
4391 {
4392 	struct xfile xf;
4393 	struct filedesc *fdp;
4394 	struct file *fp;
4395 	struct proc *p;
4396 	int error, n;
4397 
4398 	error = sysctl_wire_old_buffer(req, 0);
4399 	if (error != 0)
4400 		return (error);
4401 	if (req->oldptr == NULL) {
4402 		n = 0;
4403 		sx_slock(&allproc_lock);
4404 		FOREACH_PROC_IN_SYSTEM(p) {
4405 			PROC_LOCK(p);
4406 			if (p->p_state == PRS_NEW) {
4407 				PROC_UNLOCK(p);
4408 				continue;
4409 			}
4410 			fdp = fdhold(p);
4411 			PROC_UNLOCK(p);
4412 			if (fdp == NULL)
4413 				continue;
4414 			/* overestimates sparse tables. */
4415 			n += fdp->fd_nfiles;
4416 			fddrop(fdp);
4417 		}
4418 		sx_sunlock(&allproc_lock);
4419 		return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
4420 	}
4421 	error = 0;
4422 	bzero(&xf, sizeof(xf));
4423 	xf.xf_size = sizeof(xf);
4424 	sx_slock(&allproc_lock);
4425 	FOREACH_PROC_IN_SYSTEM(p) {
4426 		PROC_LOCK(p);
4427 		if (p->p_state == PRS_NEW) {
4428 			PROC_UNLOCK(p);
4429 			continue;
4430 		}
4431 		if (p_cansee(req->td, p) != 0) {
4432 			PROC_UNLOCK(p);
4433 			continue;
4434 		}
4435 		xf.xf_pid = p->p_pid;
4436 		xf.xf_uid = p->p_ucred->cr_uid;
4437 		fdp = fdhold(p);
4438 		PROC_UNLOCK(p);
4439 		if (fdp == NULL)
4440 			continue;
4441 		FILEDESC_SLOCK(fdp);
4442 		if (refcount_load(&fdp->fd_refcnt) == 0)
4443 			goto nextproc;
4444 		FILEDESC_FOREACH_FP(fdp, n, fp) {
4445 			xf.xf_fd = n;
4446 			xf.xf_file = (uintptr_t)fp;
4447 			xf.xf_data = (uintptr_t)fp->f_data;
4448 			xf.xf_vnode = (uintptr_t)fp->f_vnode;
4449 			xf.xf_type = (uintptr_t)fp->f_type;
4450 			xf.xf_count = refcount_load(&fp->f_count);
4451 			xf.xf_msgcount = 0;
4452 			xf.xf_offset = foffset_get(fp);
4453 			xf.xf_flag = fp->f_flag;
4454 			error = SYSCTL_OUT(req, &xf, sizeof(xf));
4455 
4456 			/*
4457 			 * There is no need to re-check the fdtable refcount
4458 			 * here since the filedesc lock is not dropped in the
4459 			 * loop body.
4460 			 */
4461 			if (error != 0)
4462 				break;
4463 		}
4464 nextproc:
4465 		FILEDESC_SUNLOCK(fdp);
4466 		fddrop(fdp);
4467 		if (error)
4468 			break;
4469 	}
4470 	sx_sunlock(&allproc_lock);
4471 	return (error);
4472 }
4473 
4474 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
4475     0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
4476 
4477 #ifdef KINFO_FILE_SIZE
4478 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
4479 #endif
4480 
4481 static int
xlate_fflags(int fflags)4482 xlate_fflags(int fflags)
4483 {
4484 	static const struct {
4485 		int	fflag;
4486 		int	kf_fflag;
4487 	} fflags_table[] = {
4488 		{ FAPPEND, KF_FLAG_APPEND },
4489 		{ FASYNC, KF_FLAG_ASYNC },
4490 		{ FFSYNC, KF_FLAG_FSYNC },
4491 		{ FHASLOCK, KF_FLAG_HASLOCK },
4492 		{ FNONBLOCK, KF_FLAG_NONBLOCK },
4493 		{ FREAD, KF_FLAG_READ },
4494 		{ FWRITE, KF_FLAG_WRITE },
4495 		{ O_CREAT, KF_FLAG_CREAT },
4496 		{ O_DIRECT, KF_FLAG_DIRECT },
4497 		{ O_EXCL, KF_FLAG_EXCL },
4498 		{ O_EXEC, KF_FLAG_EXEC },
4499 		{ O_EXLOCK, KF_FLAG_EXLOCK },
4500 		{ O_NOFOLLOW, KF_FLAG_NOFOLLOW },
4501 		{ O_SHLOCK, KF_FLAG_SHLOCK },
4502 		{ O_TRUNC, KF_FLAG_TRUNC }
4503 	};
4504 	unsigned int i;
4505 	int kflags;
4506 
4507 	kflags = 0;
4508 	for (i = 0; i < nitems(fflags_table); i++)
4509 		if (fflags & fflags_table[i].fflag)
4510 			kflags |=  fflags_table[i].kf_fflag;
4511 	return (kflags);
4512 }
4513 
4514 /* Trim unused data from kf_path by truncating the structure size. */
4515 void
pack_kinfo(struct kinfo_file * kif)4516 pack_kinfo(struct kinfo_file *kif)
4517 {
4518 
4519 	kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
4520 	    strlen(kif->kf_path) + 1;
4521 	kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
4522 }
4523 
4524 static void
export_file_to_kinfo(struct file * fp,int fd,cap_rights_t * rightsp,struct kinfo_file * kif,struct filedesc * fdp,int flags)4525 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp,
4526     struct kinfo_file *kif, struct filedesc *fdp, int flags)
4527 {
4528 	int error;
4529 
4530 	bzero(kif, sizeof(*kif));
4531 
4532 	/* Set a default type to allow for empty fill_kinfo() methods. */
4533 	kif->kf_type = KF_TYPE_UNKNOWN;
4534 	kif->kf_flags = xlate_fflags(fp->f_flag);
4535 	if (rightsp != NULL)
4536 		kif->kf_cap_rights = *rightsp;
4537 	else
4538 		cap_rights_init_zero(&kif->kf_cap_rights);
4539 	kif->kf_fd = fd;
4540 	kif->kf_ref_count = refcount_load(&fp->f_count);
4541 	kif->kf_offset = foffset_get(fp);
4542 
4543 	/*
4544 	 * This may drop the filedesc lock, so the 'fp' cannot be
4545 	 * accessed after this call.
4546 	 */
4547 	error = fo_fill_kinfo(fp, kif, fdp);
4548 	if (error == 0)
4549 		kif->kf_status |= KF_ATTR_VALID;
4550 	if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
4551 		pack_kinfo(kif);
4552 	else
4553 		kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
4554 }
4555 
4556 static void
export_vnode_to_kinfo(struct vnode * vp,int fd,int fflags,struct kinfo_file * kif,int flags)4557 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags,
4558     struct kinfo_file *kif, int flags)
4559 {
4560 	int error;
4561 
4562 	bzero(kif, sizeof(*kif));
4563 
4564 	kif->kf_type = KF_TYPE_VNODE;
4565 	error = vn_fill_kinfo_vnode(vp, kif);
4566 	if (error == 0)
4567 		kif->kf_status |= KF_ATTR_VALID;
4568 	kif->kf_flags = xlate_fflags(fflags);
4569 	cap_rights_init_zero(&kif->kf_cap_rights);
4570 	kif->kf_fd = fd;
4571 	kif->kf_ref_count = -1;
4572 	kif->kf_offset = -1;
4573 	if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
4574 		pack_kinfo(kif);
4575 	else
4576 		kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
4577 	vrele(vp);
4578 }
4579 
4580 struct export_fd_buf {
4581 	struct filedesc		*fdp;
4582 	struct pwddesc	*pdp;
4583 	struct sbuf 		*sb;
4584 	ssize_t			remainder;
4585 	struct kinfo_file	kif;
4586 	int			flags;
4587 };
4588 
4589 static int
export_kinfo_to_sb(struct export_fd_buf * efbuf)4590 export_kinfo_to_sb(struct export_fd_buf *efbuf)
4591 {
4592 	struct kinfo_file *kif;
4593 
4594 	kif = &efbuf->kif;
4595 	if (efbuf->remainder != -1) {
4596 		if (efbuf->remainder < kif->kf_structsize)
4597 			return (ENOMEM);
4598 		efbuf->remainder -= kif->kf_structsize;
4599 	}
4600 	if (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) != 0)
4601 		return (sbuf_error(efbuf->sb));
4602 	return (0);
4603 }
4604 
4605 static int
export_file_to_sb(struct file * fp,int fd,cap_rights_t * rightsp,struct export_fd_buf * efbuf)4606 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp,
4607     struct export_fd_buf *efbuf)
4608 {
4609 	int error;
4610 
4611 	if (efbuf->remainder == 0)
4612 		return (ENOMEM);
4613 	export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp,
4614 	    efbuf->flags);
4615 	FILEDESC_SUNLOCK(efbuf->fdp);
4616 	error = export_kinfo_to_sb(efbuf);
4617 	FILEDESC_SLOCK(efbuf->fdp);
4618 	return (error);
4619 }
4620 
4621 static int
export_vnode_to_sb(struct vnode * vp,int fd,int fflags,struct export_fd_buf * efbuf)4622 export_vnode_to_sb(struct vnode *vp, int fd, int fflags,
4623     struct export_fd_buf *efbuf)
4624 {
4625 	int error;
4626 
4627 	if (efbuf->remainder == 0)
4628 		return (ENOMEM);
4629 	if (efbuf->pdp != NULL)
4630 		PWDDESC_XUNLOCK(efbuf->pdp);
4631 	export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif, efbuf->flags);
4632 	error = export_kinfo_to_sb(efbuf);
4633 	if (efbuf->pdp != NULL)
4634 		PWDDESC_XLOCK(efbuf->pdp);
4635 	return (error);
4636 }
4637 
4638 /*
4639  * Store a process file descriptor information to sbuf.
4640  *
4641  * Takes a locked proc as argument, and returns with the proc unlocked.
4642  */
4643 int
kern_proc_filedesc_out(struct proc * p,struct sbuf * sb,ssize_t maxlen,int flags)4644 kern_proc_filedesc_out(struct proc *p,  struct sbuf *sb, ssize_t maxlen,
4645     int flags)
4646 {
4647 	struct file *fp;
4648 	struct filedesc *fdp;
4649 	struct pwddesc *pdp;
4650 	struct export_fd_buf *efbuf;
4651 	struct vnode *cttyvp, *textvp, *tracevp;
4652 	struct pwd *pwd;
4653 	int error, i;
4654 	cap_rights_t rights;
4655 
4656 	PROC_LOCK_ASSERT(p, MA_OWNED);
4657 
4658 	/* ktrace vnode */
4659 	tracevp = ktr_get_tracevp(p, true);
4660 	/* text vnode */
4661 	textvp = p->p_textvp;
4662 	if (textvp != NULL)
4663 		vrefact(textvp);
4664 	/* Controlling tty. */
4665 	cttyvp = NULL;
4666 	if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
4667 		cttyvp = p->p_pgrp->pg_session->s_ttyvp;
4668 		if (cttyvp != NULL)
4669 			vrefact(cttyvp);
4670 	}
4671 	fdp = fdhold(p);
4672 	pdp = pdhold(p);
4673 	PROC_UNLOCK(p);
4674 
4675 	efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
4676 	efbuf->fdp = NULL;
4677 	efbuf->pdp = NULL;
4678 	efbuf->sb = sb;
4679 	efbuf->remainder = maxlen;
4680 	efbuf->flags = flags;
4681 
4682 	error = 0;
4683 	if (tracevp != NULL)
4684 		error = export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE,
4685 		    FREAD | FWRITE, efbuf);
4686 	if (error == 0 && textvp != NULL)
4687 		error = export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD,
4688 		    efbuf);
4689 	if (error == 0 && cttyvp != NULL)
4690 		error = export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY,
4691 		    FREAD | FWRITE, efbuf);
4692 	if (error != 0 || pdp == NULL || fdp == NULL)
4693 		goto fail;
4694 	efbuf->fdp = fdp;
4695 	efbuf->pdp = pdp;
4696 	PWDDESC_XLOCK(pdp);
4697 	pwd = pwd_hold_pwddesc(pdp);
4698 	if (pwd != NULL) {
4699 		/* working directory */
4700 		if (pwd->pwd_cdir != NULL) {
4701 			vrefact(pwd->pwd_cdir);
4702 			error = export_vnode_to_sb(pwd->pwd_cdir,
4703 			    KF_FD_TYPE_CWD, FREAD, efbuf);
4704 		}
4705 		/* root directory */
4706 		if (error == 0 && pwd->pwd_rdir != NULL) {
4707 			vrefact(pwd->pwd_rdir);
4708 			error = export_vnode_to_sb(pwd->pwd_rdir,
4709 			    KF_FD_TYPE_ROOT, FREAD, efbuf);
4710 		}
4711 		/* jail directory */
4712 		if (error == 0 && pwd->pwd_jdir != NULL) {
4713 			vrefact(pwd->pwd_jdir);
4714 			error = export_vnode_to_sb(pwd->pwd_jdir,
4715 			    KF_FD_TYPE_JAIL, FREAD, efbuf);
4716 		}
4717 	}
4718 	PWDDESC_XUNLOCK(pdp);
4719 	if (error != 0)
4720 		goto fail;
4721 	if (pwd != NULL)
4722 		pwd_drop(pwd);
4723 	FILEDESC_SLOCK(fdp);
4724 	if (refcount_load(&fdp->fd_refcnt) == 0)
4725 		goto skip;
4726 	FILEDESC_FOREACH_FP(fdp, i, fp) {
4727 #ifdef CAPABILITIES
4728 		rights = *cap_rights(fdp, i);
4729 #else /* !CAPABILITIES */
4730 		rights = cap_no_rights;
4731 #endif
4732 		/*
4733 		 * Create sysctl entry.  It is OK to drop the filedesc
4734 		 * lock inside of export_file_to_sb() as we will
4735 		 * re-validate and re-evaluate its properties when the
4736 		 * loop continues.
4737 		 */
4738 		error = export_file_to_sb(fp, i, &rights, efbuf);
4739 		if (error != 0 || refcount_load(&fdp->fd_refcnt) == 0)
4740 			break;
4741 	}
4742 skip:
4743 	FILEDESC_SUNLOCK(fdp);
4744 fail:
4745 	if (fdp != NULL)
4746 		fddrop(fdp);
4747 	if (pdp != NULL)
4748 		pddrop(pdp);
4749 	free(efbuf, M_TEMP);
4750 	return (error);
4751 }
4752 
4753 #define FILEDESC_SBUF_SIZE	(sizeof(struct kinfo_file) * 5)
4754 
4755 /*
4756  * Get per-process file descriptors for use by procstat(1), et al.
4757  */
4758 static int
sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)4759 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
4760 {
4761 	struct sbuf sb;
4762 	struct proc *p;
4763 	ssize_t maxlen;
4764 	u_int namelen;
4765 	int error, error2, *name;
4766 
4767 	namelen = arg2;
4768 	if (namelen != 1)
4769 		return (EINVAL);
4770 
4771 	name = (int *)arg1;
4772 
4773 	sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
4774 	sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
4775 	error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4776 	if (error != 0) {
4777 		sbuf_delete(&sb);
4778 		return (error);
4779 	}
4780 	maxlen = req->oldptr != NULL ? req->oldlen : -1;
4781 	error = kern_proc_filedesc_out(p, &sb, maxlen,
4782 	    KERN_FILEDESC_PACK_KINFO);
4783 	error2 = sbuf_finish(&sb);
4784 	sbuf_delete(&sb);
4785 	return (error != 0 ? error : error2);
4786 }
4787 
4788 #ifdef COMPAT_FREEBSD7
4789 #ifdef KINFO_OFILE_SIZE
4790 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
4791 #endif
4792 
4793 static void
kinfo_to_okinfo(struct kinfo_file * kif,struct kinfo_ofile * okif)4794 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif)
4795 {
4796 
4797 	okif->kf_structsize = sizeof(*okif);
4798 	okif->kf_type = kif->kf_type;
4799 	okif->kf_fd = kif->kf_fd;
4800 	okif->kf_ref_count = kif->kf_ref_count;
4801 	okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE |
4802 	    KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK |
4803 	    KF_FLAG_DIRECT | KF_FLAG_HASLOCK);
4804 	okif->kf_offset = kif->kf_offset;
4805 	if (kif->kf_type == KF_TYPE_VNODE)
4806 		okif->kf_vnode_type = kif->kf_un.kf_file.kf_file_type;
4807 	else
4808 		okif->kf_vnode_type = KF_VTYPE_VNON;
4809 	strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path));
4810 	if (kif->kf_type == KF_TYPE_SOCKET) {
4811 		okif->kf_sock_domain = kif->kf_un.kf_sock.kf_sock_domain0;
4812 		okif->kf_sock_type = kif->kf_un.kf_sock.kf_sock_type0;
4813 		okif->kf_sock_protocol = kif->kf_un.kf_sock.kf_sock_protocol0;
4814 		okif->kf_sa_local = kif->kf_un.kf_sock.kf_sa_local;
4815 		okif->kf_sa_peer = kif->kf_un.kf_sock.kf_sa_peer;
4816 	} else {
4817 		okif->kf_sa_local.ss_family = AF_UNSPEC;
4818 		okif->kf_sa_peer.ss_family = AF_UNSPEC;
4819 	}
4820 }
4821 
4822 static int
export_vnode_for_osysctl(struct vnode * vp,int type,struct kinfo_file * kif,struct kinfo_ofile * okif,struct pwddesc * pdp,struct sysctl_req * req)4823 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif,
4824     struct kinfo_ofile *okif, struct pwddesc *pdp, struct sysctl_req *req)
4825 {
4826 	int error;
4827 
4828 	vrefact(vp);
4829 	PWDDESC_XUNLOCK(pdp);
4830 	export_vnode_to_kinfo(vp, type, 0, kif, KERN_FILEDESC_PACK_KINFO);
4831 	kinfo_to_okinfo(kif, okif);
4832 	error = SYSCTL_OUT(req, okif, sizeof(*okif));
4833 	PWDDESC_XLOCK(pdp);
4834 	return (error);
4835 }
4836 
4837 /*
4838  * Get per-process file descriptors for use by procstat(1), et al.
4839  */
4840 static int
sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)4841 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
4842 {
4843 	struct kinfo_ofile *okif;
4844 	struct kinfo_file *kif;
4845 	struct filedesc *fdp;
4846 	struct pwddesc *pdp;
4847 	struct pwd *pwd;
4848 	u_int namelen;
4849 	int error, i, *name;
4850 	struct file *fp;
4851 	struct proc *p;
4852 
4853 	namelen = arg2;
4854 	if (namelen != 1)
4855 		return (EINVAL);
4856 
4857 	name = (int *)arg1;
4858 	error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4859 	if (error != 0)
4860 		return (error);
4861 	fdp = fdhold(p);
4862 	if (fdp != NULL)
4863 		pdp = pdhold(p);
4864 	PROC_UNLOCK(p);
4865 	if (fdp == NULL || pdp == NULL) {
4866 		if (fdp != NULL)
4867 			fddrop(fdp);
4868 		return (ENOENT);
4869 	}
4870 	kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
4871 	okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK);
4872 	PWDDESC_XLOCK(pdp);
4873 	pwd = pwd_hold_pwddesc(pdp);
4874 	if (pwd != NULL) {
4875 		if (pwd->pwd_cdir != NULL)
4876 			export_vnode_for_osysctl(pwd->pwd_cdir, KF_FD_TYPE_CWD, kif,
4877 			    okif, pdp, req);
4878 		if (pwd->pwd_rdir != NULL)
4879 			export_vnode_for_osysctl(pwd->pwd_rdir, KF_FD_TYPE_ROOT, kif,
4880 			    okif, pdp, req);
4881 		if (pwd->pwd_jdir != NULL)
4882 			export_vnode_for_osysctl(pwd->pwd_jdir, KF_FD_TYPE_JAIL, kif,
4883 			    okif, pdp, req);
4884 	}
4885 	PWDDESC_XUNLOCK(pdp);
4886 	if (pwd != NULL)
4887 		pwd_drop(pwd);
4888 	FILEDESC_SLOCK(fdp);
4889 	if (refcount_load(&fdp->fd_refcnt) == 0)
4890 		goto skip;
4891 	FILEDESC_FOREACH_FP(fdp, i, fp) {
4892 		export_file_to_kinfo(fp, i, NULL, kif, fdp,
4893 		    KERN_FILEDESC_PACK_KINFO);
4894 		FILEDESC_SUNLOCK(fdp);
4895 		kinfo_to_okinfo(kif, okif);
4896 		error = SYSCTL_OUT(req, okif, sizeof(*okif));
4897 		FILEDESC_SLOCK(fdp);
4898 		if (error != 0 || refcount_load(&fdp->fd_refcnt) == 0)
4899 			break;
4900 	}
4901 skip:
4902 	FILEDESC_SUNLOCK(fdp);
4903 	fddrop(fdp);
4904 	pddrop(pdp);
4905 	free(kif, M_TEMP);
4906 	free(okif, M_TEMP);
4907 	return (0);
4908 }
4909 
4910 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
4911     CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
4912     "Process ofiledesc entries");
4913 #endif	/* COMPAT_FREEBSD7 */
4914 
4915 int
vntype_to_kinfo(int vtype)4916 vntype_to_kinfo(int vtype)
4917 {
4918 	struct {
4919 		int	vtype;
4920 		int	kf_vtype;
4921 	} vtypes_table[] = {
4922 		{ VBAD, KF_VTYPE_VBAD },
4923 		{ VBLK, KF_VTYPE_VBLK },
4924 		{ VCHR, KF_VTYPE_VCHR },
4925 		{ VDIR, KF_VTYPE_VDIR },
4926 		{ VFIFO, KF_VTYPE_VFIFO },
4927 		{ VLNK, KF_VTYPE_VLNK },
4928 		{ VNON, KF_VTYPE_VNON },
4929 		{ VREG, KF_VTYPE_VREG },
4930 		{ VSOCK, KF_VTYPE_VSOCK }
4931 	};
4932 	unsigned int i;
4933 
4934 	/*
4935 	 * Perform vtype translation.
4936 	 */
4937 	for (i = 0; i < nitems(vtypes_table); i++)
4938 		if (vtypes_table[i].vtype == vtype)
4939 			return (vtypes_table[i].kf_vtype);
4940 
4941 	return (KF_VTYPE_UNKNOWN);
4942 }
4943 
4944 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
4945     CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
4946     "Process filedesc entries");
4947 
4948 /*
4949  * Store a process current working directory information to sbuf.
4950  *
4951  * Takes a locked proc as argument, and returns with the proc unlocked.
4952  */
4953 int
kern_proc_cwd_out(struct proc * p,struct sbuf * sb,ssize_t maxlen)4954 kern_proc_cwd_out(struct proc *p,  struct sbuf *sb, ssize_t maxlen)
4955 {
4956 	struct pwddesc *pdp;
4957 	struct pwd *pwd;
4958 	struct export_fd_buf *efbuf;
4959 	struct vnode *cdir;
4960 	int error;
4961 
4962 	PROC_LOCK_ASSERT(p, MA_OWNED);
4963 
4964 	pdp = pdhold(p);
4965 	PROC_UNLOCK(p);
4966 	if (pdp == NULL)
4967 		return (EINVAL);
4968 
4969 	efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
4970 	efbuf->fdp = NULL;
4971 	efbuf->pdp = pdp;
4972 	efbuf->sb = sb;
4973 	efbuf->remainder = maxlen;
4974 	efbuf->flags = 0;
4975 
4976 	PWDDESC_XLOCK(pdp);
4977 	pwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4978 	cdir = pwd->pwd_cdir;
4979 	if (cdir == NULL) {
4980 		error = EINVAL;
4981 	} else {
4982 		vrefact(cdir);
4983 		error = export_vnode_to_sb(cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
4984 	}
4985 	PWDDESC_XUNLOCK(pdp);
4986 	pddrop(pdp);
4987 	free(efbuf, M_TEMP);
4988 	return (error);
4989 }
4990 
4991 /*
4992  * Get per-process current working directory.
4993  */
4994 static int
sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)4995 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
4996 {
4997 	struct sbuf sb;
4998 	struct proc *p;
4999 	ssize_t maxlen;
5000 	u_int namelen;
5001 	int error, error2, *name;
5002 
5003 	namelen = arg2;
5004 	if (namelen != 1)
5005 		return (EINVAL);
5006 
5007 	name = (int *)arg1;
5008 
5009 	sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req);
5010 	sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
5011 	error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
5012 	if (error != 0) {
5013 		sbuf_delete(&sb);
5014 		return (error);
5015 	}
5016 	maxlen = req->oldptr != NULL ? req->oldlen : -1;
5017 	error = kern_proc_cwd_out(p, &sb, maxlen);
5018 	error2 = sbuf_finish(&sb);
5019 	sbuf_delete(&sb);
5020 	return (error != 0 ? error : error2);
5021 }
5022 
5023 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE,
5024     sysctl_kern_proc_cwd, "Process current working directory");
5025 
5026 #ifdef DDB
5027 /*
5028  * For the purposes of debugging, generate a human-readable string for the
5029  * file type.
5030  */
5031 static const char *
file_type_to_name(short type)5032 file_type_to_name(short type)
5033 {
5034 
5035 	switch (type) {
5036 	case 0:
5037 		return ("zero");
5038 	case DTYPE_VNODE:
5039 		return ("vnode");
5040 	case DTYPE_SOCKET:
5041 		return ("socket");
5042 	case DTYPE_PIPE:
5043 		return ("pipe");
5044 	case DTYPE_FIFO:
5045 		return ("fifo");
5046 	case DTYPE_KQUEUE:
5047 		return ("kqueue");
5048 	case DTYPE_CRYPTO:
5049 		return ("crypto");
5050 	case DTYPE_MQUEUE:
5051 		return ("mqueue");
5052 	case DTYPE_SHM:
5053 		return ("shm");
5054 	case DTYPE_SEM:
5055 		return ("ksem");
5056 	case DTYPE_PTS:
5057 		return ("pts");
5058 	case DTYPE_DEV:
5059 		return ("dev");
5060 	case DTYPE_PROCDESC:
5061 		return ("proc");
5062 	case DTYPE_EVENTFD:
5063 		return ("eventfd");
5064 	case DTYPE_TIMERFD:
5065 		return ("timerfd");
5066 	default:
5067 		return ("unkn");
5068 	}
5069 }
5070 
5071 /*
5072  * For the purposes of debugging, identify a process (if any, perhaps one of
5073  * many) that references the passed file in its file descriptor array. Return
5074  * NULL if none.
5075  */
5076 static struct proc *
file_to_first_proc(struct file * fp)5077 file_to_first_proc(struct file *fp)
5078 {
5079 	struct filedesc *fdp;
5080 	struct proc *p;
5081 	int n;
5082 
5083 	FOREACH_PROC_IN_SYSTEM(p) {
5084 		if (p->p_state == PRS_NEW)
5085 			continue;
5086 		fdp = p->p_fd;
5087 		if (fdp == NULL)
5088 			continue;
5089 		for (n = 0; n < fdp->fd_nfiles; n++) {
5090 			if (fp == fdp->fd_ofiles[n].fde_file)
5091 				return (p);
5092 		}
5093 	}
5094 	return (NULL);
5095 }
5096 
5097 static void
db_print_file(struct file * fp,int header)5098 db_print_file(struct file *fp, int header)
5099 {
5100 #define XPTRWIDTH ((int)howmany(sizeof(void *) * NBBY, 4))
5101 	struct proc *p;
5102 
5103 	if (header)
5104 		db_printf("%*s %6s %*s %8s %4s %5s %6s %*s %5s %s\n",
5105 		    XPTRWIDTH, "File", "Type", XPTRWIDTH, "Data", "Flag",
5106 		    "GCFl", "Count", "MCount", XPTRWIDTH, "Vnode", "FPID",
5107 		    "FCmd");
5108 	p = file_to_first_proc(fp);
5109 	db_printf("%*p %6s %*p %08x %04x %5d %6d %*p %5d %s\n", XPTRWIDTH,
5110 	    fp, file_type_to_name(fp->f_type), XPTRWIDTH, fp->f_data,
5111 	    fp->f_flag, 0, refcount_load(&fp->f_count), 0, XPTRWIDTH, fp->f_vnode,
5112 	    p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
5113 
5114 #undef XPTRWIDTH
5115 }
5116 
DB_SHOW_COMMAND(file,db_show_file)5117 DB_SHOW_COMMAND(file, db_show_file)
5118 {
5119 	struct file *fp;
5120 
5121 	if (!have_addr) {
5122 		db_printf("usage: show file <addr>\n");
5123 		return;
5124 	}
5125 	fp = (struct file *)addr;
5126 	db_print_file(fp, 1);
5127 }
5128 
DB_SHOW_COMMAND_FLAGS(files,db_show_files,DB_CMD_MEMSAFE)5129 DB_SHOW_COMMAND_FLAGS(files, db_show_files, DB_CMD_MEMSAFE)
5130 {
5131 	struct filedesc *fdp;
5132 	struct file *fp;
5133 	struct proc *p;
5134 	int header;
5135 	int n;
5136 
5137 	header = 1;
5138 	FOREACH_PROC_IN_SYSTEM(p) {
5139 		if (p->p_state == PRS_NEW)
5140 			continue;
5141 		if ((fdp = p->p_fd) == NULL)
5142 			continue;
5143 		for (n = 0; n < fdp->fd_nfiles; ++n) {
5144 			if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
5145 				continue;
5146 			db_print_file(fp, header);
5147 			header = 0;
5148 		}
5149 	}
5150 }
5151 #endif
5152 
5153 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc,
5154     CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
5155     &maxfilesperproc, 0, "Maximum files allowed open per process");
5156 
5157 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
5158     &maxfiles, 0, "Maximum number of files");
5159 
5160 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
5161     &openfiles, 0, "System-wide number of open files");
5162 
5163 /* ARGSUSED*/
5164 static void
filelistinit(void * dummy)5165 filelistinit(void *dummy)
5166 {
5167 
5168 	file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
5169 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
5170 	filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0),
5171 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
5172 	pwd_zone = uma_zcreate("PWD", sizeof(struct pwd), NULL, NULL,
5173 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_SMR);
5174 	/*
5175 	 * XXXMJG this is a temporary hack due to boot ordering issues against
5176 	 * the vnode zone.
5177 	 */
5178 	vfs_smr = uma_zone_get_smr(pwd_zone);
5179 	mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
5180 }
5181 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
5182 
5183 /*-------------------------------------------------------------------*/
5184 
5185 static int
badfo_readwrite(struct file * fp,struct uio * uio,struct ucred * active_cred,int flags,struct thread * td)5186 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
5187     int flags, struct thread *td)
5188 {
5189 
5190 	return (EBADF);
5191 }
5192 
5193 static int
badfo_truncate(struct file * fp,off_t length,struct ucred * active_cred,struct thread * td)5194 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
5195     struct thread *td)
5196 {
5197 
5198 	return (EINVAL);
5199 }
5200 
5201 static int
badfo_ioctl(struct file * fp,u_long com,void * data,struct ucred * active_cred,struct thread * td)5202 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
5203     struct thread *td)
5204 {
5205 
5206 	return (EBADF);
5207 }
5208 
5209 static int
badfo_poll(struct file * fp,int events,struct ucred * active_cred,struct thread * td)5210 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
5211     struct thread *td)
5212 {
5213 
5214 	return (0);
5215 }
5216 
5217 static int
badfo_kqfilter(struct file * fp,struct knote * kn)5218 badfo_kqfilter(struct file *fp, struct knote *kn)
5219 {
5220 
5221 	return (EBADF);
5222 }
5223 
5224 static int
badfo_stat(struct file * fp,struct stat * sb,struct ucred * active_cred)5225 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred)
5226 {
5227 
5228 	return (EBADF);
5229 }
5230 
5231 static int
badfo_close(struct file * fp,struct thread * td)5232 badfo_close(struct file *fp, struct thread *td)
5233 {
5234 
5235 	return (0);
5236 }
5237 
5238 static int
badfo_chmod(struct file * fp,mode_t mode,struct ucred * active_cred,struct thread * td)5239 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
5240     struct thread *td)
5241 {
5242 
5243 	return (EBADF);
5244 }
5245 
5246 static int
badfo_chown(struct file * fp,uid_t uid,gid_t gid,struct ucred * active_cred,struct thread * td)5247 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
5248     struct thread *td)
5249 {
5250 
5251 	return (EBADF);
5252 }
5253 
5254 static int
badfo_sendfile(struct file * fp,int sockfd,struct uio * hdr_uio,struct uio * trl_uio,off_t offset,size_t nbytes,off_t * sent,int flags,struct thread * td)5255 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
5256     struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
5257     struct thread *td)
5258 {
5259 
5260 	return (EBADF);
5261 }
5262 
5263 static int
badfo_fill_kinfo(struct file * fp,struct kinfo_file * kif,struct filedesc * fdp)5264 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
5265 {
5266 
5267 	return (0);
5268 }
5269 
5270 struct fileops badfileops = {
5271 	.fo_read = badfo_readwrite,
5272 	.fo_write = badfo_readwrite,
5273 	.fo_truncate = badfo_truncate,
5274 	.fo_ioctl = badfo_ioctl,
5275 	.fo_poll = badfo_poll,
5276 	.fo_kqfilter = badfo_kqfilter,
5277 	.fo_stat = badfo_stat,
5278 	.fo_close = badfo_close,
5279 	.fo_chmod = badfo_chmod,
5280 	.fo_chown = badfo_chown,
5281 	.fo_sendfile = badfo_sendfile,
5282 	.fo_fill_kinfo = badfo_fill_kinfo,
5283 };
5284 
5285 static int
path_poll(struct file * fp,int events,struct ucred * active_cred,struct thread * td)5286 path_poll(struct file *fp, int events, struct ucred *active_cred,
5287     struct thread *td)
5288 {
5289 	return (POLLNVAL);
5290 }
5291 
5292 static int
path_close(struct file * fp,struct thread * td)5293 path_close(struct file *fp, struct thread *td)
5294 {
5295 	MPASS(fp->f_type == DTYPE_VNODE);
5296 	fp->f_ops = &badfileops;
5297 	vrele(fp->f_vnode);
5298 	return (0);
5299 }
5300 
5301 struct fileops path_fileops = {
5302 	.fo_read = badfo_readwrite,
5303 	.fo_write = badfo_readwrite,
5304 	.fo_truncate = badfo_truncate,
5305 	.fo_ioctl = badfo_ioctl,
5306 	.fo_poll = path_poll,
5307 	.fo_kqfilter = vn_kqfilter_opath,
5308 	.fo_stat = vn_statfile,
5309 	.fo_close = path_close,
5310 	.fo_chmod = badfo_chmod,
5311 	.fo_chown = badfo_chown,
5312 	.fo_sendfile = badfo_sendfile,
5313 	.fo_fill_kinfo = vn_fill_kinfo,
5314 	.fo_cmp = vn_cmp,
5315 	.fo_flags = DFLAG_PASSABLE,
5316 };
5317 
5318 int
invfo_rdwr(struct file * fp,struct uio * uio,struct ucred * active_cred,int flags,struct thread * td)5319 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred,
5320     int flags, struct thread *td)
5321 {
5322 
5323 	return (EOPNOTSUPP);
5324 }
5325 
5326 int
invfo_truncate(struct file * fp,off_t length,struct ucred * active_cred,struct thread * td)5327 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
5328     struct thread *td)
5329 {
5330 
5331 	return (EINVAL);
5332 }
5333 
5334 int
invfo_ioctl(struct file * fp,u_long com,void * data,struct ucred * active_cred,struct thread * td)5335 invfo_ioctl(struct file *fp, u_long com, void *data,
5336     struct ucred *active_cred, struct thread *td)
5337 {
5338 
5339 	return (ENOTTY);
5340 }
5341 
5342 int
invfo_poll(struct file * fp,int events,struct ucred * active_cred,struct thread * td)5343 invfo_poll(struct file *fp, int events, struct ucred *active_cred,
5344     struct thread *td)
5345 {
5346 
5347 	return (poll_no_poll(events));
5348 }
5349 
5350 int
invfo_kqfilter(struct file * fp,struct knote * kn)5351 invfo_kqfilter(struct file *fp, struct knote *kn)
5352 {
5353 
5354 	return (EINVAL);
5355 }
5356 
5357 int
invfo_chmod(struct file * fp,mode_t mode,struct ucred * active_cred,struct thread * td)5358 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
5359     struct thread *td)
5360 {
5361 
5362 	return (EINVAL);
5363 }
5364 
5365 int
invfo_chown(struct file * fp,uid_t uid,gid_t gid,struct ucred * active_cred,struct thread * td)5366 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
5367     struct thread *td)
5368 {
5369 
5370 	return (EINVAL);
5371 }
5372 
5373 int
invfo_sendfile(struct file * fp,int sockfd,struct uio * hdr_uio,struct uio * trl_uio,off_t offset,size_t nbytes,off_t * sent,int flags,struct thread * td)5374 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
5375     struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
5376     struct thread *td)
5377 {
5378 
5379 	return (EINVAL);
5380 }
5381 
5382 /*-------------------------------------------------------------------*/
5383 
5384 /*
5385  * File Descriptor pseudo-device driver (/dev/fd/).
5386  *
5387  * Opening minor device N dup()s the file (if any) connected to file
5388  * descriptor N belonging to the calling process.  Note that this driver
5389  * consists of only the ``open()'' routine, because all subsequent
5390  * references to this file will be direct to the other driver.
5391  *
5392  * XXX: we could give this one a cloning event handler if necessary.
5393  */
5394 
5395 /* ARGSUSED */
5396 static int
fdopen(struct cdev * dev,int mode,int type,struct thread * td)5397 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
5398 {
5399 
5400 	/*
5401 	 * XXX Kludge: set curthread->td_dupfd to contain the value of the
5402 	 * the file descriptor being sought for duplication. The error
5403 	 * return ensures that the vnode for this device will be released
5404 	 * by vn_open. Open will detect this special error and take the
5405 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
5406 	 * will simply report the error.
5407 	 */
5408 	td->td_dupfd = dev2unit(dev);
5409 	return (ENODEV);
5410 }
5411 
5412 static struct cdevsw fildesc_cdevsw = {
5413 	.d_version =	D_VERSION,
5414 	.d_open =	fdopen,
5415 	.d_name =	"FD",
5416 };
5417 
5418 static void
fildesc_drvinit(void * unused)5419 fildesc_drvinit(void *unused)
5420 {
5421 	struct cdev *dev;
5422 
5423 	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
5424 	    UID_ROOT, GID_WHEEL, 0666, "fd/0");
5425 	make_dev_alias(dev, "stdin");
5426 	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
5427 	    UID_ROOT, GID_WHEEL, 0666, "fd/1");
5428 	make_dev_alias(dev, "stdout");
5429 	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
5430 	    UID_ROOT, GID_WHEEL, 0666, "fd/2");
5431 	make_dev_alias(dev, "stderr");
5432 }
5433 
5434 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);
5435