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