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