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