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