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