]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_descrip.c
Merge release 1.14 of bsnmp.
[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_FILEDESC_TO_LEADER, "filedesc_to_leader",
97     "file desc to leader structures");
98 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
99 MALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities");
100
101 MALLOC_DECLARE(M_FADVISE);
102
103 static __read_mostly uma_zone_t file_zone;
104 static __read_mostly uma_zone_t filedesc0_zone;
105 static __read_mostly uma_zone_t pwd_zone;
106 static __read_mostly smr_t pwd_smr;
107
108 static int      closefp(struct filedesc *fdp, int fd, struct file *fp,
109                     struct thread *td, int holdleaders);
110 static int      fd_first_free(struct filedesc *fdp, int low, int size);
111 static int      fd_last_used(struct filedesc *fdp, 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 highest non-zero bit in the given bitmap, starting at 0 and
217  * not exceeding size - 1. Return -1 if not found.
218  */
219 static int
220 fd_last_used(struct filedesc *fdp, int size)
221 {
222         NDSLOTTYPE *map = fdp->fd_map;
223         NDSLOTTYPE mask;
224         int off, minoff;
225
226         off = NDSLOT(size);
227         if (size % NDENTRIES) {
228                 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
229                 if ((mask &= map[off]) != 0)
230                         return (off * NDENTRIES + flsl(mask) - 1);
231                 --off;
232         }
233         for (minoff = NDSLOT(0); off >= minoff; --off)
234                 if (map[off] != 0)
235                         return (off * NDENTRIES + flsl(map[off]) - 1);
236         return (-1);
237 }
238
239 static int
240 fdisused(struct filedesc *fdp, int fd)
241 {
242
243         KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
244             ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
245
246         return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
247 }
248
249 /*
250  * Mark a file descriptor as used.
251  */
252 static void
253 fdused_init(struct filedesc *fdp, int fd)
254 {
255
256         KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
257
258         fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
259 }
260
261 static void
262 fdused(struct filedesc *fdp, int fd)
263 {
264
265         FILEDESC_XLOCK_ASSERT(fdp);
266
267         fdused_init(fdp, fd);
268         if (fd > fdp->fd_lastfile)
269                 fdp->fd_lastfile = fd;
270         if (fd == fdp->fd_freefile)
271                 fdp->fd_freefile++;
272 }
273
274 /*
275  * Mark a file descriptor as unused.
276  */
277 static void
278 fdunused(struct filedesc *fdp, int fd)
279 {
280
281         FILEDESC_XLOCK_ASSERT(fdp);
282
283         KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
284         KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
285             ("fd=%d is still in use", fd));
286
287         fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
288         if (fd < fdp->fd_freefile)
289                 fdp->fd_freefile = fd;
290         if (fd == fdp->fd_lastfile)
291                 fdp->fd_lastfile = fd_last_used(fdp, fd);
292 }
293
294 /*
295  * Free a file descriptor.
296  *
297  * Avoid some work if fdp is about to be destroyed.
298  */
299 static inline void
300 fdefree_last(struct filedescent *fde)
301 {
302
303         filecaps_free(&fde->fde_caps);
304 }
305
306 static inline void
307 fdfree(struct filedesc *fdp, int fd)
308 {
309         struct filedescent *fde;
310
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 = 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;
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         if (!fhold(oldfde->fde_file))
915                 goto unlock;
916
917         /*
918          * If the caller specified a file descriptor, make sure the file
919          * table is large enough to hold it, and grab it.  Otherwise, just
920          * allocate a new descriptor the usual way.
921          */
922         switch (mode) {
923         case FDDUP_NORMAL:
924         case FDDUP_FCNTL:
925                 if ((error = fdalloc(td, new, &new)) != 0) {
926                         fdrop(oldfde->fde_file, td);
927                         goto unlock;
928                 }
929                 break;
930         case FDDUP_MUSTREPLACE:
931                 /* Target file descriptor must exist. */
932                 if (fget_locked(fdp, new) == NULL) {
933                         fdrop(oldfde->fde_file, td);
934                         goto unlock;
935                 }
936                 break;
937         case FDDUP_FIXED:
938                 if (new >= fdp->fd_nfiles) {
939                         /*
940                          * The resource limits are here instead of e.g.
941                          * fdalloc(), because the file descriptor table may be
942                          * shared between processes, so we can't really use
943                          * racct_add()/racct_sub().  Instead of counting the
944                          * number of actually allocated descriptors, just put
945                          * the limit on the size of the file descriptor table.
946                          */
947 #ifdef RACCT
948                         if (RACCT_ENABLED()) {
949                                 error = racct_set_unlocked(p, RACCT_NOFILE, new + 1);
950                                 if (error != 0) {
951                                         error = EMFILE;
952                                         fdrop(oldfde->fde_file, td);
953                                         goto unlock;
954                                 }
955                         }
956 #endif
957                         fdgrowtable_exp(fdp, new + 1);
958                 }
959                 if (!fdisused(fdp, new))
960                         fdused(fdp, new);
961                 break;
962         default:
963                 KASSERT(0, ("%s unsupported mode %d", __func__, mode));
964         }
965
966         KASSERT(old != new, ("new fd is same as old"));
967
968         newfde = &fdp->fd_ofiles[new];
969         delfp = newfde->fde_file;
970
971         nioctls = filecaps_copy_prep(&oldfde->fde_caps);
972
973         /*
974          * Duplicate the source descriptor.
975          */
976 #ifdef CAPABILITIES
977         seqc_write_begin(&newfde->fde_seqc);
978 #endif
979         oioctls = filecaps_free_prep(&newfde->fde_caps);
980         memcpy(newfde, oldfde, fde_change_size);
981         filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
982             nioctls);
983         if ((flags & FDDUP_FLAG_CLOEXEC) != 0)
984                 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
985         else
986                 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
987 #ifdef CAPABILITIES
988         seqc_write_end(&newfde->fde_seqc);
989 #endif
990         td->td_retval[0] = new;
991
992         error = 0;
993
994         if (delfp != NULL) {
995                 (void) closefp(fdp, new, delfp, td, 1);
996                 FILEDESC_UNLOCK_ASSERT(fdp);
997         } else {
998 unlock:
999                 FILEDESC_XUNLOCK(fdp);
1000         }
1001
1002         filecaps_free_finish(oioctls);
1003         return (error);
1004 }
1005
1006 /*
1007  * If sigio is on the list associated with a process or process group,
1008  * disable signalling from the device, remove sigio from the list and
1009  * free sigio.
1010  */
1011 void
1012 funsetown(struct sigio **sigiop)
1013 {
1014         struct sigio *sigio;
1015
1016         if (*sigiop == NULL)
1017                 return;
1018         SIGIO_LOCK();
1019         sigio = *sigiop;
1020         if (sigio == NULL) {
1021                 SIGIO_UNLOCK();
1022                 return;
1023         }
1024         *(sigio->sio_myref) = NULL;
1025         if ((sigio)->sio_pgid < 0) {
1026                 struct pgrp *pg = (sigio)->sio_pgrp;
1027                 PGRP_LOCK(pg);
1028                 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
1029                             sigio, sio_pgsigio);
1030                 PGRP_UNLOCK(pg);
1031         } else {
1032                 struct proc *p = (sigio)->sio_proc;
1033                 PROC_LOCK(p);
1034                 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
1035                             sigio, sio_pgsigio);
1036                 PROC_UNLOCK(p);
1037         }
1038         SIGIO_UNLOCK();
1039         crfree(sigio->sio_ucred);
1040         free(sigio, M_SIGIO);
1041 }
1042
1043 /*
1044  * Free a list of sigio structures.
1045  * We only need to lock the SIGIO_LOCK because we have made ourselves
1046  * inaccessible to callers of fsetown and therefore do not need to lock
1047  * the proc or pgrp struct for the list manipulation.
1048  */
1049 void
1050 funsetownlst(struct sigiolst *sigiolst)
1051 {
1052         struct proc *p;
1053         struct pgrp *pg;
1054         struct sigio *sigio;
1055
1056         sigio = SLIST_FIRST(sigiolst);
1057         if (sigio == NULL)
1058                 return;
1059         p = NULL;
1060         pg = NULL;
1061
1062         /*
1063          * Every entry of the list should belong
1064          * to a single proc or pgrp.
1065          */
1066         if (sigio->sio_pgid < 0) {
1067                 pg = sigio->sio_pgrp;
1068                 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
1069         } else /* if (sigio->sio_pgid > 0) */ {
1070                 p = sigio->sio_proc;
1071                 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1072         }
1073
1074         SIGIO_LOCK();
1075         while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
1076                 *(sigio->sio_myref) = NULL;
1077                 if (pg != NULL) {
1078                         KASSERT(sigio->sio_pgid < 0,
1079                             ("Proc sigio in pgrp sigio list"));
1080                         KASSERT(sigio->sio_pgrp == pg,
1081                             ("Bogus pgrp in sigio list"));
1082                         PGRP_LOCK(pg);
1083                         SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
1084                             sio_pgsigio);
1085                         PGRP_UNLOCK(pg);
1086                 } else /* if (p != NULL) */ {
1087                         KASSERT(sigio->sio_pgid > 0,
1088                             ("Pgrp sigio in proc sigio list"));
1089                         KASSERT(sigio->sio_proc == p,
1090                             ("Bogus proc in sigio list"));
1091                         PROC_LOCK(p);
1092                         SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1093                             sio_pgsigio);
1094                         PROC_UNLOCK(p);
1095                 }
1096                 SIGIO_UNLOCK();
1097                 crfree(sigio->sio_ucred);
1098                 free(sigio, M_SIGIO);
1099                 SIGIO_LOCK();
1100         }
1101         SIGIO_UNLOCK();
1102 }
1103
1104 /*
1105  * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1106  *
1107  * After permission checking, add a sigio structure to the sigio list for
1108  * the process or process group.
1109  */
1110 int
1111 fsetown(pid_t pgid, struct sigio **sigiop)
1112 {
1113         struct proc *proc;
1114         struct pgrp *pgrp;
1115         struct sigio *sigio;
1116         int ret;
1117
1118         if (pgid == 0) {
1119                 funsetown(sigiop);
1120                 return (0);
1121         }
1122
1123         ret = 0;
1124
1125         /* Allocate and fill in the new sigio out of locks. */
1126         sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1127         sigio->sio_pgid = pgid;
1128         sigio->sio_ucred = crhold(curthread->td_ucred);
1129         sigio->sio_myref = sigiop;
1130
1131         sx_slock(&proctree_lock);
1132         if (pgid > 0) {
1133                 proc = pfind(pgid);
1134                 if (proc == NULL) {
1135                         ret = ESRCH;
1136                         goto fail;
1137                 }
1138
1139                 /*
1140                  * Policy - Don't allow a process to FSETOWN a process
1141                  * in another session.
1142                  *
1143                  * Remove this test to allow maximum flexibility or
1144                  * restrict FSETOWN to the current process or process
1145                  * group for maximum safety.
1146                  */
1147                 PROC_UNLOCK(proc);
1148                 if (proc->p_session != curthread->td_proc->p_session) {
1149                         ret = EPERM;
1150                         goto fail;
1151                 }
1152
1153                 pgrp = NULL;
1154         } else /* if (pgid < 0) */ {
1155                 pgrp = pgfind(-pgid);
1156                 if (pgrp == NULL) {
1157                         ret = ESRCH;
1158                         goto fail;
1159                 }
1160                 PGRP_UNLOCK(pgrp);
1161
1162                 /*
1163                  * Policy - Don't allow a process to FSETOWN a process
1164                  * in another session.
1165                  *
1166                  * Remove this test to allow maximum flexibility or
1167                  * restrict FSETOWN to the current process or process
1168                  * group for maximum safety.
1169                  */
1170                 if (pgrp->pg_session != curthread->td_proc->p_session) {
1171                         ret = EPERM;
1172                         goto fail;
1173                 }
1174
1175                 proc = NULL;
1176         }
1177         funsetown(sigiop);
1178         if (pgid > 0) {
1179                 PROC_LOCK(proc);
1180                 /*
1181                  * Since funsetownlst() is called without the proctree
1182                  * locked, we need to check for P_WEXIT.
1183                  * XXX: is ESRCH correct?
1184                  */
1185                 if ((proc->p_flag & P_WEXIT) != 0) {
1186                         PROC_UNLOCK(proc);
1187                         ret = ESRCH;
1188                         goto fail;
1189                 }
1190                 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1191                 sigio->sio_proc = proc;
1192                 PROC_UNLOCK(proc);
1193         } else {
1194                 PGRP_LOCK(pgrp);
1195                 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1196                 sigio->sio_pgrp = pgrp;
1197                 PGRP_UNLOCK(pgrp);
1198         }
1199         sx_sunlock(&proctree_lock);
1200         SIGIO_LOCK();
1201         *sigiop = sigio;
1202         SIGIO_UNLOCK();
1203         return (0);
1204
1205 fail:
1206         sx_sunlock(&proctree_lock);
1207         crfree(sigio->sio_ucred);
1208         free(sigio, M_SIGIO);
1209         return (ret);
1210 }
1211
1212 /*
1213  * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1214  */
1215 pid_t
1216 fgetown(struct sigio **sigiop)
1217 {
1218         pid_t pgid;
1219
1220         SIGIO_LOCK();
1221         pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1222         SIGIO_UNLOCK();
1223         return (pgid);
1224 }
1225
1226 /*
1227  * Function drops the filedesc lock on return.
1228  */
1229 static int
1230 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1231     int holdleaders)
1232 {
1233         int error;
1234
1235         FILEDESC_XLOCK_ASSERT(fdp);
1236
1237         if (holdleaders) {
1238                 if (td->td_proc->p_fdtol != NULL) {
1239                         /*
1240                          * Ask fdfree() to sleep to ensure that all relevant
1241                          * process leaders can be traversed in closef().
1242                          */
1243                         fdp->fd_holdleaderscount++;
1244                 } else {
1245                         holdleaders = 0;
1246                 }
1247         }
1248
1249         /*
1250          * We now hold the fp reference that used to be owned by the
1251          * descriptor array.  We have to unlock the FILEDESC *AFTER*
1252          * knote_fdclose to prevent a race of the fd getting opened, a knote
1253          * added, and deleteing a knote for the new fd.
1254          */
1255         if (__predict_false(!TAILQ_EMPTY(&fdp->fd_kqlist)))
1256                 knote_fdclose(td, fd);
1257
1258         /*
1259          * We need to notify mqueue if the object is of type mqueue.
1260          */
1261         if (__predict_false(fp->f_type == DTYPE_MQUEUE))
1262                 mq_fdclose(td, fd, fp);
1263         FILEDESC_XUNLOCK(fdp);
1264
1265         error = closef(fp, td);
1266         if (holdleaders) {
1267                 FILEDESC_XLOCK(fdp);
1268                 fdp->fd_holdleaderscount--;
1269                 if (fdp->fd_holdleaderscount == 0 &&
1270                     fdp->fd_holdleaderswakeup != 0) {
1271                         fdp->fd_holdleaderswakeup = 0;
1272                         wakeup(&fdp->fd_holdleaderscount);
1273                 }
1274                 FILEDESC_XUNLOCK(fdp);
1275         }
1276         return (error);
1277 }
1278
1279 /*
1280  * Close a file descriptor.
1281  */
1282 #ifndef _SYS_SYSPROTO_H_
1283 struct close_args {
1284         int     fd;
1285 };
1286 #endif
1287 /* ARGSUSED */
1288 int
1289 sys_close(struct thread *td, struct close_args *uap)
1290 {
1291
1292         return (kern_close(td, uap->fd));
1293 }
1294
1295 int
1296 kern_close(struct thread *td, int fd)
1297 {
1298         struct filedesc *fdp;
1299         struct file *fp;
1300
1301         fdp = td->td_proc->p_fd;
1302
1303         AUDIT_SYSCLOSE(td, fd);
1304
1305         FILEDESC_XLOCK(fdp);
1306         if ((fp = fget_locked(fdp, fd)) == NULL) {
1307                 FILEDESC_XUNLOCK(fdp);
1308                 return (EBADF);
1309         }
1310         fdfree(fdp, fd);
1311
1312         /* closefp() drops the FILEDESC lock for us. */
1313         return (closefp(fdp, fd, fp, td, 1));
1314 }
1315
1316 /*
1317  * Close open file descriptors.
1318  */
1319 #ifndef _SYS_SYSPROTO_H_
1320 struct closefrom_args {
1321         int     lowfd;
1322 };
1323 #endif
1324 /* ARGSUSED */
1325 int
1326 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1327 {
1328         struct filedesc *fdp;
1329         int fd;
1330
1331         fdp = td->td_proc->p_fd;
1332         AUDIT_ARG_FD(uap->lowfd);
1333
1334         /*
1335          * Treat negative starting file descriptor values identical to
1336          * closefrom(0) which closes all files.
1337          */
1338         if (uap->lowfd < 0)
1339                 uap->lowfd = 0;
1340         FILEDESC_SLOCK(fdp);
1341         for (fd = uap->lowfd; fd <= fdp->fd_lastfile; fd++) {
1342                 if (fdp->fd_ofiles[fd].fde_file != NULL) {
1343                         FILEDESC_SUNLOCK(fdp);
1344                         (void)kern_close(td, fd);
1345                         FILEDESC_SLOCK(fdp);
1346                 }
1347         }
1348         FILEDESC_SUNLOCK(fdp);
1349         return (0);
1350 }
1351
1352 #if defined(COMPAT_43)
1353 /*
1354  * Return status information about a file descriptor.
1355  */
1356 #ifndef _SYS_SYSPROTO_H_
1357 struct ofstat_args {
1358         int     fd;
1359         struct  ostat *sb;
1360 };
1361 #endif
1362 /* ARGSUSED */
1363 int
1364 ofstat(struct thread *td, struct ofstat_args *uap)
1365 {
1366         struct ostat oub;
1367         struct stat ub;
1368         int error;
1369
1370         error = kern_fstat(td, uap->fd, &ub);
1371         if (error == 0) {
1372                 cvtstat(&ub, &oub);
1373                 error = copyout(&oub, uap->sb, sizeof(oub));
1374         }
1375         return (error);
1376 }
1377 #endif /* COMPAT_43 */
1378
1379 #if defined(COMPAT_FREEBSD11)
1380 int
1381 freebsd11_fstat(struct thread *td, struct freebsd11_fstat_args *uap)
1382 {
1383         struct stat sb;
1384         struct freebsd11_stat osb;
1385         int error;
1386
1387         error = kern_fstat(td, uap->fd, &sb);
1388         if (error != 0)
1389                 return (error);
1390         error = freebsd11_cvtstat(&sb, &osb);
1391         if (error == 0)
1392                 error = copyout(&osb, uap->sb, sizeof(osb));
1393         return (error);
1394 }
1395 #endif  /* COMPAT_FREEBSD11 */
1396
1397 /*
1398  * Return status information about a file descriptor.
1399  */
1400 #ifndef _SYS_SYSPROTO_H_
1401 struct fstat_args {
1402         int     fd;
1403         struct  stat *sb;
1404 };
1405 #endif
1406 /* ARGSUSED */
1407 int
1408 sys_fstat(struct thread *td, struct fstat_args *uap)
1409 {
1410         struct stat ub;
1411         int error;
1412
1413         error = kern_fstat(td, uap->fd, &ub);
1414         if (error == 0)
1415                 error = copyout(&ub, uap->sb, sizeof(ub));
1416         return (error);
1417 }
1418
1419 int
1420 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1421 {
1422         struct file *fp;
1423         int error;
1424
1425         AUDIT_ARG_FD(fd);
1426
1427         error = fget(td, fd, &cap_fstat_rights, &fp);
1428         if (__predict_false(error != 0))
1429                 return (error);
1430
1431         AUDIT_ARG_FILE(td->td_proc, fp);
1432
1433         error = fo_stat(fp, sbp, td->td_ucred, td);
1434         fdrop(fp, td);
1435 #ifdef __STAT_TIME_T_EXT
1436         sbp->st_atim_ext = 0;
1437         sbp->st_mtim_ext = 0;
1438         sbp->st_ctim_ext = 0;
1439         sbp->st_btim_ext = 0;
1440 #endif
1441 #ifdef KTRACE
1442         if (KTRPOINT(td, KTR_STRUCT))
1443                 ktrstat_error(sbp, error);
1444 #endif
1445         return (error);
1446 }
1447
1448 #if defined(COMPAT_FREEBSD11)
1449 /*
1450  * Return status information about a file descriptor.
1451  */
1452 #ifndef _SYS_SYSPROTO_H_
1453 struct freebsd11_nfstat_args {
1454         int     fd;
1455         struct  nstat *sb;
1456 };
1457 #endif
1458 /* ARGSUSED */
1459 int
1460 freebsd11_nfstat(struct thread *td, struct freebsd11_nfstat_args *uap)
1461 {
1462         struct nstat nub;
1463         struct stat ub;
1464         int error;
1465
1466         error = kern_fstat(td, uap->fd, &ub);
1467         if (error == 0) {
1468                 freebsd11_cvtnstat(&ub, &nub);
1469                 error = copyout(&nub, uap->sb, sizeof(nub));
1470         }
1471         return (error);
1472 }
1473 #endif /* COMPAT_FREEBSD11 */
1474
1475 /*
1476  * Return pathconf information about a file descriptor.
1477  */
1478 #ifndef _SYS_SYSPROTO_H_
1479 struct fpathconf_args {
1480         int     fd;
1481         int     name;
1482 };
1483 #endif
1484 /* ARGSUSED */
1485 int
1486 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1487 {
1488         long value;
1489         int error;
1490
1491         error = kern_fpathconf(td, uap->fd, uap->name, &value);
1492         if (error == 0)
1493                 td->td_retval[0] = value;
1494         return (error);
1495 }
1496
1497 int
1498 kern_fpathconf(struct thread *td, int fd, int name, long *valuep)
1499 {
1500         struct file *fp;
1501         struct vnode *vp;
1502         int error;
1503
1504         error = fget(td, fd, &cap_fpathconf_rights, &fp);
1505         if (error != 0)
1506                 return (error);
1507
1508         if (name == _PC_ASYNC_IO) {
1509                 *valuep = _POSIX_ASYNCHRONOUS_IO;
1510                 goto out;
1511         }
1512         vp = fp->f_vnode;
1513         if (vp != NULL) {
1514                 vn_lock(vp, LK_SHARED | LK_RETRY);
1515                 error = VOP_PATHCONF(vp, name, valuep);
1516                 VOP_UNLOCK(vp);
1517         } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1518                 if (name != _PC_PIPE_BUF) {
1519                         error = EINVAL;
1520                 } else {
1521                         *valuep = PIPE_BUF;
1522                         error = 0;
1523                 }
1524         } else {
1525                 error = EOPNOTSUPP;
1526         }
1527 out:
1528         fdrop(fp, td);
1529         return (error);
1530 }
1531
1532 /*
1533  * Copy filecaps structure allocating memory for ioctls array if needed.
1534  *
1535  * The last parameter indicates whether the fdtable is locked. If it is not and
1536  * ioctls are encountered, copying fails and the caller must lock the table.
1537  *
1538  * Note that if the table was not locked, the caller has to check the relevant
1539  * sequence counter to determine whether the operation was successful.
1540  */
1541 bool
1542 filecaps_copy(const struct filecaps *src, struct filecaps *dst, bool locked)
1543 {
1544         size_t size;
1545
1546         if (src->fc_ioctls != NULL && !locked)
1547                 return (false);
1548         memcpy(dst, src, sizeof(*src));
1549         if (src->fc_ioctls == NULL)
1550                 return (true);
1551
1552         KASSERT(src->fc_nioctls > 0,
1553             ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1554
1555         size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1556         dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1557         memcpy(dst->fc_ioctls, src->fc_ioctls, size);
1558         return (true);
1559 }
1560
1561 static u_long *
1562 filecaps_copy_prep(const struct filecaps *src)
1563 {
1564         u_long *ioctls;
1565         size_t size;
1566
1567         if (__predict_true(src->fc_ioctls == NULL))
1568                 return (NULL);
1569
1570         KASSERT(src->fc_nioctls > 0,
1571             ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1572
1573         size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1574         ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1575         return (ioctls);
1576 }
1577
1578 static void
1579 filecaps_copy_finish(const struct filecaps *src, struct filecaps *dst,
1580     u_long *ioctls)
1581 {
1582         size_t size;
1583
1584         *dst = *src;
1585         if (__predict_true(src->fc_ioctls == NULL)) {
1586                 MPASS(ioctls == NULL);
1587                 return;
1588         }
1589
1590         size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1591         dst->fc_ioctls = ioctls;
1592         bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1593 }
1594
1595 /*
1596  * Move filecaps structure to the new place and clear the old place.
1597  */
1598 void
1599 filecaps_move(struct filecaps *src, struct filecaps *dst)
1600 {
1601
1602         *dst = *src;
1603         bzero(src, sizeof(*src));
1604 }
1605
1606 /*
1607  * Fill the given filecaps structure with full rights.
1608  */
1609 static void
1610 filecaps_fill(struct filecaps *fcaps)
1611 {
1612
1613         CAP_ALL(&fcaps->fc_rights);
1614         fcaps->fc_ioctls = NULL;
1615         fcaps->fc_nioctls = -1;
1616         fcaps->fc_fcntls = CAP_FCNTL_ALL;
1617 }
1618
1619 /*
1620  * Free memory allocated within filecaps structure.
1621  */
1622 void
1623 filecaps_free(struct filecaps *fcaps)
1624 {
1625
1626         free(fcaps->fc_ioctls, M_FILECAPS);
1627         bzero(fcaps, sizeof(*fcaps));
1628 }
1629
1630 static u_long *
1631 filecaps_free_prep(struct filecaps *fcaps)
1632 {
1633         u_long *ioctls;
1634
1635         ioctls = fcaps->fc_ioctls;
1636         bzero(fcaps, sizeof(*fcaps));
1637         return (ioctls);
1638 }
1639
1640 static void
1641 filecaps_free_finish(u_long *ioctls)
1642 {
1643
1644         free(ioctls, M_FILECAPS);
1645 }
1646
1647 /*
1648  * Validate the given filecaps structure.
1649  */
1650 static void
1651 filecaps_validate(const struct filecaps *fcaps, const char *func)
1652 {
1653
1654         KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1655             ("%s: invalid rights", func));
1656         KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1657             ("%s: invalid fcntls", func));
1658         KASSERT(fcaps->fc_fcntls == 0 ||
1659             cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1660             ("%s: fcntls without CAP_FCNTL", func));
1661         KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1662             (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1663             ("%s: invalid ioctls", func));
1664         KASSERT(fcaps->fc_nioctls == 0 ||
1665             cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1666             ("%s: ioctls without CAP_IOCTL", func));
1667 }
1668
1669 static void
1670 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1671 {
1672         int nfd1;
1673
1674         FILEDESC_XLOCK_ASSERT(fdp);
1675
1676         nfd1 = fdp->fd_nfiles * 2;
1677         if (nfd1 < nfd)
1678                 nfd1 = nfd;
1679         fdgrowtable(fdp, nfd1);
1680 }
1681
1682 /*
1683  * Grow the file table to accommodate (at least) nfd descriptors.
1684  */
1685 static void
1686 fdgrowtable(struct filedesc *fdp, int nfd)
1687 {
1688         struct filedesc0 *fdp0;
1689         struct freetable *ft;
1690         struct fdescenttbl *ntable;
1691         struct fdescenttbl *otable;
1692         int nnfiles, onfiles;
1693         NDSLOTTYPE *nmap, *omap;
1694
1695         /*
1696          * If lastfile is -1 this struct filedesc was just allocated and we are
1697          * growing it to accommodate for the one we are going to copy from. There
1698          * is no need to have a lock on this one as it's not visible to anyone.
1699          */
1700         if (fdp->fd_lastfile != -1)
1701                 FILEDESC_XLOCK_ASSERT(fdp);
1702
1703         KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1704
1705         /* save old values */
1706         onfiles = fdp->fd_nfiles;
1707         otable = fdp->fd_files;
1708         omap = fdp->fd_map;
1709
1710         /* compute the size of the new table */
1711         nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1712         if (nnfiles <= onfiles)
1713                 /* the table is already large enough */
1714                 return;
1715
1716         /*
1717          * Allocate a new table.  We need enough space for the number of
1718          * entries, file entries themselves and the struct freetable we will use
1719          * when we decommission the table and place it on the freelist.
1720          * We place the struct freetable in the middle so we don't have
1721          * to worry about padding.
1722          */
1723         ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1724             nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1725             sizeof(struct freetable),
1726             M_FILEDESC, M_ZERO | M_WAITOK);
1727         /* copy the old data */
1728         ntable->fdt_nfiles = nnfiles;
1729         memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1730             onfiles * sizeof(ntable->fdt_ofiles[0]));
1731
1732         /*
1733          * Allocate a new map only if the old is not large enough.  It will
1734          * grow at a slower rate than the table as it can map more
1735          * entries than the table can hold.
1736          */
1737         if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1738                 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1739                     M_ZERO | M_WAITOK);
1740                 /* copy over the old data and update the pointer */
1741                 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1742                 fdp->fd_map = nmap;
1743         }
1744
1745         /*
1746          * Make sure that ntable is correctly initialized before we replace
1747          * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1748          * data.
1749          */
1750         atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1751
1752         /*
1753          * Do not free the old file table, as some threads may still
1754          * reference entries within it.  Instead, place it on a freelist
1755          * which will be processed when the struct filedesc is released.
1756          *
1757          * Note that if onfiles == NDFILE, we're dealing with the original
1758          * static allocation contained within (struct filedesc0 *)fdp,
1759          * which must not be freed.
1760          */
1761         if (onfiles > NDFILE) {
1762                 ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1763                 fdp0 = (struct filedesc0 *)fdp;
1764                 ft->ft_table = otable;
1765                 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1766         }
1767         /*
1768          * The map does not have the same possibility of threads still
1769          * holding references to it.  So always free it as long as it
1770          * does not reference the original static allocation.
1771          */
1772         if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1773                 free(omap, M_FILEDESC);
1774 }
1775
1776 /*
1777  * Allocate a file descriptor for the process.
1778  */
1779 int
1780 fdalloc(struct thread *td, int minfd, int *result)
1781 {
1782         struct proc *p = td->td_proc;
1783         struct filedesc *fdp = p->p_fd;
1784         int fd, maxfd, allocfd;
1785 #ifdef RACCT
1786         int error;
1787 #endif
1788
1789         FILEDESC_XLOCK_ASSERT(fdp);
1790
1791         if (fdp->fd_freefile > minfd)
1792                 minfd = fdp->fd_freefile;
1793
1794         maxfd = getmaxfd(td);
1795
1796         /*
1797          * Search the bitmap for a free descriptor starting at minfd.
1798          * If none is found, grow the file table.
1799          */
1800         fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1801         if (fd >= maxfd)
1802                 return (EMFILE);
1803         if (fd >= fdp->fd_nfiles) {
1804                 allocfd = min(fd * 2, maxfd);
1805 #ifdef RACCT
1806                 if (RACCT_ENABLED()) {
1807                         error = racct_set_unlocked(p, RACCT_NOFILE, allocfd);
1808                         if (error != 0)
1809                                 return (EMFILE);
1810                 }
1811 #endif
1812                 /*
1813                  * fd is already equal to first free descriptor >= minfd, so
1814                  * we only need to grow the table and we are done.
1815                  */
1816                 fdgrowtable_exp(fdp, allocfd);
1817         }
1818
1819         /*
1820          * Perform some sanity checks, then mark the file descriptor as
1821          * used and return it to the caller.
1822          */
1823         KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1824             ("invalid descriptor %d", fd));
1825         KASSERT(!fdisused(fdp, fd),
1826             ("fd_first_free() returned non-free descriptor"));
1827         KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1828             ("file descriptor isn't free"));
1829         fdused(fdp, fd);
1830         *result = fd;
1831         return (0);
1832 }
1833
1834 /*
1835  * Allocate n file descriptors for the process.
1836  */
1837 int
1838 fdallocn(struct thread *td, int minfd, int *fds, int n)
1839 {
1840         struct proc *p = td->td_proc;
1841         struct filedesc *fdp = p->p_fd;
1842         int i;
1843
1844         FILEDESC_XLOCK_ASSERT(fdp);
1845
1846         for (i = 0; i < n; i++)
1847                 if (fdalloc(td, 0, &fds[i]) != 0)
1848                         break;
1849
1850         if (i < n) {
1851                 for (i--; i >= 0; i--)
1852                         fdunused(fdp, fds[i]);
1853                 return (EMFILE);
1854         }
1855
1856         return (0);
1857 }
1858
1859 /*
1860  * Create a new open file structure and allocate a file descriptor for the
1861  * process that refers to it.  We add one reference to the file for the
1862  * descriptor table and one reference for resultfp. This is to prevent us
1863  * being preempted and the entry in the descriptor table closed after we
1864  * release the FILEDESC lock.
1865  */
1866 int
1867 falloc_caps(struct thread *td, struct file **resultfp, int *resultfd, int flags,
1868     struct filecaps *fcaps)
1869 {
1870         struct file *fp;
1871         int error, fd;
1872
1873         error = falloc_noinstall(td, &fp);
1874         if (error)
1875                 return (error);         /* no reference held on error */
1876
1877         error = finstall(td, fp, &fd, flags, fcaps);
1878         if (error) {
1879                 fdrop(fp, td);          /* one reference (fp only) */
1880                 return (error);
1881         }
1882
1883         if (resultfp != NULL)
1884                 *resultfp = fp;         /* copy out result */
1885         else
1886                 fdrop(fp, td);          /* release local reference */
1887
1888         if (resultfd != NULL)
1889                 *resultfd = fd;
1890
1891         return (0);
1892 }
1893
1894 /*
1895  * Create a new open file structure without allocating a file descriptor.
1896  */
1897 int
1898 falloc_noinstall(struct thread *td, struct file **resultfp)
1899 {
1900         struct file *fp;
1901         int maxuserfiles = maxfiles - (maxfiles / 20);
1902         int openfiles_new;
1903         static struct timeval lastfail;
1904         static int curfail;
1905
1906         KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1907
1908         openfiles_new = atomic_fetchadd_int(&openfiles, 1) + 1;
1909         if ((openfiles_new >= maxuserfiles &&
1910             priv_check(td, PRIV_MAXFILES) != 0) ||
1911             openfiles_new >= maxfiles) {
1912                 atomic_subtract_int(&openfiles, 1);
1913                 if (ppsratecheck(&lastfail, &curfail, 1)) {
1914                         printf("kern.maxfiles limit exceeded by uid %i, (%s) "
1915                             "please see tuning(7).\n", td->td_ucred->cr_ruid, td->td_proc->p_comm);
1916                 }
1917                 return (ENFILE);
1918         }
1919         fp = uma_zalloc(file_zone, M_WAITOK);
1920         bzero(fp, sizeof(*fp));
1921         refcount_init(&fp->f_count, 1);
1922         fp->f_cred = crhold(td->td_ucred);
1923         fp->f_ops = &badfileops;
1924         *resultfp = fp;
1925         return (0);
1926 }
1927
1928 /*
1929  * Install a file in a file descriptor table.
1930  */
1931 void
1932 _finstall(struct filedesc *fdp, struct file *fp, int fd, int flags,
1933     struct filecaps *fcaps)
1934 {
1935         struct filedescent *fde;
1936
1937         MPASS(fp != NULL);
1938         if (fcaps != NULL)
1939                 filecaps_validate(fcaps, __func__);
1940         FILEDESC_XLOCK_ASSERT(fdp);
1941
1942         fde = &fdp->fd_ofiles[fd];
1943 #ifdef CAPABILITIES
1944         seqc_write_begin(&fde->fde_seqc);
1945 #endif
1946         fde->fde_file = fp;
1947         fde->fde_flags = (flags & O_CLOEXEC) != 0 ? UF_EXCLOSE : 0;
1948         if (fcaps != NULL)
1949                 filecaps_move(fcaps, &fde->fde_caps);
1950         else
1951                 filecaps_fill(&fde->fde_caps);
1952 #ifdef CAPABILITIES
1953         seqc_write_end(&fde->fde_seqc);
1954 #endif
1955 }
1956
1957 int
1958 finstall(struct thread *td, struct file *fp, int *fd, int flags,
1959     struct filecaps *fcaps)
1960 {
1961         struct filedesc *fdp = td->td_proc->p_fd;
1962         int error;
1963
1964         MPASS(fd != NULL);
1965
1966         if (!fhold(fp))
1967                 return (EBADF);
1968         FILEDESC_XLOCK(fdp);
1969         error = fdalloc(td, 0, fd);
1970         if (__predict_false(error != 0)) {
1971                 FILEDESC_XUNLOCK(fdp);
1972                 fdrop(fp, td);
1973                 return (error);
1974         }
1975         _finstall(fdp, fp, *fd, flags, fcaps);
1976         FILEDESC_XUNLOCK(fdp);
1977         return (0);
1978 }
1979
1980 /*
1981  * Build a new filedesc structure from another.
1982  * Copy the current, root, and jail root vnode references.
1983  *
1984  * If fdp is not NULL, return with it shared locked.
1985  */
1986 struct filedesc *
1987 fdinit(struct filedesc *fdp, bool prepfiles)
1988 {
1989         struct filedesc0 *newfdp0;
1990         struct filedesc *newfdp;
1991         struct pwd *newpwd;
1992
1993         newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO);
1994         newfdp = &newfdp0->fd_fd;
1995
1996         /* Create the file descriptor table. */
1997         FILEDESC_LOCK_INIT(newfdp);
1998         refcount_init(&newfdp->fd_refcnt, 1);
1999         refcount_init(&newfdp->fd_holdcnt, 1);
2000         newfdp->fd_cmask = CMASK;
2001         newfdp->fd_map = newfdp0->fd_dmap;
2002         newfdp->fd_lastfile = -1;
2003         newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles;
2004         newfdp->fd_files->fdt_nfiles = NDFILE;
2005
2006         if (fdp == NULL) {
2007                 newpwd = pwd_alloc();
2008                 smr_serialized_store(&newfdp->fd_pwd, newpwd, true);
2009                 return (newfdp);
2010         }
2011
2012         if (prepfiles && fdp->fd_lastfile >= newfdp->fd_nfiles)
2013                 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
2014
2015         FILEDESC_SLOCK(fdp);
2016         newpwd = pwd_hold_filedesc(fdp);
2017         smr_serialized_store(&newfdp->fd_pwd, newpwd, true);
2018
2019         if (!prepfiles) {
2020                 FILEDESC_SUNLOCK(fdp);
2021         } else {
2022                 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
2023                         FILEDESC_SUNLOCK(fdp);
2024                         fdgrowtable(newfdp, fdp->fd_lastfile + 1);
2025                         FILEDESC_SLOCK(fdp);
2026                 }
2027         }
2028
2029         return (newfdp);
2030 }
2031
2032 static struct filedesc *
2033 fdhold(struct proc *p)
2034 {
2035         struct filedesc *fdp;
2036
2037         PROC_LOCK_ASSERT(p, MA_OWNED);
2038         fdp = p->p_fd;
2039         if (fdp != NULL)
2040                 refcount_acquire(&fdp->fd_holdcnt);
2041         return (fdp);
2042 }
2043
2044 static void
2045 fddrop(struct filedesc *fdp)
2046 {
2047
2048         if (fdp->fd_holdcnt > 1) {
2049                 if (refcount_release(&fdp->fd_holdcnt) == 0)
2050                         return;
2051         }
2052
2053         FILEDESC_LOCK_DESTROY(fdp);
2054         uma_zfree(filedesc0_zone, fdp);
2055 }
2056
2057 /*
2058  * Share a filedesc structure.
2059  */
2060 struct filedesc *
2061 fdshare(struct filedesc *fdp)
2062 {
2063
2064         refcount_acquire(&fdp->fd_refcnt);
2065         return (fdp);
2066 }
2067
2068 /*
2069  * Unshare a filedesc structure, if necessary by making a copy
2070  */
2071 void
2072 fdunshare(struct thread *td)
2073 {
2074         struct filedesc *tmp;
2075         struct proc *p = td->td_proc;
2076
2077         if (p->p_fd->fd_refcnt == 1)
2078                 return;
2079
2080         tmp = fdcopy(p->p_fd);
2081         fdescfree(td);
2082         p->p_fd = tmp;
2083 }
2084
2085 void
2086 fdinstall_remapped(struct thread *td, struct filedesc *fdp)
2087 {
2088
2089         fdescfree(td);
2090         td->td_proc->p_fd = fdp;
2091 }
2092
2093 /*
2094  * Copy a filedesc structure.  A NULL pointer in returns a NULL reference,
2095  * this is to ease callers, not catch errors.
2096  */
2097 struct filedesc *
2098 fdcopy(struct filedesc *fdp)
2099 {
2100         struct filedesc *newfdp;
2101         struct filedescent *nfde, *ofde;
2102         int i;
2103
2104         MPASS(fdp != NULL);
2105
2106         newfdp = fdinit(fdp, true);
2107         /* copy all passable descriptors (i.e. not kqueue) */
2108         newfdp->fd_freefile = -1;
2109         for (i = 0; i <= fdp->fd_lastfile; ++i) {
2110                 ofde = &fdp->fd_ofiles[i];
2111                 if (ofde->fde_file == NULL ||
2112                     (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0 ||
2113                     !fhold(ofde->fde_file)) {
2114                         if (newfdp->fd_freefile == -1)
2115                                 newfdp->fd_freefile = i;
2116                         continue;
2117                 }
2118                 nfde = &newfdp->fd_ofiles[i];
2119                 *nfde = *ofde;
2120                 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2121                 fdused_init(newfdp, i);
2122                 newfdp->fd_lastfile = i;
2123         }
2124         if (newfdp->fd_freefile == -1)
2125                 newfdp->fd_freefile = i;
2126         newfdp->fd_cmask = fdp->fd_cmask;
2127         FILEDESC_SUNLOCK(fdp);
2128         return (newfdp);
2129 }
2130
2131 /*
2132  * Copies a filedesc structure, while remapping all file descriptors
2133  * stored inside using a translation table.
2134  *
2135  * File descriptors are copied over to the new file descriptor table,
2136  * regardless of whether the close-on-exec flag is set.
2137  */
2138 int
2139 fdcopy_remapped(struct filedesc *fdp, const int *fds, size_t nfds,
2140     struct filedesc **ret)
2141 {
2142         struct filedesc *newfdp;
2143         struct filedescent *nfde, *ofde;
2144         int error, i;
2145
2146         MPASS(fdp != NULL);
2147
2148         newfdp = fdinit(fdp, true);
2149         if (nfds > fdp->fd_lastfile + 1) {
2150                 /* New table cannot be larger than the old one. */
2151                 error = E2BIG;
2152                 goto bad;
2153         }
2154         /* Copy all passable descriptors (i.e. not kqueue). */
2155         newfdp->fd_freefile = nfds;
2156         for (i = 0; i < nfds; ++i) {
2157                 if (fds[i] < 0 || fds[i] > fdp->fd_lastfile) {
2158                         /* File descriptor out of bounds. */
2159                         error = EBADF;
2160                         goto bad;
2161                 }
2162                 ofde = &fdp->fd_ofiles[fds[i]];
2163                 if (ofde->fde_file == NULL) {
2164                         /* Unused file descriptor. */
2165                         error = EBADF;
2166                         goto bad;
2167                 }
2168                 if ((ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
2169                         /* File descriptor cannot be passed. */
2170                         error = EINVAL;
2171                         goto bad;
2172                 }
2173                 if (!fhold(nfde->fde_file)) {
2174                         error = EBADF;
2175                         goto bad;
2176                 }
2177                 nfde = &newfdp->fd_ofiles[i];
2178                 *nfde = *ofde;
2179                 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2180                 fdused_init(newfdp, i);
2181                 newfdp->fd_lastfile = i;
2182         }
2183         newfdp->fd_cmask = fdp->fd_cmask;
2184         FILEDESC_SUNLOCK(fdp);
2185         *ret = newfdp;
2186         return (0);
2187 bad:
2188         FILEDESC_SUNLOCK(fdp);
2189         fdescfree_remapped(newfdp);
2190         return (error);
2191 }
2192
2193 /*
2194  * Clear POSIX style locks. This is only used when fdp looses a reference (i.e.
2195  * one of processes using it exits) and the table used to be shared.
2196  */
2197 static void
2198 fdclearlocks(struct thread *td)
2199 {
2200         struct filedesc *fdp;
2201         struct filedesc_to_leader *fdtol;
2202         struct flock lf;
2203         struct file *fp;
2204         struct proc *p;
2205         struct vnode *vp;
2206         int i;
2207
2208         p = td->td_proc;
2209         fdp = p->p_fd;
2210         fdtol = p->p_fdtol;
2211         MPASS(fdtol != NULL);
2212
2213         FILEDESC_XLOCK(fdp);
2214         KASSERT(fdtol->fdl_refcount > 0,
2215             ("filedesc_to_refcount botch: fdl_refcount=%d",
2216             fdtol->fdl_refcount));
2217         if (fdtol->fdl_refcount == 1 &&
2218             (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2219                 for (i = 0; i <= fdp->fd_lastfile; i++) {
2220                         fp = fdp->fd_ofiles[i].fde_file;
2221                         if (fp == NULL || fp->f_type != DTYPE_VNODE ||
2222                             !fhold(fp))
2223                                 continue;
2224                         FILEDESC_XUNLOCK(fdp);
2225                         lf.l_whence = SEEK_SET;
2226                         lf.l_start = 0;
2227                         lf.l_len = 0;
2228                         lf.l_type = F_UNLCK;
2229                         vp = fp->f_vnode;
2230                         (void) VOP_ADVLOCK(vp,
2231                             (caddr_t)p->p_leader, F_UNLCK,
2232                             &lf, F_POSIX);
2233                         FILEDESC_XLOCK(fdp);
2234                         fdrop(fp, td);
2235                 }
2236         }
2237 retry:
2238         if (fdtol->fdl_refcount == 1) {
2239                 if (fdp->fd_holdleaderscount > 0 &&
2240                     (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2241                         /*
2242                          * close() or kern_dup() has cleared a reference
2243                          * in a shared file descriptor table.
2244                          */
2245                         fdp->fd_holdleaderswakeup = 1;
2246                         sx_sleep(&fdp->fd_holdleaderscount,
2247                             FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2248                         goto retry;
2249                 }
2250                 if (fdtol->fdl_holdcount > 0) {
2251                         /*
2252                          * Ensure that fdtol->fdl_leader remains
2253                          * valid in closef().
2254                          */
2255                         fdtol->fdl_wakeup = 1;
2256                         sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2257                             "fdlhold", 0);
2258                         goto retry;
2259                 }
2260         }
2261         fdtol->fdl_refcount--;
2262         if (fdtol->fdl_refcount == 0 &&
2263             fdtol->fdl_holdcount == 0) {
2264                 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2265                 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2266         } else
2267                 fdtol = NULL;
2268         p->p_fdtol = NULL;
2269         FILEDESC_XUNLOCK(fdp);
2270         if (fdtol != NULL)
2271                 free(fdtol, M_FILEDESC_TO_LEADER);
2272 }
2273
2274 /*
2275  * Release a filedesc structure.
2276  */
2277 static void
2278 fdescfree_fds(struct thread *td, struct filedesc *fdp, bool needclose)
2279 {
2280         struct filedesc0 *fdp0;
2281         struct freetable *ft, *tft;
2282         struct filedescent *fde;
2283         struct file *fp;
2284         int i;
2285
2286         for (i = 0; i <= fdp->fd_lastfile; i++) {
2287                 fde = &fdp->fd_ofiles[i];
2288                 fp = fde->fde_file;
2289                 if (fp != NULL) {
2290                         fdefree_last(fde);
2291                         if (needclose)
2292                                 (void) closef(fp, td);
2293                         else
2294                                 fdrop(fp, td);
2295                 }
2296         }
2297
2298         if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2299                 free(fdp->fd_map, M_FILEDESC);
2300         if (fdp->fd_nfiles > NDFILE)
2301                 free(fdp->fd_files, M_FILEDESC);
2302
2303         fdp0 = (struct filedesc0 *)fdp;
2304         SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft)
2305                 free(ft->ft_table, M_FILEDESC);
2306
2307         fddrop(fdp);
2308 }
2309
2310 void
2311 fdescfree(struct thread *td)
2312 {
2313         struct proc *p;
2314         struct filedesc *fdp;
2315         struct pwd *pwd;
2316
2317         p = td->td_proc;
2318         fdp = p->p_fd;
2319         MPASS(fdp != NULL);
2320
2321 #ifdef RACCT
2322         if (RACCT_ENABLED())
2323                 racct_set_unlocked(p, RACCT_NOFILE, 0);
2324 #endif
2325
2326         if (p->p_fdtol != NULL)
2327                 fdclearlocks(td);
2328
2329         PROC_LOCK(p);
2330         p->p_fd = NULL;
2331         PROC_UNLOCK(p);
2332
2333         if (refcount_release(&fdp->fd_refcnt) == 0)
2334                 return;
2335
2336         FILEDESC_XLOCK(fdp);
2337         pwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
2338         pwd_set(fdp, NULL);
2339         FILEDESC_XUNLOCK(fdp);
2340
2341         pwd_drop(pwd);
2342
2343         fdescfree_fds(td, fdp, 1);
2344 }
2345
2346 void
2347 fdescfree_remapped(struct filedesc *fdp)
2348 {
2349
2350         pwd_drop(smr_serialized_load(&fdp->fd_pwd, true));
2351         fdescfree_fds(curthread, fdp, 0);
2352 }
2353
2354 /*
2355  * For setugid programs, we don't want to people to use that setugidness
2356  * to generate error messages which write to a file which otherwise would
2357  * otherwise be off-limits to the process.  We check for filesystems where
2358  * the vnode can change out from under us after execve (like [lin]procfs).
2359  *
2360  * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is
2361  * sufficient.  We also don't check for setugidness since we know we are.
2362  */
2363 static bool
2364 is_unsafe(struct file *fp)
2365 {
2366         struct vnode *vp;
2367
2368         if (fp->f_type != DTYPE_VNODE)
2369                 return (false);
2370
2371         vp = fp->f_vnode;
2372         return ((vp->v_vflag & VV_PROCDEP) != 0);
2373 }
2374
2375 /*
2376  * Make this setguid thing safe, if at all possible.
2377  */
2378 void
2379 fdsetugidsafety(struct thread *td)
2380 {
2381         struct filedesc *fdp;
2382         struct file *fp;
2383         int i;
2384
2385         fdp = td->td_proc->p_fd;
2386         KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2387         MPASS(fdp->fd_nfiles >= 3);
2388         for (i = 0; i <= 2; i++) {
2389                 fp = fdp->fd_ofiles[i].fde_file;
2390                 if (fp != NULL && is_unsafe(fp)) {
2391                         FILEDESC_XLOCK(fdp);
2392                         knote_fdclose(td, i);
2393                         /*
2394                          * NULL-out descriptor prior to close to avoid
2395                          * a race while close blocks.
2396                          */
2397                         fdfree(fdp, i);
2398                         FILEDESC_XUNLOCK(fdp);
2399                         (void) closef(fp, td);
2400                 }
2401         }
2402 }
2403
2404 /*
2405  * If a specific file object occupies a specific file descriptor, close the
2406  * file descriptor entry and drop a reference on the file object.  This is a
2407  * convenience function to handle a subsequent error in a function that calls
2408  * falloc() that handles the race that another thread might have closed the
2409  * file descriptor out from under the thread creating the file object.
2410  */
2411 void
2412 fdclose(struct thread *td, struct file *fp, int idx)
2413 {
2414         struct filedesc *fdp = td->td_proc->p_fd;
2415
2416         FILEDESC_XLOCK(fdp);
2417         if (fdp->fd_ofiles[idx].fde_file == fp) {
2418                 fdfree(fdp, idx);
2419                 FILEDESC_XUNLOCK(fdp);
2420                 fdrop(fp, td);
2421         } else
2422                 FILEDESC_XUNLOCK(fdp);
2423 }
2424
2425 /*
2426  * Close any files on exec?
2427  */
2428 void
2429 fdcloseexec(struct thread *td)
2430 {
2431         struct filedesc *fdp;
2432         struct filedescent *fde;
2433         struct file *fp;
2434         int i;
2435
2436         fdp = td->td_proc->p_fd;
2437         KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2438         for (i = 0; i <= fdp->fd_lastfile; i++) {
2439                 fde = &fdp->fd_ofiles[i];
2440                 fp = fde->fde_file;
2441                 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2442                     (fde->fde_flags & UF_EXCLOSE))) {
2443                         FILEDESC_XLOCK(fdp);
2444                         fdfree(fdp, i);
2445                         (void) closefp(fdp, i, fp, td, 0);
2446                         FILEDESC_UNLOCK_ASSERT(fdp);
2447                 }
2448         }
2449 }
2450
2451 /*
2452  * It is unsafe for set[ug]id processes to be started with file
2453  * descriptors 0..2 closed, as these descriptors are given implicit
2454  * significance in the Standard C library.  fdcheckstd() will create a
2455  * descriptor referencing /dev/null for each of stdin, stdout, and
2456  * stderr that is not already open.
2457  */
2458 int
2459 fdcheckstd(struct thread *td)
2460 {
2461         struct filedesc *fdp;
2462         register_t save;
2463         int i, error, devnull;
2464
2465         fdp = td->td_proc->p_fd;
2466         KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2467         MPASS(fdp->fd_nfiles >= 3);
2468         devnull = -1;
2469         for (i = 0; i <= 2; i++) {
2470                 if (fdp->fd_ofiles[i].fde_file != NULL)
2471                         continue;
2472
2473                 save = td->td_retval[0];
2474                 if (devnull != -1) {
2475                         error = kern_dup(td, FDDUP_FIXED, 0, devnull, i);
2476                 } else {
2477                         error = kern_openat(td, AT_FDCWD, "/dev/null",
2478                             UIO_SYSSPACE, O_RDWR, 0);
2479                         if (error == 0) {
2480                                 devnull = td->td_retval[0];
2481                                 KASSERT(devnull == i, ("we didn't get our fd"));
2482                         }
2483                 }
2484                 td->td_retval[0] = save;
2485                 if (error != 0)
2486                         return (error);
2487         }
2488         return (0);
2489 }
2490
2491 /*
2492  * Internal form of close.  Decrement reference count on file structure.
2493  * Note: td may be NULL when closing a file that was being passed in a
2494  * message.
2495  */
2496 int
2497 closef(struct file *fp, struct thread *td)
2498 {
2499         struct vnode *vp;
2500         struct flock lf;
2501         struct filedesc_to_leader *fdtol;
2502         struct filedesc *fdp;
2503
2504         /*
2505          * POSIX record locking dictates that any close releases ALL
2506          * locks owned by this process.  This is handled by setting
2507          * a flag in the unlock to free ONLY locks obeying POSIX
2508          * semantics, and not to free BSD-style file locks.
2509          * If the descriptor was in a message, POSIX-style locks
2510          * aren't passed with the descriptor, and the thread pointer
2511          * will be NULL.  Callers should be careful only to pass a
2512          * NULL thread pointer when there really is no owning
2513          * context that might have locks, or the locks will be
2514          * leaked.
2515          */
2516         if (fp->f_type == DTYPE_VNODE && td != NULL) {
2517                 vp = fp->f_vnode;
2518                 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2519                         lf.l_whence = SEEK_SET;
2520                         lf.l_start = 0;
2521                         lf.l_len = 0;
2522                         lf.l_type = F_UNLCK;
2523                         (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2524                             F_UNLCK, &lf, F_POSIX);
2525                 }
2526                 fdtol = td->td_proc->p_fdtol;
2527                 if (fdtol != NULL) {
2528                         /*
2529                          * Handle special case where file descriptor table is
2530                          * shared between multiple process leaders.
2531                          */
2532                         fdp = td->td_proc->p_fd;
2533                         FILEDESC_XLOCK(fdp);
2534                         for (fdtol = fdtol->fdl_next;
2535                             fdtol != td->td_proc->p_fdtol;
2536                             fdtol = fdtol->fdl_next) {
2537                                 if ((fdtol->fdl_leader->p_flag &
2538                                     P_ADVLOCK) == 0)
2539                                         continue;
2540                                 fdtol->fdl_holdcount++;
2541                                 FILEDESC_XUNLOCK(fdp);
2542                                 lf.l_whence = SEEK_SET;
2543                                 lf.l_start = 0;
2544                                 lf.l_len = 0;
2545                                 lf.l_type = F_UNLCK;
2546                                 vp = fp->f_vnode;
2547                                 (void) VOP_ADVLOCK(vp,
2548                                     (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2549                                     F_POSIX);
2550                                 FILEDESC_XLOCK(fdp);
2551                                 fdtol->fdl_holdcount--;
2552                                 if (fdtol->fdl_holdcount == 0 &&
2553                                     fdtol->fdl_wakeup != 0) {
2554                                         fdtol->fdl_wakeup = 0;
2555                                         wakeup(fdtol);
2556                                 }
2557                         }
2558                         FILEDESC_XUNLOCK(fdp);
2559                 }
2560         }
2561         return (fdrop(fp, td));
2562 }
2563
2564 /*
2565  * Initialize the file pointer with the specified properties.
2566  *
2567  * The ops are set with release semantics to be certain that the flags, type,
2568  * and data are visible when ops is.  This is to prevent ops methods from being
2569  * called with bad data.
2570  */
2571 void
2572 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2573 {
2574         fp->f_data = data;
2575         fp->f_flag = flag;
2576         fp->f_type = type;
2577         atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2578 }
2579
2580 int
2581 fget_cap_locked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2582     struct file **fpp, struct filecaps *havecapsp)
2583 {
2584         struct filedescent *fde;
2585         int error;
2586
2587         FILEDESC_LOCK_ASSERT(fdp);
2588
2589         fde = fdeget_locked(fdp, fd);
2590         if (fde == NULL) {
2591                 error = EBADF;
2592                 goto out;
2593         }
2594
2595 #ifdef CAPABILITIES
2596         error = cap_check(cap_rights_fde_inline(fde), needrightsp);
2597         if (error != 0)
2598                 goto out;
2599 #endif
2600
2601         if (havecapsp != NULL)
2602                 filecaps_copy(&fde->fde_caps, havecapsp, true);
2603
2604         *fpp = fde->fde_file;
2605
2606         error = 0;
2607 out:
2608         return (error);
2609 }
2610
2611 int
2612 fget_cap(struct thread *td, int fd, cap_rights_t *needrightsp,
2613     struct file **fpp, struct filecaps *havecapsp)
2614 {
2615         struct filedesc *fdp = td->td_proc->p_fd;
2616         int error;
2617 #ifndef CAPABILITIES
2618         error = fget_unlocked(fdp, fd, needrightsp, fpp);
2619         if (havecapsp != NULL && error == 0)
2620                 filecaps_fill(havecapsp);
2621 #else
2622         struct file *fp;
2623         seqc_t seq;
2624
2625         *fpp = NULL;
2626         for (;;) {
2627                 error = fget_unlocked_seq(fdp, fd, needrightsp, &fp, &seq);
2628                 if (error != 0)
2629                         return (error);
2630
2631                 if (havecapsp != NULL) {
2632                         if (!filecaps_copy(&fdp->fd_ofiles[fd].fde_caps,
2633                             havecapsp, false)) {
2634                                 fdrop(fp, td);
2635                                 goto get_locked;
2636                         }
2637                 }
2638
2639                 if (!fd_modified(fdp, fd, seq))
2640                         break;
2641                 fdrop(fp, td);
2642         }
2643
2644         *fpp = fp;
2645         return (0);
2646
2647 get_locked:
2648         FILEDESC_SLOCK(fdp);
2649         error = fget_cap_locked(fdp, fd, needrightsp, fpp, havecapsp);
2650         if (error == 0 && !fhold(*fpp))
2651                 error = EBADF;
2652         FILEDESC_SUNLOCK(fdp);
2653 #endif
2654         return (error);
2655 }
2656
2657 int
2658 fget_unlocked_seq(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2659     struct file **fpp, seqc_t *seqp)
2660 {
2661 #ifdef CAPABILITIES
2662         const struct filedescent *fde;
2663 #endif
2664         const struct fdescenttbl *fdt;
2665         struct file *fp;
2666 #ifdef CAPABILITIES
2667         seqc_t seq;
2668         cap_rights_t haverights;
2669         int error;
2670 #endif
2671
2672         fdt = fdp->fd_files;
2673         if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
2674                 return (EBADF);
2675         /*
2676          * Fetch the descriptor locklessly.  We avoid fdrop() races by
2677          * never raising a refcount above 0.  To accomplish this we have
2678          * to use a cmpset loop rather than an atomic_add.  The descriptor
2679          * must be re-verified once we acquire a reference to be certain
2680          * that the identity is still correct and we did not lose a race
2681          * due to preemption.
2682          */
2683         for (;;) {
2684 #ifdef CAPABILITIES
2685                 seq = seqc_read(fd_seqc(fdt, fd));
2686                 fde = &fdt->fdt_ofiles[fd];
2687                 haverights = *cap_rights_fde_inline(fde);
2688                 fp = fde->fde_file;
2689                 if (!seqc_consistent(fd_seqc(fdt, fd), seq))
2690                         continue;
2691 #else
2692                 fp = fdt->fdt_ofiles[fd].fde_file;
2693 #endif
2694                 if (fp == NULL)
2695                         return (EBADF);
2696 #ifdef CAPABILITIES
2697                 error = cap_check_inline(&haverights, needrightsp);
2698                 if (error != 0)
2699                         return (error);
2700 #endif
2701                 if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count))) {
2702                         /*
2703                          * The count was found either saturated or zero.
2704                          * This re-read is not any more racy than using the
2705                          * return value from fcmpset.
2706                          */
2707                         if (fp->f_count != 0)
2708                                 return (EBADF);
2709                         /*
2710                          * Force a reload. Other thread could reallocate the
2711                          * table before this fd was closed, so it is possible
2712                          * that there is a stale fp pointer in cached version.
2713                          */
2714                         fdt = atomic_load_ptr(&fdp->fd_files);
2715                         continue;
2716                 }
2717                 /*
2718                  * Use an acquire barrier to force re-reading of fdt so it is
2719                  * refreshed for verification.
2720                  */
2721                 atomic_thread_fence_acq();
2722                 fdt = fdp->fd_files;
2723 #ifdef  CAPABILITIES
2724                 if (seqc_consistent_nomb(fd_seqc(fdt, fd), seq))
2725 #else
2726                 if (fp == fdt->fdt_ofiles[fd].fde_file)
2727 #endif
2728                         break;
2729                 fdrop(fp, curthread);
2730         }
2731         *fpp = fp;
2732         if (seqp != NULL) {
2733 #ifdef CAPABILITIES
2734                 *seqp = seq;
2735 #endif
2736         }
2737         return (0);
2738 }
2739
2740 /*
2741  * See the comments in fget_unlocked_seq for an explanation of how this works.
2742  *
2743  * This is a simplified variant which bails out to the aforementioned routine
2744  * if anything goes wrong. In practice this only happens when userspace is
2745  * racing with itself.
2746  */
2747 int
2748 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2749     struct file **fpp)
2750 {
2751 #ifdef CAPABILITIES
2752         const struct filedescent *fde;
2753 #endif
2754         const struct fdescenttbl *fdt;
2755         struct file *fp;
2756 #ifdef CAPABILITIES
2757         seqc_t seq;
2758         const cap_rights_t *haverights;
2759 #endif
2760
2761         fdt = fdp->fd_files;
2762         if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
2763                 return (EBADF);
2764 #ifdef CAPABILITIES
2765         seq = seqc_read_any(fd_seqc(fdt, fd));
2766         if (__predict_false(seqc_in_modify(seq)))
2767                 goto out_fallback;
2768         fde = &fdt->fdt_ofiles[fd];
2769         haverights = cap_rights_fde_inline(fde);
2770         fp = fde->fde_file;
2771 #else
2772         fp = fdt->fdt_ofiles[fd].fde_file;
2773 #endif
2774         if (__predict_false(fp == NULL))
2775                 goto out_fallback;
2776 #ifdef CAPABILITIES
2777         if (__predict_false(cap_check_inline_transient(haverights, needrightsp)))
2778                 goto out_fallback;
2779 #endif
2780         if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count)))
2781                 goto out_fallback;
2782
2783         /*
2784          * Use an acquire barrier to force re-reading of fdt so it is
2785          * refreshed for verification.
2786          */
2787         atomic_thread_fence_acq();
2788         fdt = fdp->fd_files;
2789 #ifdef  CAPABILITIES
2790         if (__predict_false(!seqc_consistent_nomb(fd_seqc(fdt, fd), seq)))
2791 #else
2792         if (__predict_false(fp != fdt->fdt_ofiles[fd].fde_file))
2793 #endif
2794                 goto out_fdrop;
2795         *fpp = fp;
2796         return (0);
2797 out_fdrop:
2798         fdrop(fp, curthread);
2799 out_fallback:
2800         return (fget_unlocked_seq(fdp, fd, needrightsp, fpp, NULL));
2801 }
2802
2803 /*
2804  * Extract the file pointer associated with the specified descriptor for the
2805  * current user process.
2806  *
2807  * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2808  * returned.
2809  *
2810  * File's rights will be checked against the capability rights mask.
2811  *
2812  * If an error occurred the non-zero error is returned and *fpp is set to
2813  * NULL.  Otherwise *fpp is held and set and zero is returned.  Caller is
2814  * responsible for fdrop().
2815  */
2816 static __inline int
2817 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2818     cap_rights_t *needrightsp)
2819 {
2820         struct filedesc *fdp;
2821         struct file *fp;
2822         int error;
2823
2824         *fpp = NULL;
2825         fdp = td->td_proc->p_fd;
2826         error = fget_unlocked(fdp, fd, needrightsp, &fp);
2827         if (__predict_false(error != 0))
2828                 return (error);
2829         if (__predict_false(fp->f_ops == &badfileops)) {
2830                 fdrop(fp, td);
2831                 return (EBADF);
2832         }
2833
2834         /*
2835          * FREAD and FWRITE failure return EBADF as per POSIX.
2836          */
2837         error = 0;
2838         switch (flags) {
2839         case FREAD:
2840         case FWRITE:
2841                 if ((fp->f_flag & flags) == 0)
2842                         error = EBADF;
2843                 break;
2844         case FEXEC:
2845                 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2846                     ((fp->f_flag & FWRITE) != 0))
2847                         error = EBADF;
2848                 break;
2849         case 0:
2850                 break;
2851         default:
2852                 KASSERT(0, ("wrong flags"));
2853         }
2854
2855         if (error != 0) {
2856                 fdrop(fp, td);
2857                 return (error);
2858         }
2859
2860         *fpp = fp;
2861         return (0);
2862 }
2863
2864 int
2865 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2866 {
2867
2868         return (_fget(td, fd, fpp, 0, rightsp));
2869 }
2870
2871 int
2872 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, vm_prot_t *maxprotp,
2873     struct file **fpp)
2874 {
2875         int error;
2876 #ifndef CAPABILITIES
2877         error = _fget(td, fd, fpp, 0, rightsp);
2878         if (maxprotp != NULL)
2879                 *maxprotp = VM_PROT_ALL;
2880         return (error);
2881 #else
2882         cap_rights_t fdrights;
2883         struct filedesc *fdp;
2884         struct file *fp;
2885         seqc_t seq;
2886
2887         *fpp = NULL;
2888         fdp = td->td_proc->p_fd;
2889         MPASS(cap_rights_is_set(rightsp, CAP_MMAP));
2890         for (;;) {
2891                 error = fget_unlocked_seq(fdp, fd, rightsp, &fp, &seq);
2892                 if (__predict_false(error != 0))
2893                         return (error);
2894                 if (__predict_false(fp->f_ops == &badfileops)) {
2895                         fdrop(fp, td);
2896                         return (EBADF);
2897                 }
2898                 if (maxprotp != NULL)
2899                         fdrights = *cap_rights(fdp, fd);
2900                 if (!fd_modified(fdp, fd, seq))
2901                         break;
2902                 fdrop(fp, td);
2903         }
2904
2905         /*
2906          * If requested, convert capability rights to access flags.
2907          */
2908         if (maxprotp != NULL)
2909                 *maxprotp = cap_rights_to_vmprot(&fdrights);
2910         *fpp = fp;
2911         return (0);
2912 #endif
2913 }
2914
2915 int
2916 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2917 {
2918
2919         return (_fget(td, fd, fpp, FREAD, rightsp));
2920 }
2921
2922 int
2923 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2924 {
2925
2926         return (_fget(td, fd, fpp, FWRITE, rightsp));
2927 }
2928
2929 int
2930 fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp, int needfcntl,
2931     struct file **fpp)
2932 {
2933         struct filedesc *fdp = td->td_proc->p_fd;
2934 #ifndef CAPABILITIES
2935         return (fget_unlocked(fdp, fd, rightsp, fpp));
2936 #else
2937         struct file *fp;
2938         int error;
2939         seqc_t seq;
2940
2941         *fpp = NULL;
2942         MPASS(cap_rights_is_set(rightsp, CAP_FCNTL));
2943         for (;;) {
2944                 error = fget_unlocked_seq(fdp, fd, rightsp, &fp, &seq);
2945                 if (error != 0)
2946                         return (error);
2947                 error = cap_fcntl_check(fdp, fd, needfcntl);
2948                 if (!fd_modified(fdp, fd, seq))
2949                         break;
2950                 fdrop(fp, td);
2951         }
2952         if (error != 0) {
2953                 fdrop(fp, td);
2954                 return (error);
2955         }
2956         *fpp = fp;
2957         return (0);
2958 #endif
2959 }
2960
2961 /*
2962  * Like fget() but loads the underlying vnode, or returns an error if the
2963  * descriptor does not represent a vnode.  Note that pipes use vnodes but
2964  * never have VM objects.  The returned vnode will be vref()'d.
2965  *
2966  * XXX: what about the unused flags ?
2967  */
2968 static __inline int
2969 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
2970     struct vnode **vpp)
2971 {
2972         struct file *fp;
2973         int error;
2974
2975         *vpp = NULL;
2976         error = _fget(td, fd, &fp, flags, needrightsp);
2977         if (error != 0)
2978                 return (error);
2979         if (fp->f_vnode == NULL) {
2980                 error = EINVAL;
2981         } else {
2982                 *vpp = fp->f_vnode;
2983                 vrefact(*vpp);
2984         }
2985         fdrop(fp, td);
2986
2987         return (error);
2988 }
2989
2990 int
2991 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2992 {
2993
2994         return (_fgetvp(td, fd, 0, rightsp, vpp));
2995 }
2996
2997 int
2998 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
2999     struct filecaps *havecaps, struct vnode **vpp)
3000 {
3001         struct filecaps caps;
3002         struct file *fp;
3003         int error;
3004
3005         error = fget_cap(td, fd, needrightsp, &fp, &caps);
3006         if (error != 0)
3007                 return (error);
3008         if (fp->f_ops == &badfileops) {
3009                 error = EBADF;
3010                 goto out;
3011         }
3012         if (fp->f_vnode == NULL) {
3013                 error = EINVAL;
3014                 goto out;
3015         }
3016
3017         *havecaps = caps;
3018         *vpp = fp->f_vnode;
3019         vrefact(*vpp);
3020         fdrop(fp, td);
3021
3022         return (0);
3023 out:
3024         filecaps_free(&caps);
3025         fdrop(fp, td);
3026         return (error);
3027 }
3028
3029 int
3030 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3031 {
3032
3033         return (_fgetvp(td, fd, FREAD, rightsp, vpp));
3034 }
3035
3036 int
3037 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3038 {
3039
3040         return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
3041 }
3042
3043 #ifdef notyet
3044 int
3045 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
3046     struct vnode **vpp)
3047 {
3048
3049         return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
3050 }
3051 #endif
3052
3053 /*
3054  * Handle the last reference to a file being closed.
3055  *
3056  * Without the noinline attribute clang keeps inlining the func thorough this
3057  * file when fdrop is used.
3058  */
3059 int __noinline
3060 _fdrop(struct file *fp, struct thread *td)
3061 {
3062         int error;
3063
3064         if (fp->f_count != 0)
3065                 panic("fdrop: count %d", fp->f_count);
3066         error = fo_close(fp, td);
3067         atomic_subtract_int(&openfiles, 1);
3068         crfree(fp->f_cred);
3069         free(fp->f_advice, M_FADVISE);
3070         uma_zfree(file_zone, fp);
3071
3072         return (error);
3073 }
3074
3075 /*
3076  * Apply an advisory lock on a file descriptor.
3077  *
3078  * Just attempt to get a record lock of the requested type on the entire file
3079  * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
3080  */
3081 #ifndef _SYS_SYSPROTO_H_
3082 struct flock_args {
3083         int     fd;
3084         int     how;
3085 };
3086 #endif
3087 /* ARGSUSED */
3088 int
3089 sys_flock(struct thread *td, struct flock_args *uap)
3090 {
3091         struct file *fp;
3092         struct vnode *vp;
3093         struct flock lf;
3094         int error;
3095
3096         error = fget(td, uap->fd, &cap_flock_rights, &fp);
3097         if (error != 0)
3098                 return (error);
3099         if (fp->f_type != DTYPE_VNODE) {
3100                 fdrop(fp, td);
3101                 return (EOPNOTSUPP);
3102         }
3103
3104         vp = fp->f_vnode;
3105         lf.l_whence = SEEK_SET;
3106         lf.l_start = 0;
3107         lf.l_len = 0;
3108         if (uap->how & LOCK_UN) {
3109                 lf.l_type = F_UNLCK;
3110                 atomic_clear_int(&fp->f_flag, FHASLOCK);
3111                 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
3112                 goto done2;
3113         }
3114         if (uap->how & LOCK_EX)
3115                 lf.l_type = F_WRLCK;
3116         else if (uap->how & LOCK_SH)
3117                 lf.l_type = F_RDLCK;
3118         else {
3119                 error = EBADF;
3120                 goto done2;
3121         }
3122         atomic_set_int(&fp->f_flag, FHASLOCK);
3123         error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
3124             (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
3125 done2:
3126         fdrop(fp, td);
3127         return (error);
3128 }
3129 /*
3130  * Duplicate the specified descriptor to a free descriptor.
3131  */
3132 int
3133 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
3134     int openerror, int *indxp)
3135 {
3136         struct filedescent *newfde, *oldfde;
3137         struct file *fp;
3138         u_long *ioctls;
3139         int error, indx;
3140
3141         KASSERT(openerror == ENODEV || openerror == ENXIO,
3142             ("unexpected error %d in %s", openerror, __func__));
3143
3144         /*
3145          * If the to-be-dup'd fd number is greater than the allowed number
3146          * of file descriptors, or the fd to be dup'd has already been
3147          * closed, then reject.
3148          */
3149         FILEDESC_XLOCK(fdp);
3150         if ((fp = fget_locked(fdp, dfd)) == NULL) {
3151                 FILEDESC_XUNLOCK(fdp);
3152                 return (EBADF);
3153         }
3154
3155         error = fdalloc(td, 0, &indx);
3156         if (error != 0) {
3157                 FILEDESC_XUNLOCK(fdp);
3158                 return (error);
3159         }
3160
3161         /*
3162          * There are two cases of interest here.
3163          *
3164          * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
3165          *
3166          * For ENXIO steal away the file structure from (dfd) and store it in
3167          * (indx).  (dfd) is effectively closed by this operation.
3168          */
3169         switch (openerror) {
3170         case ENODEV:
3171                 /*
3172                  * Check that the mode the file is being opened for is a
3173                  * subset of the mode of the existing descriptor.
3174                  */
3175                 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
3176                         fdunused(fdp, indx);
3177                         FILEDESC_XUNLOCK(fdp);
3178                         return (EACCES);
3179                 }
3180                 if (!fhold(fp)) {
3181                         fdunused(fdp, indx);
3182                         FILEDESC_XUNLOCK(fdp);
3183                         return (EBADF);
3184                 }
3185                 newfde = &fdp->fd_ofiles[indx];
3186                 oldfde = &fdp->fd_ofiles[dfd];
3187                 ioctls = filecaps_copy_prep(&oldfde->fde_caps);
3188 #ifdef CAPABILITIES
3189                 seqc_write_begin(&newfde->fde_seqc);
3190 #endif
3191                 memcpy(newfde, oldfde, fde_change_size);
3192                 filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
3193                     ioctls);
3194 #ifdef CAPABILITIES
3195                 seqc_write_end(&newfde->fde_seqc);
3196 #endif
3197                 break;
3198         case ENXIO:
3199                 /*
3200                  * Steal away the file pointer from dfd and stuff it into indx.
3201                  */
3202                 newfde = &fdp->fd_ofiles[indx];
3203                 oldfde = &fdp->fd_ofiles[dfd];
3204 #ifdef CAPABILITIES
3205                 seqc_write_begin(&newfde->fde_seqc);
3206 #endif
3207                 memcpy(newfde, oldfde, fde_change_size);
3208                 oldfde->fde_file = NULL;
3209                 fdunused(fdp, dfd);
3210 #ifdef CAPABILITIES
3211                 seqc_write_end(&newfde->fde_seqc);
3212 #endif
3213                 break;
3214         }
3215         FILEDESC_XUNLOCK(fdp);
3216         *indxp = indx;
3217         return (0);
3218 }
3219
3220 /*
3221  * This sysctl determines if we will allow a process to chroot(2) if it
3222  * has a directory open:
3223  *      0: disallowed for all processes.
3224  *      1: allowed for processes that were not already chroot(2)'ed.
3225  *      2: allowed for all processes.
3226  */
3227
3228 static int chroot_allow_open_directories = 1;
3229
3230 SYSCTL_INT(_kern, OID_AUTO, chroot_allow_open_directories, CTLFLAG_RW,
3231     &chroot_allow_open_directories, 0,
3232     "Allow a process to chroot(2) if it has a directory open");
3233
3234 /*
3235  * Helper function for raised chroot(2) security function:  Refuse if
3236  * any filedescriptors are open directories.
3237  */
3238 static int
3239 chroot_refuse_vdir_fds(struct filedesc *fdp)
3240 {
3241         struct vnode *vp;
3242         struct file *fp;
3243         int fd;
3244
3245         FILEDESC_LOCK_ASSERT(fdp);
3246
3247         for (fd = 0; fd <= fdp->fd_lastfile; fd++) {
3248                 fp = fget_locked(fdp, fd);
3249                 if (fp == NULL)
3250                         continue;
3251                 if (fp->f_type == DTYPE_VNODE) {
3252                         vp = fp->f_vnode;
3253                         if (vp->v_type == VDIR)
3254                                 return (EPERM);
3255                 }
3256         }
3257         return (0);
3258 }
3259
3260 static void
3261 pwd_fill(struct pwd *oldpwd, struct pwd *newpwd)
3262 {
3263
3264         if (newpwd->pwd_cdir == NULL && oldpwd->pwd_cdir != NULL) {
3265                 vrefact(oldpwd->pwd_cdir);
3266                 newpwd->pwd_cdir = oldpwd->pwd_cdir;
3267         }
3268
3269         if (newpwd->pwd_rdir == NULL && oldpwd->pwd_rdir != NULL) {
3270                 vrefact(oldpwd->pwd_rdir);
3271                 newpwd->pwd_rdir = oldpwd->pwd_rdir;
3272         }
3273
3274         if (newpwd->pwd_jdir == NULL && oldpwd->pwd_jdir != NULL) {
3275                 vrefact(oldpwd->pwd_jdir);
3276                 newpwd->pwd_jdir = oldpwd->pwd_jdir;
3277         }
3278 }
3279
3280 struct pwd *
3281 pwd_hold_filedesc(struct filedesc *fdp)
3282 {
3283         struct pwd *pwd;
3284
3285         FILEDESC_LOCK_ASSERT(fdp);
3286         pwd = FILEDESC_LOCKED_LOAD_PWD(fdp);
3287         if (pwd != NULL)
3288                 refcount_acquire(&pwd->pwd_refcount);
3289         return (pwd);
3290 }
3291
3292 struct pwd *
3293 pwd_hold(struct thread *td)
3294 {
3295         struct filedesc *fdp;
3296         struct pwd *pwd;
3297
3298         fdp = td->td_proc->p_fd;
3299
3300         smr_enter(pwd_smr);
3301         for (;;) {
3302                 pwd = smr_entered_load(&fdp->fd_pwd, pwd_smr);
3303                 MPASS(pwd != NULL);
3304                 if (refcount_acquire_if_not_zero(&pwd->pwd_refcount))
3305                         break;
3306         }
3307         smr_exit(pwd_smr);
3308         return (pwd);
3309 }
3310
3311 static struct pwd *
3312 pwd_alloc(void)
3313 {
3314         struct pwd *pwd;
3315
3316         pwd = uma_zalloc_smr(pwd_zone, M_WAITOK);
3317         bzero(pwd, sizeof(*pwd));
3318         refcount_init(&pwd->pwd_refcount, 1);
3319         return (pwd);
3320 }
3321
3322 void
3323 pwd_drop(struct pwd *pwd)
3324 {
3325
3326         if (!refcount_release(&pwd->pwd_refcount))
3327                 return;
3328
3329         if (pwd->pwd_cdir != NULL)
3330                 vrele(pwd->pwd_cdir);
3331         if (pwd->pwd_rdir != NULL)
3332                 vrele(pwd->pwd_rdir);
3333         if (pwd->pwd_jdir != NULL)
3334                 vrele(pwd->pwd_jdir);
3335         uma_zfree_smr(pwd_zone, pwd);
3336 }
3337
3338 /*
3339 * Common routine for kern_chroot() and jail_attach().  The caller is
3340 * responsible for invoking priv_check() and mac_vnode_check_chroot() to
3341 * authorize this operation.
3342 */
3343 int
3344 pwd_chroot(struct thread *td, struct vnode *vp)
3345 {
3346         struct filedesc *fdp;
3347         struct pwd *newpwd, *oldpwd;
3348         int error;
3349
3350         fdp = td->td_proc->p_fd;
3351         newpwd = pwd_alloc();
3352         FILEDESC_XLOCK(fdp);
3353         oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3354         if (chroot_allow_open_directories == 0 ||
3355             (chroot_allow_open_directories == 1 &&
3356             oldpwd->pwd_rdir != rootvnode)) {
3357                 error = chroot_refuse_vdir_fds(fdp);
3358                 if (error != 0) {
3359                         FILEDESC_XUNLOCK(fdp);
3360                         pwd_drop(newpwd);
3361                         return (error);
3362                 }
3363         }
3364
3365         vrefact(vp);
3366         newpwd->pwd_rdir = vp;
3367         if (oldpwd->pwd_jdir == NULL) {
3368                 vrefact(vp);
3369                 newpwd->pwd_jdir = vp;
3370         }
3371         pwd_fill(oldpwd, newpwd);
3372         pwd_set(fdp, newpwd);
3373         FILEDESC_XUNLOCK(fdp);
3374         pwd_drop(oldpwd);
3375         return (0);
3376 }
3377
3378 void
3379 pwd_chdir(struct thread *td, struct vnode *vp)
3380 {
3381         struct filedesc *fdp;
3382         struct pwd *newpwd, *oldpwd;
3383
3384         VNPASS(vp->v_usecount > 0, vp);
3385
3386         newpwd = pwd_alloc();
3387         fdp = td->td_proc->p_fd;
3388         FILEDESC_XLOCK(fdp);
3389         oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3390         newpwd->pwd_cdir = vp;
3391         pwd_fill(oldpwd, newpwd);
3392         pwd_set(fdp, newpwd);
3393         FILEDESC_XUNLOCK(fdp);
3394         pwd_drop(oldpwd);
3395 }
3396
3397 void
3398 pwd_ensure_dirs(void)
3399 {
3400         struct filedesc *fdp;
3401         struct pwd *oldpwd, *newpwd;
3402
3403         fdp = curproc->p_fd;
3404         FILEDESC_XLOCK(fdp);
3405         oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3406         if (oldpwd->pwd_cdir != NULL && oldpwd->pwd_rdir != NULL) {
3407                 FILEDESC_XUNLOCK(fdp);
3408                 return;
3409         }
3410         FILEDESC_XUNLOCK(fdp);
3411
3412         newpwd = pwd_alloc();
3413         FILEDESC_XLOCK(fdp);
3414         oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3415         pwd_fill(oldpwd, newpwd);
3416         if (newpwd->pwd_cdir == NULL) {
3417                 vrefact(rootvnode);
3418                 newpwd->pwd_cdir = rootvnode;
3419         }
3420         if (newpwd->pwd_rdir == NULL) {
3421                 vrefact(rootvnode);
3422                 newpwd->pwd_rdir = rootvnode;
3423         }
3424         pwd_set(fdp, newpwd);
3425         FILEDESC_XUNLOCK(fdp);
3426         pwd_drop(oldpwd);
3427 }
3428
3429 /*
3430  * Scan all active processes and prisons to see if any of them have a current
3431  * or root directory of `olddp'. If so, replace them with the new mount point.
3432  */
3433 void
3434 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
3435 {
3436         struct filedesc *fdp;
3437         struct pwd *newpwd, *oldpwd;
3438         struct prison *pr;
3439         struct proc *p;
3440         int nrele;
3441
3442         if (vrefcnt(olddp) == 1)
3443                 return;
3444         nrele = 0;
3445         newpwd = pwd_alloc();
3446         sx_slock(&allproc_lock);
3447         FOREACH_PROC_IN_SYSTEM(p) {
3448                 PROC_LOCK(p);
3449                 fdp = fdhold(p);
3450                 PROC_UNLOCK(p);
3451                 if (fdp == NULL)
3452                         continue;
3453                 FILEDESC_XLOCK(fdp);
3454                 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3455                 if (oldpwd == NULL ||
3456                     (oldpwd->pwd_cdir != olddp &&
3457                     oldpwd->pwd_rdir != olddp &&
3458                     oldpwd->pwd_jdir != olddp)) {
3459                         FILEDESC_XUNLOCK(fdp);
3460                         fddrop(fdp);
3461                         continue;
3462                 }
3463                 if (oldpwd->pwd_cdir == olddp) {
3464                         vrefact(newdp);
3465                         newpwd->pwd_cdir = newdp;
3466                 }
3467                 if (oldpwd->pwd_rdir == olddp) {
3468                         vrefact(newdp);
3469                         newpwd->pwd_rdir = newdp;
3470                 }
3471                 if (oldpwd->pwd_jdir == olddp) {
3472                         vrefact(newdp);
3473                         newpwd->pwd_jdir = newdp;
3474                 }
3475                 pwd_fill(oldpwd, newpwd);
3476                 pwd_set(fdp, newpwd);
3477                 FILEDESC_XUNLOCK(fdp);
3478                 pwd_drop(oldpwd);
3479                 fddrop(fdp);
3480                 newpwd = pwd_alloc();
3481         }
3482         sx_sunlock(&allproc_lock);
3483         pwd_drop(newpwd);
3484         if (rootvnode == olddp) {
3485                 vrefact(newdp);
3486                 rootvnode = newdp;
3487                 nrele++;
3488         }
3489         mtx_lock(&prison0.pr_mtx);
3490         if (prison0.pr_root == olddp) {
3491                 vrefact(newdp);
3492                 prison0.pr_root = newdp;
3493                 nrele++;
3494         }
3495         mtx_unlock(&prison0.pr_mtx);
3496         sx_slock(&allprison_lock);
3497         TAILQ_FOREACH(pr, &allprison, pr_list) {
3498                 mtx_lock(&pr->pr_mtx);
3499                 if (pr->pr_root == olddp) {
3500                         vrefact(newdp);
3501                         pr->pr_root = newdp;
3502                         nrele++;
3503                 }
3504                 mtx_unlock(&pr->pr_mtx);
3505         }
3506         sx_sunlock(&allprison_lock);
3507         while (nrele--)
3508                 vrele(olddp);
3509 }
3510
3511 struct filedesc_to_leader *
3512 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
3513 {
3514         struct filedesc_to_leader *fdtol;
3515
3516         fdtol = malloc(sizeof(struct filedesc_to_leader),
3517             M_FILEDESC_TO_LEADER, M_WAITOK);
3518         fdtol->fdl_refcount = 1;
3519         fdtol->fdl_holdcount = 0;
3520         fdtol->fdl_wakeup = 0;
3521         fdtol->fdl_leader = leader;
3522         if (old != NULL) {
3523                 FILEDESC_XLOCK(fdp);
3524                 fdtol->fdl_next = old->fdl_next;
3525                 fdtol->fdl_prev = old;
3526                 old->fdl_next = fdtol;
3527                 fdtol->fdl_next->fdl_prev = fdtol;
3528                 FILEDESC_XUNLOCK(fdp);
3529         } else {
3530                 fdtol->fdl_next = fdtol;
3531                 fdtol->fdl_prev = fdtol;
3532         }
3533         return (fdtol);
3534 }
3535
3536 static int
3537 sysctl_kern_proc_nfds(SYSCTL_HANDLER_ARGS)
3538 {
3539         struct filedesc *fdp;
3540         int i, count, slots;
3541
3542         if (*(int *)arg1 != 0)
3543                 return (EINVAL);
3544
3545         fdp = curproc->p_fd;
3546         count = 0;
3547         FILEDESC_SLOCK(fdp);
3548         slots = NDSLOTS(fdp->fd_lastfile + 1);
3549         for (i = 0; i < slots; i++)
3550                 count += bitcountl(fdp->fd_map[i]);
3551         FILEDESC_SUNLOCK(fdp);
3552
3553         return (SYSCTL_OUT(req, &count, sizeof(count)));
3554 }
3555
3556 static SYSCTL_NODE(_kern_proc, KERN_PROC_NFDS, nfds,
3557     CTLFLAG_RD|CTLFLAG_CAPRD|CTLFLAG_MPSAFE, sysctl_kern_proc_nfds,
3558     "Number of open file descriptors");
3559
3560 /*
3561  * Get file structures globally.
3562  */
3563 static int
3564 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
3565 {
3566         struct xfile xf;
3567         struct filedesc *fdp;
3568         struct file *fp;
3569         struct proc *p;
3570         int error, n;
3571
3572         error = sysctl_wire_old_buffer(req, 0);
3573         if (error != 0)
3574                 return (error);
3575         if (req->oldptr == NULL) {
3576                 n = 0;
3577                 sx_slock(&allproc_lock);
3578                 FOREACH_PROC_IN_SYSTEM(p) {
3579                         PROC_LOCK(p);
3580                         if (p->p_state == PRS_NEW) {
3581                                 PROC_UNLOCK(p);
3582                                 continue;
3583                         }
3584                         fdp = fdhold(p);
3585                         PROC_UNLOCK(p);
3586                         if (fdp == NULL)
3587                                 continue;
3588                         /* overestimates sparse tables. */
3589                         if (fdp->fd_lastfile > 0)
3590                                 n += fdp->fd_lastfile;
3591                         fddrop(fdp);
3592                 }
3593                 sx_sunlock(&allproc_lock);
3594                 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
3595         }
3596         error = 0;
3597         bzero(&xf, sizeof(xf));
3598         xf.xf_size = sizeof(xf);
3599         sx_slock(&allproc_lock);
3600         FOREACH_PROC_IN_SYSTEM(p) {
3601                 PROC_LOCK(p);
3602                 if (p->p_state == PRS_NEW) {
3603                         PROC_UNLOCK(p);
3604                         continue;
3605                 }
3606                 if (p_cansee(req->td, p) != 0) {
3607                         PROC_UNLOCK(p);
3608                         continue;
3609                 }
3610                 xf.xf_pid = p->p_pid;
3611                 xf.xf_uid = p->p_ucred->cr_uid;
3612                 fdp = fdhold(p);
3613                 PROC_UNLOCK(p);
3614                 if (fdp == NULL)
3615                         continue;
3616                 FILEDESC_SLOCK(fdp);
3617                 for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) {
3618                         if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3619                                 continue;
3620                         xf.xf_fd = n;
3621                         xf.xf_file = (uintptr_t)fp;
3622                         xf.xf_data = (uintptr_t)fp->f_data;
3623                         xf.xf_vnode = (uintptr_t)fp->f_vnode;
3624                         xf.xf_type = (uintptr_t)fp->f_type;
3625                         xf.xf_count = fp->f_count;
3626                         xf.xf_msgcount = 0;
3627                         xf.xf_offset = foffset_get(fp);
3628                         xf.xf_flag = fp->f_flag;
3629                         error = SYSCTL_OUT(req, &xf, sizeof(xf));
3630                         if (error)
3631                                 break;
3632                 }
3633                 FILEDESC_SUNLOCK(fdp);
3634                 fddrop(fdp);
3635                 if (error)
3636                         break;
3637         }
3638         sx_sunlock(&allproc_lock);
3639         return (error);
3640 }
3641
3642 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
3643     0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
3644
3645 #ifdef KINFO_FILE_SIZE
3646 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3647 #endif
3648
3649 static int
3650 xlate_fflags(int fflags)
3651 {
3652         static const struct {
3653                 int     fflag;
3654                 int     kf_fflag;
3655         } fflags_table[] = {
3656                 { FAPPEND, KF_FLAG_APPEND },
3657                 { FASYNC, KF_FLAG_ASYNC },
3658                 { FFSYNC, KF_FLAG_FSYNC },
3659                 { FHASLOCK, KF_FLAG_HASLOCK },
3660                 { FNONBLOCK, KF_FLAG_NONBLOCK },
3661                 { FREAD, KF_FLAG_READ },
3662                 { FWRITE, KF_FLAG_WRITE },
3663                 { O_CREAT, KF_FLAG_CREAT },
3664                 { O_DIRECT, KF_FLAG_DIRECT },
3665                 { O_EXCL, KF_FLAG_EXCL },
3666                 { O_EXEC, KF_FLAG_EXEC },
3667                 { O_EXLOCK, KF_FLAG_EXLOCK },
3668                 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3669                 { O_SHLOCK, KF_FLAG_SHLOCK },
3670                 { O_TRUNC, KF_FLAG_TRUNC }
3671         };
3672         unsigned int i;
3673         int kflags;
3674
3675         kflags = 0;
3676         for (i = 0; i < nitems(fflags_table); i++)
3677                 if (fflags & fflags_table[i].fflag)
3678                         kflags |=  fflags_table[i].kf_fflag;
3679         return (kflags);
3680 }
3681
3682 /* Trim unused data from kf_path by truncating the structure size. */
3683 void
3684 pack_kinfo(struct kinfo_file *kif)
3685 {
3686
3687         kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3688             strlen(kif->kf_path) + 1;
3689         kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3690 }
3691
3692 static void
3693 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp,
3694     struct kinfo_file *kif, struct filedesc *fdp, int flags)
3695 {
3696         int error;
3697
3698         bzero(kif, sizeof(*kif));
3699
3700         /* Set a default type to allow for empty fill_kinfo() methods. */
3701         kif->kf_type = KF_TYPE_UNKNOWN;
3702         kif->kf_flags = xlate_fflags(fp->f_flag);
3703         if (rightsp != NULL)
3704                 kif->kf_cap_rights = *rightsp;
3705         else
3706                 cap_rights_init_zero(&kif->kf_cap_rights);
3707         kif->kf_fd = fd;
3708         kif->kf_ref_count = fp->f_count;
3709         kif->kf_offset = foffset_get(fp);
3710
3711         /*
3712          * This may drop the filedesc lock, so the 'fp' cannot be
3713          * accessed after this call.
3714          */
3715         error = fo_fill_kinfo(fp, kif, fdp);
3716         if (error == 0)
3717                 kif->kf_status |= KF_ATTR_VALID;
3718         if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3719                 pack_kinfo(kif);
3720         else
3721                 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3722 }
3723
3724 static void
3725 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags,
3726     struct kinfo_file *kif, int flags)
3727 {
3728         int error;
3729
3730         bzero(kif, sizeof(*kif));
3731
3732         kif->kf_type = KF_TYPE_VNODE;
3733         error = vn_fill_kinfo_vnode(vp, kif);
3734         if (error == 0)
3735                 kif->kf_status |= KF_ATTR_VALID;
3736         kif->kf_flags = xlate_fflags(fflags);
3737         cap_rights_init_zero(&kif->kf_cap_rights);
3738         kif->kf_fd = fd;
3739         kif->kf_ref_count = -1;
3740         kif->kf_offset = -1;
3741         if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3742                 pack_kinfo(kif);
3743         else
3744                 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3745         vrele(vp);
3746 }
3747
3748 struct export_fd_buf {
3749         struct filedesc         *fdp;
3750         struct sbuf             *sb;
3751         ssize_t                 remainder;
3752         struct kinfo_file       kif;
3753         int                     flags;
3754 };
3755
3756 static int
3757 export_kinfo_to_sb(struct export_fd_buf *efbuf)
3758 {
3759         struct kinfo_file *kif;
3760
3761         kif = &efbuf->kif;
3762         if (efbuf->remainder != -1) {
3763                 if (efbuf->remainder < kif->kf_structsize) {
3764                         /* Terminate export. */
3765                         efbuf->remainder = 0;
3766                         return (0);
3767                 }
3768                 efbuf->remainder -= kif->kf_structsize;
3769         }
3770         return (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) == 0 ? 0 : ENOMEM);
3771 }
3772
3773 static int
3774 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp,
3775     struct export_fd_buf *efbuf)
3776 {
3777         int error;
3778
3779         if (efbuf->remainder == 0)
3780                 return (0);
3781         export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp,
3782             efbuf->flags);
3783         FILEDESC_SUNLOCK(efbuf->fdp);
3784         error = export_kinfo_to_sb(efbuf);
3785         FILEDESC_SLOCK(efbuf->fdp);
3786         return (error);
3787 }
3788
3789 static int
3790 export_vnode_to_sb(struct vnode *vp, int fd, int fflags,
3791     struct export_fd_buf *efbuf)
3792 {
3793         int error;
3794
3795         if (efbuf->remainder == 0)
3796                 return (0);
3797         if (efbuf->fdp != NULL)
3798                 FILEDESC_SUNLOCK(efbuf->fdp);
3799         export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif, efbuf->flags);
3800         error = export_kinfo_to_sb(efbuf);
3801         if (efbuf->fdp != NULL)
3802                 FILEDESC_SLOCK(efbuf->fdp);
3803         return (error);
3804 }
3805
3806 /*
3807  * Store a process file descriptor information to sbuf.
3808  *
3809  * Takes a locked proc as argument, and returns with the proc unlocked.
3810  */
3811 int
3812 kern_proc_filedesc_out(struct proc *p,  struct sbuf *sb, ssize_t maxlen,
3813     int flags)
3814 {
3815         struct file *fp;
3816         struct filedesc *fdp;
3817         struct export_fd_buf *efbuf;
3818         struct vnode *cttyvp, *textvp, *tracevp;
3819         struct pwd *pwd;
3820         int error, i;
3821         cap_rights_t rights;
3822
3823         PROC_LOCK_ASSERT(p, MA_OWNED);
3824
3825         /* ktrace vnode */
3826         tracevp = p->p_tracevp;
3827         if (tracevp != NULL)
3828                 vrefact(tracevp);
3829         /* text vnode */
3830         textvp = p->p_textvp;
3831         if (textvp != NULL)
3832                 vrefact(textvp);
3833         /* Controlling tty. */
3834         cttyvp = NULL;
3835         if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3836                 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3837                 if (cttyvp != NULL)
3838                         vrefact(cttyvp);
3839         }
3840         fdp = fdhold(p);
3841         PROC_UNLOCK(p);
3842         efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3843         efbuf->fdp = NULL;
3844         efbuf->sb = sb;
3845         efbuf->remainder = maxlen;
3846         efbuf->flags = flags;
3847         if (tracevp != NULL)
3848                 export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE, FREAD | FWRITE,
3849                     efbuf);
3850         if (textvp != NULL)
3851                 export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD, efbuf);
3852         if (cttyvp != NULL)
3853                 export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY, FREAD | FWRITE,
3854                     efbuf);
3855         error = 0;
3856         if (fdp == NULL)
3857                 goto fail;
3858         efbuf->fdp = fdp;
3859         FILEDESC_SLOCK(fdp);
3860         pwd = pwd_hold_filedesc(fdp);
3861         if (pwd != NULL) {
3862                 /* working directory */
3863                 if (pwd->pwd_cdir != NULL) {
3864                         vrefact(pwd->pwd_cdir);
3865                         export_vnode_to_sb(pwd->pwd_cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
3866                 }
3867                 /* root directory */
3868                 if (pwd->pwd_rdir != NULL) {
3869                         vrefact(pwd->pwd_rdir);
3870                         export_vnode_to_sb(pwd->pwd_rdir, KF_FD_TYPE_ROOT, FREAD, efbuf);
3871                 }
3872                 /* jail directory */
3873                 if (pwd->pwd_jdir != NULL) {
3874                         vrefact(pwd->pwd_jdir);
3875                         export_vnode_to_sb(pwd->pwd_jdir, KF_FD_TYPE_JAIL, FREAD, efbuf);
3876                 }
3877                 pwd_drop(pwd);
3878         }
3879         for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3880                 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3881                         continue;
3882 #ifdef CAPABILITIES
3883                 rights = *cap_rights(fdp, i);
3884 #else /* !CAPABILITIES */
3885                 rights = cap_no_rights;
3886 #endif
3887                 /*
3888                  * Create sysctl entry.  It is OK to drop the filedesc
3889                  * lock inside of export_file_to_sb() as we will
3890                  * re-validate and re-evaluate its properties when the
3891                  * loop continues.
3892                  */
3893                 error = export_file_to_sb(fp, i, &rights, efbuf);
3894                 if (error != 0 || efbuf->remainder == 0)
3895                         break;
3896         }
3897         FILEDESC_SUNLOCK(fdp);
3898         fddrop(fdp);
3899 fail:
3900         free(efbuf, M_TEMP);
3901         return (error);
3902 }
3903
3904 #define FILEDESC_SBUF_SIZE      (sizeof(struct kinfo_file) * 5)
3905
3906 /*
3907  * Get per-process file descriptors for use by procstat(1), et al.
3908  */
3909 static int
3910 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3911 {
3912         struct sbuf sb;
3913         struct proc *p;
3914         ssize_t maxlen;
3915         int error, error2, *name;
3916
3917         name = (int *)arg1;
3918
3919         sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3920         sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
3921         error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3922         if (error != 0) {
3923                 sbuf_delete(&sb);
3924                 return (error);
3925         }
3926         maxlen = req->oldptr != NULL ? req->oldlen : -1;
3927         error = kern_proc_filedesc_out(p, &sb, maxlen,
3928             KERN_FILEDESC_PACK_KINFO);
3929         error2 = sbuf_finish(&sb);
3930         sbuf_delete(&sb);
3931         return (error != 0 ? error : error2);
3932 }
3933
3934 #ifdef COMPAT_FREEBSD7
3935 #ifdef KINFO_OFILE_SIZE
3936 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
3937 #endif
3938
3939 static void
3940 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif)
3941 {
3942
3943         okif->kf_structsize = sizeof(*okif);
3944         okif->kf_type = kif->kf_type;
3945         okif->kf_fd = kif->kf_fd;
3946         okif->kf_ref_count = kif->kf_ref_count;
3947         okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE |
3948             KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK |
3949             KF_FLAG_DIRECT | KF_FLAG_HASLOCK);
3950         okif->kf_offset = kif->kf_offset;
3951         if (kif->kf_type == KF_TYPE_VNODE)
3952                 okif->kf_vnode_type = kif->kf_un.kf_file.kf_file_type;
3953         else
3954                 okif->kf_vnode_type = KF_VTYPE_VNON;
3955         strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path));
3956         if (kif->kf_type == KF_TYPE_SOCKET) {
3957                 okif->kf_sock_domain = kif->kf_un.kf_sock.kf_sock_domain0;
3958                 okif->kf_sock_type = kif->kf_un.kf_sock.kf_sock_type0;
3959                 okif->kf_sock_protocol = kif->kf_un.kf_sock.kf_sock_protocol0;
3960                 okif->kf_sa_local = kif->kf_un.kf_sock.kf_sa_local;
3961                 okif->kf_sa_peer = kif->kf_un.kf_sock.kf_sa_peer;
3962         } else {
3963                 okif->kf_sa_local.ss_family = AF_UNSPEC;
3964                 okif->kf_sa_peer.ss_family = AF_UNSPEC;
3965         }
3966 }
3967
3968 static int
3969 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif,
3970     struct kinfo_ofile *okif, struct filedesc *fdp, struct sysctl_req *req)
3971 {
3972         int error;
3973
3974         vrefact(vp);
3975         FILEDESC_SUNLOCK(fdp);
3976         export_vnode_to_kinfo(vp, type, 0, kif, KERN_FILEDESC_PACK_KINFO);
3977         kinfo_to_okinfo(kif, okif);
3978         error = SYSCTL_OUT(req, okif, sizeof(*okif));
3979         FILEDESC_SLOCK(fdp);
3980         return (error);
3981 }
3982
3983 /*
3984  * Get per-process file descriptors for use by procstat(1), et al.
3985  */
3986 static int
3987 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3988 {
3989         struct kinfo_ofile *okif;
3990         struct kinfo_file *kif;
3991         struct filedesc *fdp;
3992         struct pwd *pwd;
3993         int error, i, *name;
3994         struct file *fp;
3995         struct proc *p;
3996
3997         name = (int *)arg1;
3998         error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3999         if (error != 0)
4000                 return (error);
4001         fdp = fdhold(p);
4002         PROC_UNLOCK(p);
4003         if (fdp == NULL)
4004                 return (ENOENT);
4005         kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
4006         okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK);
4007         FILEDESC_SLOCK(fdp);
4008         pwd = pwd_hold_filedesc(fdp);
4009         if (pwd != NULL) {
4010                 if (pwd->pwd_cdir != NULL)
4011                         export_vnode_for_osysctl(pwd->pwd_cdir, KF_FD_TYPE_CWD, kif,
4012                             okif, fdp, req);
4013                 if (pwd->pwd_rdir != NULL)
4014                         export_vnode_for_osysctl(pwd->pwd_rdir, KF_FD_TYPE_ROOT, kif,
4015                             okif, fdp, req);
4016                 if (pwd->pwd_jdir != NULL)
4017                         export_vnode_for_osysctl(pwd->pwd_jdir, KF_FD_TYPE_JAIL, kif,
4018                             okif, fdp, req);
4019                 pwd_drop(pwd);
4020         }
4021         for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
4022                 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
4023                         continue;
4024                 export_file_to_kinfo(fp, i, NULL, kif, fdp,
4025                     KERN_FILEDESC_PACK_KINFO);
4026                 FILEDESC_SUNLOCK(fdp);
4027                 kinfo_to_okinfo(kif, okif);
4028                 error = SYSCTL_OUT(req, okif, sizeof(*okif));
4029                 FILEDESC_SLOCK(fdp);
4030                 if (error)
4031                         break;
4032         }
4033         FILEDESC_SUNLOCK(fdp);
4034         fddrop(fdp);
4035         free(kif, M_TEMP);
4036         free(okif, M_TEMP);
4037         return (0);
4038 }
4039
4040 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
4041     CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
4042     "Process ofiledesc entries");
4043 #endif  /* COMPAT_FREEBSD7 */
4044
4045 int
4046 vntype_to_kinfo(int vtype)
4047 {
4048         struct {
4049                 int     vtype;
4050                 int     kf_vtype;
4051         } vtypes_table[] = {
4052                 { VBAD, KF_VTYPE_VBAD },
4053                 { VBLK, KF_VTYPE_VBLK },
4054                 { VCHR, KF_VTYPE_VCHR },
4055                 { VDIR, KF_VTYPE_VDIR },
4056                 { VFIFO, KF_VTYPE_VFIFO },
4057                 { VLNK, KF_VTYPE_VLNK },
4058                 { VNON, KF_VTYPE_VNON },
4059                 { VREG, KF_VTYPE_VREG },
4060                 { VSOCK, KF_VTYPE_VSOCK }
4061         };
4062         unsigned int i;
4063
4064         /*
4065          * Perform vtype translation.
4066          */
4067         for (i = 0; i < nitems(vtypes_table); i++)
4068                 if (vtypes_table[i].vtype == vtype)
4069                         return (vtypes_table[i].kf_vtype);
4070
4071         return (KF_VTYPE_UNKNOWN);
4072 }
4073
4074 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
4075     CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
4076     "Process filedesc entries");
4077
4078 /*
4079  * Store a process current working directory information to sbuf.
4080  *
4081  * Takes a locked proc as argument, and returns with the proc unlocked.
4082  */
4083 int
4084 kern_proc_cwd_out(struct proc *p,  struct sbuf *sb, ssize_t maxlen)
4085 {
4086         struct filedesc *fdp;
4087         struct pwd *pwd;
4088         struct export_fd_buf *efbuf;
4089         struct vnode *cdir;
4090         int error;
4091
4092         PROC_LOCK_ASSERT(p, MA_OWNED);
4093
4094         fdp = fdhold(p);
4095         PROC_UNLOCK(p);
4096         if (fdp == NULL)
4097                 return (EINVAL);
4098
4099         efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
4100         efbuf->fdp = fdp;
4101         efbuf->sb = sb;
4102         efbuf->remainder = maxlen;
4103
4104         FILEDESC_SLOCK(fdp);
4105         pwd = FILEDESC_LOCKED_LOAD_PWD(fdp);
4106         cdir = pwd->pwd_cdir;
4107         if (cdir == NULL) {
4108                 error = EINVAL;
4109         } else {
4110                 vrefact(cdir);
4111                 error = export_vnode_to_sb(cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
4112         }
4113         FILEDESC_SUNLOCK(fdp);
4114         fddrop(fdp);
4115         free(efbuf, M_TEMP);
4116         return (error);
4117 }
4118
4119 /*
4120  * Get per-process current working directory.
4121  */
4122 static int
4123 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
4124 {
4125         struct sbuf sb;
4126         struct proc *p;
4127         ssize_t maxlen;
4128         int error, error2, *name;
4129
4130         name = (int *)arg1;
4131
4132         sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req);
4133         sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
4134         error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4135         if (error != 0) {
4136                 sbuf_delete(&sb);
4137                 return (error);
4138         }
4139         maxlen = req->oldptr != NULL ? req->oldlen : -1;
4140         error = kern_proc_cwd_out(p, &sb, maxlen);
4141         error2 = sbuf_finish(&sb);
4142         sbuf_delete(&sb);
4143         return (error != 0 ? error : error2);
4144 }
4145
4146 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE,
4147     sysctl_kern_proc_cwd, "Process current working directory");
4148
4149 #ifdef DDB
4150 /*
4151  * For the purposes of debugging, generate a human-readable string for the
4152  * file type.
4153  */
4154 static const char *
4155 file_type_to_name(short type)
4156 {
4157
4158         switch (type) {
4159         case 0:
4160                 return ("zero");
4161         case DTYPE_VNODE:
4162                 return ("vnode");
4163         case DTYPE_SOCKET:
4164                 return ("socket");
4165         case DTYPE_PIPE:
4166                 return ("pipe");
4167         case DTYPE_FIFO:
4168                 return ("fifo");
4169         case DTYPE_KQUEUE:
4170                 return ("kqueue");
4171         case DTYPE_CRYPTO:
4172                 return ("crypto");
4173         case DTYPE_MQUEUE:
4174                 return ("mqueue");
4175         case DTYPE_SHM:
4176                 return ("shm");
4177         case DTYPE_SEM:
4178                 return ("ksem");
4179         case DTYPE_PTS:
4180                 return ("pts");
4181         case DTYPE_DEV:
4182                 return ("dev");
4183         case DTYPE_PROCDESC:
4184                 return ("proc");
4185         case DTYPE_LINUXEFD:
4186                 return ("levent");
4187         case DTYPE_LINUXTFD:
4188                 return ("ltimer");
4189         default:
4190                 return ("unkn");
4191         }
4192 }
4193
4194 /*
4195  * For the purposes of debugging, identify a process (if any, perhaps one of
4196  * many) that references the passed file in its file descriptor array. Return
4197  * NULL if none.
4198  */
4199 static struct proc *
4200 file_to_first_proc(struct file *fp)
4201 {
4202         struct filedesc *fdp;
4203         struct proc *p;
4204         int n;
4205
4206         FOREACH_PROC_IN_SYSTEM(p) {
4207                 if (p->p_state == PRS_NEW)
4208                         continue;
4209                 fdp = p->p_fd;
4210                 if (fdp == NULL)
4211                         continue;
4212                 for (n = 0; n <= fdp->fd_lastfile; n++) {
4213                         if (fp == fdp->fd_ofiles[n].fde_file)
4214                                 return (p);
4215                 }
4216         }
4217         return (NULL);
4218 }
4219
4220 static void
4221 db_print_file(struct file *fp, int header)
4222 {
4223 #define XPTRWIDTH ((int)howmany(sizeof(void *) * NBBY, 4))
4224         struct proc *p;
4225
4226         if (header)
4227                 db_printf("%*s %6s %*s %8s %4s %5s %6s %*s %5s %s\n",
4228                     XPTRWIDTH, "File", "Type", XPTRWIDTH, "Data", "Flag",
4229                     "GCFl", "Count", "MCount", XPTRWIDTH, "Vnode", "FPID",
4230                     "FCmd");
4231         p = file_to_first_proc(fp);
4232         db_printf("%*p %6s %*p %08x %04x %5d %6d %*p %5d %s\n", XPTRWIDTH,
4233             fp, file_type_to_name(fp->f_type), XPTRWIDTH, fp->f_data,
4234             fp->f_flag, 0, fp->f_count, 0, XPTRWIDTH, fp->f_vnode,
4235             p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
4236
4237 #undef XPTRWIDTH
4238 }
4239
4240 DB_SHOW_COMMAND(file, db_show_file)
4241 {
4242         struct file *fp;
4243
4244         if (!have_addr) {
4245                 db_printf("usage: show file <addr>\n");
4246                 return;
4247         }
4248         fp = (struct file *)addr;
4249         db_print_file(fp, 1);
4250 }
4251
4252 DB_SHOW_COMMAND(files, db_show_files)
4253 {
4254         struct filedesc *fdp;
4255         struct file *fp;
4256         struct proc *p;
4257         int header;
4258         int n;
4259
4260         header = 1;
4261         FOREACH_PROC_IN_SYSTEM(p) {
4262                 if (p->p_state == PRS_NEW)
4263                         continue;
4264                 if ((fdp = p->p_fd) == NULL)
4265                         continue;
4266                 for (n = 0; n <= fdp->fd_lastfile; ++n) {
4267                         if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
4268                                 continue;
4269                         db_print_file(fp, header);
4270                         header = 0;
4271                 }
4272         }
4273 }
4274 #endif
4275
4276 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
4277     &maxfilesperproc, 0, "Maximum files allowed open per process");
4278
4279 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
4280     &maxfiles, 0, "Maximum number of files");
4281
4282 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
4283     &openfiles, 0, "System-wide number of open files");
4284
4285 /* ARGSUSED*/
4286 static void
4287 filelistinit(void *dummy)
4288 {
4289
4290         file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
4291             NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
4292         filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0),
4293             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
4294         pwd_zone = uma_zcreate("PWD", sizeof(struct pwd), NULL, NULL,
4295             NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_SMR);
4296         pwd_smr = uma_zone_get_smr(pwd_zone);
4297         mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
4298 }
4299 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
4300
4301 /*-------------------------------------------------------------------*/
4302
4303 static int
4304 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
4305     int flags, struct thread *td)
4306 {
4307
4308         return (EBADF);
4309 }
4310
4311 static int
4312 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4313     struct thread *td)
4314 {
4315
4316         return (EINVAL);
4317 }
4318
4319 static int
4320 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
4321     struct thread *td)
4322 {
4323
4324         return (EBADF);
4325 }
4326
4327 static int
4328 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
4329     struct thread *td)
4330 {
4331
4332         return (0);
4333 }
4334
4335 static int
4336 badfo_kqfilter(struct file *fp, struct knote *kn)
4337 {
4338
4339         return (EBADF);
4340 }
4341
4342 static int
4343 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
4344     struct thread *td)
4345 {
4346
4347         return (EBADF);
4348 }
4349
4350 static int
4351 badfo_close(struct file *fp, struct thread *td)
4352 {
4353
4354         return (0);
4355 }
4356
4357 static int
4358 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4359     struct thread *td)
4360 {
4361
4362         return (EBADF);
4363 }
4364
4365 static int
4366 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4367     struct thread *td)
4368 {
4369
4370         return (EBADF);
4371 }
4372
4373 static int
4374 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4375     struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4376     struct thread *td)
4377 {
4378
4379         return (EBADF);
4380 }
4381
4382 static int
4383 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
4384 {
4385
4386         return (0);
4387 }
4388
4389 struct fileops badfileops = {
4390         .fo_read = badfo_readwrite,
4391         .fo_write = badfo_readwrite,
4392         .fo_truncate = badfo_truncate,
4393         .fo_ioctl = badfo_ioctl,
4394         .fo_poll = badfo_poll,
4395         .fo_kqfilter = badfo_kqfilter,
4396         .fo_stat = badfo_stat,
4397         .fo_close = badfo_close,
4398         .fo_chmod = badfo_chmod,
4399         .fo_chown = badfo_chown,
4400         .fo_sendfile = badfo_sendfile,
4401         .fo_fill_kinfo = badfo_fill_kinfo,
4402 };
4403
4404 int
4405 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred,
4406     int flags, struct thread *td)
4407 {
4408
4409         return (EOPNOTSUPP);
4410 }
4411
4412 int
4413 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4414     struct thread *td)
4415 {
4416
4417         return (EINVAL);
4418 }
4419
4420 int
4421 invfo_ioctl(struct file *fp, u_long com, void *data,
4422     struct ucred *active_cred, struct thread *td)
4423 {
4424
4425         return (ENOTTY);
4426 }
4427
4428 int
4429 invfo_poll(struct file *fp, int events, struct ucred *active_cred,
4430     struct thread *td)
4431 {
4432
4433         return (poll_no_poll(events));
4434 }
4435
4436 int
4437 invfo_kqfilter(struct file *fp, struct knote *kn)
4438 {
4439
4440         return (EINVAL);
4441 }
4442
4443 int
4444 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4445     struct thread *td)
4446 {
4447
4448         return (EINVAL);
4449 }
4450
4451 int
4452 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4453     struct thread *td)
4454 {
4455
4456         return (EINVAL);
4457 }
4458
4459 int
4460 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4461     struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4462     struct thread *td)
4463 {
4464
4465         return (EINVAL);
4466 }
4467
4468 /*-------------------------------------------------------------------*/
4469
4470 /*
4471  * File Descriptor pseudo-device driver (/dev/fd/).
4472  *
4473  * Opening minor device N dup()s the file (if any) connected to file
4474  * descriptor N belonging to the calling process.  Note that this driver
4475  * consists of only the ``open()'' routine, because all subsequent
4476  * references to this file will be direct to the other driver.
4477  *
4478  * XXX: we could give this one a cloning event handler if necessary.
4479  */
4480
4481 /* ARGSUSED */
4482 static int
4483 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4484 {
4485
4486         /*
4487          * XXX Kludge: set curthread->td_dupfd to contain the value of the
4488          * the file descriptor being sought for duplication. The error
4489          * return ensures that the vnode for this device will be released
4490          * by vn_open. Open will detect this special error and take the
4491          * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4492          * will simply report the error.
4493          */
4494         td->td_dupfd = dev2unit(dev);
4495         return (ENODEV);
4496 }
4497
4498 static struct cdevsw fildesc_cdevsw = {
4499         .d_version =    D_VERSION,
4500         .d_open =       fdopen,
4501         .d_name =       "FD",
4502 };
4503
4504 static void
4505 fildesc_drvinit(void *unused)
4506 {
4507         struct cdev *dev;
4508
4509         dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4510             UID_ROOT, GID_WHEEL, 0666, "fd/0");
4511         make_dev_alias(dev, "stdin");
4512         dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4513             UID_ROOT, GID_WHEEL, 0666, "fd/1");
4514         make_dev_alias(dev, "stdout");
4515         dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4516             UID_ROOT, GID_WHEEL, 0666, "fd/2");
4517         make_dev_alias(dev, "stderr");
4518 }
4519
4520 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);