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