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