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