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