Home | History | Annotate | Line # | Download | only in kern
kern_descrip.c revision 1.103
      1 /*	$NetBSD: kern_descrip.c,v 1.103 2003/02/23 14:37:33 pk Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1982, 1986, 1989, 1991, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  * (c) UNIX System Laboratories, Inc.
      7  * All or some portions of this file are derived from material licensed
      8  * to the University of California by American Telephone and Telegraph
      9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     10  * the permission of UNIX System Laboratories, Inc.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *	This product includes software developed by the University of
     23  *	California, Berkeley and its contributors.
     24  * 4. Neither the name of the University nor the names of its contributors
     25  *    may be used to endorse or promote products derived from this software
     26  *    without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     38  * SUCH DAMAGE.
     39  *
     40  *	@(#)kern_descrip.c	8.8 (Berkeley) 2/14/95
     41  */
     42 
     43 #include <sys/cdefs.h>
     44 __KERNEL_RCSID(0, "$NetBSD: kern_descrip.c,v 1.103 2003/02/23 14:37:33 pk Exp $");
     45 
     46 #include <sys/param.h>
     47 #include <sys/systm.h>
     48 #include <sys/filedesc.h>
     49 #include <sys/kernel.h>
     50 #include <sys/vnode.h>
     51 #include <sys/proc.h>
     52 #include <sys/file.h>
     53 #include <sys/namei.h>
     54 #include <sys/socket.h>
     55 #include <sys/socketvar.h>
     56 #include <sys/stat.h>
     57 #include <sys/ioctl.h>
     58 #include <sys/fcntl.h>
     59 #include <sys/malloc.h>
     60 #include <sys/pool.h>
     61 #include <sys/syslog.h>
     62 #include <sys/unistd.h>
     63 #include <sys/resourcevar.h>
     64 #include <sys/conf.h>
     65 #include <sys/event.h>
     66 
     67 #include <sys/mount.h>
     68 #include <sys/sa.h>
     69 #include <sys/syscallargs.h>
     70 
     71 /*
     72  * Descriptor management.
     73  */
     74 struct filelist	filehead;	/* head of list of open files */
     75 int		nfiles;		/* actual number of open files */
     76 struct pool	file_pool;	/* memory pool for file structures */
     77 struct pool	cwdi_pool;	/* memory pool for cwdinfo structures */
     78 struct pool	filedesc0_pool;	/* memory pool for filedesc0 structures */
     79 
     80 /* Global file list lock */
     81 static struct simplelock filelist_slock = SIMPLELOCK_INITIALIZER;
     82 
     83 MALLOC_DEFINE(M_FILE, "file", "Open file structure");
     84 MALLOC_DEFINE(M_FILEDESC, "file desc", "Open file descriptor table");
     85 MALLOC_DEFINE(M_IOCTLOPS, "ioctlops", "ioctl data buffer");
     86 
     87 static __inline void	fd_used(struct filedesc *, int);
     88 static __inline void	fd_unused(struct filedesc *, int);
     89 int			finishdup(struct proc *, int, int, register_t *);
     90 int			fcntl_forfs(int, struct proc *, int, void *);
     91 
     92 dev_type_open(filedescopen);
     93 
     94 const struct cdevsw filedesc_cdevsw = {
     95 	filedescopen, noclose, noread, nowrite, noioctl,
     96 	nostop, notty, nopoll, nommap, nokqfilter,
     97 };
     98 
     99 static __inline void
    100 fd_used(struct filedesc *fdp, int fd)
    101 {
    102 
    103 	if (fd > fdp->fd_lastfile)
    104 		fdp->fd_lastfile = fd;
    105 }
    106 
    107 static __inline void
    108 fd_unused(struct filedesc *fdp, int fd)
    109 {
    110 
    111 	if (fd < fdp->fd_freefile)
    112 		fdp->fd_freefile = fd;
    113 #ifdef DIAGNOSTIC
    114 	if (fd > fdp->fd_lastfile)
    115 		panic("fd_unused: fd_lastfile inconsistent");
    116 #endif
    117 	if (fd == fdp->fd_lastfile) {
    118 		do {
    119 			fd--;
    120 		} while (fd >= 0 && fdp->fd_ofiles[fd] == NULL);
    121 		fdp->fd_lastfile = fd;
    122 	}
    123 }
    124 
    125 /*
    126  * Lookup the file structure corresponding to a file descriptor
    127  * and return it locked.
    128  * Note: typical usage is: `fp = fd_getfile(..); FILE_USE(fp);'
    129  * The locking strategy has been optimised for this case, i.e.
    130  * fd_getfile() returns the file locked while FILE_USE() will increment
    131  * the file's use count and unlock.
    132  */
    133 struct file *
    134 fd_getfile(struct filedesc *fdp, int fd)
    135 {
    136 	struct file *fp;
    137 
    138 	if ((u_int) fd >= fdp->fd_nfiles || (fp = fdp->fd_ofiles[fd]) == NULL)
    139 		return (NULL);
    140 
    141 	simple_lock(&fp->f_slock);
    142 	if (FILE_IS_USABLE(fp) == 0) {
    143 		simple_unlock(&fp->f_slock);
    144 		return (NULL);
    145 	}
    146 
    147 	return (fp);
    148 }
    149 
    150 /*
    151  * System calls on descriptors.
    152  */
    153 
    154 /*
    155  * Duplicate a file descriptor.
    156  */
    157 /* ARGSUSED */
    158 int
    159 sys_dup(struct lwp *l, void *v, register_t *retval)
    160 {
    161 	struct sys_dup_args /* {
    162 		syscallarg(int)	fd;
    163 	} */ *uap = v;
    164 	struct file	*fp;
    165 	struct filedesc	*fdp;
    166 	struct proc	*p;
    167 	int		old, new, error;
    168 
    169 	p = l->l_proc;
    170 	fdp = p->p_fd;
    171 	old = SCARG(uap, fd);
    172 
    173  restart:
    174 	if ((fp = fd_getfile(fdp, old)) == NULL)
    175 		return (EBADF);
    176 
    177 	FILE_USE(fp);
    178 
    179 	if ((error = fdalloc(p, 0, &new)) != 0) {
    180 		if (error == ENOSPC) {
    181 			fdexpand(p);
    182 			FILE_UNUSE(fp, p);
    183 			goto restart;
    184 		}
    185 		FILE_UNUSE(fp, p);
    186 		return (error);
    187 	}
    188 
    189 	/* finishdup() will unuse the descriptors for us */
    190 	return (finishdup(p, old, new, retval));
    191 }
    192 
    193 /*
    194  * Duplicate a file descriptor to a particular value.
    195  */
    196 /* ARGSUSED */
    197 int
    198 sys_dup2(struct lwp *l, void *v, register_t *retval)
    199 {
    200 	struct sys_dup2_args /* {
    201 		syscallarg(int)	from;
    202 		syscallarg(int)	to;
    203 	} */ *uap = v;
    204 	struct file	*fp;
    205 	struct filedesc	*fdp;
    206 	struct proc	*p;
    207 	int		old, new, i, error;
    208 
    209 	p = l->l_proc;
    210 	fdp = p->p_fd;
    211 	old = SCARG(uap, from);
    212 	new = SCARG(uap, to);
    213 
    214  restart:
    215 	if ((fp = fd_getfile(fdp, old)) == NULL)
    216 		return (EBADF);
    217 
    218 	if ((u_int)new >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
    219 	    (u_int)new >= maxfiles) {
    220 		simple_unlock(&fp->f_slock);
    221 		return (EBADF);
    222 	}
    223 
    224 	if (old == new) {
    225 		simple_unlock(&fp->f_slock);
    226 		*retval = new;
    227 		return (0);
    228 	}
    229 
    230 	FILE_USE(fp);
    231 
    232 	if (new >= fdp->fd_nfiles) {
    233 		if ((error = fdalloc(p, new, &i)) != 0) {
    234 			if (error == ENOSPC) {
    235 				fdexpand(p);
    236 				FILE_UNUSE(fp, p);
    237 				goto restart;
    238 			}
    239 			FILE_UNUSE(fp, p);
    240 			return (error);
    241 		}
    242 		if (new != i)
    243 			panic("dup2: fdalloc");
    244 	}
    245 
    246 	/*
    247 	 * finishdup() will close the file that's in the `new'
    248 	 * slot, if there's one there.
    249 	 */
    250 
    251 	/* finishdup() will unuse the descriptors for us */
    252 	return (finishdup(p, old, new, retval));
    253 }
    254 
    255 /*
    256  * The file control system call.
    257  */
    258 /* ARGSUSED */
    259 int
    260 sys_fcntl(struct lwp *l, void *v, register_t *retval)
    261 {
    262 	struct sys_fcntl_args /* {
    263 		syscallarg(int)		fd;
    264 		syscallarg(int)		cmd;
    265 		syscallarg(void *)	arg;
    266 	} */ *uap = v;
    267 	struct filedesc *fdp;
    268 	struct file	*fp;
    269 	struct proc	*p;
    270 	struct vnode	*vp;
    271 	int		fd, i, tmp, error, flg, cmd, newmin;
    272 	struct flock	fl;
    273 
    274 	p = l->l_proc;
    275 	fd = SCARG(uap, fd);
    276 	fdp = p->p_fd;
    277 	error = 0;
    278 	flg = F_POSIX;
    279 
    280  restart:
    281 	if ((fp = fd_getfile(fdp, fd)) == NULL)
    282 		return (EBADF);
    283 
    284 	FILE_USE(fp);
    285 
    286 	cmd = SCARG(uap, cmd);
    287 	if ((cmd & F_FSCTL)) {
    288 		error = fcntl_forfs(fd, p, cmd, SCARG(uap, arg));
    289 		goto out;
    290 	}
    291 
    292 	switch (cmd) {
    293 
    294 	case F_DUPFD:
    295 		newmin = (long)SCARG(uap, arg);
    296 		if ((u_int)newmin >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
    297 		    (u_int)newmin >= maxfiles) {
    298 			error = EINVAL;
    299 			goto out;
    300 		}
    301 		if ((error = fdalloc(p, newmin, &i)) != 0) {
    302 			if (error == ENOSPC) {
    303 				fdexpand(p);
    304 				FILE_UNUSE(fp, p);
    305 				goto restart;
    306 			}
    307 			goto out;
    308 		}
    309 
    310 		/* finishdup() will unuse the descriptors for us */
    311 		return (finishdup(p, fd, i, retval));
    312 
    313 	case F_GETFD:
    314 		*retval = fdp->fd_ofileflags[fd] & UF_EXCLOSE ? 1 : 0;
    315 		break;
    316 
    317 	case F_SETFD:
    318 		if ((long)SCARG(uap, arg) & 1)
    319 			fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
    320 		else
    321 			fdp->fd_ofileflags[fd] &= ~UF_EXCLOSE;
    322 		break;
    323 
    324 	case F_GETFL:
    325 		*retval = OFLAGS(fp->f_flag);
    326 		break;
    327 
    328 	case F_SETFL:
    329 		tmp = FFLAGS((long)SCARG(uap, arg)) & FCNTLFLAGS;
    330 		error = (*fp->f_ops->fo_fcntl)(fp, F_SETFL, (caddr_t)&tmp, p);
    331 		if (error)
    332 			goto out;
    333 		fp->f_flag &= ~FCNTLFLAGS;
    334 		fp->f_flag |= tmp;
    335 		tmp = fp->f_flag & FNONBLOCK;
    336 		error = (*fp->f_ops->fo_ioctl)(fp, FIONBIO, (caddr_t)&tmp, p);
    337 		if (error)
    338 			goto out;
    339 		tmp = fp->f_flag & FASYNC;
    340 		error = (*fp->f_ops->fo_ioctl)(fp, FIOASYNC, (caddr_t)&tmp, p);
    341 		if (error == 0)
    342 			goto out;
    343 		fp->f_flag &= ~FNONBLOCK;
    344 		tmp = 0;
    345 		(void) (*fp->f_ops->fo_ioctl)(fp, FIONBIO, (caddr_t)&tmp, p);
    346 		break;
    347 
    348 	case F_GETOWN:
    349 		if (fp->f_type == DTYPE_SOCKET) {
    350 			*retval = ((struct socket *)fp->f_data)->so_pgid;
    351 			goto out;
    352 		}
    353 		error = (*fp->f_ops->fo_ioctl)
    354 			(fp, TIOCGPGRP, (caddr_t)&tmp, p);
    355 		*retval = -tmp;
    356 		break;
    357 
    358 	case F_SETOWN:
    359 		if (fp->f_type == DTYPE_SOCKET) {
    360 			((struct socket *)fp->f_data)->so_pgid =
    361 			    (long)SCARG(uap, arg);
    362 			goto out;
    363 		}
    364 		if ((long)SCARG(uap, arg) <= 0) {
    365 			tmp = (-(long)SCARG(uap, arg));
    366 		} else {
    367 			struct proc *p1 = pfind((long)SCARG(uap, arg));
    368 			if (p1 == 0) {
    369 				error = ESRCH;
    370 				goto out;
    371 			}
    372 			tmp = (long)p1->p_pgrp->pg_id;
    373 		}
    374 		error = (*fp->f_ops->fo_ioctl)
    375 		    (fp, TIOCSPGRP, (caddr_t)&tmp, p);
    376 		break;
    377 
    378 	case F_SETLKW:
    379 		flg |= F_WAIT;
    380 		/* Fall into F_SETLK */
    381 
    382 	case F_SETLK:
    383 		if (fp->f_type != DTYPE_VNODE) {
    384 			error = EINVAL;
    385 			goto out;
    386 		}
    387 		vp = (struct vnode *)fp->f_data;
    388 		/* Copy in the lock structure */
    389 		error = copyin((caddr_t)SCARG(uap, arg), (caddr_t)&fl,
    390 		    sizeof(fl));
    391 		if (error)
    392 			goto out;
    393 		if (fl.l_whence == SEEK_CUR)
    394 			fl.l_start += fp->f_offset;
    395 		switch (fl.l_type) {
    396 		case F_RDLCK:
    397 			if ((fp->f_flag & FREAD) == 0) {
    398 				error = EBADF;
    399 				goto out;
    400 			}
    401 			p->p_flag |= P_ADVLOCK;
    402 			error = VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &fl, flg);
    403 			goto out;
    404 
    405 		case F_WRLCK:
    406 			if ((fp->f_flag & FWRITE) == 0) {
    407 				error = EBADF;
    408 				goto out;
    409 			}
    410 			p->p_flag |= P_ADVLOCK;
    411 			error = VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &fl, flg);
    412 			goto out;
    413 
    414 		case F_UNLCK:
    415 			error = VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &fl,
    416 			    F_POSIX);
    417 			goto out;
    418 
    419 		default:
    420 			error = EINVAL;
    421 			goto out;
    422 		}
    423 
    424 	case F_GETLK:
    425 		if (fp->f_type != DTYPE_VNODE) {
    426 			error = EINVAL;
    427 			goto out;
    428 		}
    429 		vp = (struct vnode *)fp->f_data;
    430 		/* Copy in the lock structure */
    431 		error = copyin((caddr_t)SCARG(uap, arg), (caddr_t)&fl,
    432 		    sizeof(fl));
    433 		if (error)
    434 			goto out;
    435 		if (fl.l_whence == SEEK_CUR)
    436 			fl.l_start += fp->f_offset;
    437 		if (fl.l_type != F_RDLCK &&
    438 		    fl.l_type != F_WRLCK &&
    439 		    fl.l_type != F_UNLCK) {
    440 			error = EINVAL;
    441 			goto out;
    442 		}
    443 		error = VOP_ADVLOCK(vp, (caddr_t)p, F_GETLK, &fl, F_POSIX);
    444 		if (error)
    445 			goto out;
    446 		error = copyout((caddr_t)&fl, (caddr_t)SCARG(uap, arg),
    447 		    sizeof(fl));
    448 		break;
    449 
    450 	default:
    451 		error = EINVAL;
    452 	}
    453 
    454  out:
    455 	FILE_UNUSE(fp, p);
    456 	return (error);
    457 }
    458 
    459 /*
    460  * Common code for dup, dup2, and fcntl(F_DUPFD).
    461  */
    462 int
    463 finishdup(struct proc *p, int old, int new, register_t *retval)
    464 {
    465 	struct filedesc	*fdp;
    466 	struct file	*fp, *delfp;
    467 
    468 	fdp = p->p_fd;
    469 
    470 	/*
    471 	 * If there is a file in the new slot, remember it so we
    472 	 * can close it after we've finished the dup.  We need
    473 	 * to do it after the dup is finished, since closing
    474 	 * the file may block.
    475 	 *
    476 	 * Note: `old' is already used for us.
    477 	 */
    478 	delfp = fdp->fd_ofiles[new];
    479 
    480 	fp = fdp->fd_ofiles[old];
    481 	fdp->fd_ofiles[new] = fp;
    482 	fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
    483 	fp->f_count++;
    484 	/*
    485 	 * Note, don't have to mark it "used" in the table if there
    486 	 * was already a file in the `new' slot.
    487 	 */
    488 	if (delfp == NULL)
    489 		fd_used(fdp, new);
    490 	*retval = new;
    491 	FILE_UNUSE(fp, p);
    492 
    493 	if (delfp != NULL) {
    494 		simple_lock(&delfp->f_slock);
    495 		FILE_USE(delfp);
    496 		if (new < fdp->fd_knlistsize)
    497 			knote_fdclose(p, new);
    498 		(void) closef(delfp, p);
    499 	}
    500 	return (0);
    501 }
    502 
    503 void
    504 fdremove(struct filedesc *fdp, int fd)
    505 {
    506 
    507 	fdp->fd_ofiles[fd] = NULL;
    508 	fd_unused(fdp, fd);
    509 }
    510 
    511 int
    512 fdrelease(struct proc *p, int fd)
    513 {
    514 	struct filedesc	*fdp;
    515 	struct file	**fpp, *fp;
    516 
    517 	fdp = p->p_fd;
    518 	fpp = &fdp->fd_ofiles[fd];
    519 	fp = *fpp;
    520 	if (fp == NULL)
    521 		return (EBADF);
    522 
    523 	simple_lock(&fp->f_slock);
    524 	if (!FILE_IS_USABLE(fp)) {
    525 		simple_unlock(&fp->f_slock);
    526 		return (EBADF);
    527 	}
    528 
    529 	FILE_USE(fp);
    530 
    531 	*fpp = NULL;
    532 	fdp->fd_ofileflags[fd] = 0;
    533 	if (fd < fdp->fd_knlistsize)
    534 		knote_fdclose(p, fd);
    535 	fd_unused(fdp, fd);
    536 	return (closef(fp, p));
    537 }
    538 
    539 /*
    540  * Close a file descriptor.
    541  */
    542 /* ARGSUSED */
    543 int
    544 sys_close(struct lwp *l, void *v, register_t *retval)
    545 {
    546 	struct sys_close_args /* {
    547 		syscallarg(int)	fd;
    548 	} */ *uap = v;
    549 	int		fd;
    550 	struct filedesc	*fdp;
    551 	struct proc *p;
    552 
    553 	p = l->l_proc;
    554 	fd = SCARG(uap, fd);
    555 	fdp = p->p_fd;
    556 
    557 	if ((u_int) fd >= fdp->fd_nfiles)
    558 		return (NULL);
    559 #if 0
    560 	if (fd_getfile(fdp, fd) == NULL)
    561 		return (EBADF);
    562 #endif
    563 
    564 	return (fdrelease(p, fd));
    565 }
    566 
    567 /*
    568  * Return status information about a file descriptor.
    569  */
    570 /* ARGSUSED */
    571 int
    572 sys___fstat13(struct lwp *l, void *v, register_t *retval)
    573 {
    574 	struct sys___fstat13_args /* {
    575 		syscallarg(int)			fd;
    576 		syscallarg(struct stat *)	sb;
    577 	} */ *uap = v;
    578 	int		fd;
    579 	struct filedesc	*fdp;
    580 	struct file	*fp;
    581 	struct proc	*p;
    582 	struct stat	ub;
    583 	int		error;
    584 
    585 	p = l->l_proc;
    586 	fd = SCARG(uap, fd);
    587 	fdp = p->p_fd;
    588 
    589 	if ((fp = fd_getfile(fdp, fd)) == NULL)
    590 		return (EBADF);
    591 
    592 	FILE_USE(fp);
    593 	error = (*fp->f_ops->fo_stat)(fp, &ub, p);
    594 	FILE_UNUSE(fp, p);
    595 
    596 	if (error == 0)
    597 		error = copyout(&ub, SCARG(uap, sb), sizeof(ub));
    598 
    599 	return (error);
    600 }
    601 
    602 /*
    603  * Return pathconf information about a file descriptor.
    604  */
    605 /* ARGSUSED */
    606 int
    607 sys_fpathconf(struct lwp *l, void *v, register_t *retval)
    608 {
    609 	struct sys_fpathconf_args /* {
    610 		syscallarg(int)	fd;
    611 		syscallarg(int)	name;
    612 	} */ *uap = v;
    613 	int		fd;
    614 	struct filedesc	*fdp;
    615 	struct file	*fp;
    616 	struct proc 	*p;
    617 	struct vnode	*vp;
    618 	int		error;
    619 
    620 	p = l->l_proc;
    621 	fd = SCARG(uap, fd);
    622 	fdp = p->p_fd;
    623 	error = 0;
    624 
    625 	if ((fp = fd_getfile(fdp, fd)) == NULL)
    626 		return (EBADF);
    627 
    628 	FILE_USE(fp);
    629 
    630 	switch (fp->f_type) {
    631 
    632 	case DTYPE_SOCKET:
    633 	case DTYPE_PIPE:
    634 		if (SCARG(uap, name) != _PC_PIPE_BUF)
    635 			error = EINVAL;
    636 		else
    637 			*retval = PIPE_BUF;
    638 		break;
    639 
    640 	case DTYPE_VNODE:
    641 		vp = (struct vnode *)fp->f_data;
    642 		error = VOP_PATHCONF(vp, SCARG(uap, name), retval);
    643 		break;
    644 
    645 	case DTYPE_KQUEUE:
    646 		error = EINVAL;
    647 		break;
    648 
    649 	default:
    650 		error = EOPNOTSUPP;
    651 		break;
    652 	}
    653 
    654 	FILE_UNUSE(fp, p);
    655 	return (error);
    656 }
    657 
    658 /*
    659  * Allocate a file descriptor for the process.
    660  */
    661 int	fdexpanded;		/* XXX: what else uses this? */
    662 
    663 int
    664 fdalloc(struct proc *p, int want, int *result)
    665 {
    666 	struct filedesc	*fdp;
    667 	int i, lim, last;
    668 
    669 	fdp = p->p_fd;
    670 
    671 	/*
    672 	 * Search for a free descriptor starting at the higher
    673 	 * of want or fd_freefile.  If that fails, consider
    674 	 * expanding the ofile array.
    675 	 */
    676 	lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
    677 	last = min(fdp->fd_nfiles, lim);
    678 	if ((i = want) < fdp->fd_freefile)
    679 		i = fdp->fd_freefile;
    680 	for (; i < last; i++) {
    681 		if (fdp->fd_ofiles[i] == NULL) {
    682 			fd_used(fdp, i);
    683 			if (want <= fdp->fd_freefile)
    684 				fdp->fd_freefile = i;
    685 			*result = i;
    686 			return (0);
    687 		}
    688 	}
    689 
    690 	/* No space in current array.  Expand? */
    691 	if (fdp->fd_nfiles >= lim)
    692 		return (EMFILE);
    693 
    694 	/* Let the caller do it. */
    695 	return (ENOSPC);
    696 }
    697 
    698 void
    699 fdexpand(struct proc *p)
    700 {
    701 	struct filedesc	*fdp;
    702 	int		i, nfiles;
    703 	struct file	**newofile;
    704 	char		*newofileflags;
    705 
    706 	fdp = p->p_fd;
    707 
    708 	if (fdp->fd_nfiles < NDEXTENT)
    709 		nfiles = NDEXTENT;
    710 	else
    711 		nfiles = 2 * fdp->fd_nfiles;
    712 	newofile = malloc(nfiles * OFILESIZE, M_FILEDESC, M_WAITOK);
    713 	newofileflags = (char *) &newofile[nfiles];
    714 	/*
    715 	 * Copy the existing ofile and ofileflags arrays
    716 	 * and zero the new portion of each array.
    717 	 */
    718 	memcpy(newofile, fdp->fd_ofiles,
    719 	    (i = sizeof(struct file *) * fdp->fd_nfiles));
    720 	memset((char *)newofile + i, 0,
    721 	    nfiles * sizeof(struct file *) - i);
    722 	memcpy(newofileflags, fdp->fd_ofileflags,
    723 	    (i = sizeof(char) * fdp->fd_nfiles));
    724 	memset(newofileflags + i, 0, nfiles * sizeof(char) - i);
    725 	if (fdp->fd_nfiles > NDFILE)
    726 		free(fdp->fd_ofiles, M_FILEDESC);
    727 	fdp->fd_ofiles = newofile;
    728 	fdp->fd_ofileflags = newofileflags;
    729 	fdp->fd_nfiles = nfiles;
    730 	fdexpanded++;
    731 }
    732 
    733 /*
    734  * Check to see whether n user file descriptors
    735  * are available to the process p.
    736  */
    737 int
    738 fdavail(struct proc *p, int n)
    739 {
    740 	struct filedesc	*fdp;
    741 	struct file	**fpp;
    742 	int		i, lim;
    743 
    744 	fdp = p->p_fd;
    745 	lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
    746 	if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
    747 		return (1);
    748 	fpp = &fdp->fd_ofiles[fdp->fd_freefile];
    749 	for (i = min(lim,fdp->fd_nfiles) - fdp->fd_freefile; --i >= 0; fpp++)
    750 		if (*fpp == NULL && --n <= 0)
    751 			return (1);
    752 	return (0);
    753 }
    754 
    755 /*
    756  * Initialize the data structures necessary for managing files.
    757  */
    758 void
    759 finit(void)
    760 {
    761 
    762 	pool_init(&file_pool, sizeof(struct file), 0, 0, 0, "filepl",
    763 	    &pool_allocator_nointr);
    764 	pool_init(&cwdi_pool, sizeof(struct cwdinfo), 0, 0, 0, "cwdipl",
    765 	    &pool_allocator_nointr);
    766 	pool_init(&filedesc0_pool, sizeof(struct filedesc0), 0, 0, 0, "fdescpl",
    767 	    &pool_allocator_nointr);
    768 }
    769 
    770 /*
    771  * Create a new open file structure and allocate
    772  * a file descriptor for the process that refers to it.
    773  */
    774 int
    775 falloc(struct proc *p, struct file **resultfp, int *resultfd)
    776 {
    777 	struct file	*fp, *fq;
    778 	int		error, i;
    779 
    780  restart:
    781 	if ((error = fdalloc(p, 0, &i)) != 0) {
    782 		if (error == ENOSPC) {
    783 			fdexpand(p);
    784 			goto restart;
    785 		}
    786 		return (error);
    787 	}
    788 
    789 	fp = pool_get(&file_pool, PR_WAITOK);
    790 	simple_lock(&filelist_slock);
    791 	if (nfiles >= maxfiles) {
    792 		tablefull("file", "increase kern.maxfiles or MAXFILES");
    793 		simple_unlock(&filelist_slock);
    794 		pool_put(&file_pool, fp);
    795 		return (ENFILE);
    796 	}
    797 	/*
    798 	 * Allocate a new file descriptor.
    799 	 * If the process has file descriptor zero open, add to the list
    800 	 * of open files at that point, otherwise put it at the front of
    801 	 * the list of open files.
    802 	 */
    803 	nfiles++;
    804 	memset(fp, 0, sizeof(struct file));
    805 	fp->f_iflags = FIF_LARVAL;
    806 	if ((fq = p->p_fd->fd_ofiles[0]) != NULL) {
    807 		LIST_INSERT_AFTER(fq, fp, f_list);
    808 	} else {
    809 		LIST_INSERT_HEAD(&filehead, fp, f_list);
    810 	}
    811 	simple_unlock(&filelist_slock);
    812 	p->p_fd->fd_ofiles[i] = fp;
    813 	simple_lock_init(&fp->f_slock);
    814 	fp->f_count = 1;
    815 	fp->f_cred = p->p_ucred;
    816 	crhold(fp->f_cred);
    817 	if (resultfp) {
    818 		fp->f_usecount = 1;
    819 		*resultfp = fp;
    820 	}
    821 	if (resultfd)
    822 		*resultfd = i;
    823 	return (0);
    824 }
    825 
    826 /*
    827  * Free a file descriptor.
    828  */
    829 void
    830 ffree(struct file *fp)
    831 {
    832 
    833 #ifdef DIAGNOSTIC
    834 	if (fp->f_usecount)
    835 		panic("ffree");
    836 #endif
    837 
    838 	simple_lock(&filelist_slock);
    839 	LIST_REMOVE(fp, f_list);
    840 	crfree(fp->f_cred);
    841 #ifdef DIAGNOSTIC
    842 	fp->f_count = 0; /* What's the point? */
    843 #endif
    844 	nfiles--;
    845 	simple_unlock(&filelist_slock);
    846 	pool_put(&file_pool, fp);
    847 }
    848 
    849 /*
    850  * Create an initial cwdinfo structure, using the same current and root
    851  * directories as p.
    852  */
    853 struct cwdinfo *
    854 cwdinit(struct proc *p)
    855 {
    856 	struct cwdinfo *cwdi;
    857 
    858 	cwdi = pool_get(&cwdi_pool, PR_WAITOK);
    859 
    860 	cwdi->cwdi_cdir = p->p_cwdi->cwdi_cdir;
    861 	if (cwdi->cwdi_cdir)
    862 		VREF(cwdi->cwdi_cdir);
    863 	cwdi->cwdi_rdir = p->p_cwdi->cwdi_rdir;
    864 	if (cwdi->cwdi_rdir)
    865 		VREF(cwdi->cwdi_rdir);
    866 	cwdi->cwdi_cmask =  p->p_cwdi->cwdi_cmask;
    867 	cwdi->cwdi_refcnt = 1;
    868 
    869 	return (cwdi);
    870 }
    871 
    872 /*
    873  * Make p2 share p1's cwdinfo.
    874  */
    875 void
    876 cwdshare(struct proc *p1, struct proc *p2)
    877 {
    878 
    879 	p2->p_cwdi = p1->p_cwdi;
    880 	p1->p_cwdi->cwdi_refcnt++;
    881 }
    882 
    883 /*
    884  * Make this process not share its cwdinfo structure, maintaining
    885  * all cwdinfo state.
    886  */
    887 void
    888 cwdunshare(struct proc *p)
    889 {
    890 	struct cwdinfo *newcwdi;
    891 
    892 	if (p->p_cwdi->cwdi_refcnt == 1)
    893 		return;
    894 
    895 	newcwdi = cwdinit(p);
    896 	cwdfree(p);
    897 	p->p_cwdi = newcwdi;
    898 }
    899 
    900 /*
    901  * Release a cwdinfo structure.
    902  */
    903 void
    904 cwdfree(struct proc *p)
    905 {
    906 	struct cwdinfo *cwdi;
    907 
    908 	cwdi = p->p_cwdi;
    909 	if (--cwdi->cwdi_refcnt > 0)
    910 		return;
    911 
    912 	p->p_cwdi = NULL;
    913 
    914 	vrele(cwdi->cwdi_cdir);
    915 	if (cwdi->cwdi_rdir)
    916 		vrele(cwdi->cwdi_rdir);
    917 	pool_put(&cwdi_pool, cwdi);
    918 }
    919 
    920 /*
    921  * Create an initial filedesc structure, using the same current and root
    922  * directories as p.
    923  */
    924 struct filedesc *
    925 fdinit(struct proc *p)
    926 {
    927 	struct filedesc0 *newfdp;
    928 
    929 	newfdp = pool_get(&filedesc0_pool, PR_WAITOK);
    930 	memset(newfdp, 0, sizeof(struct filedesc0));
    931 
    932 	fdinit1(newfdp);
    933 
    934 	return (&newfdp->fd_fd);
    935 }
    936 
    937 /*
    938  * Initialize a file descriptor table.
    939  */
    940 void
    941 fdinit1(struct filedesc0 *newfdp)
    942 {
    943 
    944 	newfdp->fd_fd.fd_refcnt = 1;
    945 	newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
    946 	newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
    947 	newfdp->fd_fd.fd_nfiles = NDFILE;
    948 	newfdp->fd_fd.fd_knlistsize = -1;
    949 }
    950 
    951 /*
    952  * Make p2 share p1's filedesc structure.
    953  */
    954 void
    955 fdshare(struct proc *p1, struct proc *p2)
    956 {
    957 
    958 	p2->p_fd = p1->p_fd;
    959 	p1->p_fd->fd_refcnt++;
    960 }
    961 
    962 /*
    963  * Make this process not share its filedesc structure, maintaining
    964  * all file descriptor state.
    965  */
    966 void
    967 fdunshare(struct proc *p)
    968 {
    969 	struct filedesc *newfd;
    970 
    971 	if (p->p_fd->fd_refcnt == 1)
    972 		return;
    973 
    974 	newfd = fdcopy(p);
    975 	fdfree(p);
    976 	p->p_fd = newfd;
    977 }
    978 
    979 /*
    980  * Clear a process's fd table.
    981  */
    982 void
    983 fdclear(struct proc *p)
    984 {
    985 	struct filedesc *newfd;
    986 
    987 	newfd = fdinit(p);
    988 	fdfree(p);
    989 	p->p_fd = newfd;
    990 }
    991 
    992 /*
    993  * Copy a filedesc structure.
    994  */
    995 struct filedesc *
    996 fdcopy(struct proc *p)
    997 {
    998 	struct filedesc	*newfdp, *fdp;
    999 	struct file	**fpp;
   1000 	int		i;
   1001 
   1002 	fdp = p->p_fd;
   1003 	newfdp = pool_get(&filedesc0_pool, PR_WAITOK);
   1004 	memcpy(newfdp, fdp, sizeof(struct filedesc));
   1005 	newfdp->fd_refcnt = 1;
   1006 
   1007 	/*
   1008 	 * If the number of open files fits in the internal arrays
   1009 	 * of the open file structure, use them, otherwise allocate
   1010 	 * additional memory for the number of descriptors currently
   1011 	 * in use.
   1012 	 */
   1013 	if (newfdp->fd_lastfile < NDFILE) {
   1014 		newfdp->fd_ofiles = ((struct filedesc0 *) newfdp)->fd_dfiles;
   1015 		newfdp->fd_ofileflags =
   1016 		    ((struct filedesc0 *) newfdp)->fd_dfileflags;
   1017 		i = NDFILE;
   1018 	} else {
   1019 		/*
   1020 		 * Compute the smallest multiple of NDEXTENT needed
   1021 		 * for the file descriptors currently in use,
   1022 		 * allowing the table to shrink.
   1023 		 */
   1024 		i = newfdp->fd_nfiles;
   1025 		while (i >= 2 * NDEXTENT && i > newfdp->fd_lastfile * 2)
   1026 			i /= 2;
   1027 		newfdp->fd_ofiles = malloc(i * OFILESIZE, M_FILEDESC, M_WAITOK);
   1028 		newfdp->fd_ofileflags = (char *) &newfdp->fd_ofiles[i];
   1029 	}
   1030 	newfdp->fd_nfiles = i;
   1031 	memcpy(newfdp->fd_ofiles, fdp->fd_ofiles, i * sizeof(struct file **));
   1032 	memcpy(newfdp->fd_ofileflags, fdp->fd_ofileflags, i * sizeof(char));
   1033 	/*
   1034 	 * kq descriptors cannot be copied.
   1035 	 */
   1036 	if (newfdp->fd_knlistsize != -1) {
   1037 		fpp = newfdp->fd_ofiles;
   1038 		for (i = newfdp->fd_lastfile; i-- >= 0; fpp++) {
   1039 			if (*fpp != NULL && (*fpp)->f_type == DTYPE_KQUEUE)
   1040 				*fpp = NULL;
   1041 		}
   1042 		newfdp->fd_knlist = NULL;
   1043 		newfdp->fd_knlistsize = -1;
   1044 		newfdp->fd_knhash = NULL;
   1045 		newfdp->fd_knhashmask = 0;
   1046 	}
   1047 	fpp = newfdp->fd_ofiles;
   1048 	for (i = newfdp->fd_lastfile; i >= 0; i--, fpp++)
   1049 		if (*fpp != NULL)
   1050 			(*fpp)->f_count++;
   1051 	return (newfdp);
   1052 }
   1053 
   1054 /*
   1055  * Release a filedesc structure.
   1056  */
   1057 void
   1058 fdfree(struct proc *p)
   1059 {
   1060 	struct filedesc	*fdp;
   1061 	struct file	**fpp, *fp;
   1062 	int		i;
   1063 
   1064 	fdp = p->p_fd;
   1065 	if (--fdp->fd_refcnt > 0)
   1066 		return;
   1067 	fpp = fdp->fd_ofiles;
   1068 	for (i = fdp->fd_lastfile; i >= 0; i--, fpp++) {
   1069 		fp = *fpp;
   1070 		if (fp != NULL) {
   1071 			*fpp = NULL;
   1072 			simple_lock(&fp->f_slock);
   1073 			FILE_USE(fp);
   1074 			if (i < fdp->fd_knlistsize)
   1075 				knote_fdclose(p, fdp->fd_lastfile - i);
   1076 			(void) closef(fp, p);
   1077 		}
   1078 	}
   1079 	p->p_fd = NULL;
   1080 	if (fdp->fd_nfiles > NDFILE)
   1081 		free(fdp->fd_ofiles, M_FILEDESC);
   1082 	if (fdp->fd_knlist)
   1083 		free(fdp->fd_knlist, M_KEVENT);
   1084 	if (fdp->fd_knhash)
   1085 		hashdone(fdp->fd_knhash, M_KEVENT);
   1086 	pool_put(&filedesc0_pool, fdp);
   1087 }
   1088 
   1089 /*
   1090  * Internal form of close.
   1091  * Decrement reference count on file structure.
   1092  * Note: p may be NULL when closing a file
   1093  * that was being passed in a message.
   1094  *
   1095  * Note: we expect the caller is holding a usecount, and expects us
   1096  * to drop it (the caller thinks the file is going away forever).
   1097  */
   1098 int
   1099 closef(struct file *fp, struct proc *p)
   1100 {
   1101 	struct vnode	*vp;
   1102 	struct flock	lf;
   1103 	int		error;
   1104 
   1105 	if (fp == NULL)
   1106 		return (0);
   1107 
   1108 	/*
   1109 	 * POSIX record locking dictates that any close releases ALL
   1110 	 * locks owned by this process.  This is handled by setting
   1111 	 * a flag in the unlock to free ONLY locks obeying POSIX
   1112 	 * semantics, and not to free BSD-style file locks.
   1113 	 * If the descriptor was in a message, POSIX-style locks
   1114 	 * aren't passed with the descriptor.
   1115 	 */
   1116 	if (p && (p->p_flag & P_ADVLOCK) && fp->f_type == DTYPE_VNODE) {
   1117 		lf.l_whence = SEEK_SET;
   1118 		lf.l_start = 0;
   1119 		lf.l_len = 0;
   1120 		lf.l_type = F_UNLCK;
   1121 		vp = (struct vnode *)fp->f_data;
   1122 		(void) VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, F_POSIX);
   1123 	}
   1124 
   1125 	/*
   1126 	 * If WANTCLOSE is set, then the reference count on the file
   1127 	 * is 0, but there were multiple users of the file.  This can
   1128 	 * happen if a filedesc structure is shared by multiple
   1129 	 * processes.
   1130 	 */
   1131 	simple_lock(&fp->f_slock);
   1132 	if (fp->f_iflags & FIF_WANTCLOSE) {
   1133 		/*
   1134 		 * Another user of the file is already closing, and is
   1135 		 * simply waiting for other users of the file to drain.
   1136 		 * Release our usecount, and wake up the closer if it
   1137 		 * is the only remaining use.
   1138 		 */
   1139 #ifdef DIAGNOSTIC
   1140 		if (fp->f_count != 0)
   1141 			panic("closef: wantclose and count != 0");
   1142 		if (fp->f_usecount < 2)
   1143 			panic("closef: wantclose and usecount < 2");
   1144 #endif
   1145 		if (--fp->f_usecount == 1)
   1146 			wakeup(&fp->f_usecount);
   1147 		simple_unlock(&fp->f_slock);
   1148 		return (0);
   1149 	} else {
   1150 		/*
   1151 		 * Decrement the reference count.  If we were not the
   1152 		 * last reference, then release our use and just
   1153 		 * return.
   1154 		 */
   1155 		if (--fp->f_count > 0) {
   1156 #ifdef DIAGNOSTIC
   1157 			if (fp->f_usecount < 1)
   1158 				panic("closef: no wantclose and usecount < 1");
   1159 #endif
   1160 			fp->f_usecount--;
   1161 			simple_unlock(&fp->f_slock);
   1162 			return (0);
   1163 		}
   1164 	}
   1165 
   1166 	/*
   1167 	 * The reference count is now 0.  However, there may be
   1168 	 * multiple potential users of this file.  This can happen
   1169 	 * if multiple processes shared a single filedesc structure.
   1170 	 *
   1171 	 * Notify these potential users that the file is closing.
   1172 	 * This will prevent them from adding additional uses to
   1173 	 * the file.
   1174 	 */
   1175 	fp->f_iflags |= FIF_WANTCLOSE;
   1176 
   1177 	/*
   1178 	 * We expect the caller to add a use to the file.  So, if we
   1179 	 * are the last user, usecount will be 1.  If it is not, we
   1180 	 * must wait for the usecount to drain.  When it drains back
   1181 	 * to 1, we will be awakened so that we may proceed with the
   1182 	 * close.
   1183 	 */
   1184 #ifdef DIAGNOSTIC
   1185 	if (fp->f_usecount < 1)
   1186 		panic("closef: usecount < 1");
   1187 #endif
   1188 	while (fp->f_usecount > 1)
   1189 		(void) ltsleep(&fp->f_usecount, PRIBIO, "closef", 0,
   1190 				&fp->f_slock);
   1191 #ifdef DIAGNOSTIC
   1192 	if (fp->f_usecount != 1)
   1193 		panic("closef: usecount != 1");
   1194 #endif
   1195 
   1196 	simple_unlock(&fp->f_slock);
   1197 	if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
   1198 		lf.l_whence = SEEK_SET;
   1199 		lf.l_start = 0;
   1200 		lf.l_len = 0;
   1201 		lf.l_type = F_UNLCK;
   1202 		vp = (struct vnode *)fp->f_data;
   1203 		(void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
   1204 	}
   1205 	if (fp->f_ops)
   1206 		error = (*fp->f_ops->fo_close)(fp, p);
   1207 	else
   1208 		error = 0;
   1209 
   1210 	/* Nothing references the file now, drop the final use (us). */
   1211 	fp->f_usecount--;
   1212 
   1213 	ffree(fp);
   1214 	return (error);
   1215 }
   1216 
   1217 /*
   1218  * Apply an advisory lock on a file descriptor.
   1219  *
   1220  * Just attempt to get a record lock of the requested type on
   1221  * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
   1222  */
   1223 /* ARGSUSED */
   1224 int
   1225 sys_flock(struct lwp *l, void *v, register_t *retval)
   1226 {
   1227 	struct sys_flock_args /* {
   1228 		syscallarg(int)	fd;
   1229 		syscallarg(int)	how;
   1230 	} */ *uap = v;
   1231 	int		fd, how, error;
   1232 	struct proc	*p;
   1233 	struct filedesc	*fdp;
   1234 	struct file	*fp;
   1235 	struct vnode	*vp;
   1236 	struct flock	lf;
   1237 
   1238 	p = l->l_proc;
   1239 	fd = SCARG(uap, fd);
   1240 	how = SCARG(uap, how);
   1241 	fdp = p->p_fd;
   1242 	error = 0;
   1243 
   1244 	if ((fp = fd_getfile(fdp, fd)) == NULL)
   1245 		return (EBADF);
   1246 
   1247 	FILE_USE(fp);
   1248 
   1249 	if (fp->f_type != DTYPE_VNODE) {
   1250 		error = EOPNOTSUPP;
   1251 		goto out;
   1252 	}
   1253 
   1254 	vp = (struct vnode *)fp->f_data;
   1255 	lf.l_whence = SEEK_SET;
   1256 	lf.l_start = 0;
   1257 	lf.l_len = 0;
   1258 	if (how & LOCK_UN) {
   1259 		lf.l_type = F_UNLCK;
   1260 		fp->f_flag &= ~FHASLOCK;
   1261 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
   1262 		goto out;
   1263 	}
   1264 	if (how & LOCK_EX)
   1265 		lf.l_type = F_WRLCK;
   1266 	else if (how & LOCK_SH)
   1267 		lf.l_type = F_RDLCK;
   1268 	else {
   1269 		error = EINVAL;
   1270 		goto out;
   1271 	}
   1272 	fp->f_flag |= FHASLOCK;
   1273 	if (how & LOCK_NB)
   1274 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK);
   1275 	else
   1276 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
   1277 		    F_FLOCK|F_WAIT);
   1278  out:
   1279 	FILE_UNUSE(fp, p);
   1280 	return (error);
   1281 }
   1282 
   1283 /*
   1284  * File Descriptor pseudo-device driver (/dev/fd/).
   1285  *
   1286  * Opening minor device N dup()s the file (if any) connected to file
   1287  * descriptor N belonging to the calling process.  Note that this driver
   1288  * consists of only the ``open()'' routine, because all subsequent
   1289  * references to this file will be direct to the other driver.
   1290  */
   1291 /* ARGSUSED */
   1292 int
   1293 filedescopen(dev_t dev, int mode, int type, struct proc *p)
   1294 {
   1295 
   1296 	/*
   1297 	 * XXX Kludge: set p->p_dupfd to contain the value of the
   1298 	 * the file descriptor being sought for duplication. The error
   1299 	 * return ensures that the vnode for this device will be released
   1300 	 * by vn_open. Open will detect this special error and take the
   1301 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
   1302 	 * will simply report the error.
   1303 	 */
   1304 	p->p_dupfd = minor(dev);
   1305 	return (ENODEV);
   1306 }
   1307 
   1308 /*
   1309  * Duplicate the specified descriptor to a free descriptor.
   1310  */
   1311 int
   1312 dupfdopen(struct proc *p, int indx, int dfd, int mode, int error)
   1313 {
   1314 	struct filedesc	*fdp;
   1315 	struct file	*wfp, *fp;
   1316 
   1317 	fdp = p->p_fd;
   1318 	/*
   1319 	 * If the to-be-dup'd fd number is greater than the allowed number
   1320 	 * of file descriptors, or the fd to be dup'd has already been
   1321 	 * closed, reject.  Note, check for new == old is necessary as
   1322 	 * falloc could allocate an already closed to-be-dup'd descriptor
   1323 	 * as the new descriptor.
   1324 	 */
   1325 	fp = fdp->fd_ofiles[indx];
   1326 
   1327 	if ((wfp = fd_getfile(fdp, dfd)) == NULL)
   1328 		return (EBADF);
   1329 
   1330 	if (fp == wfp) {
   1331 		simple_unlock(&fp->f_slock);
   1332 		return (EBADF);
   1333 	}
   1334 
   1335 	FILE_USE(wfp);
   1336 
   1337 	/*
   1338 	 * There are two cases of interest here.
   1339 	 *
   1340 	 * For ENODEV simply dup (dfd) to file descriptor
   1341 	 * (indx) and return.
   1342 	 *
   1343 	 * For ENXIO steal away the file structure from (dfd) and
   1344 	 * store it in (indx).  (dfd) is effectively closed by
   1345 	 * this operation.
   1346 	 *
   1347 	 * Any other error code is just returned.
   1348 	 */
   1349 	switch (error) {
   1350 	case ENODEV:
   1351 		/*
   1352 		 * Check that the mode the file is being opened for is a
   1353 		 * subset of the mode of the existing descriptor.
   1354 		 */
   1355 		if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
   1356 			FILE_UNUSE(wfp, p);
   1357 			return (EACCES);
   1358 		}
   1359 		fdp->fd_ofiles[indx] = wfp;
   1360 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
   1361 		wfp->f_count++;
   1362 		fd_used(fdp, indx);
   1363 		FILE_UNUSE(wfp, p);
   1364 		return (0);
   1365 
   1366 	case ENXIO:
   1367 		/*
   1368 		 * Steal away the file pointer from dfd, and stuff it into indx.
   1369 		 */
   1370 		fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
   1371 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
   1372 		fdp->fd_ofiles[dfd] = NULL;
   1373 		fdp->fd_ofileflags[dfd] = 0;
   1374 		/*
   1375 		 * Complete the clean up of the filedesc structure by
   1376 		 * recomputing the various hints.
   1377 		 */
   1378 		fd_used(fdp, indx);
   1379 		fd_unused(fdp, dfd);
   1380 		FILE_UNUSE(wfp, p);
   1381 		return (0);
   1382 
   1383 	default:
   1384 		FILE_UNUSE(wfp, p);
   1385 		return (error);
   1386 	}
   1387 	/* NOTREACHED */
   1388 }
   1389 
   1390 /*
   1391  * fcntl call which is being passed to the file's fs.
   1392  */
   1393 int
   1394 fcntl_forfs(int fd, struct proc *p, int cmd, void *arg)
   1395 {
   1396 	struct file	*fp;
   1397 	struct filedesc	*fdp;
   1398 	int		error;
   1399 	u_int		size;
   1400 	caddr_t		data, memp;
   1401 #define STK_PARAMS	128
   1402 	char		stkbuf[STK_PARAMS];
   1403 
   1404 	/* fd's value was validated in sys_fcntl before calling this routine */
   1405 	fdp = p->p_fd;
   1406 	fp = fdp->fd_ofiles[fd];
   1407 
   1408 	if ((fp->f_flag & (FREAD | FWRITE)) == 0)
   1409 		return (EBADF);
   1410 
   1411 	/*
   1412 	 * Interpret high order word to find amount of data to be
   1413 	 * copied to/from the user's address space.
   1414 	 */
   1415 	size = (size_t)F_PARAM_LEN(cmd);
   1416 	if (size > F_PARAM_MAX)
   1417 		return (EINVAL);
   1418 	memp = NULL;
   1419 	if (size > sizeof(stkbuf)) {
   1420 		memp = (caddr_t)malloc((u_long)size, M_IOCTLOPS, M_WAITOK);
   1421 		data = memp;
   1422 	} else
   1423 		data = stkbuf;
   1424 	if (cmd & F_FSIN) {
   1425 		if (size) {
   1426 			error = copyin(arg, data, size);
   1427 			if (error) {
   1428 				if (memp)
   1429 					free(memp, M_IOCTLOPS);
   1430 				return (error);
   1431 			}
   1432 		} else
   1433 			*(caddr_t *)data = arg;
   1434 	} else if ((cmd & F_FSOUT) && size)
   1435 		/*
   1436 		 * Zero the buffer so the user always
   1437 		 * gets back something deterministic.
   1438 		 */
   1439 		memset(data, 0, size);
   1440 	else if (cmd & F_FSVOID)
   1441 		*(caddr_t *)data = arg;
   1442 
   1443 
   1444 	error = (*fp->f_ops->fo_fcntl)(fp, cmd, data, p);
   1445 
   1446 	/*
   1447 	 * Copy any data to user, size was
   1448 	 * already set and checked above.
   1449 	 */
   1450 	if (error == 0 && (cmd & F_FSOUT) && size)
   1451 		error = copyout(data, arg, size);
   1452 	if (memp)
   1453 		free(memp, M_IOCTLOPS);
   1454 	return (error);
   1455 }
   1456 
   1457 /*
   1458  * Close any files on exec?
   1459  */
   1460 void
   1461 fdcloseexec(struct proc *p)
   1462 {
   1463 	struct filedesc	*fdp;
   1464 	int		fd;
   1465 
   1466 	fdunshare(p);
   1467 	cwdunshare(p);
   1468 
   1469 	fdp = p->p_fd;
   1470 	for (fd = 0; fd <= fdp->fd_lastfile; fd++)
   1471 		if (fdp->fd_ofileflags[fd] & UF_EXCLOSE)
   1472 			(void) fdrelease(p, fd);
   1473 }
   1474 
   1475 /*
   1476  * It is unsafe for set[ug]id processes to be started with file
   1477  * descriptors 0..2 closed, as these descriptors are given implicit
   1478  * significance in the Standard C library.  fdcheckstd() will create a
   1479  * descriptor referencing /dev/null for each of stdin, stdout, and
   1480  * stderr that is not already open.
   1481  */
   1482 #define CHECK_UPTO 3
   1483 int
   1484 fdcheckstd(p)
   1485 	struct proc *p;
   1486 {
   1487 	struct nameidata nd;
   1488 	struct filedesc *fdp;
   1489 	struct file *fp;
   1490 	struct file *devnullfp = NULL;	/* Quell compiler warning */
   1491 	struct proc *pp;
   1492 	register_t retval;
   1493 	int fd, i, error, flags = FREAD|FWRITE, devnull = -1;
   1494 	char closed[CHECK_UPTO * 3 + 1], which[3 + 1];
   1495 
   1496 	closed[0] = '\0';
   1497 	if ((fdp = p->p_fd) == NULL)
   1498 		return (0);
   1499 	for (i = 0; i < CHECK_UPTO; i++) {
   1500 		if (fdp->fd_ofiles[i] != NULL)
   1501 			continue;
   1502 		snprintf(which, sizeof(which), ",%d", i);
   1503 		strcat(closed, which);
   1504 		if (devnull < 0) {
   1505 			if ((error = falloc(p, &fp, &fd)) != 0)
   1506 				return (error);
   1507 			NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, "/dev/null",
   1508 			    p);
   1509 			if ((error = vn_open(&nd, flags, 0)) != 0) {
   1510 				FILE_UNUSE(fp, p);
   1511 				ffree(fp);
   1512 				fdremove(p->p_fd, fd);
   1513 				return (error);
   1514 			}
   1515 			fp->f_data = (caddr_t)nd.ni_vp;
   1516 			fp->f_flag = flags;
   1517 			fp->f_ops = &vnops;
   1518 			fp->f_type = DTYPE_VNODE;
   1519 			VOP_UNLOCK(nd.ni_vp, 0);
   1520 			devnull = fd;
   1521 			devnullfp = fp;
   1522 			FILE_SET_MATURE(fp);
   1523 			FILE_UNUSE(fp, p);
   1524 		} else {
   1525 restart:
   1526 			if ((error = fdalloc(p, 0, &fd)) != 0) {
   1527 				if (error == ENOSPC) {
   1528 					fdexpand(p);
   1529 					goto restart;
   1530 				}
   1531 				return (error);
   1532 			}
   1533 
   1534 			FILE_USE(devnullfp);
   1535 			/* finishdup() will unuse the descriptors for us */
   1536 			if ((error = finishdup(p, devnull, fd, &retval)) != 0)
   1537 				return (error);
   1538 		}
   1539 	}
   1540 	if (closed[0] != '\0') {
   1541 		pp = p->p_pptr;
   1542 		log(LOG_WARNING, "set{u,g}id pid %d (%s) "
   1543 		    "was invoked by uid %d ppid %d (%s) "
   1544 		    "with fd %s closed\n",
   1545 		    p->p_pid, p->p_comm, pp->p_ucred->cr_uid,
   1546 		    pp->p_pid, pp->p_comm, &closed[1]);
   1547 	}
   1548 	return (0);
   1549 }
   1550 #undef CHECK_UPTO
   1551