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