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