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