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