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