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