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