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