]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/kern/kern_descrip.c
MFC r238614:
[FreeBSD/stable/8.git] / sys / kern / kern_descrip.c
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      @(#)kern_descrip.c      8.6 (Berkeley) 4/19/94
35  */
36
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39
40 #include "opt_compat.h"
41 #include "opt_ddb.h"
42 #include "opt_ktrace.h"
43
44 #include <sys/param.h>
45 #include <sys/systm.h>
46
47 #include <sys/conf.h>
48 #include <sys/domain.h>
49 #include <sys/fcntl.h>
50 #include <sys/file.h>
51 #include <sys/filedesc.h>
52 #include <sys/filio.h>
53 #include <sys/jail.h>
54 #include <sys/kernel.h>
55 #include <sys/limits.h>
56 #include <sys/lock.h>
57 #include <sys/malloc.h>
58 #include <sys/mman.h>
59 #include <sys/mount.h>
60 #include <sys/mqueue.h>
61 #include <sys/mutex.h>
62 #include <sys/namei.h>
63 #include <sys/priv.h>
64 #include <sys/proc.h>
65 #include <sys/protosw.h>
66 #include <sys/resourcevar.h>
67 #include <sys/signalvar.h>
68 #include <sys/socketvar.h>
69 #include <sys/stat.h>
70 #include <sys/sx.h>
71 #include <sys/syscallsubr.h>
72 #include <sys/sysctl.h>
73 #include <sys/sysproto.h>
74 #include <sys/tty.h>
75 #include <sys/unistd.h>
76 #include <sys/user.h>
77 #include <sys/vnode.h>
78 #ifdef KTRACE
79 #include <sys/ktrace.h>
80 #endif
81
82 #include <net/vnet.h>
83
84 #include <security/audit/audit.h>
85
86 #include <vm/uma.h>
87
88 #include <ddb/ddb.h>
89
90 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
91 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
92                      "file desc to leader structures");
93 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
94
95 MALLOC_DECLARE(M_FADVISE);
96
97 static uma_zone_t file_zone;
98
99
100 /* Flags for do_dup() */
101 #define DUP_FIXED       0x1     /* Force fixed allocation */
102 #define DUP_FCNTL       0x2     /* fcntl()-style errors */
103 #define DUP_CLOEXEC     0x4     /* Atomically set FD_CLOEXEC. */
104
105 static int do_dup(struct thread *td, int flags, int old, int new,
106     register_t *retval);
107 static int      fd_first_free(struct filedesc *, int, int);
108 static int      fd_last_used(struct filedesc *, int, int);
109 static void     fdgrowtable(struct filedesc *, int);
110 static void     fdunused(struct filedesc *fdp, int fd);
111 static void     fdused(struct filedesc *fdp, int fd);
112
113 /*
114  * A process is initially started out with NDFILE descriptors stored within
115  * this structure, selected to be enough for typical applications based on
116  * the historical limit of 20 open files (and the usage of descriptors by
117  * shells).  If these descriptors are exhausted, a larger descriptor table
118  * may be allocated, up to a process' resource limit; the internal arrays
119  * are then unused.
120  */
121 #define NDFILE          20
122 #define NDSLOTSIZE      sizeof(NDSLOTTYPE)
123 #define NDENTRIES       (NDSLOTSIZE * __CHAR_BIT)
124 #define NDSLOT(x)       ((x) / NDENTRIES)
125 #define NDBIT(x)        ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
126 #define NDSLOTS(x)      (((x) + NDENTRIES - 1) / NDENTRIES)
127
128 /*
129  * Storage required per open file descriptor.
130  */
131 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
132
133 /*
134  * Storage to hold unused ofiles that need to be reclaimed.
135  */
136 struct freetable {
137         struct file     **ft_table;
138         SLIST_ENTRY(freetable) ft_next;
139 };
140
141 /*
142  * Basic allocation of descriptors:
143  * one of the above, plus arrays for NDFILE descriptors.
144  */
145 struct filedesc0 {
146         struct  filedesc fd_fd;
147         /*
148          * ofiles which need to be reclaimed on free.
149          */
150         SLIST_HEAD(,freetable) fd_free;
151         /*
152          * These arrays are used when the number of open files is
153          * <= NDFILE, and are then pointed to by the pointers above.
154          */
155         struct  file *fd_dfiles[NDFILE];
156         char    fd_dfileflags[NDFILE];
157         NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
158 };
159
160 /*
161  * Descriptor management.
162  */
163 volatile int openfiles;                 /* actual number of open files */
164 struct mtx sigio_lock;          /* mtx to protect pointers to sigio */
165 void    (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
166
167 /* A mutex to protect the association between a proc and filedesc. */
168 static struct mtx       fdesc_mtx;
169
170 /*
171  * Find the first zero bit in the given bitmap, starting at low and not
172  * exceeding size - 1.
173  */
174 static int
175 fd_first_free(struct filedesc *fdp, int low, int size)
176 {
177         NDSLOTTYPE *map = fdp->fd_map;
178         NDSLOTTYPE mask;
179         int off, maxoff;
180
181         if (low >= size)
182                 return (low);
183
184         off = NDSLOT(low);
185         if (low % NDENTRIES) {
186                 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
187                 if ((mask &= ~map[off]) != 0UL)
188                         return (off * NDENTRIES + ffsl(mask) - 1);
189                 ++off;
190         }
191         for (maxoff = NDSLOTS(size); off < maxoff; ++off)
192                 if (map[off] != ~0UL)
193                         return (off * NDENTRIES + ffsl(~map[off]) - 1);
194         return (size);
195 }
196
197 /*
198  * Find the highest non-zero bit in the given bitmap, starting at low and
199  * not exceeding size - 1.
200  */
201 static int
202 fd_last_used(struct filedesc *fdp, int low, int size)
203 {
204         NDSLOTTYPE *map = fdp->fd_map;
205         NDSLOTTYPE mask;
206         int off, minoff;
207
208         if (low >= size)
209                 return (-1);
210
211         off = NDSLOT(size);
212         if (size % NDENTRIES) {
213                 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
214                 if ((mask &= map[off]) != 0)
215                         return (off * NDENTRIES + flsl(mask) - 1);
216                 --off;
217         }
218         for (minoff = NDSLOT(low); off >= minoff; --off)
219                 if (map[off] != 0)
220                         return (off * NDENTRIES + flsl(map[off]) - 1);
221         return (low - 1);
222 }
223
224 static int
225 fdisused(struct filedesc *fdp, int fd)
226 {
227         KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
228             ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
229         return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
230 }
231
232 /*
233  * Mark a file descriptor as used.
234  */
235 static void
236 fdused(struct filedesc *fdp, int fd)
237 {
238
239         FILEDESC_XLOCK_ASSERT(fdp);
240         KASSERT(!fdisused(fdp, fd),
241             ("fd already used"));
242
243         fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
244         if (fd > fdp->fd_lastfile)
245                 fdp->fd_lastfile = fd;
246         if (fd == fdp->fd_freefile)
247                 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
248 }
249
250 /*
251  * Mark a file descriptor as unused.
252  */
253 static void
254 fdunused(struct filedesc *fdp, int fd)
255 {
256
257         FILEDESC_XLOCK_ASSERT(fdp);
258         KASSERT(fdisused(fdp, fd),
259             ("fd is already unused"));
260         KASSERT(fdp->fd_ofiles[fd] == NULL,
261             ("fd is still in use"));
262
263         fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
264         if (fd < fdp->fd_freefile)
265                 fdp->fd_freefile = fd;
266         if (fd == fdp->fd_lastfile)
267                 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
268 }
269
270 /*
271  * System calls on descriptors.
272  */
273 #ifndef _SYS_SYSPROTO_H_
274 struct getdtablesize_args {
275         int     dummy;
276 };
277 #endif
278 /* ARGSUSED */
279 int
280 getdtablesize(struct thread *td, struct getdtablesize_args *uap)
281 {
282         struct proc *p = td->td_proc;
283
284         PROC_LOCK(p);
285         td->td_retval[0] =
286             min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
287         PROC_UNLOCK(p);
288         return (0);
289 }
290
291 /*
292  * Duplicate a file descriptor to a particular value.
293  *
294  * Note: keep in mind that a potential race condition exists when closing
295  * descriptors from a shared descriptor table (via rfork).
296  */
297 #ifndef _SYS_SYSPROTO_H_
298 struct dup2_args {
299         u_int   from;
300         u_int   to;
301 };
302 #endif
303 /* ARGSUSED */
304 int
305 dup2(struct thread *td, struct dup2_args *uap)
306 {
307
308         return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
309                     td->td_retval));
310 }
311
312 /*
313  * Duplicate a file descriptor.
314  */
315 #ifndef _SYS_SYSPROTO_H_
316 struct dup_args {
317         u_int   fd;
318 };
319 #endif
320 /* ARGSUSED */
321 int
322 dup(struct thread *td, struct dup_args *uap)
323 {
324
325         return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
326 }
327
328 /*
329  * The file control system call.
330  */
331 #ifndef _SYS_SYSPROTO_H_
332 struct fcntl_args {
333         int     fd;
334         int     cmd;
335         long    arg;
336 };
337 #endif
338 /* ARGSUSED */
339 int
340 fcntl(struct thread *td, struct fcntl_args *uap)
341 {
342         struct flock fl;
343         struct oflock ofl;
344         intptr_t arg;
345         int error;
346         int cmd;
347
348         error = 0;
349         cmd = uap->cmd;
350         switch (uap->cmd) {
351         case F_OGETLK:
352         case F_OSETLK:
353         case F_OSETLKW:
354                 /*
355                  * Convert old flock structure to new.
356                  */
357                 error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
358                 fl.l_start = ofl.l_start;
359                 fl.l_len = ofl.l_len;
360                 fl.l_pid = ofl.l_pid;
361                 fl.l_type = ofl.l_type;
362                 fl.l_whence = ofl.l_whence;
363                 fl.l_sysid = 0;
364
365                 switch (uap->cmd) {
366                 case F_OGETLK:
367                     cmd = F_GETLK;
368                     break;
369                 case F_OSETLK:
370                     cmd = F_SETLK;
371                     break;
372                 case F_OSETLKW:
373                     cmd = F_SETLKW;
374                     break;
375                 }
376                 arg = (intptr_t)&fl;
377                 break;
378         case F_GETLK:
379         case F_SETLK:
380         case F_SETLKW:
381         case F_SETLK_REMOTE:
382                 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
383                 arg = (intptr_t)&fl;
384                 break;
385         default:
386                 arg = uap->arg;
387                 break;
388         }
389         if (error)
390                 return (error);
391         error = kern_fcntl(td, uap->fd, cmd, arg);
392         if (error)
393                 return (error);
394         if (uap->cmd == F_OGETLK) {
395                 ofl.l_start = fl.l_start;
396                 ofl.l_len = fl.l_len;
397                 ofl.l_pid = fl.l_pid;
398                 ofl.l_type = fl.l_type;
399                 ofl.l_whence = fl.l_whence;
400                 error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
401         } else if (uap->cmd == F_GETLK) {
402                 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
403         }
404         return (error);
405 }
406
407 static inline struct file *
408 fdtofp(int fd, struct filedesc *fdp)
409 {
410         struct file *fp;
411
412         FILEDESC_LOCK_ASSERT(fdp);
413         if ((unsigned)fd >= fdp->fd_nfiles ||
414             (fp = fdp->fd_ofiles[fd]) == NULL)
415                 return (NULL);
416         return (fp);
417 }
418
419 int
420 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
421 {
422         struct filedesc *fdp;
423         struct flock *flp;
424         struct file *fp;
425         struct proc *p;
426         char *pop;
427         struct vnode *vp;
428         int error, flg, tmp;
429         int vfslocked;
430         u_int old, new;
431         uint64_t bsize;
432
433         vfslocked = 0;
434         error = 0;
435         flg = F_POSIX;
436         p = td->td_proc;
437         fdp = p->p_fd;
438
439         switch (cmd) {
440         case F_DUPFD:
441                 tmp = arg;
442                 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
443                 break;
444
445         case F_DUPFD_CLOEXEC:
446                 tmp = arg;
447                 error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp,
448                     td->td_retval);
449                 break;
450
451         case F_DUP2FD:
452                 tmp = arg;
453                 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
454                 break;
455
456         case F_GETFD:
457                 FILEDESC_SLOCK(fdp);
458                 if ((fp = fdtofp(fd, fdp)) == NULL) {
459                         FILEDESC_SUNLOCK(fdp);
460                         error = EBADF;
461                         break;
462                 }
463                 pop = &fdp->fd_ofileflags[fd];
464                 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
465                 FILEDESC_SUNLOCK(fdp);
466                 break;
467
468         case F_SETFD:
469                 FILEDESC_XLOCK(fdp);
470                 if ((fp = fdtofp(fd, fdp)) == NULL) {
471                         FILEDESC_XUNLOCK(fdp);
472                         error = EBADF;
473                         break;
474                 }
475                 pop = &fdp->fd_ofileflags[fd];
476                 *pop = (*pop &~ UF_EXCLOSE) |
477                     (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
478                 FILEDESC_XUNLOCK(fdp);
479                 break;
480
481         case F_GETFL:
482                 FILEDESC_SLOCK(fdp);
483                 if ((fp = fdtofp(fd, fdp)) == NULL) {
484                         FILEDESC_SUNLOCK(fdp);
485                         error = EBADF;
486                         break;
487                 }
488                 td->td_retval[0] = OFLAGS(fp->f_flag);
489                 FILEDESC_SUNLOCK(fdp);
490                 break;
491
492         case F_SETFL:
493                 FILEDESC_SLOCK(fdp);
494                 if ((fp = fdtofp(fd, fdp)) == NULL) {
495                         FILEDESC_SUNLOCK(fdp);
496                         error = EBADF;
497                         break;
498                 }
499                 fhold(fp);
500                 FILEDESC_SUNLOCK(fdp);
501                 do {
502                         tmp = flg = fp->f_flag;
503                         tmp &= ~FCNTLFLAGS;
504                         tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
505                 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
506                 tmp = fp->f_flag & FNONBLOCK;
507                 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
508                 if (error) {
509                         fdrop(fp, td);
510                         break;
511                 }
512                 tmp = fp->f_flag & FASYNC;
513                 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
514                 if (error == 0) {
515                         fdrop(fp, td);
516                         break;
517                 }
518                 atomic_clear_int(&fp->f_flag, FNONBLOCK);
519                 tmp = 0;
520                 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
521                 fdrop(fp, td);
522                 break;
523
524         case F_GETOWN:
525                 FILEDESC_SLOCK(fdp);
526                 if ((fp = fdtofp(fd, fdp)) == NULL) {
527                         FILEDESC_SUNLOCK(fdp);
528                         error = EBADF;
529                         break;
530                 }
531                 fhold(fp);
532                 FILEDESC_SUNLOCK(fdp);
533                 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
534                 if (error == 0)
535                         td->td_retval[0] = tmp;
536                 fdrop(fp, td);
537                 break;
538
539         case F_SETOWN:
540                 FILEDESC_SLOCK(fdp);
541                 if ((fp = fdtofp(fd, fdp)) == NULL) {
542                         FILEDESC_SUNLOCK(fdp);
543                         error = EBADF;
544                         break;
545                 }
546                 fhold(fp);
547                 FILEDESC_SUNLOCK(fdp);
548                 tmp = arg;
549                 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
550                 fdrop(fp, td);
551                 break;
552
553         case F_SETLK_REMOTE:
554                 error = priv_check(td, PRIV_NFS_LOCKD);
555                 if (error)
556                         return (error);
557                 flg = F_REMOTE;
558                 goto do_setlk;
559
560         case F_SETLKW:
561                 flg |= F_WAIT;
562                 /* FALLTHROUGH F_SETLK */
563
564         case F_SETLK:
565         do_setlk:
566                 FILEDESC_SLOCK(fdp);
567                 if ((fp = fdtofp(fd, fdp)) == NULL) {
568                         FILEDESC_SUNLOCK(fdp);
569                         error = EBADF;
570                         break;
571                 }
572                 if (fp->f_type != DTYPE_VNODE) {
573                         FILEDESC_SUNLOCK(fdp);
574                         error = EBADF;
575                         break;
576                 }
577                 flp = (struct flock *)arg;
578                 if (flp->l_whence == SEEK_CUR) {
579                         if (fp->f_offset < 0 ||
580                             (flp->l_start > 0 &&
581                              fp->f_offset > OFF_MAX - flp->l_start)) {
582                                 FILEDESC_SUNLOCK(fdp);
583                                 error = EOVERFLOW;
584                                 break;
585                         }
586                         flp->l_start += fp->f_offset;
587                 }
588
589                 /*
590                  * VOP_ADVLOCK() may block.
591                  */
592                 fhold(fp);
593                 FILEDESC_SUNLOCK(fdp);
594                 vp = fp->f_vnode;
595                 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
596                 switch (flp->l_type) {
597                 case F_RDLCK:
598                         if ((fp->f_flag & FREAD) == 0) {
599                                 error = EBADF;
600                                 break;
601                         }
602                         PROC_LOCK(p->p_leader);
603                         p->p_leader->p_flag |= P_ADVLOCK;
604                         PROC_UNLOCK(p->p_leader);
605                         error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
606                             flp, flg);
607                         break;
608                 case F_WRLCK:
609                         if ((fp->f_flag & FWRITE) == 0) {
610                                 error = EBADF;
611                                 break;
612                         }
613                         PROC_LOCK(p->p_leader);
614                         p->p_leader->p_flag |= P_ADVLOCK;
615                         PROC_UNLOCK(p->p_leader);
616                         error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
617                             flp, flg);
618                         break;
619                 case F_UNLCK:
620                         error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
621                             flp, flg);
622                         break;
623                 case F_UNLCKSYS:
624                         /*
625                          * Temporary api for testing remote lock
626                          * infrastructure.
627                          */
628                         if (flg != F_REMOTE) {
629                                 error = EINVAL;
630                                 break;
631                         }
632                         error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
633                             F_UNLCKSYS, flp, flg);
634                         break;
635                 default:
636                         error = EINVAL;
637                         break;
638                 }
639                 VFS_UNLOCK_GIANT(vfslocked);
640                 vfslocked = 0;
641                 /* Check for race with close */
642                 FILEDESC_SLOCK(fdp);
643                 if ((unsigned) fd >= fdp->fd_nfiles ||
644                     fp != fdp->fd_ofiles[fd]) {
645                         FILEDESC_SUNLOCK(fdp);
646                         flp->l_whence = SEEK_SET;
647                         flp->l_start = 0;
648                         flp->l_len = 0;
649                         flp->l_type = F_UNLCK;
650                         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
651                         (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
652                                            F_UNLCK, flp, F_POSIX);
653                         VFS_UNLOCK_GIANT(vfslocked);
654                         vfslocked = 0;
655                 } else
656                         FILEDESC_SUNLOCK(fdp);
657                 fdrop(fp, td);
658                 break;
659
660         case F_GETLK:
661                 FILEDESC_SLOCK(fdp);
662                 if ((fp = fdtofp(fd, fdp)) == NULL) {
663                         FILEDESC_SUNLOCK(fdp);
664                         error = EBADF;
665                         break;
666                 }
667                 if (fp->f_type != DTYPE_VNODE) {
668                         FILEDESC_SUNLOCK(fdp);
669                         error = EBADF;
670                         break;
671                 }
672                 flp = (struct flock *)arg;
673                 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
674                     flp->l_type != F_UNLCK) {
675                         FILEDESC_SUNLOCK(fdp);
676                         error = EINVAL;
677                         break;
678                 }
679                 if (flp->l_whence == SEEK_CUR) {
680                         if ((flp->l_start > 0 &&
681                             fp->f_offset > OFF_MAX - flp->l_start) ||
682                             (flp->l_start < 0 &&
683                              fp->f_offset < OFF_MIN - flp->l_start)) {
684                                 FILEDESC_SUNLOCK(fdp);
685                                 error = EOVERFLOW;
686                                 break;
687                         }
688                         flp->l_start += fp->f_offset;
689                 }
690                 /*
691                  * VOP_ADVLOCK() may block.
692                  */
693                 fhold(fp);
694                 FILEDESC_SUNLOCK(fdp);
695                 vp = fp->f_vnode;
696                 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
697                 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
698                     F_POSIX);
699                 VFS_UNLOCK_GIANT(vfslocked);
700                 vfslocked = 0;
701                 fdrop(fp, td);
702                 break;
703
704         case F_RDAHEAD:
705                 arg = arg ? 128 * 1024: 0;
706                 /* FALLTHROUGH */
707         case F_READAHEAD:
708                 FILEDESC_SLOCK(fdp);
709                 if ((fp = fdtofp(fd, fdp)) == NULL) {
710                         FILEDESC_SUNLOCK(fdp);
711                         error = EBADF;
712                         break;
713                 }
714                 if (fp->f_type != DTYPE_VNODE) {
715                         FILEDESC_SUNLOCK(fdp);
716                         error = EBADF;
717                         break;
718                 }
719                 fhold(fp);
720                 FILEDESC_SUNLOCK(fdp);
721                 if (arg != 0) {
722                         vp = fp->f_vnode;
723                         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
724                         error = vn_lock(vp, LK_SHARED);
725                         if (error != 0)
726                                 goto readahead_vnlock_fail;
727                         bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
728                         VOP_UNLOCK(vp, 0);
729                         fp->f_seqcount = (arg + bsize - 1) / bsize;
730                         do {
731                                 new = old = fp->f_flag;
732                                 new |= FRDAHEAD;
733                         } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
734 readahead_vnlock_fail:
735                         VFS_UNLOCK_GIANT(vfslocked);
736                         vfslocked = 0;
737                 } else {
738                         do {
739                                 new = old = fp->f_flag;
740                                 new &= ~FRDAHEAD;
741                         } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
742                 }
743                 fdrop(fp, td);
744                 break;
745
746         default:
747                 error = EINVAL;
748                 break;
749         }
750         VFS_UNLOCK_GIANT(vfslocked);
751         return (error);
752 }
753
754 /*
755  * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
756  */
757 static int
758 do_dup(struct thread *td, int flags, int old, int new,
759     register_t *retval)
760 {
761         struct filedesc *fdp;
762         struct proc *p;
763         struct file *fp;
764         struct file *delfp;
765         int error, holdleaders, maxfd;
766
767         p = td->td_proc;
768         fdp = p->p_fd;
769
770         /*
771          * Verify we have a valid descriptor to dup from and possibly to
772          * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
773          * return EINVAL when the new descriptor is out of bounds.
774          */
775         if (old < 0)
776                 return (EBADF);
777         if (new < 0)
778                 return (flags & DUP_FCNTL ? EINVAL : EBADF);
779         PROC_LOCK(p);
780         maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
781         PROC_UNLOCK(p);
782         if (new >= maxfd)
783                 return (flags & DUP_FCNTL ? EINVAL : EBADF);
784
785         FILEDESC_XLOCK(fdp);
786         if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
787                 FILEDESC_XUNLOCK(fdp);
788                 return (EBADF);
789         }
790         if (flags & DUP_FIXED && old == new) {
791                 *retval = new;
792                 FILEDESC_XUNLOCK(fdp);
793                 return (0);
794         }
795         fp = fdp->fd_ofiles[old];
796         fhold(fp);
797
798         /*
799          * If the caller specified a file descriptor, make sure the file
800          * table is large enough to hold it, and grab it.  Otherwise, just
801          * allocate a new descriptor the usual way.  Since the filedesc
802          * lock may be temporarily dropped in the process, we have to look
803          * out for a race.
804          */
805         if (flags & DUP_FIXED) {
806                 if (new >= fdp->fd_nfiles)
807                         fdgrowtable(fdp, new + 1);
808                 if (fdp->fd_ofiles[new] == NULL)
809                         fdused(fdp, new);
810         } else {
811                 if ((error = fdalloc(td, new, &new)) != 0) {
812                         FILEDESC_XUNLOCK(fdp);
813                         fdrop(fp, td);
814                         return (error);
815                 }
816         }
817
818         /*
819          * If the old file changed out from under us then treat it as a
820          * bad file descriptor.  Userland should do its own locking to
821          * avoid this case.
822          */
823         if (fdp->fd_ofiles[old] != fp) {
824                 /* we've allocated a descriptor which we won't use */
825                 if (fdp->fd_ofiles[new] == NULL)
826                         fdunused(fdp, new);
827                 FILEDESC_XUNLOCK(fdp);
828                 fdrop(fp, td);
829                 return (EBADF);
830         }
831         KASSERT(old != new,
832             ("new fd is same as old"));
833
834         /*
835          * Save info on the descriptor being overwritten.  We cannot close
836          * it without introducing an ownership race for the slot, since we
837          * need to drop the filedesc lock to call closef().
838          *
839          * XXX this duplicates parts of close().
840          */
841         delfp = fdp->fd_ofiles[new];
842         holdleaders = 0;
843         if (delfp != NULL) {
844                 if (td->td_proc->p_fdtol != NULL) {
845                         /*
846                          * Ask fdfree() to sleep to ensure that all relevant
847                          * process leaders can be traversed in closef().
848                          */
849                         fdp->fd_holdleaderscount++;
850                         holdleaders = 1;
851                 }
852         }
853
854         /*
855          * Duplicate the source descriptor
856          */
857         fdp->fd_ofiles[new] = fp;
858         if ((flags & DUP_CLOEXEC) != 0)
859                 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] | UF_EXCLOSE;
860         else
861                 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] & ~UF_EXCLOSE;
862         if (new > fdp->fd_lastfile)
863                 fdp->fd_lastfile = new;
864         *retval = new;
865
866         /*
867          * If we dup'd over a valid file, we now own the reference to it
868          * and must dispose of it using closef() semantics (as if a
869          * close() were performed on it).
870          *
871          * XXX this duplicates parts of close().
872          */
873         if (delfp != NULL) {
874                 knote_fdclose(td, new);
875                 if (delfp->f_type == DTYPE_MQUEUE)
876                         mq_fdclose(td, new, delfp);
877                 FILEDESC_XUNLOCK(fdp);
878                 (void) closef(delfp, td);
879                 if (holdleaders) {
880                         FILEDESC_XLOCK(fdp);
881                         fdp->fd_holdleaderscount--;
882                         if (fdp->fd_holdleaderscount == 0 &&
883                             fdp->fd_holdleaderswakeup != 0) {
884                                 fdp->fd_holdleaderswakeup = 0;
885                                 wakeup(&fdp->fd_holdleaderscount);
886                         }
887                         FILEDESC_XUNLOCK(fdp);
888                 }
889         } else {
890                 FILEDESC_XUNLOCK(fdp);
891         }
892         return (0);
893 }
894
895 /*
896  * If sigio is on the list associated with a process or process group,
897  * disable signalling from the device, remove sigio from the list and
898  * free sigio.
899  */
900 void
901 funsetown(struct sigio **sigiop)
902 {
903         struct sigio *sigio;
904
905         SIGIO_LOCK();
906         sigio = *sigiop;
907         if (sigio == NULL) {
908                 SIGIO_UNLOCK();
909                 return;
910         }
911         *(sigio->sio_myref) = NULL;
912         if ((sigio)->sio_pgid < 0) {
913                 struct pgrp *pg = (sigio)->sio_pgrp;
914                 PGRP_LOCK(pg);
915                 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
916                              sigio, sio_pgsigio);
917                 PGRP_UNLOCK(pg);
918         } else {
919                 struct proc *p = (sigio)->sio_proc;
920                 PROC_LOCK(p);
921                 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
922                              sigio, sio_pgsigio);
923                 PROC_UNLOCK(p);
924         }
925         SIGIO_UNLOCK();
926         crfree(sigio->sio_ucred);
927         free(sigio, M_SIGIO);
928 }
929
930 /*
931  * Free a list of sigio structures.
932  * We only need to lock the SIGIO_LOCK because we have made ourselves
933  * inaccessible to callers of fsetown and therefore do not need to lock
934  * the proc or pgrp struct for the list manipulation.
935  */
936 void
937 funsetownlst(struct sigiolst *sigiolst)
938 {
939         struct proc *p;
940         struct pgrp *pg;
941         struct sigio *sigio;
942
943         sigio = SLIST_FIRST(sigiolst);
944         if (sigio == NULL)
945                 return;
946         p = NULL;
947         pg = NULL;
948
949         /*
950          * Every entry of the list should belong
951          * to a single proc or pgrp.
952          */
953         if (sigio->sio_pgid < 0) {
954                 pg = sigio->sio_pgrp;
955                 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
956         } else /* if (sigio->sio_pgid > 0) */ {
957                 p = sigio->sio_proc;
958                 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
959         }
960
961         SIGIO_LOCK();
962         while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
963                 *(sigio->sio_myref) = NULL;
964                 if (pg != NULL) {
965                         KASSERT(sigio->sio_pgid < 0,
966                             ("Proc sigio in pgrp sigio list"));
967                         KASSERT(sigio->sio_pgrp == pg,
968                             ("Bogus pgrp in sigio list"));
969                         PGRP_LOCK(pg);
970                         SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
971                             sio_pgsigio);
972                         PGRP_UNLOCK(pg);
973                 } else /* if (p != NULL) */ {
974                         KASSERT(sigio->sio_pgid > 0,
975                             ("Pgrp sigio in proc sigio list"));
976                         KASSERT(sigio->sio_proc == p,
977                             ("Bogus proc in sigio list"));
978                         PROC_LOCK(p);
979                         SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
980                             sio_pgsigio);
981                         PROC_UNLOCK(p);
982                 }
983                 SIGIO_UNLOCK();
984                 crfree(sigio->sio_ucred);
985                 free(sigio, M_SIGIO);
986                 SIGIO_LOCK();
987         }
988         SIGIO_UNLOCK();
989 }
990
991 /*
992  * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
993  *
994  * After permission checking, add a sigio structure to the sigio list for
995  * the process or process group.
996  */
997 int
998 fsetown(pid_t pgid, struct sigio **sigiop)
999 {
1000         struct proc *proc;
1001         struct pgrp *pgrp;
1002         struct sigio *sigio;
1003         int ret;
1004
1005         if (pgid == 0) {
1006                 funsetown(sigiop);
1007                 return (0);
1008         }
1009
1010         ret = 0;
1011
1012         /* Allocate and fill in the new sigio out of locks. */
1013         sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1014         sigio->sio_pgid = pgid;
1015         sigio->sio_ucred = crhold(curthread->td_ucred);
1016         sigio->sio_myref = sigiop;
1017
1018         sx_slock(&proctree_lock);
1019         if (pgid > 0) {
1020                 proc = pfind(pgid);
1021                 if (proc == NULL) {
1022                         ret = ESRCH;
1023                         goto fail;
1024                 }
1025
1026                 /*
1027                  * Policy - Don't allow a process to FSETOWN a process
1028                  * in another session.
1029                  *
1030                  * Remove this test to allow maximum flexibility or
1031                  * restrict FSETOWN to the current process or process
1032                  * group for maximum safety.
1033                  */
1034                 PROC_UNLOCK(proc);
1035                 if (proc->p_session != curthread->td_proc->p_session) {
1036                         ret = EPERM;
1037                         goto fail;
1038                 }
1039
1040                 pgrp = NULL;
1041         } else /* if (pgid < 0) */ {
1042                 pgrp = pgfind(-pgid);
1043                 if (pgrp == NULL) {
1044                         ret = ESRCH;
1045                         goto fail;
1046                 }
1047                 PGRP_UNLOCK(pgrp);
1048
1049                 /*
1050                  * Policy - Don't allow a process to FSETOWN a process
1051                  * in another session.
1052                  *
1053                  * Remove this test to allow maximum flexibility or
1054                  * restrict FSETOWN to the current process or process
1055                  * group for maximum safety.
1056                  */
1057                 if (pgrp->pg_session != curthread->td_proc->p_session) {
1058                         ret = EPERM;
1059                         goto fail;
1060                 }
1061
1062                 proc = NULL;
1063         }
1064         funsetown(sigiop);
1065         if (pgid > 0) {
1066                 PROC_LOCK(proc);
1067                 /*
1068                  * Since funsetownlst() is called without the proctree
1069                  * locked, we need to check for P_WEXIT.
1070                  * XXX: is ESRCH correct?
1071                  */
1072                 if ((proc->p_flag & P_WEXIT) != 0) {
1073                         PROC_UNLOCK(proc);
1074                         ret = ESRCH;
1075                         goto fail;
1076                 }
1077                 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1078                 sigio->sio_proc = proc;
1079                 PROC_UNLOCK(proc);
1080         } else {
1081                 PGRP_LOCK(pgrp);
1082                 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1083                 sigio->sio_pgrp = pgrp;
1084                 PGRP_UNLOCK(pgrp);
1085         }
1086         sx_sunlock(&proctree_lock);
1087         SIGIO_LOCK();
1088         *sigiop = sigio;
1089         SIGIO_UNLOCK();
1090         return (0);
1091
1092 fail:
1093         sx_sunlock(&proctree_lock);
1094         crfree(sigio->sio_ucred);
1095         free(sigio, M_SIGIO);
1096         return (ret);
1097 }
1098
1099 /*
1100  * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1101  */
1102 pid_t
1103 fgetown(sigiop)
1104         struct sigio **sigiop;
1105 {
1106         pid_t pgid;
1107
1108         SIGIO_LOCK();
1109         pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1110         SIGIO_UNLOCK();
1111         return (pgid);
1112 }
1113
1114 /*
1115  * Close a file descriptor.
1116  */
1117 #ifndef _SYS_SYSPROTO_H_
1118 struct close_args {
1119         int     fd;
1120 };
1121 #endif
1122 /* ARGSUSED */
1123 int
1124 close(td, uap)
1125         struct thread *td;
1126         struct close_args *uap;
1127 {
1128
1129         return (kern_close(td, uap->fd));
1130 }
1131
1132 int
1133 kern_close(td, fd)
1134         struct thread *td;
1135         int fd;
1136 {
1137         struct filedesc *fdp;
1138         struct file *fp;
1139         int error;
1140         int holdleaders;
1141
1142         error = 0;
1143         holdleaders = 0;
1144         fdp = td->td_proc->p_fd;
1145
1146         AUDIT_SYSCLOSE(td, fd);
1147
1148         FILEDESC_XLOCK(fdp);
1149         if ((unsigned)fd >= fdp->fd_nfiles ||
1150             (fp = fdp->fd_ofiles[fd]) == NULL) {
1151                 FILEDESC_XUNLOCK(fdp);
1152                 return (EBADF);
1153         }
1154         fdp->fd_ofiles[fd] = NULL;
1155         fdp->fd_ofileflags[fd] = 0;
1156         fdunused(fdp, fd);
1157         if (td->td_proc->p_fdtol != NULL) {
1158                 /*
1159                  * Ask fdfree() to sleep to ensure that all relevant
1160                  * process leaders can be traversed in closef().
1161                  */
1162                 fdp->fd_holdleaderscount++;
1163                 holdleaders = 1;
1164         }
1165
1166         /*
1167          * We now hold the fp reference that used to be owned by the
1168          * descriptor array.  We have to unlock the FILEDESC *AFTER*
1169          * knote_fdclose to prevent a race of the fd getting opened, a knote
1170          * added, and deleteing a knote for the new fd.
1171          */
1172         knote_fdclose(td, fd);
1173         if (fp->f_type == DTYPE_MQUEUE)
1174                 mq_fdclose(td, fd, fp);
1175         FILEDESC_XUNLOCK(fdp);
1176
1177         error = closef(fp, td);
1178         if (holdleaders) {
1179                 FILEDESC_XLOCK(fdp);
1180                 fdp->fd_holdleaderscount--;
1181                 if (fdp->fd_holdleaderscount == 0 &&
1182                     fdp->fd_holdleaderswakeup != 0) {
1183                         fdp->fd_holdleaderswakeup = 0;
1184                         wakeup(&fdp->fd_holdleaderscount);
1185                 }
1186                 FILEDESC_XUNLOCK(fdp);
1187         }
1188         return (error);
1189 }
1190
1191 /*
1192  * Close open file descriptors.
1193  */
1194 #ifndef _SYS_SYSPROTO_H_
1195 struct closefrom_args {
1196         int     lowfd;
1197 };
1198 #endif
1199 /* ARGSUSED */
1200 int
1201 closefrom(struct thread *td, struct closefrom_args *uap)
1202 {
1203         struct filedesc *fdp;
1204         int fd;
1205
1206         fdp = td->td_proc->p_fd;
1207         AUDIT_ARG_FD(uap->lowfd);
1208
1209         /*
1210          * Treat negative starting file descriptor values identical to
1211          * closefrom(0) which closes all files.
1212          */
1213         if (uap->lowfd < 0)
1214                 uap->lowfd = 0;
1215         FILEDESC_SLOCK(fdp);
1216         for (fd = uap->lowfd; fd < fdp->fd_nfiles; fd++) {
1217                 if (fdp->fd_ofiles[fd] != NULL) {
1218                         FILEDESC_SUNLOCK(fdp);
1219                         (void)kern_close(td, fd);
1220                         FILEDESC_SLOCK(fdp);
1221                 }
1222         }
1223         FILEDESC_SUNLOCK(fdp);
1224         return (0);
1225 }
1226
1227 #if defined(COMPAT_43)
1228 /*
1229  * Return status information about a file descriptor.
1230  */
1231 #ifndef _SYS_SYSPROTO_H_
1232 struct ofstat_args {
1233         int     fd;
1234         struct  ostat *sb;
1235 };
1236 #endif
1237 /* ARGSUSED */
1238 int
1239 ofstat(struct thread *td, struct ofstat_args *uap)
1240 {
1241         struct ostat oub;
1242         struct stat ub;
1243         int error;
1244
1245         error = kern_fstat(td, uap->fd, &ub);
1246         if (error == 0) {
1247                 cvtstat(&ub, &oub);
1248                 error = copyout(&oub, uap->sb, sizeof(oub));
1249         }
1250         return (error);
1251 }
1252 #endif /* COMPAT_43 */
1253
1254 /*
1255  * Return status information about a file descriptor.
1256  */
1257 #ifndef _SYS_SYSPROTO_H_
1258 struct fstat_args {
1259         int     fd;
1260         struct  stat *sb;
1261 };
1262 #endif
1263 /* ARGSUSED */
1264 int
1265 fstat(struct thread *td, struct fstat_args *uap)
1266 {
1267         struct stat ub;
1268         int error;
1269
1270         error = kern_fstat(td, uap->fd, &ub);
1271         if (error == 0)
1272                 error = copyout(&ub, uap->sb, sizeof(ub));
1273         return (error);
1274 }
1275
1276 int
1277 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1278 {
1279         struct file *fp;
1280         int error;
1281
1282         AUDIT_ARG_FD(fd);
1283
1284         if ((error = fget(td, fd, &fp)) != 0)
1285                 return (error);
1286
1287         AUDIT_ARG_FILE(td->td_proc, fp);
1288
1289         error = fo_stat(fp, sbp, td->td_ucred, td);
1290         fdrop(fp, td);
1291 #ifdef KTRACE
1292         if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1293                 ktrstat(sbp);
1294 #endif
1295         return (error);
1296 }
1297
1298 /*
1299  * Return status information about a file descriptor.
1300  */
1301 #ifndef _SYS_SYSPROTO_H_
1302 struct nfstat_args {
1303         int     fd;
1304         struct  nstat *sb;
1305 };
1306 #endif
1307 /* ARGSUSED */
1308 int
1309 nfstat(struct thread *td, struct nfstat_args *uap)
1310 {
1311         struct nstat nub;
1312         struct stat ub;
1313         int error;
1314
1315         error = kern_fstat(td, uap->fd, &ub);
1316         if (error == 0) {
1317                 cvtnstat(&ub, &nub);
1318                 error = copyout(&nub, uap->sb, sizeof(nub));
1319         }
1320         return (error);
1321 }
1322
1323 /*
1324  * Return pathconf information about a file descriptor.
1325  */
1326 #ifndef _SYS_SYSPROTO_H_
1327 struct fpathconf_args {
1328         int     fd;
1329         int     name;
1330 };
1331 #endif
1332 /* ARGSUSED */
1333 int
1334 fpathconf(struct thread *td, struct fpathconf_args *uap)
1335 {
1336         struct file *fp;
1337         struct vnode *vp;
1338         int error;
1339
1340         if ((error = fget(td, uap->fd, &fp)) != 0)
1341                 return (error);
1342
1343         /* If asynchronous I/O is available, it works for all descriptors. */
1344         if (uap->name == _PC_ASYNC_IO) {
1345                 td->td_retval[0] = async_io_version;
1346                 goto out;
1347         }
1348         vp = fp->f_vnode;
1349         if (vp != NULL) {
1350                 int vfslocked;
1351                 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1352                 vn_lock(vp, LK_SHARED | LK_RETRY);
1353                 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1354                 VOP_UNLOCK(vp, 0);
1355                 VFS_UNLOCK_GIANT(vfslocked);
1356         } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1357                 if (uap->name != _PC_PIPE_BUF) {
1358                         error = EINVAL;
1359                 } else {
1360                         td->td_retval[0] = PIPE_BUF;
1361                 error = 0;
1362                 }
1363         } else {
1364                 error = EOPNOTSUPP;
1365         }
1366 out:
1367         fdrop(fp, td);
1368         return (error);
1369 }
1370
1371 /*
1372  * Grow the file table to accomodate (at least) nfd descriptors.  This may
1373  * block and drop the filedesc lock, but it will reacquire it before
1374  * returning.
1375  */
1376 static void
1377 fdgrowtable(struct filedesc *fdp, int nfd)
1378 {
1379         struct filedesc0 *fdp0;
1380         struct freetable *fo;
1381         struct file **ntable;
1382         struct file **otable;
1383         char *nfileflags;
1384         int nnfiles, onfiles;
1385         NDSLOTTYPE *nmap;
1386
1387         FILEDESC_XLOCK_ASSERT(fdp);
1388
1389         KASSERT(fdp->fd_nfiles > 0,
1390             ("zero-length file table"));
1391
1392         /* compute the size of the new table */
1393         onfiles = fdp->fd_nfiles;
1394         nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1395         if (nnfiles <= onfiles)
1396                 /* the table is already large enough */
1397                 return;
1398
1399         /* allocate a new table and (if required) new bitmaps */
1400         FILEDESC_XUNLOCK(fdp);
1401         ntable = malloc((nnfiles * OFILESIZE) + sizeof(struct freetable),
1402             M_FILEDESC, M_ZERO | M_WAITOK);
1403         nfileflags = (char *)&ntable[nnfiles];
1404         if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1405                 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE,
1406                     M_FILEDESC, M_ZERO | M_WAITOK);
1407         else
1408                 nmap = NULL;
1409         FILEDESC_XLOCK(fdp);
1410
1411         /*
1412          * We now have new tables ready to go.  Since we dropped the
1413          * filedesc lock to call malloc(), watch out for a race.
1414          */
1415         onfiles = fdp->fd_nfiles;
1416         if (onfiles >= nnfiles) {
1417                 /* we lost the race, but that's OK */
1418                 free(ntable, M_FILEDESC);
1419                 if (nmap != NULL)
1420                         free(nmap, M_FILEDESC);
1421                 return;
1422         }
1423         bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1424         bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1425         otable = fdp->fd_ofiles;
1426         fdp->fd_ofileflags = nfileflags;
1427         fdp->fd_ofiles = ntable;
1428         /*
1429          * We must preserve ofiles until the process exits because we can't
1430          * be certain that no threads have references to the old table via
1431          * _fget().
1432          */
1433         if (onfiles > NDFILE) {
1434                 fo = (struct freetable *)&otable[onfiles];
1435                 fdp0 = (struct filedesc0 *)fdp;
1436                 fo->ft_table = otable;
1437                 SLIST_INSERT_HEAD(&fdp0->fd_free, fo, ft_next);
1438         }
1439         if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1440                 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1441                 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1442                         free(fdp->fd_map, M_FILEDESC);
1443                 fdp->fd_map = nmap;
1444         }
1445         fdp->fd_nfiles = nnfiles;
1446 }
1447
1448 /*
1449  * Allocate a file descriptor for the process.
1450  */
1451 int
1452 fdalloc(struct thread *td, int minfd, int *result)
1453 {
1454         struct proc *p = td->td_proc;
1455         struct filedesc *fdp = p->p_fd;
1456         int fd = -1, maxfd;
1457
1458         FILEDESC_XLOCK_ASSERT(fdp);
1459
1460         if (fdp->fd_freefile > minfd)
1461                 minfd = fdp->fd_freefile;          
1462
1463         PROC_LOCK(p);
1464         maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1465         PROC_UNLOCK(p);
1466
1467         /*
1468          * Search the bitmap for a free descriptor.  If none is found, try
1469          * to grow the file table.  Keep at it until we either get a file
1470          * descriptor or run into process or system limits; fdgrowtable()
1471          * may drop the filedesc lock, so we're in a race.
1472          */
1473         for (;;) {
1474                 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1475                 if (fd >= maxfd)
1476                         return (EMFILE);
1477                 if (fd < fdp->fd_nfiles)
1478                         break;
1479                 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1480         }
1481
1482         /*
1483          * Perform some sanity checks, then mark the file descriptor as
1484          * used and return it to the caller.
1485          */
1486         KASSERT(!fdisused(fdp, fd),
1487             ("fd_first_free() returned non-free descriptor"));
1488         KASSERT(fdp->fd_ofiles[fd] == NULL,
1489             ("free descriptor isn't"));
1490         fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1491         fdused(fdp, fd);
1492         *result = fd;
1493         return (0);
1494 }
1495
1496 /*
1497  * Check to see whether n user file descriptors are available to the process
1498  * p.
1499  */
1500 int
1501 fdavail(struct thread *td, int n)
1502 {
1503         struct proc *p = td->td_proc;
1504         struct filedesc *fdp = td->td_proc->p_fd;
1505         struct file **fpp;
1506         int i, lim, last;
1507
1508         FILEDESC_LOCK_ASSERT(fdp);
1509
1510         PROC_LOCK(p);
1511         lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1512         PROC_UNLOCK(p);
1513         if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1514                 return (1);
1515         last = min(fdp->fd_nfiles, lim);
1516         fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1517         for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1518                 if (*fpp == NULL && --n <= 0)
1519                         return (1);
1520         }
1521         return (0);
1522 }
1523
1524 /*
1525  * Create a new open file structure and allocate a file decriptor for the
1526  * process that refers to it.  We add one reference to the file for the
1527  * descriptor table and one reference for resultfp. This is to prevent us
1528  * being preempted and the entry in the descriptor table closed after we
1529  * release the FILEDESC lock.
1530  */
1531 int
1532 fallocf(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1533 {
1534         struct proc *p = td->td_proc;
1535         struct file *fp;
1536         int error, i;
1537         int maxuserfiles = maxfiles - (maxfiles / 20);
1538         static struct timeval lastfail;
1539         static int curfail;
1540
1541         fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1542         if ((openfiles >= maxuserfiles &&
1543             priv_check(td, PRIV_MAXFILES) != 0) ||
1544             openfiles >= maxfiles) {
1545                 if (ppsratecheck(&lastfail, &curfail, 1)) {
1546                         printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1547                                 td->td_ucred->cr_ruid);
1548                 }
1549                 uma_zfree(file_zone, fp);
1550                 return (ENFILE);
1551         }
1552         atomic_add_int(&openfiles, 1);
1553
1554         /*
1555          * If the process has file descriptor zero open, add the new file
1556          * descriptor to the list of open files at that point, otherwise
1557          * put it at the front of the list of open files.
1558          */
1559         refcount_init(&fp->f_count, 1);
1560         if (resultfp)
1561                 fhold(fp);
1562         fp->f_cred = crhold(td->td_ucred);
1563         fp->f_ops = &badfileops;
1564         fp->f_data = NULL;
1565         fp->f_vnode = NULL;
1566         FILEDESC_XLOCK(p->p_fd);
1567         if ((error = fdalloc(td, 0, &i))) {
1568                 FILEDESC_XUNLOCK(p->p_fd);
1569                 fdrop(fp, td);
1570                 if (resultfp)
1571                         fdrop(fp, td);
1572                 return (error);
1573         }
1574         p->p_fd->fd_ofiles[i] = fp;
1575         if ((flags & O_CLOEXEC) != 0)
1576                 p->p_fd->fd_ofileflags[i] |= UF_EXCLOSE;
1577         FILEDESC_XUNLOCK(p->p_fd);
1578         if (resultfp)
1579                 *resultfp = fp;
1580         if (resultfd)
1581                 *resultfd = i;
1582         return (0);
1583 }
1584
1585 int
1586 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1587 {
1588
1589         return (fallocf(td, resultfp, resultfd, 0));
1590 }
1591
1592 /*
1593  * Build a new filedesc structure from another.
1594  * Copy the current, root, and jail root vnode references.
1595  */
1596 struct filedesc *
1597 fdinit(struct filedesc *fdp)
1598 {
1599         struct filedesc0 *newfdp;
1600
1601         newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1602         FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1603         if (fdp != NULL) {
1604                 FILEDESC_XLOCK(fdp);
1605                 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1606                 if (newfdp->fd_fd.fd_cdir)
1607                         VREF(newfdp->fd_fd.fd_cdir);
1608                 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1609                 if (newfdp->fd_fd.fd_rdir)
1610                         VREF(newfdp->fd_fd.fd_rdir);
1611                 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1612                 if (newfdp->fd_fd.fd_jdir)
1613                         VREF(newfdp->fd_fd.fd_jdir);
1614                 FILEDESC_XUNLOCK(fdp);
1615         }
1616
1617         /* Create the file descriptor table. */
1618         newfdp->fd_fd.fd_refcnt = 1;
1619         newfdp->fd_fd.fd_holdcnt = 1;
1620         newfdp->fd_fd.fd_cmask = CMASK;
1621         newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1622         newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1623         newfdp->fd_fd.fd_nfiles = NDFILE;
1624         newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1625         newfdp->fd_fd.fd_lastfile = -1;
1626         return (&newfdp->fd_fd);
1627 }
1628
1629 static struct filedesc *
1630 fdhold(struct proc *p)
1631 {
1632         struct filedesc *fdp;
1633
1634         mtx_lock(&fdesc_mtx);
1635         fdp = p->p_fd;
1636         if (fdp != NULL)
1637                 fdp->fd_holdcnt++;
1638         mtx_unlock(&fdesc_mtx);
1639         return (fdp);
1640 }
1641
1642 static void
1643 fddrop(struct filedesc *fdp)
1644 {
1645         struct filedesc0 *fdp0;
1646         struct freetable *ft;
1647         int i;
1648
1649         mtx_lock(&fdesc_mtx);
1650         i = --fdp->fd_holdcnt;
1651         mtx_unlock(&fdesc_mtx);
1652         if (i > 0)
1653                 return;
1654
1655         FILEDESC_LOCK_DESTROY(fdp);
1656         fdp0 = (struct filedesc0 *)fdp;
1657         while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1658                 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1659                 free(ft->ft_table, M_FILEDESC);
1660         }
1661         free(fdp, M_FILEDESC);
1662 }
1663
1664 /*
1665  * Share a filedesc structure.
1666  */
1667 struct filedesc *
1668 fdshare(struct filedesc *fdp)
1669 {
1670
1671         FILEDESC_XLOCK(fdp);
1672         fdp->fd_refcnt++;
1673         FILEDESC_XUNLOCK(fdp);
1674         return (fdp);
1675 }
1676
1677 /*
1678  * Unshare a filedesc structure, if necessary by making a copy
1679  */
1680 void
1681 fdunshare(struct proc *p, struct thread *td)
1682 {
1683
1684         FILEDESC_XLOCK(p->p_fd);
1685         if (p->p_fd->fd_refcnt > 1) {
1686                 struct filedesc *tmp;
1687
1688                 FILEDESC_XUNLOCK(p->p_fd);
1689                 tmp = fdcopy(p->p_fd);
1690                 fdfree(td);
1691                 p->p_fd = tmp;
1692         } else
1693                 FILEDESC_XUNLOCK(p->p_fd);
1694 }
1695
1696 /*
1697  * Copy a filedesc structure.  A NULL pointer in returns a NULL reference,
1698  * this is to ease callers, not catch errors.
1699  */
1700 struct filedesc *
1701 fdcopy(struct filedesc *fdp)
1702 {
1703         struct filedesc *newfdp;
1704         int i;
1705
1706         /* Certain daemons might not have file descriptors. */
1707         if (fdp == NULL)
1708                 return (NULL);
1709
1710         newfdp = fdinit(fdp);
1711         FILEDESC_SLOCK(fdp);
1712         while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1713                 FILEDESC_SUNLOCK(fdp);
1714                 FILEDESC_XLOCK(newfdp);
1715                 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1716                 FILEDESC_XUNLOCK(newfdp);
1717                 FILEDESC_SLOCK(fdp);
1718         }
1719         /* copy everything except kqueue descriptors */
1720         newfdp->fd_freefile = -1;
1721         for (i = 0; i <= fdp->fd_lastfile; ++i) {
1722                 if (fdisused(fdp, i) &&
1723                     fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE &&
1724                     fdp->fd_ofiles[i]->f_ops != &badfileops) {
1725                         newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1726                         newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1727                         fhold(newfdp->fd_ofiles[i]);
1728                         newfdp->fd_lastfile = i;
1729                 } else {
1730                         if (newfdp->fd_freefile == -1)
1731                                 newfdp->fd_freefile = i;
1732                 }
1733         }
1734         newfdp->fd_cmask = fdp->fd_cmask;
1735         FILEDESC_SUNLOCK(fdp);
1736         FILEDESC_XLOCK(newfdp);
1737         for (i = 0; i <= newfdp->fd_lastfile; ++i)
1738                 if (newfdp->fd_ofiles[i] != NULL)
1739                         fdused(newfdp, i);
1740         if (newfdp->fd_freefile == -1)
1741                 newfdp->fd_freefile = i;
1742         FILEDESC_XUNLOCK(newfdp);
1743         return (newfdp);
1744 }
1745
1746 /*
1747  * Release a filedesc structure.
1748  */
1749 void
1750 fdfree(struct thread *td)
1751 {
1752         struct filedesc *fdp;
1753         struct file **fpp;
1754         int i, locked;
1755         struct filedesc_to_leader *fdtol;
1756         struct file *fp;
1757         struct vnode *cdir, *jdir, *rdir, *vp;
1758         struct flock lf;
1759
1760         /* Certain daemons might not have file descriptors. */
1761         fdp = td->td_proc->p_fd;
1762         if (fdp == NULL)
1763                 return;
1764
1765         /* Check for special need to clear POSIX style locks */
1766         fdtol = td->td_proc->p_fdtol;
1767         if (fdtol != NULL) {
1768                 FILEDESC_XLOCK(fdp);
1769                 KASSERT(fdtol->fdl_refcount > 0,
1770                         ("filedesc_to_refcount botch: fdl_refcount=%d",
1771                          fdtol->fdl_refcount));
1772                 if (fdtol->fdl_refcount == 1 &&
1773                     (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1774                         for (i = 0, fpp = fdp->fd_ofiles;
1775                              i <= fdp->fd_lastfile;
1776                              i++, fpp++) {
1777                                 if (*fpp == NULL ||
1778                                     (*fpp)->f_type != DTYPE_VNODE)
1779                                         continue;
1780                                 fp = *fpp;
1781                                 fhold(fp);
1782                                 FILEDESC_XUNLOCK(fdp);
1783                                 lf.l_whence = SEEK_SET;
1784                                 lf.l_start = 0;
1785                                 lf.l_len = 0;
1786                                 lf.l_type = F_UNLCK;
1787                                 vp = fp->f_vnode;
1788                                 locked = VFS_LOCK_GIANT(vp->v_mount);
1789                                 (void) VOP_ADVLOCK(vp,
1790                                                    (caddr_t)td->td_proc->
1791                                                    p_leader,
1792                                                    F_UNLCK,
1793                                                    &lf,
1794                                                    F_POSIX);
1795                                 VFS_UNLOCK_GIANT(locked);
1796                                 FILEDESC_XLOCK(fdp);
1797                                 fdrop(fp, td);
1798                                 fpp = fdp->fd_ofiles + i;
1799                         }
1800                 }
1801         retry:
1802                 if (fdtol->fdl_refcount == 1) {
1803                         if (fdp->fd_holdleaderscount > 0 &&
1804                             (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1805                                 /*
1806                                  * close() or do_dup() has cleared a reference
1807                                  * in a shared file descriptor table.
1808                                  */
1809                                 fdp->fd_holdleaderswakeup = 1;
1810                                 sx_sleep(&fdp->fd_holdleaderscount,
1811                                     FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1812                                 goto retry;
1813                         }
1814                         if (fdtol->fdl_holdcount > 0) {
1815                                 /*
1816                                  * Ensure that fdtol->fdl_leader remains
1817                                  * valid in closef().
1818                                  */
1819                                 fdtol->fdl_wakeup = 1;
1820                                 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1821                                     "fdlhold", 0);
1822                                 goto retry;
1823                         }
1824                 }
1825                 fdtol->fdl_refcount--;
1826                 if (fdtol->fdl_refcount == 0 &&
1827                     fdtol->fdl_holdcount == 0) {
1828                         fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1829                         fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1830                 } else
1831                         fdtol = NULL;
1832                 td->td_proc->p_fdtol = NULL;
1833                 FILEDESC_XUNLOCK(fdp);
1834                 if (fdtol != NULL)
1835                         free(fdtol, M_FILEDESC_TO_LEADER);
1836         }
1837         FILEDESC_XLOCK(fdp);
1838         i = --fdp->fd_refcnt;
1839         FILEDESC_XUNLOCK(fdp);
1840         if (i > 0)
1841                 return;
1842
1843         fpp = fdp->fd_ofiles;
1844         for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1845                 if (*fpp) {
1846                         FILEDESC_XLOCK(fdp);
1847                         fp = *fpp;
1848                         *fpp = NULL;
1849                         FILEDESC_XUNLOCK(fdp);
1850                         (void) closef(fp, td);
1851                 }
1852         }
1853         FILEDESC_XLOCK(fdp);
1854
1855         /* XXX This should happen earlier. */
1856         mtx_lock(&fdesc_mtx);
1857         td->td_proc->p_fd = NULL;
1858         mtx_unlock(&fdesc_mtx);
1859
1860         if (fdp->fd_nfiles > NDFILE)
1861                 free(fdp->fd_ofiles, M_FILEDESC);
1862         if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1863                 free(fdp->fd_map, M_FILEDESC);
1864
1865         fdp->fd_nfiles = 0;
1866
1867         cdir = fdp->fd_cdir;
1868         fdp->fd_cdir = NULL;
1869         rdir = fdp->fd_rdir;
1870         fdp->fd_rdir = NULL;
1871         jdir = fdp->fd_jdir;
1872         fdp->fd_jdir = NULL;
1873         FILEDESC_XUNLOCK(fdp);
1874
1875         if (cdir) {
1876                 locked = VFS_LOCK_GIANT(cdir->v_mount);
1877                 vrele(cdir);
1878                 VFS_UNLOCK_GIANT(locked);
1879         }
1880         if (rdir) {
1881                 locked = VFS_LOCK_GIANT(rdir->v_mount);
1882                 vrele(rdir);
1883                 VFS_UNLOCK_GIANT(locked);
1884         }
1885         if (jdir) {
1886                 locked = VFS_LOCK_GIANT(jdir->v_mount);
1887                 vrele(jdir);
1888                 VFS_UNLOCK_GIANT(locked);
1889         }
1890
1891         fddrop(fdp);
1892 }
1893
1894 /*
1895  * For setugid programs, we don't want to people to use that setugidness
1896  * to generate error messages which write to a file which otherwise would
1897  * otherwise be off-limits to the process.  We check for filesystems where
1898  * the vnode can change out from under us after execve (like [lin]procfs).
1899  *
1900  * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1901  * sufficient.  We also don't check for setugidness since we know we are.
1902  */
1903 static int
1904 is_unsafe(struct file *fp)
1905 {
1906         if (fp->f_type == DTYPE_VNODE) {
1907                 struct vnode *vp = fp->f_vnode;
1908
1909                 if ((vp->v_vflag & VV_PROCDEP) != 0)
1910                         return (1);
1911         }
1912         return (0);
1913 }
1914
1915 /*
1916  * Make this setguid thing safe, if at all possible.
1917  */
1918 void
1919 setugidsafety(struct thread *td)
1920 {
1921         struct filedesc *fdp;
1922         int i;
1923
1924         /* Certain daemons might not have file descriptors. */
1925         fdp = td->td_proc->p_fd;
1926         if (fdp == NULL)
1927                 return;
1928
1929         /*
1930          * Note: fdp->fd_ofiles may be reallocated out from under us while
1931          * we are blocked in a close.  Be careful!
1932          */
1933         FILEDESC_XLOCK(fdp);
1934         for (i = 0; i <= fdp->fd_lastfile; i++) {
1935                 if (i > 2)
1936                         break;
1937                 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1938                         struct file *fp;
1939
1940                         knote_fdclose(td, i);
1941                         /*
1942                          * NULL-out descriptor prior to close to avoid
1943                          * a race while close blocks.
1944                          */
1945                         fp = fdp->fd_ofiles[i];
1946                         fdp->fd_ofiles[i] = NULL;
1947                         fdp->fd_ofileflags[i] = 0;
1948                         fdunused(fdp, i);
1949                         FILEDESC_XUNLOCK(fdp);
1950                         (void) closef(fp, td);
1951                         FILEDESC_XLOCK(fdp);
1952                 }
1953         }
1954         FILEDESC_XUNLOCK(fdp);
1955 }
1956
1957 /*
1958  * If a specific file object occupies a specific file descriptor, close the
1959  * file descriptor entry and drop a reference on the file object.  This is a
1960  * convenience function to handle a subsequent error in a function that calls
1961  * falloc() that handles the race that another thread might have closed the
1962  * file descriptor out from under the thread creating the file object.
1963  */
1964 void
1965 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1966 {
1967
1968         FILEDESC_XLOCK(fdp);
1969         if (fdp->fd_ofiles[idx] == fp) {
1970                 fdp->fd_ofiles[idx] = NULL;
1971                 fdunused(fdp, idx);
1972                 FILEDESC_XUNLOCK(fdp);
1973                 fdrop(fp, td);
1974         } else
1975                 FILEDESC_XUNLOCK(fdp);
1976 }
1977
1978 /*
1979  * Close any files on exec?
1980  */
1981 void
1982 fdcloseexec(struct thread *td)
1983 {
1984         struct filedesc *fdp;
1985         int i;
1986
1987         /* Certain daemons might not have file descriptors. */
1988         fdp = td->td_proc->p_fd;
1989         if (fdp == NULL)
1990                 return;
1991
1992         FILEDESC_XLOCK(fdp);
1993
1994         /*
1995          * We cannot cache fd_ofiles or fd_ofileflags since operations
1996          * may block and rip them out from under us.
1997          */
1998         for (i = 0; i <= fdp->fd_lastfile; i++) {
1999                 if (fdp->fd_ofiles[i] != NULL &&
2000                     (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
2001                     (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
2002                         struct file *fp;
2003
2004                         knote_fdclose(td, i);
2005                         /*
2006                          * NULL-out descriptor prior to close to avoid
2007                          * a race while close blocks.
2008                          */
2009                         fp = fdp->fd_ofiles[i];
2010                         fdp->fd_ofiles[i] = NULL;
2011                         fdp->fd_ofileflags[i] = 0;
2012                         fdunused(fdp, i);
2013                         if (fp->f_type == DTYPE_MQUEUE)
2014                                 mq_fdclose(td, i, fp);
2015                         FILEDESC_XUNLOCK(fdp);
2016                         (void) closef(fp, td);
2017                         FILEDESC_XLOCK(fdp);
2018                 }
2019         }
2020         FILEDESC_XUNLOCK(fdp);
2021 }
2022
2023 /*
2024  * It is unsafe for set[ug]id processes to be started with file
2025  * descriptors 0..2 closed, as these descriptors are given implicit
2026  * significance in the Standard C library.  fdcheckstd() will create a
2027  * descriptor referencing /dev/null for each of stdin, stdout, and
2028  * stderr that is not already open.
2029  */
2030 int
2031 fdcheckstd(struct thread *td)
2032 {
2033         struct filedesc *fdp;
2034         register_t retval, save;
2035         int i, error, devnull;
2036
2037         fdp = td->td_proc->p_fd;
2038         if (fdp == NULL)
2039                 return (0);
2040         KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2041         devnull = -1;
2042         error = 0;
2043         for (i = 0; i < 3; i++) {
2044                 if (fdp->fd_ofiles[i] != NULL)
2045                         continue;
2046                 if (devnull < 0) {
2047                         save = td->td_retval[0];
2048                         error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2049                             O_RDWR, 0);
2050                         devnull = td->td_retval[0];
2051                         td->td_retval[0] = save;
2052                         if (error)
2053                                 break;
2054                         KASSERT(devnull == i, ("oof, we didn't get our fd"));
2055                 } else {
2056                         error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2057                         if (error != 0)
2058                                 break;
2059                 }
2060         }
2061         return (error);
2062 }
2063
2064 /*
2065  * Internal form of close.  Decrement reference count on file structure.
2066  * Note: td may be NULL when closing a file that was being passed in a
2067  * message.
2068  *
2069  * XXXRW: Giant is not required for the caller, but often will be held; this
2070  * makes it moderately likely the Giant will be recursed in the VFS case.
2071  */
2072 int
2073 closef(struct file *fp, struct thread *td)
2074 {
2075         struct vnode *vp;
2076         struct flock lf;
2077         struct filedesc_to_leader *fdtol;
2078         struct filedesc *fdp;
2079
2080         /*
2081          * POSIX record locking dictates that any close releases ALL
2082          * locks owned by this process.  This is handled by setting
2083          * a flag in the unlock to free ONLY locks obeying POSIX
2084          * semantics, and not to free BSD-style file locks.
2085          * If the descriptor was in a message, POSIX-style locks
2086          * aren't passed with the descriptor, and the thread pointer
2087          * will be NULL.  Callers should be careful only to pass a
2088          * NULL thread pointer when there really is no owning
2089          * context that might have locks, or the locks will be
2090          * leaked.
2091          */
2092         if (fp->f_type == DTYPE_VNODE && td != NULL) {
2093                 int vfslocked;
2094
2095                 vp = fp->f_vnode;
2096                 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2097                 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2098                         lf.l_whence = SEEK_SET;
2099                         lf.l_start = 0;
2100                         lf.l_len = 0;
2101                         lf.l_type = F_UNLCK;
2102                         (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2103                                            F_UNLCK, &lf, F_POSIX);
2104                 }
2105                 fdtol = td->td_proc->p_fdtol;
2106                 if (fdtol != NULL) {
2107                         /*
2108                          * Handle special case where file descriptor table is
2109                          * shared between multiple process leaders.
2110                          */
2111                         fdp = td->td_proc->p_fd;
2112                         FILEDESC_XLOCK(fdp);
2113                         for (fdtol = fdtol->fdl_next;
2114                              fdtol != td->td_proc->p_fdtol;
2115                              fdtol = fdtol->fdl_next) {
2116                                 if ((fdtol->fdl_leader->p_flag &
2117                                      P_ADVLOCK) == 0)
2118                                         continue;
2119                                 fdtol->fdl_holdcount++;
2120                                 FILEDESC_XUNLOCK(fdp);
2121                                 lf.l_whence = SEEK_SET;
2122                                 lf.l_start = 0;
2123                                 lf.l_len = 0;
2124                                 lf.l_type = F_UNLCK;
2125                                 vp = fp->f_vnode;
2126                                 (void) VOP_ADVLOCK(vp,
2127                                                    (caddr_t)fdtol->fdl_leader,
2128                                                    F_UNLCK, &lf, F_POSIX);
2129                                 FILEDESC_XLOCK(fdp);
2130                                 fdtol->fdl_holdcount--;
2131                                 if (fdtol->fdl_holdcount == 0 &&
2132                                     fdtol->fdl_wakeup != 0) {
2133                                         fdtol->fdl_wakeup = 0;
2134                                         wakeup(fdtol);
2135                                 }
2136                         }
2137                         FILEDESC_XUNLOCK(fdp);
2138                 }
2139                 VFS_UNLOCK_GIANT(vfslocked);
2140         }
2141         return (fdrop(fp, td));
2142 }
2143
2144 /*
2145  * Initialize the file pointer with the specified properties.
2146  * 
2147  * The ops are set with release semantics to be certain that the flags, type,
2148  * and data are visible when ops is.  This is to prevent ops methods from being
2149  * called with bad data.
2150  */
2151 void
2152 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2153 {
2154         fp->f_data = data;
2155         fp->f_flag = flag;
2156         fp->f_type = type;
2157         atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2158 }
2159
2160 struct file *
2161 fget_unlocked(struct filedesc *fdp, int fd)
2162 {
2163         struct file *fp;
2164         u_int count;
2165
2166         if (fd < 0 || fd >= fdp->fd_nfiles)
2167                 return (NULL);
2168         /*
2169          * Fetch the descriptor locklessly.  We avoid fdrop() races by
2170          * never raising a refcount above 0.  To accomplish this we have
2171          * to use a cmpset loop rather than an atomic_add.  The descriptor
2172          * must be re-verified once we acquire a reference to be certain
2173          * that the identity is still correct and we did not lose a race
2174          * due to preemption.
2175          */
2176         for (;;) {
2177                 fp = fdp->fd_ofiles[fd];
2178                 if (fp == NULL)
2179                         break;
2180                 count = fp->f_count;
2181                 if (count == 0)
2182                         continue;
2183                 /*
2184                  * Use an acquire barrier to prevent caching of fd_ofiles
2185                  * so it is refreshed for verification.
2186                  */
2187                 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2188                         continue;
2189                 if (fp == fdp->fd_ofiles[fd])
2190                         break;
2191                 fdrop(fp, curthread);
2192         }
2193
2194         return (fp);
2195 }
2196
2197 /*
2198  * Extract the file pointer associated with the specified descriptor for the
2199  * current user process.
2200  *
2201  * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2202  * returned.
2203  *
2204  * If an error occured the non-zero error is returned and *fpp is set to
2205  * NULL.  Otherwise *fpp is held and set and zero is returned.  Caller is
2206  * responsible for fdrop().
2207  */
2208 static __inline int
2209 _fget(struct thread *td, int fd, struct file **fpp, int flags)
2210 {
2211         struct filedesc *fdp;
2212         struct file *fp;
2213
2214         *fpp = NULL;
2215         if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2216                 return (EBADF);
2217         if ((fp = fget_unlocked(fdp, fd)) == NULL)
2218                 return (EBADF);
2219         if (fp->f_ops == &badfileops) {
2220                 fdrop(fp, td);
2221                 return (EBADF);
2222         }
2223         /*
2224          * FREAD and FWRITE failure return EBADF as per POSIX.
2225          *
2226          * Only one flag, or 0, may be specified.
2227          */
2228         if ((flags == FREAD && (fp->f_flag & FREAD) == 0) ||
2229             (flags == FWRITE && (fp->f_flag & FWRITE) == 0)) {
2230                 fdrop(fp, td);
2231                 return (EBADF);
2232         }
2233         *fpp = fp;
2234         return (0);
2235 }
2236
2237 int
2238 fget(struct thread *td, int fd, struct file **fpp)
2239 {
2240
2241         return(_fget(td, fd, fpp, 0));
2242 }
2243
2244 int
2245 fget_read(struct thread *td, int fd, struct file **fpp)
2246 {
2247
2248         return(_fget(td, fd, fpp, FREAD));
2249 }
2250
2251 int
2252 fget_write(struct thread *td, int fd, struct file **fpp)
2253 {
2254
2255         return(_fget(td, fd, fpp, FWRITE));
2256 }
2257
2258 /*
2259  * Like fget() but loads the underlying vnode, or returns an error if the
2260  * descriptor does not represent a vnode.  Note that pipes use vnodes but
2261  * never have VM objects.  The returned vnode will be vref()'d.
2262  *
2263  * XXX: what about the unused flags ?
2264  */
2265 static __inline int
2266 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2267 {
2268         struct file *fp;
2269         int error;
2270
2271         *vpp = NULL;
2272         if ((error = _fget(td, fd, &fp, flags)) != 0)
2273                 return (error);
2274         if (fp->f_vnode == NULL) {
2275                 error = EINVAL;
2276         } else {
2277                 *vpp = fp->f_vnode;
2278                 vref(*vpp);
2279         }
2280         fdrop(fp, td);
2281
2282         return (error);
2283 }
2284
2285 int
2286 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2287 {
2288
2289         return (_fgetvp(td, fd, vpp, 0));
2290 }
2291
2292 int
2293 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2294 {
2295
2296         return (_fgetvp(td, fd, vpp, FREAD));
2297 }
2298
2299 #ifdef notyet
2300 int
2301 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2302 {
2303
2304         return (_fgetvp(td, fd, vpp, FWRITE));
2305 }
2306 #endif
2307
2308 /*
2309  * Like fget() but loads the underlying socket, or returns an error if the
2310  * descriptor does not represent a socket.
2311  *
2312  * We bump the ref count on the returned socket.  XXX Also obtain the SX lock
2313  * in the future.
2314  *
2315  * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2316  * on their file descriptor reference to prevent the socket from being free'd
2317  * during use.
2318  */
2319 int
2320 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2321 {
2322         struct file *fp;
2323         int error;
2324
2325         *spp = NULL;
2326         if (fflagp != NULL)
2327                 *fflagp = 0;
2328         if ((error = _fget(td, fd, &fp, 0)) != 0)
2329                 return (error);
2330         if (fp->f_type != DTYPE_SOCKET) {
2331                 error = ENOTSOCK;
2332         } else {
2333                 *spp = fp->f_data;
2334                 if (fflagp)
2335                         *fflagp = fp->f_flag;
2336                 SOCK_LOCK(*spp);
2337                 soref(*spp);
2338                 SOCK_UNLOCK(*spp);
2339         }
2340         fdrop(fp, td);
2341
2342         return (error);
2343 }
2344
2345 /*
2346  * Drop the reference count on the socket and XXX release the SX lock in the
2347  * future.  The last reference closes the socket.
2348  *
2349  * Note: fputsock() is deprecated, see comment for fgetsock().
2350  */
2351 void
2352 fputsock(struct socket *so)
2353 {
2354
2355         ACCEPT_LOCK();
2356         SOCK_LOCK(so);
2357         CURVNET_SET(so->so_vnet);
2358         sorele(so);
2359         CURVNET_RESTORE();
2360 }
2361
2362 /*
2363  * Handle the last reference to a file being closed.
2364  */
2365 int
2366 _fdrop(struct file *fp, struct thread *td)
2367 {
2368         int error;
2369
2370         error = 0;
2371         if (fp->f_count != 0)
2372                 panic("fdrop: count %d", fp->f_count);
2373         if (fp->f_ops != &badfileops)
2374                 error = fo_close(fp, td);
2375         atomic_subtract_int(&openfiles, 1);
2376         crfree(fp->f_cred);
2377         free(fp->f_advice, M_FADVISE);
2378         uma_zfree(file_zone, fp);
2379
2380         return (error);
2381 }
2382
2383 /*
2384  * Apply an advisory lock on a file descriptor.
2385  *
2386  * Just attempt to get a record lock of the requested type on the entire file
2387  * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2388  */
2389 #ifndef _SYS_SYSPROTO_H_
2390 struct flock_args {
2391         int     fd;
2392         int     how;
2393 };
2394 #endif
2395 /* ARGSUSED */
2396 int
2397 flock(struct thread *td, struct flock_args *uap)
2398 {
2399         struct file *fp;
2400         struct vnode *vp;
2401         struct flock lf;
2402         int vfslocked;
2403         int error;
2404
2405         if ((error = fget(td, uap->fd, &fp)) != 0)
2406                 return (error);
2407         if (fp->f_type != DTYPE_VNODE) {
2408                 fdrop(fp, td);
2409                 return (EOPNOTSUPP);
2410         }
2411
2412         vp = fp->f_vnode;
2413         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2414         lf.l_whence = SEEK_SET;
2415         lf.l_start = 0;
2416         lf.l_len = 0;
2417         if (uap->how & LOCK_UN) {
2418                 lf.l_type = F_UNLCK;
2419                 atomic_clear_int(&fp->f_flag, FHASLOCK);
2420                 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2421                 goto done2;
2422         }
2423         if (uap->how & LOCK_EX)
2424                 lf.l_type = F_WRLCK;
2425         else if (uap->how & LOCK_SH)
2426                 lf.l_type = F_RDLCK;
2427         else {
2428                 error = EBADF;
2429                 goto done2;
2430         }
2431         atomic_set_int(&fp->f_flag, FHASLOCK);
2432         error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2433             (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2434 done2:
2435         fdrop(fp, td);
2436         VFS_UNLOCK_GIANT(vfslocked);
2437         return (error);
2438 }
2439 /*
2440  * Duplicate the specified descriptor to a free descriptor.
2441  */
2442 int
2443 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2444 {
2445         struct file *wfp;
2446         struct file *fp;
2447
2448         /*
2449          * If the to-be-dup'd fd number is greater than the allowed number
2450          * of file descriptors, or the fd to be dup'd has already been
2451          * closed, then reject.
2452          */
2453         FILEDESC_XLOCK(fdp);
2454         if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2455             (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2456                 FILEDESC_XUNLOCK(fdp);
2457                 return (EBADF);
2458         }
2459
2460         /*
2461          * There are two cases of interest here.
2462          *
2463          * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2464          *
2465          * For ENXIO steal away the file structure from (dfd) and store it in
2466          * (indx).  (dfd) is effectively closed by this operation.
2467          *
2468          * Any other error code is just returned.
2469          */
2470         switch (error) {
2471         case ENODEV:
2472                 /*
2473                  * Check that the mode the file is being opened for is a
2474                  * subset of the mode of the existing descriptor.
2475                  */
2476                 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2477                         FILEDESC_XUNLOCK(fdp);
2478                         return (EACCES);
2479                 }
2480                 fp = fdp->fd_ofiles[indx];
2481                 fdp->fd_ofiles[indx] = wfp;
2482                 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2483                 if (fp == NULL)
2484                         fdused(fdp, indx);
2485                 fhold(wfp);
2486                 FILEDESC_XUNLOCK(fdp);
2487                 if (fp != NULL)
2488                         /*
2489                          * We now own the reference to fp that the ofiles[]
2490                          * array used to own.  Release it.
2491                          */
2492                         fdrop(fp, td);
2493                 return (0);
2494
2495         case ENXIO:
2496                 /*
2497                  * Steal away the file pointer from dfd and stuff it into indx.
2498                  */
2499                 fp = fdp->fd_ofiles[indx];
2500                 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2501                 fdp->fd_ofiles[dfd] = NULL;
2502                 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2503                 fdp->fd_ofileflags[dfd] = 0;
2504                 fdunused(fdp, dfd);
2505                 if (fp == NULL)
2506                         fdused(fdp, indx);
2507                 FILEDESC_XUNLOCK(fdp);
2508
2509                 /*
2510                  * We now own the reference to fp that the ofiles[] array
2511                  * used to own.  Release it.
2512                  */
2513                 if (fp != NULL)
2514                         fdrop(fp, td);
2515                 return (0);
2516
2517         default:
2518                 FILEDESC_XUNLOCK(fdp);
2519                 return (error);
2520         }
2521         /* NOTREACHED */
2522 }
2523
2524 /*
2525  * Scan all active processes and prisons to see if any of them have a current
2526  * or root directory of `olddp'. If so, replace them with the new mount point.
2527  */
2528 void
2529 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2530 {
2531         struct filedesc *fdp;
2532         struct prison *pr;
2533         struct proc *p;
2534         int nrele;
2535
2536         if (vrefcnt(olddp) == 1)
2537                 return;
2538         nrele = 0;
2539         sx_slock(&allproc_lock);
2540         FOREACH_PROC_IN_SYSTEM(p) {
2541                 fdp = fdhold(p);
2542                 if (fdp == NULL)
2543                         continue;
2544                 FILEDESC_XLOCK(fdp);
2545                 if (fdp->fd_cdir == olddp) {
2546                         vref(newdp);
2547                         fdp->fd_cdir = newdp;
2548                         nrele++;
2549                 }
2550                 if (fdp->fd_rdir == olddp) {
2551                         vref(newdp);
2552                         fdp->fd_rdir = newdp;
2553                         nrele++;
2554                 }
2555                 if (fdp->fd_jdir == olddp) {
2556                         vref(newdp);
2557                         fdp->fd_jdir = newdp;
2558                         nrele++;
2559                 }
2560                 FILEDESC_XUNLOCK(fdp);
2561                 fddrop(fdp);
2562         }
2563         sx_sunlock(&allproc_lock);
2564         if (rootvnode == olddp) {
2565                 vref(newdp);
2566                 rootvnode = newdp;
2567                 nrele++;
2568         }
2569         mtx_lock(&prison0.pr_mtx);
2570         if (prison0.pr_root == olddp) {
2571                 vref(newdp);
2572                 prison0.pr_root = newdp;
2573                 nrele++;
2574         }
2575         mtx_unlock(&prison0.pr_mtx);
2576         sx_slock(&allprison_lock);
2577         TAILQ_FOREACH(pr, &allprison, pr_list) {
2578                 mtx_lock(&pr->pr_mtx);
2579                 if (pr->pr_root == olddp) {
2580                         vref(newdp);
2581                         pr->pr_root = newdp;
2582                         nrele++;
2583                 }
2584                 mtx_unlock(&pr->pr_mtx);
2585         }
2586         sx_sunlock(&allprison_lock);
2587         while (nrele--)
2588                 vrele(olddp);
2589 }
2590
2591 struct filedesc_to_leader *
2592 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2593 {
2594         struct filedesc_to_leader *fdtol;
2595
2596         fdtol = malloc(sizeof(struct filedesc_to_leader),
2597                M_FILEDESC_TO_LEADER,
2598                M_WAITOK);
2599         fdtol->fdl_refcount = 1;
2600         fdtol->fdl_holdcount = 0;
2601         fdtol->fdl_wakeup = 0;
2602         fdtol->fdl_leader = leader;
2603         if (old != NULL) {
2604                 FILEDESC_XLOCK(fdp);
2605                 fdtol->fdl_next = old->fdl_next;
2606                 fdtol->fdl_prev = old;
2607                 old->fdl_next = fdtol;
2608                 fdtol->fdl_next->fdl_prev = fdtol;
2609                 FILEDESC_XUNLOCK(fdp);
2610         } else {
2611                 fdtol->fdl_next = fdtol;
2612                 fdtol->fdl_prev = fdtol;
2613         }
2614         return (fdtol);
2615 }
2616
2617 /*
2618  * Get file structures globally.
2619  */
2620 static int
2621 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2622 {
2623         struct xfile xf;
2624         struct filedesc *fdp;
2625         struct file *fp;
2626         struct proc *p;
2627         int error, n;
2628
2629         error = sysctl_wire_old_buffer(req, 0);
2630         if (error != 0)
2631                 return (error);
2632         if (req->oldptr == NULL) {
2633                 n = 0;
2634                 sx_slock(&allproc_lock);
2635                 FOREACH_PROC_IN_SYSTEM(p) {
2636                         if (p->p_state == PRS_NEW)
2637                                 continue;
2638                         fdp = fdhold(p);
2639                         if (fdp == NULL)
2640                                 continue;
2641                         /* overestimates sparse tables. */
2642                         if (fdp->fd_lastfile > 0)
2643                                 n += fdp->fd_lastfile;
2644                         fddrop(fdp);
2645                 }
2646                 sx_sunlock(&allproc_lock);
2647                 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2648         }
2649         error = 0;
2650         bzero(&xf, sizeof(xf));
2651         xf.xf_size = sizeof(xf);
2652         sx_slock(&allproc_lock);
2653         FOREACH_PROC_IN_SYSTEM(p) {
2654                 PROC_LOCK(p);
2655                 if (p->p_state == PRS_NEW) {
2656                         PROC_UNLOCK(p);
2657                         continue;
2658                 }
2659                 if (p_cansee(req->td, p) != 0) {
2660                         PROC_UNLOCK(p);
2661                         continue;
2662                 }
2663                 xf.xf_pid = p->p_pid;
2664                 xf.xf_uid = p->p_ucred->cr_uid;
2665                 PROC_UNLOCK(p);
2666                 fdp = fdhold(p);
2667                 if (fdp == NULL)
2668                         continue;
2669                 FILEDESC_SLOCK(fdp);
2670                 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2671                         if ((fp = fdp->fd_ofiles[n]) == NULL)
2672                                 continue;
2673                         xf.xf_fd = n;
2674                         xf.xf_file = fp;
2675                         xf.xf_data = fp->f_data;
2676                         xf.xf_vnode = fp->f_vnode;
2677                         xf.xf_type = fp->f_type;
2678                         xf.xf_count = fp->f_count;
2679                         xf.xf_msgcount = 0;
2680                         xf.xf_offset = fp->f_offset;
2681                         xf.xf_flag = fp->f_flag;
2682                         error = SYSCTL_OUT(req, &xf, sizeof(xf));
2683                         if (error)
2684                                 break;
2685                 }
2686                 FILEDESC_SUNLOCK(fdp);
2687                 fddrop(fdp);
2688                 if (error)
2689                         break;
2690         }
2691         sx_sunlock(&allproc_lock);
2692         return (error);
2693 }
2694
2695 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2696     0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2697
2698 #ifdef KINFO_OFILE_SIZE
2699 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2700 #endif
2701
2702 #ifdef COMPAT_FREEBSD7
2703 static int
2704 export_vnode_for_osysctl(struct vnode *vp, int type,
2705     struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2706 {
2707         int error;
2708         char *fullpath, *freepath;
2709         int vfslocked;
2710
2711         bzero(kif, sizeof(*kif));
2712         kif->kf_structsize = sizeof(*kif);
2713
2714         vref(vp);
2715         kif->kf_fd = type;
2716         kif->kf_type = KF_TYPE_VNODE;
2717         /* This function only handles directories. */
2718         if (vp->v_type != VDIR) {
2719                 vrele(vp);
2720                 return (ENOTDIR);
2721         }
2722         kif->kf_vnode_type = KF_VTYPE_VDIR;
2723
2724         /*
2725          * This is not a true file descriptor, so we set a bogus refcount
2726          * and offset to indicate these fields should be ignored.
2727          */
2728         kif->kf_ref_count = -1;
2729         kif->kf_offset = -1;
2730
2731         freepath = NULL;
2732         fullpath = "-";
2733         FILEDESC_SUNLOCK(fdp);
2734         vn_fullpath(curthread, vp, &fullpath, &freepath);
2735         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2736         vrele(vp);
2737         VFS_UNLOCK_GIANT(vfslocked);
2738         strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2739         if (freepath != NULL)
2740                 free(freepath, M_TEMP);
2741         error = SYSCTL_OUT(req, kif, sizeof(*kif));
2742         FILEDESC_SLOCK(fdp);
2743         return (error);
2744 }
2745
2746 /*
2747  * Get per-process file descriptors for use by procstat(1), et al.
2748  */
2749 static int
2750 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
2751 {
2752         char *fullpath, *freepath;
2753         struct kinfo_ofile *kif;
2754         struct filedesc *fdp;
2755         int error, i, *name;
2756         struct shmfd *shmfd;
2757         struct socket *so;
2758         struct vnode *vp;
2759         struct file *fp;
2760         struct proc *p;
2761         struct tty *tp;
2762         int vfslocked;
2763
2764         name = (int *)arg1;
2765         if ((p = pfind((pid_t)name[0])) == NULL)
2766                 return (ESRCH);
2767         if ((error = p_candebug(curthread, p))) {
2768                 PROC_UNLOCK(p);
2769                 return (error);
2770         }
2771         fdp = fdhold(p);
2772         PROC_UNLOCK(p);
2773         if (fdp == NULL)
2774                 return (ENOENT);
2775         kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
2776         FILEDESC_SLOCK(fdp);
2777         if (fdp->fd_cdir != NULL)
2778                 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
2779                                 fdp, req);
2780         if (fdp->fd_rdir != NULL)
2781                 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
2782                                 fdp, req);
2783         if (fdp->fd_jdir != NULL)
2784                 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
2785                                 fdp, req);
2786         for (i = 0; i < fdp->fd_nfiles; i++) {
2787                 if ((fp = fdp->fd_ofiles[i]) == NULL)
2788                         continue;
2789                 bzero(kif, sizeof(*kif));
2790                 kif->kf_structsize = sizeof(*kif);
2791                 vp = NULL;
2792                 so = NULL;
2793                 tp = NULL;
2794                 shmfd = NULL;
2795                 kif->kf_fd = i;
2796                 switch (fp->f_type) {
2797                 case DTYPE_VNODE:
2798                         kif->kf_type = KF_TYPE_VNODE;
2799                         vp = fp->f_vnode;
2800                         break;
2801
2802                 case DTYPE_SOCKET:
2803                         kif->kf_type = KF_TYPE_SOCKET;
2804                         so = fp->f_data;
2805                         break;
2806
2807                 case DTYPE_PIPE:
2808                         kif->kf_type = KF_TYPE_PIPE;
2809                         break;
2810
2811                 case DTYPE_FIFO:
2812                         kif->kf_type = KF_TYPE_FIFO;
2813                         vp = fp->f_vnode;
2814                         break;
2815
2816                 case DTYPE_KQUEUE:
2817                         kif->kf_type = KF_TYPE_KQUEUE;
2818                         break;
2819
2820                 case DTYPE_CRYPTO:
2821                         kif->kf_type = KF_TYPE_CRYPTO;
2822                         break;
2823
2824                 case DTYPE_MQUEUE:
2825                         kif->kf_type = KF_TYPE_MQUEUE;
2826                         break;
2827
2828                 case DTYPE_SHM:
2829                         kif->kf_type = KF_TYPE_SHM;
2830                         shmfd = fp->f_data;
2831                         break;
2832
2833                 case DTYPE_SEM:
2834                         kif->kf_type = KF_TYPE_SEM;
2835                         break;
2836
2837                 case DTYPE_PTS:
2838                         kif->kf_type = KF_TYPE_PTS;
2839                         tp = fp->f_data;
2840                         break;
2841
2842                 default:
2843                         kif->kf_type = KF_TYPE_UNKNOWN;
2844                         break;
2845                 }
2846                 kif->kf_ref_count = fp->f_count;
2847                 if (fp->f_flag & FREAD)
2848                         kif->kf_flags |= KF_FLAG_READ;
2849                 if (fp->f_flag & FWRITE)
2850                         kif->kf_flags |= KF_FLAG_WRITE;
2851                 if (fp->f_flag & FAPPEND)
2852                         kif->kf_flags |= KF_FLAG_APPEND;
2853                 if (fp->f_flag & FASYNC)
2854                         kif->kf_flags |= KF_FLAG_ASYNC;
2855                 if (fp->f_flag & FFSYNC)
2856                         kif->kf_flags |= KF_FLAG_FSYNC;
2857                 if (fp->f_flag & FNONBLOCK)
2858                         kif->kf_flags |= KF_FLAG_NONBLOCK;
2859                 if (fp->f_flag & O_DIRECT)
2860                         kif->kf_flags |= KF_FLAG_DIRECT;
2861                 if (fp->f_flag & FHASLOCK)
2862                         kif->kf_flags |= KF_FLAG_HASLOCK;
2863                 kif->kf_offset = fp->f_offset;
2864                 if (vp != NULL) {
2865                         vref(vp);
2866                         switch (vp->v_type) {
2867                         case VNON:
2868                                 kif->kf_vnode_type = KF_VTYPE_VNON;
2869                                 break;
2870                         case VREG:
2871                                 kif->kf_vnode_type = KF_VTYPE_VREG;
2872                                 break;
2873                         case VDIR:
2874                                 kif->kf_vnode_type = KF_VTYPE_VDIR;
2875                                 break;
2876                         case VBLK:
2877                                 kif->kf_vnode_type = KF_VTYPE_VBLK;
2878                                 break;
2879                         case VCHR:
2880                                 kif->kf_vnode_type = KF_VTYPE_VCHR;
2881                                 break;
2882                         case VLNK:
2883                                 kif->kf_vnode_type = KF_VTYPE_VLNK;
2884                                 break;
2885                         case VSOCK:
2886                                 kif->kf_vnode_type = KF_VTYPE_VSOCK;
2887                                 break;
2888                         case VFIFO:
2889                                 kif->kf_vnode_type = KF_VTYPE_VFIFO;
2890                                 break;
2891                         case VBAD:
2892                                 kif->kf_vnode_type = KF_VTYPE_VBAD;
2893                                 break;
2894                         default:
2895                                 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
2896                                 break;
2897                         }
2898                         /*
2899                          * It is OK to drop the filedesc lock here as we will
2900                          * re-validate and re-evaluate its properties when
2901                          * the loop continues.
2902                          */
2903                         freepath = NULL;
2904                         fullpath = "-";
2905                         FILEDESC_SUNLOCK(fdp);
2906                         vn_fullpath(curthread, vp, &fullpath, &freepath);
2907                         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2908                         vrele(vp);
2909                         VFS_UNLOCK_GIANT(vfslocked);
2910                         strlcpy(kif->kf_path, fullpath,
2911                             sizeof(kif->kf_path));
2912                         if (freepath != NULL)
2913                                 free(freepath, M_TEMP);
2914                         FILEDESC_SLOCK(fdp);
2915                 }
2916                 if (so != NULL) {
2917                         struct sockaddr *sa;
2918
2919                         if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
2920                             == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
2921                                 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
2922                                 free(sa, M_SONAME);
2923                         }
2924                         if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
2925                             == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
2926                                 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
2927                                 free(sa, M_SONAME);
2928                         }
2929                         kif->kf_sock_domain =
2930                             so->so_proto->pr_domain->dom_family;
2931                         kif->kf_sock_type = so->so_type;
2932                         kif->kf_sock_protocol = so->so_proto->pr_protocol;
2933                 }
2934                 if (tp != NULL) {
2935                         strlcpy(kif->kf_path, tty_devname(tp),
2936                             sizeof(kif->kf_path));
2937                 }
2938                 if (shmfd != NULL)
2939                         shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
2940                 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2941                 if (error)
2942                         break;
2943         }
2944         FILEDESC_SUNLOCK(fdp);
2945         fddrop(fdp);
2946         free(kif, M_TEMP);
2947         return (0);
2948 }
2949
2950 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
2951     sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
2952 #endif  /* COMPAT_FREEBSD7 */
2953
2954 #ifdef KINFO_FILE_SIZE
2955 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
2956 #endif
2957
2958 static int
2959 export_vnode_for_sysctl(struct vnode *vp, int type,
2960     struct kinfo_file *kif, struct filedesc *fdp, struct sysctl_req *req)
2961 {
2962         int error;
2963         char *fullpath, *freepath;
2964         int vfslocked;
2965
2966         bzero(kif, sizeof(*kif));
2967
2968         vref(vp);
2969         kif->kf_fd = type;
2970         kif->kf_type = KF_TYPE_VNODE;
2971         /* This function only handles directories. */
2972         if (vp->v_type != VDIR) {
2973                 vrele(vp);
2974                 return (ENOTDIR);
2975         }
2976         kif->kf_vnode_type = KF_VTYPE_VDIR;
2977
2978         /*
2979          * This is not a true file descriptor, so we set a bogus refcount
2980          * and offset to indicate these fields should be ignored.
2981          */
2982         kif->kf_ref_count = -1;
2983         kif->kf_offset = -1;
2984
2985         freepath = NULL;
2986         fullpath = "-";
2987         FILEDESC_SUNLOCK(fdp);
2988         vn_fullpath(curthread, vp, &fullpath, &freepath);
2989         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2990         vrele(vp);
2991         VFS_UNLOCK_GIANT(vfslocked);
2992         strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2993         if (freepath != NULL)
2994                 free(freepath, M_TEMP);
2995         /* Pack record size down */
2996         kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
2997             strlen(kif->kf_path) + 1;
2998         kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
2999         error = SYSCTL_OUT(req, kif, kif->kf_structsize);
3000         FILEDESC_SLOCK(fdp);
3001         return (error);
3002 }
3003
3004 /*
3005  * Get per-process file descriptors for use by procstat(1), et al.
3006  */
3007 static int
3008 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3009 {
3010         char *fullpath, *freepath;
3011         struct kinfo_file *kif;
3012         struct filedesc *fdp;
3013         int error, i, *name;
3014         struct shmfd *shmfd;
3015         struct socket *so;
3016         struct vnode *vp;
3017         struct file *fp;
3018         struct proc *p;
3019         struct tty *tp;
3020         int vfslocked;
3021         size_t oldidx;
3022
3023         name = (int *)arg1;
3024         if ((p = pfind((pid_t)name[0])) == NULL)
3025                 return (ESRCH);
3026         if ((error = p_candebug(curthread, p))) {
3027                 PROC_UNLOCK(p);
3028                 return (error);
3029         }
3030         fdp = fdhold(p);
3031         PROC_UNLOCK(p);
3032         if (fdp == NULL)
3033                 return (ENOENT);
3034         kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3035         FILEDESC_SLOCK(fdp);
3036         if (fdp->fd_cdir != NULL)
3037                 export_vnode_for_sysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3038                                 fdp, req);
3039         if (fdp->fd_rdir != NULL)
3040                 export_vnode_for_sysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3041                                 fdp, req);
3042         if (fdp->fd_jdir != NULL)
3043                 export_vnode_for_sysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3044                                 fdp, req);
3045         for (i = 0; i < fdp->fd_nfiles; i++) {
3046                 if ((fp = fdp->fd_ofiles[i]) == NULL)
3047                         continue;
3048                 bzero(kif, sizeof(*kif));
3049                 vp = NULL;
3050                 so = NULL;
3051                 tp = NULL;
3052                 shmfd = NULL;
3053                 kif->kf_fd = i;
3054                 switch (fp->f_type) {
3055                 case DTYPE_VNODE:
3056                         kif->kf_type = KF_TYPE_VNODE;
3057                         vp = fp->f_vnode;
3058                         break;
3059
3060                 case DTYPE_SOCKET:
3061                         kif->kf_type = KF_TYPE_SOCKET;
3062                         so = fp->f_data;
3063                         break;
3064
3065                 case DTYPE_PIPE:
3066                         kif->kf_type = KF_TYPE_PIPE;
3067                         break;
3068
3069                 case DTYPE_FIFO:
3070                         kif->kf_type = KF_TYPE_FIFO;
3071                         vp = fp->f_vnode;
3072                         break;
3073
3074                 case DTYPE_KQUEUE:
3075                         kif->kf_type = KF_TYPE_KQUEUE;
3076                         break;
3077
3078                 case DTYPE_CRYPTO:
3079                         kif->kf_type = KF_TYPE_CRYPTO;
3080                         break;
3081
3082                 case DTYPE_MQUEUE:
3083                         kif->kf_type = KF_TYPE_MQUEUE;
3084                         break;
3085
3086                 case DTYPE_SHM:
3087                         kif->kf_type = KF_TYPE_SHM;
3088                         shmfd = fp->f_data;
3089                         break;
3090
3091                 case DTYPE_SEM:
3092                         kif->kf_type = KF_TYPE_SEM;
3093                         break;
3094
3095                 case DTYPE_PTS:
3096                         kif->kf_type = KF_TYPE_PTS;
3097                         tp = fp->f_data;
3098                         break;
3099
3100                 default:
3101                         kif->kf_type = KF_TYPE_UNKNOWN;
3102                         break;
3103                 }
3104                 kif->kf_ref_count = fp->f_count;
3105                 if (fp->f_flag & FREAD)
3106                         kif->kf_flags |= KF_FLAG_READ;
3107                 if (fp->f_flag & FWRITE)
3108                         kif->kf_flags |= KF_FLAG_WRITE;
3109                 if (fp->f_flag & FAPPEND)
3110                         kif->kf_flags |= KF_FLAG_APPEND;
3111                 if (fp->f_flag & FASYNC)
3112                         kif->kf_flags |= KF_FLAG_ASYNC;
3113                 if (fp->f_flag & FFSYNC)
3114                         kif->kf_flags |= KF_FLAG_FSYNC;
3115                 if (fp->f_flag & FNONBLOCK)
3116                         kif->kf_flags |= KF_FLAG_NONBLOCK;
3117                 if (fp->f_flag & O_DIRECT)
3118                         kif->kf_flags |= KF_FLAG_DIRECT;
3119                 if (fp->f_flag & FHASLOCK)
3120                         kif->kf_flags |= KF_FLAG_HASLOCK;
3121                 kif->kf_offset = fp->f_offset;
3122                 if (vp != NULL) {
3123                         vref(vp);
3124                         switch (vp->v_type) {
3125                         case VNON:
3126                                 kif->kf_vnode_type = KF_VTYPE_VNON;
3127                                 break;
3128                         case VREG:
3129                                 kif->kf_vnode_type = KF_VTYPE_VREG;
3130                                 break;
3131                         case VDIR:
3132                                 kif->kf_vnode_type = KF_VTYPE_VDIR;
3133                                 break;
3134                         case VBLK:
3135                                 kif->kf_vnode_type = KF_VTYPE_VBLK;
3136                                 break;
3137                         case VCHR:
3138                                 kif->kf_vnode_type = KF_VTYPE_VCHR;
3139                                 break;
3140                         case VLNK:
3141                                 kif->kf_vnode_type = KF_VTYPE_VLNK;
3142                                 break;
3143                         case VSOCK:
3144                                 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3145                                 break;
3146                         case VFIFO:
3147                                 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3148                                 break;
3149                         case VBAD:
3150                                 kif->kf_vnode_type = KF_VTYPE_VBAD;
3151                                 break;
3152                         default:
3153                                 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3154                                 break;
3155                         }
3156                         /*
3157                          * It is OK to drop the filedesc lock here as we will
3158                          * re-validate and re-evaluate its properties when
3159                          * the loop continues.
3160                          */
3161                         freepath = NULL;
3162                         fullpath = "-";
3163                         FILEDESC_SUNLOCK(fdp);
3164                         vn_fullpath(curthread, vp, &fullpath, &freepath);
3165                         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3166                         vrele(vp);
3167                         VFS_UNLOCK_GIANT(vfslocked);
3168                         strlcpy(kif->kf_path, fullpath,
3169                             sizeof(kif->kf_path));
3170                         if (freepath != NULL)
3171                                 free(freepath, M_TEMP);
3172                         FILEDESC_SLOCK(fdp);
3173                 }
3174                 if (so != NULL) {
3175                         struct sockaddr *sa;
3176
3177                         if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3178                             == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3179                                 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3180                                 free(sa, M_SONAME);
3181                         }
3182                         if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3183                             == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3184                                 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3185                                 free(sa, M_SONAME);
3186                         }
3187                         kif->kf_sock_domain =
3188                             so->so_proto->pr_domain->dom_family;
3189                         kif->kf_sock_type = so->so_type;
3190                         kif->kf_sock_protocol = so->so_proto->pr_protocol;
3191                 }
3192                 if (tp != NULL) {
3193                         strlcpy(kif->kf_path, tty_devname(tp),
3194                             sizeof(kif->kf_path));
3195                 }
3196                 if (shmfd != NULL)
3197                         shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3198                 /* Pack record size down */
3199                 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3200                     strlen(kif->kf_path) + 1;
3201                 kif->kf_structsize = roundup(kif->kf_structsize,
3202                     sizeof(uint64_t));
3203                 oldidx = req->oldidx;
3204                 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
3205                 if (error) {
3206                         if (error == ENOMEM) {
3207                                 /*
3208                                  * The hack to keep the ABI of sysctl
3209                                  * kern.proc.filedesc intact, but not
3210                                  * to account a partially copied
3211                                  * kinfo_file into the oldidx.
3212                                  */
3213                                 req->oldidx = oldidx;
3214                                 error = 0;
3215                         }
3216                         break;
3217                 }
3218         }
3219         FILEDESC_SUNLOCK(fdp);
3220         fddrop(fdp);
3221         free(kif, M_TEMP);
3222         return (error);
3223 }
3224
3225 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3226     sysctl_kern_proc_filedesc, "Process filedesc entries");
3227
3228 #ifdef DDB
3229 /*
3230  * For the purposes of debugging, generate a human-readable string for the
3231  * file type.
3232  */
3233 static const char *
3234 file_type_to_name(short type)
3235 {
3236
3237         switch (type) {
3238         case 0:
3239                 return ("zero");
3240         case DTYPE_VNODE:
3241                 return ("vnod");
3242         case DTYPE_SOCKET:
3243                 return ("sock");
3244         case DTYPE_PIPE:
3245                 return ("pipe");
3246         case DTYPE_FIFO:
3247                 return ("fifo");
3248         case DTYPE_KQUEUE:
3249                 return ("kque");
3250         case DTYPE_CRYPTO:
3251                 return ("crpt");
3252         case DTYPE_MQUEUE:
3253                 return ("mque");
3254         case DTYPE_SHM:
3255                 return ("shm");
3256         case DTYPE_SEM:
3257                 return ("ksem");
3258         default:
3259                 return ("unkn");
3260         }
3261 }
3262
3263 /*
3264  * For the purposes of debugging, identify a process (if any, perhaps one of
3265  * many) that references the passed file in its file descriptor array. Return
3266  * NULL if none.
3267  */
3268 static struct proc *
3269 file_to_first_proc(struct file *fp)
3270 {
3271         struct filedesc *fdp;
3272         struct proc *p;
3273         int n;
3274
3275         FOREACH_PROC_IN_SYSTEM(p) {
3276                 if (p->p_state == PRS_NEW)
3277                         continue;
3278                 fdp = p->p_fd;
3279                 if (fdp == NULL)
3280                         continue;
3281                 for (n = 0; n < fdp->fd_nfiles; n++) {
3282                         if (fp == fdp->fd_ofiles[n])
3283                                 return (p);
3284                 }
3285         }
3286         return (NULL);
3287 }
3288
3289 static void
3290 db_print_file(struct file *fp, int header)
3291 {
3292         struct proc *p;
3293
3294         if (header)
3295                 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3296                     "File", "Type", "Data", "Flag", "GCFl", "Count",
3297                     "MCount", "Vnode", "FPID", "FCmd");
3298         p = file_to_first_proc(fp);
3299         db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3300             file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3301             0, fp->f_count, 0, fp->f_vnode,
3302             p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3303 }
3304
3305 DB_SHOW_COMMAND(file, db_show_file)
3306 {
3307         struct file *fp;
3308
3309         if (!have_addr) {
3310                 db_printf("usage: show file <addr>\n");
3311                 return;
3312         }
3313         fp = (struct file *)addr;
3314         db_print_file(fp, 1);
3315 }
3316
3317 DB_SHOW_COMMAND(files, db_show_files)
3318 {
3319         struct filedesc *fdp;
3320         struct file *fp;
3321         struct proc *p;
3322         int header;
3323         int n;
3324
3325         header = 1;
3326         FOREACH_PROC_IN_SYSTEM(p) {
3327                 if (p->p_state == PRS_NEW)
3328                         continue;
3329                 if ((fdp = p->p_fd) == NULL)
3330                         continue;
3331                 for (n = 0; n < fdp->fd_nfiles; ++n) {
3332                         if ((fp = fdp->fd_ofiles[n]) == NULL)
3333                                 continue;
3334                         db_print_file(fp, header);
3335                         header = 0;
3336                 }
3337         }
3338 }
3339 #endif
3340
3341 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3342     &maxfilesperproc, 0, "Maximum files allowed open per process");
3343
3344 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3345     &maxfiles, 0, "Maximum number of files");
3346
3347 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3348     __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3349
3350 /* ARGSUSED*/
3351 static void
3352 filelistinit(void *dummy)
3353 {
3354
3355         file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3356             NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3357         mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3358         mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3359 }
3360 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3361
3362 /*-------------------------------------------------------------------*/
3363
3364 static int
3365 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
3366 {
3367
3368         return (EBADF);
3369 }
3370
3371 static int
3372 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred, struct thread *td)
3373 {
3374
3375         return (EINVAL);
3376 }
3377
3378 static int
3379 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
3380 {
3381
3382         return (EBADF);
3383 }
3384
3385 static int
3386 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
3387 {
3388
3389         return (0);
3390 }
3391
3392 static int
3393 badfo_kqfilter(struct file *fp, struct knote *kn)
3394 {
3395
3396         return (EBADF);
3397 }
3398
3399 static int
3400 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
3401 {
3402
3403         return (EBADF);
3404 }
3405
3406 static int
3407 badfo_close(struct file *fp, struct thread *td)
3408 {
3409
3410         return (EBADF);
3411 }
3412
3413 struct fileops badfileops = {
3414         .fo_read = badfo_readwrite,
3415         .fo_write = badfo_readwrite,
3416         .fo_truncate = badfo_truncate,
3417         .fo_ioctl = badfo_ioctl,
3418         .fo_poll = badfo_poll,
3419         .fo_kqfilter = badfo_kqfilter,
3420         .fo_stat = badfo_stat,
3421         .fo_close = badfo_close,
3422 };
3423
3424
3425 /*-------------------------------------------------------------------*/
3426
3427 /*
3428  * File Descriptor pseudo-device driver (/dev/fd/).
3429  *
3430  * Opening minor device N dup()s the file (if any) connected to file
3431  * descriptor N belonging to the calling process.  Note that this driver
3432  * consists of only the ``open()'' routine, because all subsequent
3433  * references to this file will be direct to the other driver.
3434  *
3435  * XXX: we could give this one a cloning event handler if necessary.
3436  */
3437
3438 /* ARGSUSED */
3439 static int
3440 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
3441 {
3442
3443         /*
3444          * XXX Kludge: set curthread->td_dupfd to contain the value of the
3445          * the file descriptor being sought for duplication. The error
3446          * return ensures that the vnode for this device will be released
3447          * by vn_open. Open will detect this special error and take the
3448          * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3449          * will simply report the error.
3450          */
3451         td->td_dupfd = dev2unit(dev);
3452         return (ENODEV);
3453 }
3454
3455 static struct cdevsw fildesc_cdevsw = {
3456         .d_version =    D_VERSION,
3457         .d_open =       fdopen,
3458         .d_name =       "FD",
3459 };
3460
3461 static void
3462 fildesc_drvinit(void *unused)
3463 {
3464         struct cdev *dev;
3465
3466         dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
3467             UID_ROOT, GID_WHEEL, 0666, "fd/0");
3468         make_dev_alias(dev, "stdin");
3469         dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
3470             UID_ROOT, GID_WHEEL, 0666, "fd/1");
3471         make_dev_alias(dev, "stdout");
3472         dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
3473             UID_ROOT, GID_WHEEL, 0666, "fd/2");
3474         make_dev_alias(dev, "stderr");
3475 }
3476
3477 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);