Home | History | Annotate | Line # | Download | only in kern
kern_descrip.c revision 1.57
      1 /*	$NetBSD: kern_descrip.c,v 1.57 1999/03/24 05:51:22 mrg 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/param.h>
     44 #include <sys/systm.h>
     45 #include <sys/filedesc.h>
     46 #include <sys/kernel.h>
     47 #include <sys/vnode.h>
     48 #include <sys/proc.h>
     49 #include <sys/file.h>
     50 #include <sys/socket.h>
     51 #include <sys/socketvar.h>
     52 #include <sys/stat.h>
     53 #include <sys/ioctl.h>
     54 #include <sys/fcntl.h>
     55 #include <sys/malloc.h>
     56 #include <sys/pool.h>
     57 #include <sys/syslog.h>
     58 #include <sys/unistd.h>
     59 #include <sys/resourcevar.h>
     60 #include <sys/conf.h>
     61 
     62 #include <sys/mount.h>
     63 #include <sys/syscallargs.h>
     64 
     65 #include <vm/vm.h>
     66 
     67 /*
     68  * Descriptor management.
     69  */
     70 struct filelist filehead;	/* head of list of open files */
     71 int nfiles;			/* actual number of open files */
     72 struct pool file_pool;		/* memory pool for file structures */
     73 
     74 static __inline void fd_used __P((struct filedesc *, int));
     75 static __inline void fd_unused __P((struct filedesc *, int));
     76 int finishdup __P((struct filedesc *, int, int, register_t *));
     77 
     78 static __inline void
     79 fd_used(fdp, fd)
     80 	register struct filedesc *fdp;
     81 	register int fd;
     82 {
     83 
     84 	if (fd > fdp->fd_lastfile)
     85 		fdp->fd_lastfile = fd;
     86 }
     87 
     88 static __inline void
     89 fd_unused(fdp, fd)
     90 	register struct filedesc *fdp;
     91 	register int fd;
     92 {
     93 
     94 	if (fd < fdp->fd_freefile)
     95 		fdp->fd_freefile = fd;
     96 #ifdef DIAGNOSTIC
     97 	if (fd > fdp->fd_lastfile)
     98 		panic("fd_unused: fd_lastfile inconsistent");
     99 #endif
    100 	if (fd == fdp->fd_lastfile) {
    101 		do {
    102 			fd--;
    103 		} while (fd >= 0 && fdp->fd_ofiles[fd] == NULL);
    104 		fdp->fd_lastfile = fd;
    105 	}
    106 }
    107 
    108 /*
    109  * System calls on descriptors.
    110  */
    111 
    112 /*
    113  * Duplicate a file descriptor.
    114  */
    115 /* ARGSUSED */
    116 int
    117 sys_dup(p, v, retval)
    118 	struct proc *p;
    119 	void *v;
    120 	register_t *retval;
    121 {
    122 	struct sys_dup_args /* {
    123 		syscallarg(int) fd;
    124 	} */ *uap = v;
    125 	register struct filedesc *fdp = p->p_fd;
    126 	register int old = SCARG(uap, fd);
    127 	int new;
    128 	int error;
    129 
    130 	if ((u_int)old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL)
    131 		return (EBADF);
    132 	if ((error = fdalloc(p, 0, &new)) != 0)
    133 		return (error);
    134 	return (finishdup(fdp, old, new, retval));
    135 }
    136 
    137 /*
    138  * Duplicate a file descriptor to a particular value.
    139  */
    140 /* ARGSUSED */
    141 int
    142 sys_dup2(p, v, retval)
    143 	struct proc *p;
    144 	void *v;
    145 	register_t *retval;
    146 {
    147 	struct sys_dup2_args /* {
    148 		syscallarg(int) from;
    149 		syscallarg(int) to;
    150 	} */ *uap = v;
    151 	register struct filedesc *fdp = p->p_fd;
    152 	register int old = SCARG(uap, from), new = SCARG(uap, to);
    153 	int i, error;
    154 
    155 	if ((u_int)old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL ||
    156 	    (u_int)new >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
    157 	    (u_int)new >= maxfiles)
    158 		return (EBADF);
    159 	if (old == new) {
    160 		*retval = new;
    161 		return (0);
    162 	}
    163 	if (new >= fdp->fd_nfiles) {
    164 		if ((error = fdalloc(p, new, &i)) != 0)
    165 			return (error);
    166 		if (new != i)
    167 			panic("dup2: fdalloc");
    168 	} else {
    169 		(void) fdrelease(p, new);
    170 	}
    171 	return (finishdup(fdp, old, new, retval));
    172 }
    173 
    174 /*
    175  * The file control system call.
    176  */
    177 /* ARGSUSED */
    178 int
    179 sys_fcntl(p, v, retval)
    180 	struct proc *p;
    181 	void *v;
    182 	register_t *retval;
    183 {
    184 	register struct sys_fcntl_args /* {
    185 		syscallarg(int) fd;
    186 		syscallarg(int) cmd;
    187 		syscallarg(void *) arg;
    188 	} */ *uap = v;
    189 	int fd = SCARG(uap, fd);
    190 	register struct filedesc *fdp = p->p_fd;
    191 	register struct file *fp;
    192 	struct vnode *vp;
    193 	int i, tmp, error, flg = F_POSIX;
    194 	struct flock fl;
    195 	int newmin;
    196 
    197 	if ((u_int)fd >= fdp->fd_nfiles ||
    198 	    (fp = fdp->fd_ofiles[fd]) == NULL)
    199 		return (EBADF);
    200 	switch (SCARG(uap, cmd)) {
    201 
    202 	case F_DUPFD:
    203 		newmin = (long)SCARG(uap, arg);
    204 		if ((u_int)newmin >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
    205 		    (u_int)newmin >= maxfiles)
    206 			return (EINVAL);
    207 		if ((error = fdalloc(p, newmin, &i)) != 0)
    208 			return (error);
    209 		return (finishdup(fdp, fd, i, retval));
    210 
    211 	case F_GETFD:
    212 		*retval = fdp->fd_ofileflags[fd] & UF_EXCLOSE ? 1 : 0;
    213 		return (0);
    214 
    215 	case F_SETFD:
    216 		if ((long)SCARG(uap, arg) & 1)
    217 			fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
    218 		else
    219 			fdp->fd_ofileflags[fd] &= ~UF_EXCLOSE;
    220 		return (0);
    221 
    222 	case F_GETFL:
    223 		*retval = OFLAGS(fp->f_flag);
    224 		return (0);
    225 
    226 	case F_SETFL:
    227 		fp->f_flag &= ~FCNTLFLAGS;
    228 		fp->f_flag |= FFLAGS((long)SCARG(uap, arg)) & FCNTLFLAGS;
    229 		tmp = fp->f_flag & FNONBLOCK;
    230 		error = (*fp->f_ops->fo_ioctl)(fp, FIONBIO, (caddr_t)&tmp, p);
    231 		if (error)
    232 			return (error);
    233 		tmp = fp->f_flag & FASYNC;
    234 		error = (*fp->f_ops->fo_ioctl)(fp, FIOASYNC, (caddr_t)&tmp, p);
    235 		if (!error)
    236 			return (0);
    237 		fp->f_flag &= ~FNONBLOCK;
    238 		tmp = 0;
    239 		(void) (*fp->f_ops->fo_ioctl)(fp, FIONBIO, (caddr_t)&tmp, p);
    240 		return (error);
    241 
    242 	case F_GETOWN:
    243 		if (fp->f_type == DTYPE_SOCKET) {
    244 			*retval = ((struct socket *)fp->f_data)->so_pgid;
    245 			return (0);
    246 		}
    247 		error = (*fp->f_ops->fo_ioctl)
    248 			(fp, TIOCGPGRP, (caddr_t)retval, p);
    249 		*retval = -*retval;
    250 		return (error);
    251 
    252 	case F_SETOWN:
    253 		if (fp->f_type == DTYPE_SOCKET) {
    254 			((struct socket *)fp->f_data)->so_pgid =
    255 			    (long)SCARG(uap, arg);
    256 			return (0);
    257 		}
    258 		if ((long)SCARG(uap, arg) <= 0) {
    259 			SCARG(uap, arg) = (void *)(-(long)SCARG(uap, arg));
    260 		} else {
    261 			struct proc *p1 = pfind((long)SCARG(uap, arg));
    262 			if (p1 == 0)
    263 				return (ESRCH);
    264 			SCARG(uap, arg) = (void *)(long)p1->p_pgrp->pg_id;
    265 		}
    266 		return ((*fp->f_ops->fo_ioctl)
    267 			(fp, TIOCSPGRP, (caddr_t)&SCARG(uap, arg), p));
    268 
    269 	case F_SETLKW:
    270 		flg |= F_WAIT;
    271 		/* Fall into F_SETLK */
    272 
    273 	case F_SETLK:
    274 		if (fp->f_type != DTYPE_VNODE)
    275 			return (EINVAL);
    276 		vp = (struct vnode *)fp->f_data;
    277 		/* Copy in the lock structure */
    278 		error = copyin((caddr_t)SCARG(uap, arg), (caddr_t)&fl,
    279 		    sizeof(fl));
    280 		if (error)
    281 			return (error);
    282 		if (fl.l_whence == SEEK_CUR)
    283 			fl.l_start += fp->f_offset;
    284 		switch (fl.l_type) {
    285 		case F_RDLCK:
    286 			if ((fp->f_flag & FREAD) == 0)
    287 				return (EBADF);
    288 			p->p_flag |= P_ADVLOCK;
    289 			return (VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &fl, flg));
    290 
    291 		case F_WRLCK:
    292 			if ((fp->f_flag & FWRITE) == 0)
    293 				return (EBADF);
    294 			p->p_flag |= P_ADVLOCK;
    295 			return (VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &fl, flg));
    296 
    297 		case F_UNLCK:
    298 			return (VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &fl,
    299 				F_POSIX));
    300 
    301 		default:
    302 			return (EINVAL);
    303 		}
    304 
    305 	case F_GETLK:
    306 		if (fp->f_type != DTYPE_VNODE)
    307 			return (EINVAL);
    308 		vp = (struct vnode *)fp->f_data;
    309 		/* Copy in the lock structure */
    310 		error = copyin((caddr_t)SCARG(uap, arg), (caddr_t)&fl,
    311 		    sizeof(fl));
    312 		if (error)
    313 			return (error);
    314 		if (fl.l_whence == SEEK_CUR)
    315 			fl.l_start += fp->f_offset;
    316 		if (fl.l_type != F_RDLCK &&
    317 		    fl.l_type != F_WRLCK &&
    318 		    fl.l_type != F_UNLCK)
    319 			return (EINVAL);
    320 		error = VOP_ADVLOCK(vp, (caddr_t)p, F_GETLK, &fl, F_POSIX);
    321 		if (error)
    322 			return (error);
    323 		return (copyout((caddr_t)&fl, (caddr_t)SCARG(uap, arg),
    324 		    sizeof(fl)));
    325 
    326 	default:
    327 		return (EINVAL);
    328 	}
    329 	/* NOTREACHED */
    330 }
    331 
    332 /*
    333  * Common code for dup, dup2, and fcntl(F_DUPFD).
    334  */
    335 int
    336 finishdup(fdp, old, new, retval)
    337 	register struct filedesc *fdp;
    338 	register int old, new;
    339 	register_t *retval;
    340 {
    341 	register struct file *fp;
    342 
    343 	fp = fdp->fd_ofiles[old];
    344 	fdp->fd_ofiles[new] = fp;
    345 	fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
    346 	fp->f_count++;
    347 	fd_used(fdp, new);
    348 	*retval = new;
    349 	return (0);
    350 }
    351 
    352 int
    353 fdrelease(p, fd)
    354 	struct proc *p;
    355 	int fd;
    356 {
    357 	register struct filedesc *fdp = p->p_fd;
    358 	register struct file **fpp, *fp;
    359 	register char *pf;
    360 
    361 	fpp = &fdp->fd_ofiles[fd];
    362 	fp = *fpp;
    363 	if (fp == NULL)
    364 		return (EBADF);
    365 	pf = &fdp->fd_ofileflags[fd];
    366 	if (*pf & UF_MAPPED) {
    367 		/* XXX: USELESS? XXXCDC check it */
    368 		p->p_fd->fd_ofileflags[fd] &= ~UF_MAPPED;
    369 	}
    370 	*fpp = NULL;
    371 	*pf = 0;
    372 	fd_unused(fdp, fd);
    373 	return (closef(fp, p));
    374 }
    375 
    376 /*
    377  * Close a file descriptor.
    378  */
    379 /* ARGSUSED */
    380 int
    381 sys_close(p, v, retval)
    382 	struct proc *p;
    383 	void *v;
    384 	register_t *retval;
    385 {
    386 	struct sys_close_args /* {
    387 		syscallarg(int) fd;
    388 	} */ *uap = v;
    389 	int fd = SCARG(uap, fd);
    390 	register struct filedesc *fdp = p->p_fd;
    391 
    392 	if ((u_int)fd >= fdp->fd_nfiles)
    393 		return (EBADF);
    394 	return (fdrelease(p, fd));
    395 }
    396 
    397 /*
    398  * Return status information about a file descriptor.
    399  */
    400 /* ARGSUSED */
    401 int
    402 sys___fstat13(p, v, retval)
    403 	struct proc *p;
    404 	void *v;
    405 	register_t *retval;
    406 {
    407 	register struct sys___fstat13_args /* {
    408 		syscallarg(int) fd;
    409 		syscallarg(struct stat *) sb;
    410 	} */ *uap = v;
    411 	int fd = SCARG(uap, fd);
    412 	register struct filedesc *fdp = p->p_fd;
    413 	register struct file *fp;
    414 	struct stat ub;
    415 	int error;
    416 
    417 	if ((u_int)fd >= fdp->fd_nfiles ||
    418 	    (fp = fdp->fd_ofiles[fd]) == NULL)
    419 		return (EBADF);
    420 	switch (fp->f_type) {
    421 
    422 	case DTYPE_VNODE:
    423 		error = vn_stat((struct vnode *)fp->f_data, &ub, p);
    424 		break;
    425 
    426 	case DTYPE_SOCKET:
    427 		error = soo_stat((struct socket *)fp->f_data, &ub);
    428 		break;
    429 
    430 	default:
    431 		panic("fstat");
    432 		/*NOTREACHED*/
    433 	}
    434 	if (error == 0)
    435 		error = copyout(&ub, SCARG(uap, sb), sizeof(ub));
    436 	return (error);
    437 }
    438 
    439 /*
    440  * Return pathconf information about a file descriptor.
    441  */
    442 /* ARGSUSED */
    443 int
    444 sys_fpathconf(p, v, retval)
    445 	struct proc *p;
    446 	void *v;
    447 	register_t *retval;
    448 {
    449 	register struct sys_fpathconf_args /* {
    450 		syscallarg(int) fd;
    451 		syscallarg(int) name;
    452 	} */ *uap = v;
    453 	int fd = SCARG(uap, fd);
    454 	struct filedesc *fdp = p->p_fd;
    455 	struct file *fp;
    456 	struct vnode *vp;
    457 
    458 	if ((u_int)fd >= fdp->fd_nfiles ||
    459 	    (fp = fdp->fd_ofiles[fd]) == NULL)
    460 		return (EBADF);
    461 	switch (fp->f_type) {
    462 
    463 	case DTYPE_SOCKET:
    464 		if (SCARG(uap, name) != _PC_PIPE_BUF)
    465 			return (EINVAL);
    466 		*retval = PIPE_BUF;
    467 		return (0);
    468 
    469 	case DTYPE_VNODE:
    470 		vp = (struct vnode *)fp->f_data;
    471 		return (VOP_PATHCONF(vp, SCARG(uap, name), retval));
    472 
    473 	default:
    474 		panic("fpathconf");
    475 	}
    476 	/*NOTREACHED*/
    477 }
    478 
    479 /*
    480  * Allocate a file descriptor for the process.
    481  */
    482 int fdexpand;
    483 
    484 int
    485 fdalloc(p, want, result)
    486 	struct proc *p;
    487 	int want;
    488 	int *result;
    489 {
    490 	register struct filedesc *fdp = p->p_fd;
    491 	register int i;
    492 	int lim, last, nfiles;
    493 	struct file **newofile;
    494 	char *newofileflags;
    495 
    496 	/*
    497 	 * Search for a free descriptor starting at the higher
    498 	 * of want or fd_freefile.  If that fails, consider
    499 	 * expanding the ofile array.
    500 	 */
    501 	lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
    502 	for (;;) {
    503 		last = min(fdp->fd_nfiles, lim);
    504 		if ((i = want) < fdp->fd_freefile)
    505 			i = fdp->fd_freefile;
    506 		for (; i < last; i++) {
    507 			if (fdp->fd_ofiles[i] == NULL) {
    508 				fd_used(fdp, i);
    509 				if (want <= fdp->fd_freefile)
    510 					fdp->fd_freefile = i;
    511 				*result = i;
    512 				return (0);
    513 			}
    514 		}
    515 
    516 		/*
    517 		 * No space in current array.  Expand?
    518 		 */
    519 		if (fdp->fd_nfiles >= lim)
    520 			return (EMFILE);
    521 		if (fdp->fd_nfiles < NDEXTENT)
    522 			nfiles = NDEXTENT;
    523 		else
    524 			nfiles = 2 * fdp->fd_nfiles;
    525 		MALLOC(newofile, struct file **, nfiles * OFILESIZE,
    526 		    M_FILEDESC, M_WAITOK);
    527 		newofileflags = (char *) &newofile[nfiles];
    528 		/*
    529 		 * Copy the existing ofile and ofileflags arrays
    530 		 * and zero the new portion of each array.
    531 		 */
    532 		memcpy(newofile, fdp->fd_ofiles,
    533 			(i = sizeof(struct file *) * fdp->fd_nfiles));
    534 		memset((char *)newofile + i, 0, nfiles * sizeof(struct file *) - i);
    535 		memcpy(newofileflags, fdp->fd_ofileflags,
    536 			(i = sizeof(char) * fdp->fd_nfiles));
    537 		memset(newofileflags + i, 0, nfiles * sizeof(char) - i);
    538 		if (fdp->fd_nfiles > NDFILE)
    539 			FREE(fdp->fd_ofiles, M_FILEDESC);
    540 		fdp->fd_ofiles = newofile;
    541 		fdp->fd_ofileflags = newofileflags;
    542 		fdp->fd_nfiles = nfiles;
    543 		fdexpand++;
    544 	}
    545 }
    546 
    547 /*
    548  * Check to see whether n user file descriptors
    549  * are available to the process p.
    550  */
    551 int
    552 fdavail(p, n)
    553 	struct proc *p;
    554 	register int n;
    555 {
    556 	register struct filedesc *fdp = p->p_fd;
    557 	register struct file **fpp;
    558 	register int i, lim;
    559 
    560 	lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
    561 	if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
    562 		return (1);
    563 	fpp = &fdp->fd_ofiles[fdp->fd_freefile];
    564 	for (i = min(lim,fdp->fd_nfiles) - fdp->fd_freefile; --i >= 0; fpp++)
    565 		if (*fpp == NULL && --n <= 0)
    566 			return (1);
    567 	return (0);
    568 }
    569 
    570 /*
    571  * Initialize the data structures necessary for managing files.
    572  */
    573 void
    574 finit()
    575 {
    576 
    577 	pool_init(&file_pool, sizeof(struct file), 0, 0, 0, "filepl",
    578 	    0, pool_page_alloc_nointr, pool_page_free_nointr, M_FILE);
    579 }
    580 
    581 /*
    582  * Create a new open file structure and allocate
    583  * a file decriptor for the process that refers to it.
    584  */
    585 int
    586 falloc(p, resultfp, resultfd)
    587 	register struct proc *p;
    588 	struct file **resultfp;
    589 	int *resultfd;
    590 {
    591 	register struct file *fp, *fq;
    592 	int error, i;
    593 
    594 	if ((error = fdalloc(p, 0, &i)) != 0)
    595 		return (error);
    596 	if (nfiles >= maxfiles) {
    597 		tablefull("file");
    598 		return (ENFILE);
    599 	}
    600 	/*
    601 	 * Allocate a new file descriptor.
    602 	 * If the process has file descriptor zero open, add to the list
    603 	 * of open files at that point, otherwise put it at the front of
    604 	 * the list of open files.
    605 	 */
    606 	nfiles++;
    607 	fp = pool_get(&file_pool, PR_WAITOK);
    608 	memset(fp, 0, sizeof(struct file));
    609 	if ((fq = p->p_fd->fd_ofiles[0]) != NULL) {
    610 		LIST_INSERT_AFTER(fq, fp, f_list);
    611 	} else {
    612 		LIST_INSERT_HEAD(&filehead, fp, f_list);
    613 	}
    614 	p->p_fd->fd_ofiles[i] = fp;
    615 	fp->f_count = 1;
    616 	fp->f_cred = p->p_ucred;
    617 	crhold(fp->f_cred);
    618 	if (resultfp)
    619 		*resultfp = fp;
    620 	if (resultfd)
    621 		*resultfd = i;
    622 	return (0);
    623 }
    624 
    625 /*
    626  * Free a file descriptor.
    627  */
    628 void
    629 ffree(fp)
    630 	register struct file *fp;
    631 {
    632 	LIST_REMOVE(fp, f_list);
    633 	crfree(fp->f_cred);
    634 #ifdef DIAGNOSTIC
    635 	fp->f_count = 0;
    636 #endif
    637 	nfiles--;
    638 	pool_put(&file_pool, fp);
    639 }
    640 
    641 /*
    642  * Create an initial filedesc structure, using the same current and root
    643  * directories as p.
    644  */
    645 struct filedesc *
    646 fdinit(p)
    647 	struct proc *p;
    648 {
    649 	struct filedesc0 *newfdp;
    650 	struct filedesc *fdp = p->p_fd;
    651 
    652 	MALLOC(newfdp, struct filedesc0 *, sizeof(struct filedesc0),
    653 	    M_FILEDESC, M_WAITOK);
    654 	memset(newfdp, 0, sizeof(struct filedesc0));
    655 	newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
    656 	VREF(newfdp->fd_fd.fd_cdir);
    657 	newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
    658 	if (newfdp->fd_fd.fd_rdir)
    659 		VREF(newfdp->fd_fd.fd_rdir);
    660 
    661 	fdinit1(newfdp);
    662 
    663 	return (&newfdp->fd_fd);
    664 }
    665 
    666 /*
    667  * Initialize a file descriptor table.
    668  */
    669 void
    670 fdinit1(newfdp)
    671 	struct filedesc0 *newfdp;
    672 {
    673 	extern int cmask;		/* init_main.c */
    674 
    675 	newfdp->fd_fd.fd_refcnt = 1;
    676 	newfdp->fd_fd.fd_cmask = cmask;
    677 	newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
    678 	newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
    679 	newfdp->fd_fd.fd_nfiles = NDFILE;
    680 }
    681 
    682 /*
    683  * Make p2 share p1's filedesc structure.
    684  */
    685 void
    686 fdshare(p1, p2)
    687 	struct proc *p1, *p2;
    688 {
    689 
    690 	p2->p_fd = p1->p_fd;
    691 	p1->p_fd->fd_refcnt++;
    692 }
    693 
    694 /*
    695  * Make this process not share its filedesc structure, maintaining
    696  * all file descriptor state.
    697  */
    698 void
    699 fdunshare(p)
    700 	struct proc *p;
    701 {
    702 	struct filedesc *newfd;
    703 
    704 	if (p->p_fd->fd_refcnt == 1)
    705 		return;
    706 
    707 	newfd = fdcopy(p);
    708 	fdfree(p);
    709 	p->p_fd = newfd;
    710 }
    711 
    712 /*
    713  * Clear a process's fd table.
    714  */
    715 void
    716 fdclear(p)
    717 	struct proc *p;
    718 {
    719 	struct filedesc *newfd;
    720 
    721 	newfd = fdinit(p);
    722 	fdfree(p);
    723 	p->p_fd = newfd;
    724 }
    725 
    726 /*
    727  * Copy a filedesc structure.
    728  */
    729 struct filedesc *
    730 fdcopy(p)
    731 	struct proc *p;
    732 {
    733 	register struct filedesc *newfdp, *fdp = p->p_fd;
    734 	register struct file **fpp;
    735 	register int i;
    736 
    737 	MALLOC(newfdp, struct filedesc *, sizeof(struct filedesc0),
    738 	    M_FILEDESC, M_WAITOK);
    739 	memcpy(newfdp, fdp, sizeof(struct filedesc));
    740 	VREF(newfdp->fd_cdir);
    741 	if (newfdp->fd_rdir)
    742 		VREF(newfdp->fd_rdir);
    743 	newfdp->fd_refcnt = 1;
    744 
    745 	/*
    746 	 * If the number of open files fits in the internal arrays
    747 	 * of the open file structure, use them, otherwise allocate
    748 	 * additional memory for the number of descriptors currently
    749 	 * in use.
    750 	 */
    751 	if (newfdp->fd_lastfile < NDFILE) {
    752 		newfdp->fd_ofiles = ((struct filedesc0 *) newfdp)->fd_dfiles;
    753 		newfdp->fd_ofileflags =
    754 		    ((struct filedesc0 *) newfdp)->fd_dfileflags;
    755 		i = NDFILE;
    756 	} else {
    757 		/*
    758 		 * Compute the smallest multiple of NDEXTENT needed
    759 		 * for the file descriptors currently in use,
    760 		 * allowing the table to shrink.
    761 		 */
    762 		i = newfdp->fd_nfiles;
    763 		while (i >= 2 * NDEXTENT && i > newfdp->fd_lastfile * 2)
    764 			i /= 2;
    765 		MALLOC(newfdp->fd_ofiles, struct file **, i * OFILESIZE,
    766 		    M_FILEDESC, M_WAITOK);
    767 		newfdp->fd_ofileflags = (char *) &newfdp->fd_ofiles[i];
    768 	}
    769 	newfdp->fd_nfiles = i;
    770 	memcpy(newfdp->fd_ofiles, fdp->fd_ofiles, i * sizeof(struct file **));
    771 	memcpy(newfdp->fd_ofileflags, fdp->fd_ofileflags, i * sizeof(char));
    772 	fpp = newfdp->fd_ofiles;
    773 	for (i = newfdp->fd_lastfile; i >= 0; i--, fpp++)
    774 		if (*fpp != NULL)
    775 			(*fpp)->f_count++;
    776 	return (newfdp);
    777 }
    778 
    779 /*
    780  * Release a filedesc structure.
    781  */
    782 void
    783 fdfree(p)
    784 	struct proc *p;
    785 {
    786 	register struct filedesc *fdp = p->p_fd;
    787 	register struct file **fpp, *fp;
    788 	register int i;
    789 
    790 	if (--fdp->fd_refcnt > 0)
    791 		return;
    792 	fpp = fdp->fd_ofiles;
    793 	for (i = fdp->fd_lastfile; i >= 0; i--, fpp++) {
    794 		fp = *fpp;
    795 		if (fp != NULL) {
    796 			*fpp = NULL;
    797 			(void) closef(fp, p);
    798 		}
    799 	}
    800 	p->p_fd = NULL;
    801 	if (fdp->fd_nfiles > NDFILE)
    802 		FREE(fdp->fd_ofiles, M_FILEDESC);
    803 	vrele(fdp->fd_cdir);
    804 	if (fdp->fd_rdir)
    805 		vrele(fdp->fd_rdir);
    806 	FREE(fdp, M_FILEDESC);
    807 }
    808 
    809 /*
    810  * Internal form of close.
    811  * Decrement reference count on file structure.
    812  * Note: p may be NULL when closing a file
    813  * that was being passed in a message.
    814  */
    815 int
    816 closef(fp, p)
    817 	register struct file *fp;
    818 	register struct proc *p;
    819 {
    820 	struct vnode *vp;
    821 	struct flock lf;
    822 	int error;
    823 
    824 	if (fp == NULL)
    825 		return (0);
    826 	/*
    827 	 * POSIX record locking dictates that any close releases ALL
    828 	 * locks owned by this process.  This is handled by setting
    829 	 * a flag in the unlock to free ONLY locks obeying POSIX
    830 	 * semantics, and not to free BSD-style file locks.
    831 	 * If the descriptor was in a message, POSIX-style locks
    832 	 * aren't passed with the descriptor.
    833 	 */
    834 	if (p && (p->p_flag & P_ADVLOCK) && fp->f_type == DTYPE_VNODE) {
    835 		lf.l_whence = SEEK_SET;
    836 		lf.l_start = 0;
    837 		lf.l_len = 0;
    838 		lf.l_type = F_UNLCK;
    839 		vp = (struct vnode *)fp->f_data;
    840 		(void) VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, F_POSIX);
    841 	}
    842 	if (--fp->f_count > 0)
    843 		return (0);
    844 	if (fp->f_count < 0)
    845 		panic("closef: count < 0");
    846 	if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
    847 		lf.l_whence = SEEK_SET;
    848 		lf.l_start = 0;
    849 		lf.l_len = 0;
    850 		lf.l_type = F_UNLCK;
    851 		vp = (struct vnode *)fp->f_data;
    852 		(void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
    853 	}
    854 	if (fp->f_ops)
    855 		error = (*fp->f_ops->fo_close)(fp, p);
    856 	else
    857 		error = 0;
    858 	ffree(fp);
    859 	return (error);
    860 }
    861 
    862 /*
    863  * Apply an advisory lock on a file descriptor.
    864  *
    865  * Just attempt to get a record lock of the requested type on
    866  * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
    867  */
    868 /* ARGSUSED */
    869 int
    870 sys_flock(p, v, retval)
    871 	struct proc *p;
    872 	void *v;
    873 	register_t *retval;
    874 {
    875 	register struct sys_flock_args /* {
    876 		syscallarg(int) fd;
    877 		syscallarg(int) how;
    878 	} */ *uap = v;
    879 	int fd = SCARG(uap, fd);
    880 	int how = SCARG(uap, how);
    881 	register struct filedesc *fdp = p->p_fd;
    882 	register struct file *fp;
    883 	struct vnode *vp;
    884 	struct flock lf;
    885 
    886 	if ((u_int)fd >= fdp->fd_nfiles ||
    887 	    (fp = fdp->fd_ofiles[fd]) == NULL)
    888 		return (EBADF);
    889 	if (fp->f_type != DTYPE_VNODE)
    890 		return (EOPNOTSUPP);
    891 	vp = (struct vnode *)fp->f_data;
    892 	lf.l_whence = SEEK_SET;
    893 	lf.l_start = 0;
    894 	lf.l_len = 0;
    895 	if (how & LOCK_UN) {
    896 		lf.l_type = F_UNLCK;
    897 		fp->f_flag &= ~FHASLOCK;
    898 		return (VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK));
    899 	}
    900 	if (how & LOCK_EX)
    901 		lf.l_type = F_WRLCK;
    902 	else if (how & LOCK_SH)
    903 		lf.l_type = F_RDLCK;
    904 	else
    905 		return (EINVAL);
    906 	fp->f_flag |= FHASLOCK;
    907 	if (how & LOCK_NB)
    908 		return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK));
    909 	return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK|F_WAIT));
    910 }
    911 
    912 /*
    913  * File Descriptor pseudo-device driver (/dev/fd/).
    914  *
    915  * Opening minor device N dup()s the file (if any) connected to file
    916  * descriptor N belonging to the calling process.  Note that this driver
    917  * consists of only the ``open()'' routine, because all subsequent
    918  * references to this file will be direct to the other driver.
    919  */
    920 /* ARGSUSED */
    921 int
    922 filedescopen(dev, mode, type, p)
    923 	dev_t dev;
    924 	int mode, type;
    925 	struct proc *p;
    926 {
    927 
    928 	/*
    929 	 * XXX Kludge: set curproc->p_dupfd to contain the value of the
    930 	 * the file descriptor being sought for duplication. The error
    931 	 * return ensures that the vnode for this device will be released
    932 	 * by vn_open. Open will detect this special error and take the
    933 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
    934 	 * will simply report the error.
    935 	 */
    936 	p->p_dupfd = minor(dev);
    937 	return (ENODEV);
    938 }
    939 
    940 /*
    941  * Duplicate the specified descriptor to a free descriptor.
    942  */
    943 int
    944 dupfdopen(fdp, indx, dfd, mode, error)
    945 	register struct filedesc *fdp;
    946 	register int indx, dfd;
    947 	int mode;
    948 	int error;
    949 {
    950 	register struct file *wfp;
    951 	struct file *fp;
    952 
    953 	/*
    954 	 * If the to-be-dup'd fd number is greater than the allowed number
    955 	 * of file descriptors, or the fd to be dup'd has already been
    956 	 * closed, reject.  Note, check for new == old is necessary as
    957 	 * falloc could allocate an already closed to-be-dup'd descriptor
    958 	 * as the new descriptor.
    959 	 */
    960 	fp = fdp->fd_ofiles[indx];
    961 	if ((u_int)dfd >= fdp->fd_nfiles ||
    962 	    (wfp = fdp->fd_ofiles[dfd]) == NULL || fp == wfp)
    963 		return (EBADF);
    964 
    965 	/*
    966 	 * There are two cases of interest here.
    967 	 *
    968 	 * For ENODEV simply dup (dfd) to file descriptor
    969 	 * (indx) and return.
    970 	 *
    971 	 * For ENXIO steal away the file structure from (dfd) and
    972 	 * store it in (indx).  (dfd) is effectively closed by
    973 	 * this operation.
    974 	 *
    975 	 * Any other error code is just returned.
    976 	 */
    977 	switch (error) {
    978 	case ENODEV:
    979 		/*
    980 		 * Check that the mode the file is being opened for is a
    981 		 * subset of the mode of the existing descriptor.
    982 		 */
    983 		if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag)
    984 			return (EACCES);
    985 		fdp->fd_ofiles[indx] = wfp;
    986 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
    987 		wfp->f_count++;
    988 		fd_used(fdp, indx);
    989 		return (0);
    990 
    991 	case ENXIO:
    992 		/*
    993 		 * Steal away the file pointer from dfd, and stuff it into indx.
    994 		 */
    995 		fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
    996 		fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
    997 		fdp->fd_ofiles[dfd] = NULL;
    998 		fdp->fd_ofileflags[dfd] = 0;
    999 		/*
   1000 		 * Complete the clean up of the filedesc structure by
   1001 		 * recomputing the various hints.
   1002 		 */
   1003 		fd_used(fdp, indx);
   1004 		fd_unused(fdp, dfd);
   1005 		return (0);
   1006 
   1007 	default:
   1008 		return (error);
   1009 	}
   1010 	/* NOTREACHED */
   1011 }
   1012 
   1013 /*
   1014  * Close any files on exec?
   1015  */
   1016 void
   1017 fdcloseexec(p)
   1018 	struct proc *p;
   1019 {
   1020 	register struct filedesc *fdp = p->p_fd;
   1021 	register int fd;
   1022 
   1023 	for (fd = 0; fd <= fdp->fd_lastfile; fd++)
   1024 		if (fdp->fd_ofileflags[fd] & UF_EXCLOSE)
   1025 			(void) fdrelease(p, fd);
   1026 }
   1027