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