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