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