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