Fix "ls: not found" problem during buildworld. mdate.sh script
[dragonfly.git] / sys / kern / kern_descrip.c
blobb5d1c9451490e2ed3d5e35d5b7315cc7c64ed817
1 /*
2 * Copyright (c) 2005 The DragonFly Project. All rights reserved.
3 *
4 * This code is derived from software contributed to The DragonFly Project
5 * by Jeffrey Hsu.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in
15 * the documentation and/or other materials provided with the
16 * distribution.
17 * 3. Neither the name of The DragonFly Project nor the names of its
18 * contributors may be used to endorse or promote products derived
19 * from this software without specific, prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
35 * Copyright (c) 1982, 1986, 1989, 1991, 1993
36 * The Regents of the University of California. All rights reserved.
37 * (c) UNIX System Laboratories, Inc.
38 * All or some portions of this file are derived from material licensed
39 * to the University of California by American Telephone and Telegraph
40 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
41 * the permission of UNIX System Laboratories, Inc.
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
45 * are met:
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 * 3. All advertising materials mentioning features or use of this software
52 * must display the following acknowledgement:
53 * This product includes software developed by the University of
54 * California, Berkeley and its contributors.
55 * 4. Neither the name of the University nor the names of its contributors
56 * may be used to endorse or promote products derived from this software
57 * without specific prior written permission.
59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 * SUCH DAMAGE.
71 * @(#)kern_descrip.c 8.6 (Berkeley) 4/19/94
72 * $FreeBSD: src/sys/kern/kern_descrip.c,v 1.81.2.19 2004/02/28 00:43:31 tegge Exp $
73 * $DragonFly: src/sys/kern/kern_descrip.c,v 1.51 2005/12/01 18:30:08 dillon Exp $
76 #include "opt_compat.h"
77 #include <sys/param.h>
78 #include <sys/systm.h>
79 #include <sys/malloc.h>
80 #include <sys/sysproto.h>
81 #include <sys/conf.h>
82 #include <sys/filedesc.h>
83 #include <sys/kernel.h>
84 #include <sys/sysctl.h>
85 #include <sys/vnode.h>
86 #include <sys/proc.h>
87 #include <sys/nlookup.h>
88 #include <sys/file.h>
89 #include <sys/stat.h>
90 #include <sys/filio.h>
91 #include <sys/fcntl.h>
92 #include <sys/unistd.h>
93 #include <sys/resourcevar.h>
94 #include <sys/event.h>
95 #include <sys/kern_syscall.h>
96 #include <sys/kcore.h>
97 #include <sys/kinfo.h>
99 #include <vm/vm.h>
100 #include <vm/vm_extern.h>
102 #include <sys/thread2.h>
103 #include <sys/file2.h>
105 static MALLOC_DEFINE(M_FILEDESC, "file desc", "Open file descriptor table");
106 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "file desc to leader",
107 "file desc to leader structures");
108 MALLOC_DEFINE(M_FILE, "file", "Open file structure");
109 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
111 static d_open_t fdopen;
112 #define NUMFDESC 64
114 #define CDEV_MAJOR 22
115 static struct cdevsw fildesc_cdevsw = {
116 /* name */ "FD",
117 /* maj */ CDEV_MAJOR,
118 /* flags */ 0,
119 /* port */ NULL,
120 /* clone */ NULL,
122 /* open */ fdopen,
123 /* close */ noclose,
124 /* read */ noread,
125 /* write */ nowrite,
126 /* ioctl */ noioctl,
127 /* poll */ nopoll,
128 /* mmap */ nommap,
129 /* strategy */ nostrategy,
130 /* dump */ nodump,
131 /* psize */ nopsize
134 static int badfo_readwrite (struct file *fp, struct uio *uio,
135 struct ucred *cred, int flags, struct thread *td);
136 static int badfo_ioctl (struct file *fp, u_long com, caddr_t data,
137 struct thread *td);
138 static int badfo_poll (struct file *fp, int events,
139 struct ucred *cred, struct thread *td);
140 static int badfo_kqfilter (struct file *fp, struct knote *kn);
141 static int badfo_stat (struct file *fp, struct stat *sb, struct thread *td);
142 static int badfo_close (struct file *fp, struct thread *td);
143 static int badfo_shutdown (struct file *fp, int how, struct thread *td);
146 * Descriptor management.
148 struct filelist filehead; /* head of list of open files */
149 int nfiles; /* actual number of open files */
150 extern int cmask;
153 * System calls on descriptors.
155 /* ARGSUSED */
157 getdtablesize(struct getdtablesize_args *uap)
159 struct proc *p = curproc;
161 uap->sysmsg_result =
162 min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
163 return (0);
167 * Duplicate a file descriptor to a particular value.
169 * note: keep in mind that a potential race condition exists when closing
170 * descriptors from a shared descriptor table (via rfork).
172 /* ARGSUSED */
174 dup2(struct dup2_args *uap)
176 int error;
178 error = kern_dup(DUP_FIXED, uap->from, uap->to, uap->sysmsg_fds);
180 return (error);
184 * Duplicate a file descriptor.
186 /* ARGSUSED */
188 dup(struct dup_args *uap)
190 int error;
192 error = kern_dup(DUP_VARIABLE, uap->fd, 0, uap->sysmsg_fds);
194 return (error);
198 kern_fcntl(int fd, int cmd, union fcntl_dat *dat)
200 struct thread *td = curthread;
201 struct proc *p = td->td_proc;
202 struct filedesc *fdp = p->p_fd;
203 struct file *fp;
204 char *pop;
205 struct vnode *vp;
206 u_int newmin;
207 int tmp, error, flg = F_POSIX;
209 KKASSERT(p);
211 if ((unsigned)fd >= fdp->fd_nfiles ||
212 (fp = fdp->fd_files[fd].fp) == NULL)
213 return (EBADF);
214 pop = &fdp->fd_files[fd].fileflags;
216 switch (cmd) {
217 case F_DUPFD:
218 newmin = dat->fc_fd;
219 if (newmin >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
220 newmin > maxfilesperproc)
221 return (EINVAL);
222 error = kern_dup(DUP_VARIABLE, fd, newmin, &dat->fc_fd);
223 return (error);
225 case F_GETFD:
226 dat->fc_cloexec = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
227 return (0);
229 case F_SETFD:
230 *pop = (*pop &~ UF_EXCLOSE) |
231 (dat->fc_cloexec & FD_CLOEXEC ? UF_EXCLOSE : 0);
232 return (0);
234 case F_GETFL:
235 dat->fc_flags = OFLAGS(fp->f_flag);
236 return (0);
238 case F_SETFL:
239 fhold(fp);
240 fp->f_flag &= ~FCNTLFLAGS;
241 fp->f_flag |= FFLAGS(dat->fc_flags & ~O_ACCMODE) & FCNTLFLAGS;
242 tmp = fp->f_flag & FNONBLOCK;
243 error = fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, td);
244 if (error) {
245 fdrop(fp, td);
246 return (error);
248 tmp = fp->f_flag & FASYNC;
249 error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp, td);
250 if (!error) {
251 fdrop(fp, td);
252 return (0);
254 fp->f_flag &= ~FNONBLOCK;
255 tmp = 0;
256 fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, td);
257 fdrop(fp, td);
258 return (error);
260 case F_GETOWN:
261 fhold(fp);
262 error = fo_ioctl(fp, FIOGETOWN, (caddr_t)&dat->fc_owner, td);
263 fdrop(fp, td);
264 return(error);
266 case F_SETOWN:
267 fhold(fp);
268 error = fo_ioctl(fp, FIOSETOWN, (caddr_t)&dat->fc_owner, td);
269 fdrop(fp, td);
270 return(error);
272 case F_SETLKW:
273 flg |= F_WAIT;
274 /* Fall into F_SETLK */
276 case F_SETLK:
277 if (fp->f_type != DTYPE_VNODE)
278 return (EBADF);
279 vp = (struct vnode *)fp->f_data;
282 * copyin/lockop may block
284 fhold(fp);
285 if (dat->fc_flock.l_whence == SEEK_CUR)
286 dat->fc_flock.l_start += fp->f_offset;
288 switch (dat->fc_flock.l_type) {
289 case F_RDLCK:
290 if ((fp->f_flag & FREAD) == 0) {
291 error = EBADF;
292 break;
294 p->p_leader->p_flag |= P_ADVLOCK;
295 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
296 &dat->fc_flock, flg);
297 break;
298 case F_WRLCK:
299 if ((fp->f_flag & FWRITE) == 0) {
300 error = EBADF;
301 break;
303 p->p_leader->p_flag |= P_ADVLOCK;
304 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
305 &dat->fc_flock, flg);
306 break;
307 case F_UNLCK:
308 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
309 &dat->fc_flock, F_POSIX);
310 break;
311 default:
312 error = EINVAL;
313 break;
315 /* Check for race with close */
316 if ((unsigned) fd >= fdp->fd_nfiles ||
317 fp != fdp->fd_files[fd].fp) {
318 dat->fc_flock.l_whence = SEEK_SET;
319 dat->fc_flock.l_start = 0;
320 dat->fc_flock.l_len = 0;
321 dat->fc_flock.l_type = F_UNLCK;
322 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
323 F_UNLCK, &dat->fc_flock, F_POSIX);
325 fdrop(fp, td);
326 return(error);
328 case F_GETLK:
329 if (fp->f_type != DTYPE_VNODE)
330 return (EBADF);
331 vp = (struct vnode *)fp->f_data;
333 * copyin/lockop may block
335 fhold(fp);
336 if (dat->fc_flock.l_type != F_RDLCK &&
337 dat->fc_flock.l_type != F_WRLCK &&
338 dat->fc_flock.l_type != F_UNLCK) {
339 fdrop(fp, td);
340 return (EINVAL);
342 if (dat->fc_flock.l_whence == SEEK_CUR)
343 dat->fc_flock.l_start += fp->f_offset;
344 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK,
345 &dat->fc_flock, F_POSIX);
346 fdrop(fp, td);
347 return(error);
348 default:
349 return (EINVAL);
351 /* NOTREACHED */
355 * The file control system call.
358 fcntl(struct fcntl_args *uap)
360 union fcntl_dat dat;
361 int error;
363 switch (uap->cmd) {
364 case F_DUPFD:
365 dat.fc_fd = uap->arg;
366 break;
367 case F_SETFD:
368 dat.fc_cloexec = uap->arg;
369 break;
370 case F_SETFL:
371 dat.fc_flags = uap->arg;
372 break;
373 case F_SETOWN:
374 dat.fc_owner = uap->arg;
375 break;
376 case F_SETLKW:
377 case F_SETLK:
378 case F_GETLK:
379 error = copyin((caddr_t)uap->arg, &dat.fc_flock,
380 sizeof(struct flock));
381 if (error)
382 return (error);
383 break;
386 error = kern_fcntl(uap->fd, uap->cmd, &dat);
388 if (error == 0) {
389 switch (uap->cmd) {
390 case F_DUPFD:
391 uap->sysmsg_result = dat.fc_fd;
392 break;
393 case F_GETFD:
394 uap->sysmsg_result = dat.fc_cloexec;
395 break;
396 case F_GETFL:
397 uap->sysmsg_result = dat.fc_flags;
398 break;
399 case F_GETOWN:
400 uap->sysmsg_result = dat.fc_owner;
401 case F_GETLK:
402 error = copyout(&dat.fc_flock, (caddr_t)uap->arg,
403 sizeof(struct flock));
404 break;
408 return (error);
412 * Common code for dup, dup2, and fcntl(F_DUPFD).
414 * The type flag can be either DUP_FIXED or DUP_VARIABLE. DUP_FIXED tells
415 * kern_dup() to destructively dup over an existing file descriptor if new
416 * is already open. DUP_VARIABLE tells kern_dup() to find the lowest
417 * unused file descriptor that is greater than or equal to new.
420 kern_dup(enum dup_type type, int old, int new, int *res)
422 struct thread *td = curthread;
423 struct proc *p = td->td_proc;
424 struct filedesc *fdp = p->p_fd;
425 struct file *fp;
426 struct file *delfp;
427 int holdleaders;
428 boolean_t fdalloced = FALSE;
429 int error, newfd;
432 * Verify that we have a valid descriptor to dup from and
433 * possibly to dup to.
435 if (old < 0 || new < 0 || new > p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
436 new >= maxfilesperproc)
437 return (EBADF);
438 if (old >= fdp->fd_nfiles || fdp->fd_files[old].fp == NULL)
439 return (EBADF);
440 if (type == DUP_FIXED && old == new) {
441 *res = new;
442 return (0);
444 fp = fdp->fd_files[old].fp;
445 fhold(fp);
448 * Expand the table for the new descriptor if needed. This may
449 * block and drop and reacquire the fidedesc lock.
451 if (type == DUP_VARIABLE || new >= fdp->fd_nfiles) {
452 error = fdalloc(p, new, &newfd);
453 if (error) {
454 fdrop(fp, td);
455 return (error);
457 fdalloced = TRUE;
459 if (type == DUP_VARIABLE)
460 new = newfd;
463 * If the old file changed out from under us then treat it as a
464 * bad file descriptor. Userland should do its own locking to
465 * avoid this case.
467 if (fdp->fd_files[old].fp != fp) {
468 if (fdp->fd_files[new].fp == NULL) {
469 if (fdalloced)
470 fdreserve(fdp, newfd, -1);
471 if (new < fdp->fd_freefile)
472 fdp->fd_freefile = new;
473 while (fdp->fd_lastfile > 0 &&
474 fdp->fd_files[fdp->fd_lastfile].fp == NULL)
475 fdp->fd_lastfile--;
477 fdrop(fp, td);
478 return (EBADF);
480 KASSERT(old != new, ("new fd is same as old"));
483 * Save info on the descriptor being overwritten. We have
484 * to do the unmap now, but we cannot close it without
485 * introducing an ownership race for the slot.
487 delfp = fdp->fd_files[new].fp;
488 if (delfp != NULL && p->p_fdtol != NULL) {
490 * Ask fdfree() to sleep to ensure that all relevant
491 * process leaders can be traversed in closef().
493 fdp->fd_holdleaderscount++;
494 holdleaders = 1;
495 } else
496 holdleaders = 0;
497 KASSERT(delfp == NULL || type == DUP_FIXED,
498 ("dup() picked an open file"));
499 #if 0
500 if (delfp && (fdp->fd_files[new].fileflags & UF_MAPPED))
501 (void) munmapfd(p, new);
502 #endif
505 * Duplicate the source descriptor, update lastfile
507 if (new > fdp->fd_lastfile)
508 fdp->fd_lastfile = new;
509 if (!fdalloced && fdp->fd_files[new].fp == NULL)
510 fdreserve(fdp, new, 1);
511 fdp->fd_files[new].fp = fp;
512 fdp->fd_files[new].fileflags =
513 fdp->fd_files[old].fileflags & ~UF_EXCLOSE;
514 *res = new;
517 * If we dup'd over a valid file, we now own the reference to it
518 * and must dispose of it using closef() semantics (as if a
519 * close() were performed on it).
521 if (delfp) {
522 (void) closef(delfp, td);
523 if (holdleaders) {
524 fdp->fd_holdleaderscount--;
525 if (fdp->fd_holdleaderscount == 0 &&
526 fdp->fd_holdleaderswakeup != 0) {
527 fdp->fd_holdleaderswakeup = 0;
528 wakeup(&fdp->fd_holdleaderscount);
532 return (0);
536 * If sigio is on the list associated with a process or process group,
537 * disable signalling from the device, remove sigio from the list and
538 * free sigio.
540 void
541 funsetown(struct sigio *sigio)
543 if (sigio == NULL)
544 return;
545 crit_enter();
546 *(sigio->sio_myref) = NULL;
547 crit_exit();
548 if (sigio->sio_pgid < 0) {
549 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
550 sigio, sio_pgsigio);
551 } else /* if ((*sigiop)->sio_pgid > 0) */ {
552 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
553 sigio, sio_pgsigio);
555 crfree(sigio->sio_ucred);
556 free(sigio, M_SIGIO);
559 /* Free a list of sigio structures. */
560 void
561 funsetownlst(struct sigiolst *sigiolst)
563 struct sigio *sigio;
565 while ((sigio = SLIST_FIRST(sigiolst)) != NULL)
566 funsetown(sigio);
570 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
572 * After permission checking, add a sigio structure to the sigio list for
573 * the process or process group.
576 fsetown(pid_t pgid, struct sigio **sigiop)
578 struct proc *proc;
579 struct pgrp *pgrp;
580 struct sigio *sigio;
582 if (pgid == 0) {
583 funsetown(*sigiop);
584 return (0);
586 if (pgid > 0) {
587 proc = pfind(pgid);
588 if (proc == NULL)
589 return (ESRCH);
592 * Policy - Don't allow a process to FSETOWN a process
593 * in another session.
595 * Remove this test to allow maximum flexibility or
596 * restrict FSETOWN to the current process or process
597 * group for maximum safety.
599 if (proc->p_session != curproc->p_session)
600 return (EPERM);
602 pgrp = NULL;
603 } else /* if (pgid < 0) */ {
604 pgrp = pgfind(-pgid);
605 if (pgrp == NULL)
606 return (ESRCH);
609 * Policy - Don't allow a process to FSETOWN a process
610 * in another session.
612 * Remove this test to allow maximum flexibility or
613 * restrict FSETOWN to the current process or process
614 * group for maximum safety.
616 if (pgrp->pg_session != curproc->p_session)
617 return (EPERM);
619 proc = NULL;
621 funsetown(*sigiop);
622 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
623 if (pgid > 0) {
624 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
625 sigio->sio_proc = proc;
626 } else {
627 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
628 sigio->sio_pgrp = pgrp;
630 sigio->sio_pgid = pgid;
631 sigio->sio_ucred = crhold(curproc->p_ucred);
632 /* It would be convenient if p_ruid was in ucred. */
633 sigio->sio_ruid = curproc->p_ucred->cr_ruid;
634 sigio->sio_myref = sigiop;
635 crit_enter();
636 *sigiop = sigio;
637 crit_exit();
638 return (0);
642 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
644 pid_t
645 fgetown(struct sigio *sigio)
647 return (sigio != NULL ? sigio->sio_pgid : 0);
651 * Close many file descriptors.
653 /* ARGSUSED */
656 closefrom(struct closefrom_args *uap)
658 return(kern_closefrom(uap->fd));
662 kern_closefrom(int fd)
664 struct thread *td = curthread;
665 struct proc *p = td->td_proc;
666 struct filedesc *fdp;
668 KKASSERT(p);
669 fdp = p->p_fd;
671 if (fd < 0 || fd > fdp->fd_lastfile)
672 return (0);
674 do {
675 if (kern_close(fdp->fd_lastfile) == EINTR)
676 return (EINTR);
677 } while (fdp->fd_lastfile > fd);
679 return (0);
683 * Close a file descriptor.
685 /* ARGSUSED */
688 close(struct close_args *uap)
690 return(kern_close(uap->fd));
694 kern_close(int fd)
696 struct thread *td = curthread;
697 struct proc *p = td->td_proc;
698 struct filedesc *fdp;
699 struct file *fp;
700 int error;
701 int holdleaders;
703 KKASSERT(p);
704 fdp = p->p_fd;
706 if ((unsigned)fd >= fdp->fd_nfiles ||
707 (fp = fdp->fd_files[fd].fp) == NULL)
708 return (EBADF);
709 #if 0
710 if (fdp->fd_files[fd].fileflags & UF_MAPPED)
711 (void) munmapfd(p, fd);
712 #endif
713 funsetfd(fdp, fd);
714 holdleaders = 0;
715 if (p->p_fdtol != NULL) {
717 * Ask fdfree() to sleep to ensure that all relevant
718 * process leaders can be traversed in closef().
720 fdp->fd_holdleaderscount++;
721 holdleaders = 1;
725 * we now hold the fp reference that used to be owned by the descriptor
726 * array.
728 while (fdp->fd_lastfile > 0 && fdp->fd_files[fdp->fd_lastfile].fp == NULL)
729 fdp->fd_lastfile--;
730 if (fd < fdp->fd_knlistsize)
731 knote_fdclose(p, fd);
732 error = closef(fp, td);
733 if (holdleaders) {
734 fdp->fd_holdleaderscount--;
735 if (fdp->fd_holdleaderscount == 0 &&
736 fdp->fd_holdleaderswakeup != 0) {
737 fdp->fd_holdleaderswakeup = 0;
738 wakeup(&fdp->fd_holdleaderscount);
741 return (error);
745 * shutdown_args(int fd, int how)
748 kern_shutdown(int fd, int how)
750 struct thread *td = curthread;
751 struct proc *p = td->td_proc;
752 struct filedesc *fdp;
753 struct file *fp;
754 int error;
756 KKASSERT(p);
758 fdp = p->p_fd;
759 if ((unsigned)fd >= fdp->fd_nfiles ||
760 (fp = fdp->fd_files[fd].fp) == NULL)
761 return (EBADF);
762 fhold(fp);
763 error = fo_shutdown(fp, how, td);
764 fdrop(fp, td);
766 return (error);
770 shutdown(struct shutdown_args *uap)
772 int error;
774 error = kern_shutdown(uap->s, uap->how);
776 return (error);
780 kern_fstat(int fd, struct stat *ub)
782 struct thread *td = curthread;
783 struct proc *p = td->td_proc;
784 struct filedesc *fdp;
785 struct file *fp;
786 int error;
788 KKASSERT(p);
790 fdp = p->p_fd;
791 if ((unsigned)fd >= fdp->fd_nfiles ||
792 (fp = fdp->fd_files[fd].fp) == NULL)
793 return (EBADF);
794 fhold(fp);
795 error = fo_stat(fp, ub, td);
796 fdrop(fp, td);
798 return (error);
802 * Return status information about a file descriptor.
805 fstat(struct fstat_args *uap)
807 struct stat st;
808 int error;
810 error = kern_fstat(uap->fd, &st);
812 if (error == 0)
813 error = copyout(&st, uap->sb, sizeof(st));
814 return (error);
818 * Return pathconf information about a file descriptor.
820 /* ARGSUSED */
822 fpathconf(struct fpathconf_args *uap)
824 struct thread *td = curthread;
825 struct proc *p = td->td_proc;
826 struct filedesc *fdp;
827 struct file *fp;
828 struct vnode *vp;
829 int error = 0;
831 KKASSERT(p);
832 fdp = p->p_fd;
833 if ((unsigned)uap->fd >= fdp->fd_nfiles ||
834 (fp = fdp->fd_files[uap->fd].fp) == NULL)
835 return (EBADF);
837 fhold(fp);
839 switch (fp->f_type) {
840 case DTYPE_PIPE:
841 case DTYPE_SOCKET:
842 if (uap->name != _PC_PIPE_BUF) {
843 error = EINVAL;
844 } else {
845 uap->sysmsg_result = PIPE_BUF;
846 error = 0;
848 break;
849 case DTYPE_FIFO:
850 case DTYPE_VNODE:
851 vp = (struct vnode *)fp->f_data;
852 error = VOP_PATHCONF(vp, uap->name, uap->sysmsg_fds);
853 break;
854 default:
855 error = EOPNOTSUPP;
856 break;
858 fdrop(fp, td);
859 return(error);
862 static int fdexpand;
863 SYSCTL_INT(_debug, OID_AUTO, fdexpand, CTLFLAG_RD, &fdexpand, 0, "");
865 static void
866 fdgrow(struct filedesc *fdp, int want)
868 struct fdnode *newfiles;
869 struct fdnode *oldfiles;
870 int nf, extra;
872 nf = fdp->fd_nfiles;
873 do {
874 /* nf has to be of the form 2^n - 1 */
875 nf = 2 * nf + 1;
876 } while (nf <= want);
878 newfiles = malloc(nf * sizeof(struct fdnode), M_FILEDESC, M_WAITOK);
881 * deal with file-table extend race that might have occured
882 * when malloc was blocked.
884 if (fdp->fd_nfiles >= nf) {
885 free(newfiles, M_FILEDESC);
886 return;
889 * Copy the existing ofile and ofileflags arrays
890 * and zero the new portion of each array.
892 extra = nf - fdp->fd_nfiles;
893 bcopy(fdp->fd_files, newfiles, fdp->fd_nfiles * sizeof(struct fdnode));
894 bzero(&newfiles[fdp->fd_nfiles], extra * sizeof(struct fdnode));
896 oldfiles = fdp->fd_files;
897 fdp->fd_files = newfiles;
898 fdp->fd_nfiles = nf;
900 if (oldfiles != fdp->fd_builtin_files)
901 free(oldfiles, M_FILEDESC);
902 fdexpand++;
906 * Number of nodes in right subtree, including the root.
908 static __inline int
909 right_subtree_size(int n)
911 return (n ^ (n | (n + 1)));
915 * Bigger ancestor.
917 static __inline int
918 right_ancestor(int n)
920 return (n | (n + 1));
924 * Smaller ancestor.
926 static __inline int
927 left_ancestor(int n)
929 return ((n & (n + 1)) - 1);
932 void
933 fdreserve(struct filedesc *fdp, int fd, int incr)
935 while (fd >= 0) {
936 fdp->fd_files[fd].allocated += incr;
937 KKASSERT(fdp->fd_files[fd].allocated >= 0);
938 fd = left_ancestor(fd);
943 * Allocate a file descriptor for the process.
946 fdalloc(struct proc *p, int want, int *result)
948 struct filedesc *fdp = p->p_fd;
949 int fd, rsize, rsum, node, lim;
951 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
952 if (want >= lim)
953 return (EMFILE);
954 if (want >= fdp->fd_nfiles)
955 fdgrow(fdp, want);
958 * Search for a free descriptor starting at the higher
959 * of want or fd_freefile. If that fails, consider
960 * expanding the ofile array.
962 retry:
963 /* move up the tree looking for a subtree with a free node */
964 for (fd = max(want, fdp->fd_freefile); fd < min(fdp->fd_nfiles, lim);
965 fd = right_ancestor(fd)) {
966 if (fdp->fd_files[fd].allocated == 0)
967 goto found;
969 rsize = right_subtree_size(fd);
970 if (fdp->fd_files[fd].allocated == rsize)
971 continue; /* right subtree full */
974 * Free fd is in the right subtree of the tree rooted at fd.
975 * Call that subtree R. Look for the smallest (leftmost)
976 * subtree of R with an unallocated fd: continue moving
977 * down the left branch until encountering a full left
978 * subtree, then move to the right.
980 for (rsum = 0, rsize /= 2; rsize > 0; rsize /= 2) {
981 node = fd + rsize;
982 rsum += fdp->fd_files[node].allocated;
983 if (fdp->fd_files[fd].allocated == rsum + rsize) {
984 fd = node; /* move to the right */
985 if (fdp->fd_files[node].allocated == 0)
986 goto found;
987 rsum = 0;
990 goto found;
994 * No space in current array. Expand?
996 if (fdp->fd_nfiles >= lim)
997 return (EMFILE);
998 fdgrow(fdp, want);
999 goto retry;
1001 found:
1002 KKASSERT(fd < fdp->fd_nfiles);
1003 fdp->fd_files[fd].fileflags = 0;
1004 if (fd > fdp->fd_lastfile)
1005 fdp->fd_lastfile = fd;
1006 if (want <= fdp->fd_freefile)
1007 fdp->fd_freefile = fd;
1008 *result = fd;
1009 KKASSERT(fdp->fd_files[fd].fp == NULL);
1010 fdreserve(fdp, fd, 1);
1011 return (0);
1015 * Check to see whether n user file descriptors
1016 * are available to the process p.
1019 fdavail(struct proc *p, int n)
1021 struct filedesc *fdp = p->p_fd;
1022 struct fdnode *fdnode;
1023 int i, lim, last;
1025 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
1026 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1027 return (1);
1029 last = min(fdp->fd_nfiles, lim);
1030 fdnode = &fdp->fd_files[fdp->fd_freefile];
1031 for (i = last - fdp->fd_freefile; --i >= 0; ++fdnode) {
1032 if (fdnode->fp == NULL && --n <= 0)
1033 return (1);
1035 return (0);
1039 * falloc:
1040 * Create a new open file structure and allocate a file decriptor
1041 * for the process that refers to it. If p is NULL, no descriptor
1042 * is allocated and the file pointer is returned unassociated with
1043 * any process. resultfd is only used if p is not NULL and may
1044 * separately be NULL indicating that you don't need the returned fd.
1046 * A held file pointer is returned. If a descriptor has been allocated
1047 * an additional hold on the fp will be made due to the fd_files[]
1048 * reference.
1051 falloc(struct proc *p, struct file **resultfp, int *resultfd)
1053 static struct timeval lastfail;
1054 static int curfail;
1055 struct file *fp;
1056 int error;
1058 fp = NULL;
1061 * Handle filetable full issues and root overfill.
1063 if (nfiles >= maxfiles - maxfilesrootres &&
1064 ((p && p->p_ucred->cr_ruid != 0) || nfiles >= maxfiles)) {
1065 if (ppsratecheck(&lastfail, &curfail, 1)) {
1066 printf("kern.maxfiles limit exceeded by uid %d, please see tuning(7).\n",
1067 (p ? p->p_ucred->cr_ruid : -1));
1069 error = ENFILE;
1070 goto done;
1074 * Allocate a new file descriptor.
1076 nfiles++;
1077 fp = malloc(sizeof(struct file), M_FILE, M_WAITOK | M_ZERO);
1078 fp->f_count = 1;
1079 fp->f_ops = &badfileops;
1080 fp->f_seqcount = 1;
1081 if (p)
1082 fp->f_cred = crhold(p->p_ucred);
1083 else
1084 fp->f_cred = crhold(proc0.p_ucred);
1085 LIST_INSERT_HEAD(&filehead, fp, f_list);
1086 if (resultfd) {
1087 if ((error = fsetfd(p, fp, resultfd)) != 0) {
1088 fdrop(fp, p->p_thread);
1089 fp = NULL;
1091 } else {
1092 error = 0;
1094 done:
1095 *resultfp = fp;
1096 return (error);
1100 * Associate a file pointer with a file descriptor. On success the fp
1101 * will have an additional ref representing the fd_files[] association.
1104 fsetfd(struct proc *p, struct file *fp, int *resultfd)
1106 int fd, error;
1108 fd = -1;
1109 if ((error = fdalloc(p, 0, &fd)) == 0) {
1110 fhold(fp);
1111 p->p_fd->fd_files[fd].fp = fp;
1113 *resultfd = fd;
1114 return (error);
1117 void
1118 funsetfd(struct filedesc *fdp, int fd)
1120 fdp->fd_files[fd].fp = NULL;
1121 fdp->fd_files[fd].fileflags = 0;
1122 fdreserve(fdp, fd, -1);
1123 if (fd < fdp->fd_freefile)
1124 fdp->fd_freefile = fd;
1127 void
1128 fsetcred(struct file *fp, struct ucred *cr)
1130 crhold(cr);
1131 crfree(fp->f_cred);
1132 fp->f_cred = cr;
1136 * Free a file descriptor.
1138 void
1139 ffree(struct file *fp)
1141 KASSERT((fp->f_count == 0), ("ffree: fp_fcount not 0!"));
1142 LIST_REMOVE(fp, f_list);
1143 crfree(fp->f_cred);
1144 if (fp->f_ncp) {
1145 cache_drop(fp->f_ncp);
1146 fp->f_ncp = NULL;
1148 nfiles--;
1149 free(fp, M_FILE);
1153 * Build a new filedesc structure.
1155 struct filedesc *
1156 fdinit(struct proc *p)
1158 struct filedesc *newfdp;
1159 struct filedesc *fdp = p->p_fd;
1161 newfdp = malloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK|M_ZERO);
1162 if (fdp->fd_cdir) {
1163 newfdp->fd_cdir = fdp->fd_cdir;
1164 vref(newfdp->fd_cdir);
1165 newfdp->fd_ncdir = cache_hold(fdp->fd_ncdir);
1169 * rdir may not be set in e.g. proc0 or anything vm_fork'd off of
1170 * proc0, but should unconditionally exist in other processes.
1172 if (fdp->fd_rdir) {
1173 newfdp->fd_rdir = fdp->fd_rdir;
1174 vref(newfdp->fd_rdir);
1175 newfdp->fd_nrdir = cache_hold(fdp->fd_nrdir);
1177 if (fdp->fd_jdir) {
1178 newfdp->fd_jdir = fdp->fd_jdir;
1179 vref(newfdp->fd_jdir);
1180 newfdp->fd_njdir = cache_hold(fdp->fd_njdir);
1183 /* Create the file descriptor table. */
1184 newfdp->fd_refcnt = 1;
1185 newfdp->fd_cmask = cmask;
1186 newfdp->fd_files = newfdp->fd_builtin_files;
1187 newfdp->fd_nfiles = NDFILE;
1188 newfdp->fd_knlistsize = -1;
1190 return (newfdp);
1194 * Share a filedesc structure.
1196 struct filedesc *
1197 fdshare(struct proc *p)
1199 p->p_fd->fd_refcnt++;
1200 return (p->p_fd);
1204 * Copy a filedesc structure.
1206 struct filedesc *
1207 fdcopy(struct proc *p)
1209 struct filedesc *newfdp, *fdp = p->p_fd;
1210 struct fdnode *fdnode;
1211 int i;
1213 /* Certain daemons might not have file descriptors. */
1214 if (fdp == NULL)
1215 return (NULL);
1217 newfdp = malloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK);
1218 *newfdp = *fdp;
1219 if (newfdp->fd_cdir) {
1220 vref(newfdp->fd_cdir);
1221 newfdp->fd_ncdir = cache_hold(newfdp->fd_ncdir);
1224 * We must check for fd_rdir here, at least for now because
1225 * the init process is created before we have access to the
1226 * rootvode to take a reference to it.
1228 if (newfdp->fd_rdir) {
1229 vref(newfdp->fd_rdir);
1230 newfdp->fd_nrdir = cache_hold(newfdp->fd_nrdir);
1232 if (newfdp->fd_jdir) {
1233 vref(newfdp->fd_jdir);
1234 newfdp->fd_njdir = cache_hold(newfdp->fd_njdir);
1236 newfdp->fd_refcnt = 1;
1239 * If the number of open files fits in the internal arrays
1240 * of the open file structure, use them, otherwise allocate
1241 * additional memory for the number of descriptors currently
1242 * in use.
1244 if (newfdp->fd_lastfile < NDFILE) {
1245 newfdp->fd_files = newfdp->fd_builtin_files;
1246 i = NDFILE;
1247 } else {
1249 * Compute the smallest file table size
1250 * for the file descriptors currently in use,
1251 * allowing the table to shrink.
1253 i = newfdp->fd_nfiles;
1254 while ((i-1)/2 > newfdp->fd_lastfile && (i-1)/2 > NDFILE)
1255 i = (i-1)/2;
1256 newfdp->fd_files = malloc(i * sizeof(struct fdnode),
1257 M_FILEDESC, M_WAITOK);
1259 newfdp->fd_nfiles = i;
1261 if (fdp->fd_files != fdp->fd_builtin_files ||
1262 newfdp->fd_files != newfdp->fd_builtin_files
1264 bcopy(fdp->fd_files, newfdp->fd_files,
1265 i * sizeof(struct fdnode));
1269 * kq descriptors cannot be copied.
1271 if (newfdp->fd_knlistsize != -1) {
1272 fdnode = &newfdp->fd_files[newfdp->fd_lastfile];
1273 for (i = newfdp->fd_lastfile; i >= 0; i--, fdnode--) {
1274 if (fdnode->fp != NULL && fdnode->fp->f_type == DTYPE_KQUEUE)
1275 funsetfd(newfdp, i); /* nulls out *fpp */
1276 if (fdnode->fp == NULL && i == newfdp->fd_lastfile && i > 0)
1277 newfdp->fd_lastfile--;
1279 newfdp->fd_knlist = NULL;
1280 newfdp->fd_knlistsize = -1;
1281 newfdp->fd_knhash = NULL;
1282 newfdp->fd_knhashmask = 0;
1285 fdnode = newfdp->fd_files;
1286 for (i = newfdp->fd_lastfile; i-- >= 0; fdnode++) {
1287 if (fdnode->fp != NULL)
1288 fhold(fdnode->fp);
1290 return (newfdp);
1294 * Release a filedesc structure.
1296 void
1297 fdfree(struct proc *p)
1299 struct thread *td = p->p_thread;
1300 struct filedesc *fdp = p->p_fd;
1301 struct fdnode *fdnode;
1302 int i;
1303 struct filedesc_to_leader *fdtol;
1304 struct file *fp;
1305 struct vnode *vp;
1306 struct flock lf;
1308 /* Certain daemons might not have file descriptors. */
1309 if (fdp == NULL)
1310 return;
1312 /* Check for special need to clear POSIX style locks */
1313 fdtol = p->p_fdtol;
1314 if (fdtol != NULL) {
1315 KASSERT(fdtol->fdl_refcount > 0,
1316 ("filedesc_to_refcount botch: fdl_refcount=%d",
1317 fdtol->fdl_refcount));
1318 if (fdtol->fdl_refcount == 1 &&
1319 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1320 i = 0;
1321 fdnode = fdp->fd_files;
1322 for (i = 0; i <= fdp->fd_lastfile; i++, fdnode++) {
1323 if (fdnode->fp == NULL ||
1324 fdnode->fp->f_type != DTYPE_VNODE)
1325 continue;
1326 fp = fdnode->fp;
1327 fhold(fp);
1328 lf.l_whence = SEEK_SET;
1329 lf.l_start = 0;
1330 lf.l_len = 0;
1331 lf.l_type = F_UNLCK;
1332 vp = (struct vnode *)fp->f_data;
1333 (void) VOP_ADVLOCK(vp,
1334 (caddr_t)p->p_leader,
1335 F_UNLCK,
1336 &lf,
1337 F_POSIX);
1338 fdrop(fp, p->p_thread);
1339 /* reload due to possible reallocation */
1340 fdnode = &fdp->fd_files[i];
1343 retry:
1344 if (fdtol->fdl_refcount == 1) {
1345 if (fdp->fd_holdleaderscount > 0 &&
1346 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1348 * close() or do_dup() has cleared a reference
1349 * in a shared file descriptor table.
1351 fdp->fd_holdleaderswakeup = 1;
1352 tsleep(&fdp->fd_holdleaderscount,
1353 0, "fdlhold", 0);
1354 goto retry;
1356 if (fdtol->fdl_holdcount > 0) {
1358 * Ensure that fdtol->fdl_leader
1359 * remains valid in closef().
1361 fdtol->fdl_wakeup = 1;
1362 tsleep(fdtol, 0, "fdlhold", 0);
1363 goto retry;
1366 fdtol->fdl_refcount--;
1367 if (fdtol->fdl_refcount == 0 &&
1368 fdtol->fdl_holdcount == 0) {
1369 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1370 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1371 } else
1372 fdtol = NULL;
1373 p->p_fdtol = NULL;
1374 if (fdtol != NULL)
1375 free(fdtol, M_FILEDESC_TO_LEADER);
1377 if (--fdp->fd_refcnt > 0)
1378 return;
1380 * we are the last reference to the structure, we can
1381 * safely assume it will not change out from under us.
1383 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1384 if (fdp->fd_files[i].fp)
1385 closef(fdp->fd_files[i].fp, td);
1387 if (fdp->fd_files != fdp->fd_builtin_files)
1388 free(fdp->fd_files, M_FILEDESC);
1389 if (fdp->fd_cdir) {
1390 cache_drop(fdp->fd_ncdir);
1391 vrele(fdp->fd_cdir);
1393 if (fdp->fd_rdir) {
1394 cache_drop(fdp->fd_nrdir);
1395 vrele(fdp->fd_rdir);
1397 if (fdp->fd_jdir) {
1398 cache_drop(fdp->fd_njdir);
1399 vrele(fdp->fd_jdir);
1401 if (fdp->fd_knlist)
1402 free(fdp->fd_knlist, M_KQUEUE);
1403 if (fdp->fd_knhash)
1404 free(fdp->fd_knhash, M_KQUEUE);
1405 free(fdp, M_FILEDESC);
1409 * For setugid programs, we don't want to people to use that setugidness
1410 * to generate error messages which write to a file which otherwise would
1411 * otherwise be off-limits to the process.
1413 * This is a gross hack to plug the hole. A better solution would involve
1414 * a special vop or other form of generalized access control mechanism. We
1415 * go ahead and just reject all procfs file systems accesses as dangerous.
1417 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1418 * sufficient. We also don't for check setugidness since we know we are.
1420 static int
1421 is_unsafe(struct file *fp)
1423 if (fp->f_type == DTYPE_VNODE &&
1424 ((struct vnode *)(fp->f_data))->v_tag == VT_PROCFS)
1425 return (1);
1426 return (0);
1430 * Make this setguid thing safe, if at all possible.
1432 void
1433 setugidsafety(struct proc *p)
1435 struct thread *td = p->p_thread;
1436 struct filedesc *fdp = p->p_fd;
1437 int i;
1439 /* Certain daemons might not have file descriptors. */
1440 if (fdp == NULL)
1441 return;
1444 * note: fdp->fd_files may be reallocated out from under us while
1445 * we are blocked in a close. Be careful!
1447 for (i = 0; i <= fdp->fd_lastfile; i++) {
1448 if (i > 2)
1449 break;
1450 if (fdp->fd_files[i].fp && is_unsafe(fdp->fd_files[i].fp)) {
1451 struct file *fp;
1453 #if 0
1454 if ((fdp->fd_files[i].fileflags & UF_MAPPED) != 0)
1455 (void) munmapfd(p, i);
1456 #endif
1457 if (i < fdp->fd_knlistsize)
1458 knote_fdclose(p, i);
1460 * NULL-out descriptor prior to close to avoid
1461 * a race while close blocks.
1463 fp = fdp->fd_files[i].fp;
1464 funsetfd(fdp, i);
1465 closef(fp, td);
1468 while (fdp->fd_lastfile > 0 && fdp->fd_files[fdp->fd_lastfile].fp == NULL)
1469 fdp->fd_lastfile--;
1473 * Close any files on exec?
1475 void
1476 fdcloseexec(struct proc *p)
1478 struct thread *td = p->p_thread;
1479 struct filedesc *fdp = p->p_fd;
1480 int i;
1482 /* Certain daemons might not have file descriptors. */
1483 if (fdp == NULL)
1484 return;
1487 * We cannot cache fd_files since operations may block and rip
1488 * them out from under us.
1490 for (i = 0; i <= fdp->fd_lastfile; i++) {
1491 if (fdp->fd_files[i].fp != NULL &&
1492 (fdp->fd_files[i].fileflags & UF_EXCLOSE)) {
1493 struct file *fp;
1495 #if 0
1496 if (fdp->fd_files[i].fileflags & UF_MAPPED)
1497 (void) munmapfd(p, i);
1498 #endif
1499 if (i < fdp->fd_knlistsize)
1500 knote_fdclose(p, i);
1502 * NULL-out descriptor prior to close to avoid
1503 * a race while close blocks.
1505 fp = fdp->fd_files[i].fp;
1506 funsetfd(fdp, i);
1507 closef(fp, td);
1510 while (fdp->fd_lastfile > 0 && fdp->fd_files[fdp->fd_lastfile].fp == NULL)
1511 fdp->fd_lastfile--;
1515 * It is unsafe for set[ug]id processes to be started with file
1516 * descriptors 0..2 closed, as these descriptors are given implicit
1517 * significance in the Standard C library. fdcheckstd() will create a
1518 * descriptor referencing /dev/null for each of stdin, stdout, and
1519 * stderr that is not already open.
1522 fdcheckstd(struct proc *p)
1524 struct thread *td = p->p_thread;
1525 struct nlookupdata nd;
1526 struct filedesc *fdp;
1527 struct file *fp;
1528 register_t retval;
1529 int fd, i, error, flags, devnull;
1531 fdp = p->p_fd;
1532 if (fdp == NULL)
1533 return (0);
1534 devnull = -1;
1535 error = 0;
1536 for (i = 0; i < 3; i++) {
1537 if (fdp->fd_files[i].fp != NULL)
1538 continue;
1539 if (devnull < 0) {
1540 if ((error = falloc(p, &fp, NULL)) != 0)
1541 break;
1543 error = nlookup_init(&nd, "/dev/null", UIO_SYSSPACE,
1544 NLC_FOLLOW|NLC_LOCKVP);
1545 flags = FREAD | FWRITE;
1546 if (error == 0)
1547 error = vn_open(&nd, fp, flags, 0);
1548 if (error == 0)
1549 error = fsetfd(p, fp, &fd);
1550 fdrop(fp, td);
1551 nlookup_done(&nd);
1552 if (error)
1553 break;
1554 KKASSERT(i == fd);
1555 devnull = fd;
1556 } else {
1557 error = kern_dup(DUP_FIXED, devnull, i, &retval);
1558 if (error != 0)
1559 break;
1562 return (error);
1566 * Internal form of close.
1567 * Decrement reference count on file structure.
1568 * Note: td and/or p may be NULL when closing a file
1569 * that was being passed in a message.
1572 closef(struct file *fp, struct thread *td)
1574 struct vnode *vp;
1575 struct flock lf;
1576 struct filedesc_to_leader *fdtol;
1577 struct proc *p;
1579 if (fp == NULL)
1580 return (0);
1581 if (td == NULL) {
1582 td = curthread;
1583 p = NULL; /* allow no proc association */
1584 } else {
1585 p = td->td_proc; /* can also be NULL */
1588 * POSIX record locking dictates that any close releases ALL
1589 * locks owned by this process. This is handled by setting
1590 * a flag in the unlock to free ONLY locks obeying POSIX
1591 * semantics, and not to free BSD-style file locks.
1592 * If the descriptor was in a message, POSIX-style locks
1593 * aren't passed with the descriptor.
1595 if (p != NULL &&
1596 fp->f_type == DTYPE_VNODE) {
1597 if ((p->p_leader->p_flag & P_ADVLOCK) != 0) {
1598 lf.l_whence = SEEK_SET;
1599 lf.l_start = 0;
1600 lf.l_len = 0;
1601 lf.l_type = F_UNLCK;
1602 vp = (struct vnode *)fp->f_data;
1603 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
1604 &lf, F_POSIX);
1606 fdtol = p->p_fdtol;
1607 if (fdtol != NULL) {
1609 * Handle special case where file descriptor table
1610 * is shared between multiple process leaders.
1612 for (fdtol = fdtol->fdl_next;
1613 fdtol != p->p_fdtol;
1614 fdtol = fdtol->fdl_next) {
1615 if ((fdtol->fdl_leader->p_flag &
1616 P_ADVLOCK) == 0)
1617 continue;
1618 fdtol->fdl_holdcount++;
1619 lf.l_whence = SEEK_SET;
1620 lf.l_start = 0;
1621 lf.l_len = 0;
1622 lf.l_type = F_UNLCK;
1623 vp = (struct vnode *)fp->f_data;
1624 (void) VOP_ADVLOCK(vp,
1625 (caddr_t)p->p_leader,
1626 F_UNLCK, &lf, F_POSIX);
1627 fdtol->fdl_holdcount--;
1628 if (fdtol->fdl_holdcount == 0 &&
1629 fdtol->fdl_wakeup != 0) {
1630 fdtol->fdl_wakeup = 0;
1631 wakeup(fdtol);
1636 return (fdrop(fp, td));
1640 fdrop(struct file *fp, struct thread *td)
1642 struct flock lf;
1643 struct vnode *vp;
1644 int error;
1646 if (--fp->f_count > 0)
1647 return (0);
1648 if (fp->f_count < 0)
1649 panic("fdrop: count < 0");
1650 if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
1651 lf.l_whence = SEEK_SET;
1652 lf.l_start = 0;
1653 lf.l_len = 0;
1654 lf.l_type = F_UNLCK;
1655 vp = (struct vnode *)fp->f_data;
1656 (void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
1658 if (fp->f_ops != &badfileops)
1659 error = fo_close(fp, td);
1660 else
1661 error = 0;
1662 ffree(fp);
1663 return (error);
1667 * Apply an advisory lock on a file descriptor.
1669 * Just attempt to get a record lock of the requested type on
1670 * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
1672 /* ARGSUSED */
1674 flock(struct flock_args *uap)
1676 struct proc *p = curproc;
1677 struct filedesc *fdp = p->p_fd;
1678 struct file *fp;
1679 struct vnode *vp;
1680 struct flock lf;
1682 if ((unsigned)uap->fd >= fdp->fd_nfiles ||
1683 (fp = fdp->fd_files[uap->fd].fp) == NULL)
1684 return (EBADF);
1685 if (fp->f_type != DTYPE_VNODE)
1686 return (EOPNOTSUPP);
1687 vp = (struct vnode *)fp->f_data;
1688 lf.l_whence = SEEK_SET;
1689 lf.l_start = 0;
1690 lf.l_len = 0;
1691 if (uap->how & LOCK_UN) {
1692 lf.l_type = F_UNLCK;
1693 fp->f_flag &= ~FHASLOCK;
1694 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK));
1696 if (uap->how & LOCK_EX)
1697 lf.l_type = F_WRLCK;
1698 else if (uap->how & LOCK_SH)
1699 lf.l_type = F_RDLCK;
1700 else
1701 return (EBADF);
1702 fp->f_flag |= FHASLOCK;
1703 if (uap->how & LOCK_NB)
1704 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK));
1705 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK|F_WAIT));
1709 * File Descriptor pseudo-device driver (/dev/fd/).
1711 * Opening minor device N dup()s the file (if any) connected to file
1712 * descriptor N belonging to the calling process. Note that this driver
1713 * consists of only the ``open()'' routine, because all subsequent
1714 * references to this file will be direct to the other driver.
1716 /* ARGSUSED */
1717 static int
1718 fdopen(dev_t dev, int mode, int type, struct thread *td)
1720 KKASSERT(td->td_lwp != NULL);
1723 * XXX Kludge: set curlwp->lwp_dupfd to contain the value of the
1724 * the file descriptor being sought for duplication. The error
1725 * return ensures that the vnode for this device will be released
1726 * by vn_open. Open will detect this special error and take the
1727 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
1728 * will simply report the error.
1730 td->td_lwp->lwp_dupfd = minor(dev);
1731 return (ENODEV);
1735 * Duplicate the specified descriptor to a free descriptor.
1738 dupfdopen(struct filedesc *fdp, int indx, int dfd, int mode, int error)
1740 struct file *wfp;
1741 struct file *fp;
1744 * If the to-be-dup'd fd number is greater than the allowed number
1745 * of file descriptors, or the fd to be dup'd has already been
1746 * closed, then reject.
1748 if ((u_int)dfd >= fdp->fd_nfiles ||
1749 (wfp = fdp->fd_files[dfd].fp) == NULL) {
1750 return (EBADF);
1754 * There are two cases of interest here.
1756 * For ENODEV simply dup (dfd) to file descriptor
1757 * (indx) and return.
1759 * For ENXIO steal away the file structure from (dfd) and
1760 * store it in (indx). (dfd) is effectively closed by
1761 * this operation.
1763 * Any other error code is just returned.
1765 switch (error) {
1766 case ENODEV:
1768 * Check that the mode the file is being opened for is a
1769 * subset of the mode of the existing descriptor.
1771 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag)
1772 return (EACCES);
1773 fp = fdp->fd_files[indx].fp;
1774 #if 0
1775 if (fp && fdp->fd_files[indx].fileflags & UF_MAPPED)
1776 (void) munmapfd(p, indx);
1777 #endif
1778 fdp->fd_files[indx].fp = wfp;
1779 fdp->fd_files[indx].fileflags = fdp->fd_files[dfd].fileflags;
1780 fhold(wfp);
1781 if (indx > fdp->fd_lastfile)
1782 fdp->fd_lastfile = indx;
1784 * we now own the reference to fp that the ofiles[] array
1785 * used to own. Release it.
1787 if (fp)
1788 fdrop(fp, curthread);
1789 return (0);
1791 case ENXIO:
1793 * Steal away the file pointer from dfd, and stuff it into indx.
1795 fp = fdp->fd_files[indx].fp;
1796 #if 0
1797 if (fp && fdp->fd_files[indx].fileflags & UF_MAPPED)
1798 (void) munmapfd(p, indx);
1799 #endif
1800 fdp->fd_files[indx].fp = fdp->fd_files[dfd].fp;
1801 fdp->fd_files[indx].fileflags = fdp->fd_files[dfd].fileflags;
1802 funsetfd(fdp, dfd);
1805 * we now own the reference to fp that the files[] array
1806 * used to own. Release it.
1808 if (fp)
1809 fdrop(fp, curthread);
1811 * Complete the clean up of the filedesc structure by
1812 * recomputing the various hints.
1814 if (indx > fdp->fd_lastfile) {
1815 fdp->fd_lastfile = indx;
1816 } else {
1817 while (fdp->fd_lastfile > 0 &&
1818 fdp->fd_files[fdp->fd_lastfile].fp == NULL) {
1819 fdp->fd_lastfile--;
1822 return (0);
1824 default:
1825 return (error);
1827 /* NOTREACHED */
1831 struct filedesc_to_leader *
1832 filedesc_to_leader_alloc(struct filedesc_to_leader *old,
1833 struct proc *leader)
1835 struct filedesc_to_leader *fdtol;
1837 fdtol = malloc(sizeof(struct filedesc_to_leader),
1838 M_FILEDESC_TO_LEADER, M_WAITOK);
1839 fdtol->fdl_refcount = 1;
1840 fdtol->fdl_holdcount = 0;
1841 fdtol->fdl_wakeup = 0;
1842 fdtol->fdl_leader = leader;
1843 if (old != NULL) {
1844 fdtol->fdl_next = old->fdl_next;
1845 fdtol->fdl_prev = old;
1846 old->fdl_next = fdtol;
1847 fdtol->fdl_next->fdl_prev = fdtol;
1848 } else {
1849 fdtol->fdl_next = fdtol;
1850 fdtol->fdl_prev = fdtol;
1852 return fdtol;
1856 * Get file structures.
1858 static int
1859 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
1861 struct kinfo_file kf;
1862 struct filedesc *fdp;
1863 struct file *fp;
1864 struct proc *p;
1865 uid_t uid;
1866 int count;
1867 int error;
1868 int n;
1871 * Note: because the number of file descriptors is calculated
1872 * in different ways for sizing vs returning the data,
1873 * there is information leakage from the first loop. However,
1874 * it is of a similar order of magnitude to the leakage from
1875 * global system statistics such as kern.openfiles.
1877 * When just doing a count, note that we cannot just count
1878 * the elements and add f_count via the filehead list because
1879 * threaded processes share their descriptor table and f_count might
1880 * still be '1' in that case.
1882 * Since the SYSCTL op can block, we must hold the process to
1883 * prevent it being ripped out from under us either in the
1884 * file descriptor loop or in the greater LIST_FOREACH. The
1885 * process may be in varying states of disrepair. If the process
1886 * is in SZOMB we may have caught it just as it is being removed
1887 * from the allproc list, we must skip it in that case to maintain
1888 * an unbroken chain through the allproc list.
1890 count = 0;
1891 error = 0;
1892 LIST_FOREACH(p, &allproc, p_list) {
1893 if (p->p_stat == SIDL || (p->p_flag & P_ZOMBIE))
1894 continue;
1895 if (!PRISON_CHECK(req->td->td_proc->p_ucred, p->p_ucred) != 0)
1896 continue;
1897 if ((fdp = p->p_fd) == NULL)
1898 continue;
1899 PHOLD(p);
1900 for (n = 0; n < fdp->fd_nfiles; ++n) {
1901 if ((fp = fdp->fd_files[n].fp) == NULL)
1902 continue;
1903 if (req->oldptr == NULL) {
1904 ++count;
1905 } else {
1906 uid = p->p_ucred ? p->p_ucred->cr_uid : -1;
1907 kcore_make_file(&kf, fp, p->p_pid, uid, n);
1908 error = SYSCTL_OUT(req, &kf, sizeof(kf));
1909 if (error)
1910 break;
1913 PRELE(p);
1914 if (error)
1915 break;
1919 * When just calculating the size, overestimate a bit to try to
1920 * prevent system activity from causing the buffer-fill call
1921 * to fail later on.
1923 if (req->oldptr == NULL) {
1924 count = (count + 16) + (count / 10);
1925 error = SYSCTL_OUT(req, NULL, count * sizeof(kf));
1927 return (error);
1930 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
1931 0, 0, sysctl_kern_file, "S,file", "Entire file table");
1933 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
1934 &maxfilesperproc, 0, "Maximum files allowed open per process");
1936 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
1937 &maxfiles, 0, "Maximum number of files");
1939 SYSCTL_INT(_kern, OID_AUTO, maxfilesrootres, CTLFLAG_RW,
1940 &maxfilesrootres, 0, "Descriptors reserved for root use");
1942 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
1943 &nfiles, 0, "System-wide number of open files");
1945 static void
1946 fildesc_drvinit(void *unused)
1948 int fd;
1950 cdevsw_add(&fildesc_cdevsw, 0, 0);
1951 for (fd = 0; fd < NUMFDESC; fd++) {
1952 make_dev(&fildesc_cdevsw, fd,
1953 UID_BIN, GID_BIN, 0666, "fd/%d", fd);
1955 make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "stdin");
1956 make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "stdout");
1957 make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "stderr");
1960 struct fileops badfileops = {
1961 NULL, /* port */
1962 NULL, /* clone */
1963 badfo_readwrite,
1964 badfo_readwrite,
1965 badfo_ioctl,
1966 badfo_poll,
1967 badfo_kqfilter,
1968 badfo_stat,
1969 badfo_close,
1970 badfo_shutdown
1973 static int
1974 badfo_readwrite(
1975 struct file *fp,
1976 struct uio *uio,
1977 struct ucred *cred,
1978 int flags,
1979 struct thread *td
1981 return (EBADF);
1984 static int
1985 badfo_ioctl(struct file *fp, u_long com, caddr_t data, struct thread *td)
1987 return (EBADF);
1990 static int
1991 badfo_poll(struct file *fp, int events, struct ucred *cred, struct thread *td)
1993 return (0);
1996 static int
1997 badfo_kqfilter(struct file *fp, struct knote *kn)
1999 return (0);
2002 static int
2003 badfo_stat(struct file *fp, struct stat *sb, struct thread *td)
2005 return (EBADF);
2008 static int
2009 badfo_close(struct file *fp, struct thread *td)
2011 return (EBADF);
2014 static int
2015 badfo_shutdown(struct file *fp, int how, struct thread *td)
2017 return (EBADF);
2021 nofo_shutdown(struct file *fp, int how, struct thread *td)
2023 return (EOPNOTSUPP);
2026 SYSINIT(fildescdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,
2027 fildesc_drvinit,NULL)