xref: /openbsd-src/sys/kern/kern_descrip.c (revision 46035553bfdd96e63c94e32da0210227ec2e3cf1)
1 /*	$OpenBSD: kern_descrip.c,v 1.202 2020/06/11 13:23:18 visa Exp $	*/
2 /*	$NetBSD: kern_descrip.c,v 1.42 1996/03/30 22:24:38 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1989, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  * (c) UNIX System Laboratories, Inc.
8  * All or some portions of this file are derived from material licensed
9  * to the University of California by American Telephone and Telegraph
10  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11  * the permission of UNIX System Laboratories, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	@(#)kern_descrip.c	8.6 (Berkeley) 4/19/94
38  */
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/filedesc.h>
43 #include <sys/kernel.h>
44 #include <sys/vnode.h>
45 #include <sys/proc.h>
46 #include <sys/file.h>
47 #include <sys/socket.h>
48 #include <sys/socketvar.h>
49 #include <sys/stat.h>
50 #include <sys/ioctl.h>
51 #include <sys/fcntl.h>
52 #include <sys/lock.h>
53 #include <sys/malloc.h>
54 #include <sys/syslog.h>
55 #include <sys/ucred.h>
56 #include <sys/unistd.h>
57 #include <sys/resourcevar.h>
58 #include <sys/mount.h>
59 #include <sys/syscallargs.h>
60 #include <sys/event.h>
61 #include <sys/pool.h>
62 #include <sys/ktrace.h>
63 #include <sys/pledge.h>
64 
65 #include <sys/pipe.h>
66 
67 /*
68  * Descriptor management.
69  *
70  * We need to block interrupts as long as `fhdlk' is being taken
71  * with and without the KERNEL_LOCK().
72  */
73 struct mutex fhdlk = MUTEX_INITIALIZER(IPL_MPFLOOR);
74 struct filelist filehead;	/* head of list of open files */
75 int numfiles;			/* actual number of open files */
76 
77 static __inline void fd_used(struct filedesc *, int);
78 static __inline void fd_unused(struct filedesc *, int);
79 static __inline int find_next_zero(u_int *, int, u_int);
80 static __inline int fd_inuse(struct filedesc *, int);
81 int finishdup(struct proc *, struct file *, int, int, register_t *, int);
82 int find_last_set(struct filedesc *, int);
83 int dodup3(struct proc *, int, int, int, register_t *);
84 
85 #define DUPF_CLOEXEC	0x01
86 #define DUPF_DUP2	0x02
87 
88 struct pool file_pool;
89 struct pool fdesc_pool;
90 
91 void
92 filedesc_init(void)
93 {
94 	pool_init(&file_pool, sizeof(struct file), 0, IPL_MPFLOOR,
95 	    PR_WAITOK, "filepl", NULL);
96 	pool_init(&fdesc_pool, sizeof(struct filedesc0), 0, IPL_NONE,
97 	    PR_WAITOK, "fdescpl", NULL);
98 	LIST_INIT(&filehead);
99 }
100 
101 static __inline int
102 find_next_zero (u_int *bitmap, int want, u_int bits)
103 {
104 	int i, off, maxoff;
105 	u_int sub;
106 
107 	if (want > bits)
108 		return -1;
109 
110 	off = want >> NDENTRYSHIFT;
111 	i = want & NDENTRYMASK;
112 	if (i) {
113 		sub = bitmap[off] | ((u_int)~0 >> (NDENTRIES - i));
114 		if (sub != ~0)
115 			goto found;
116 		off++;
117 	}
118 
119 	maxoff = NDLOSLOTS(bits);
120 	while (off < maxoff) {
121 		if ((sub = bitmap[off]) != ~0)
122 			goto found;
123 		off++;
124 	}
125 
126 	return -1;
127 
128  found:
129 	return (off << NDENTRYSHIFT) + ffs(~sub) - 1;
130 }
131 
132 int
133 find_last_set(struct filedesc *fd, int last)
134 {
135 	int off, i;
136 	u_int *bitmap = fd->fd_lomap;
137 
138 	off = (last - 1) >> NDENTRYSHIFT;
139 
140 	while (off >= 0 && !bitmap[off])
141 		off--;
142 	if (off < 0)
143 		return 0;
144 
145 	i = ((off + 1) << NDENTRYSHIFT) - 1;
146 	if (i >= last)
147 		i = last - 1;
148 
149 	while (i > 0 && !fd_inuse(fd, i))
150 		i--;
151 	return i;
152 }
153 
154 static __inline int
155 fd_inuse(struct filedesc *fdp, int fd)
156 {
157 	u_int off = fd >> NDENTRYSHIFT;
158 
159 	if (fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK)))
160 		return 1;
161 
162 	return 0;
163 }
164 
165 static __inline void
166 fd_used(struct filedesc *fdp, int fd)
167 {
168 	u_int off = fd >> NDENTRYSHIFT;
169 
170 	fdp->fd_lomap[off] |= 1 << (fd & NDENTRYMASK);
171 	if (fdp->fd_lomap[off] == ~0)
172 		fdp->fd_himap[off >> NDENTRYSHIFT] |= 1 << (off & NDENTRYMASK);
173 
174 	if (fd > fdp->fd_lastfile)
175 		fdp->fd_lastfile = fd;
176 	fdp->fd_openfd++;
177 }
178 
179 static __inline void
180 fd_unused(struct filedesc *fdp, int fd)
181 {
182 	u_int off = fd >> NDENTRYSHIFT;
183 
184 	if (fd < fdp->fd_freefile)
185 		fdp->fd_freefile = fd;
186 
187 	if (fdp->fd_lomap[off] == ~0)
188 		fdp->fd_himap[off >> NDENTRYSHIFT] &= ~(1 << (off & NDENTRYMASK));
189 	fdp->fd_lomap[off] &= ~(1 << (fd & NDENTRYMASK));
190 
191 #ifdef DIAGNOSTIC
192 	if (fd > fdp->fd_lastfile)
193 		panic("fd_unused: fd_lastfile inconsistent");
194 #endif
195 	if (fd == fdp->fd_lastfile)
196 		fdp->fd_lastfile = find_last_set(fdp, fd);
197 	fdp->fd_openfd--;
198 }
199 
200 struct file *
201 fd_iterfile(struct file *fp, struct proc *p)
202 {
203 	struct file *nfp;
204 	unsigned int count;
205 
206 	mtx_enter(&fhdlk);
207 	if (fp == NULL)
208 		nfp = LIST_FIRST(&filehead);
209 	else
210 		nfp = LIST_NEXT(fp, f_list);
211 
212 	/* don't refcount when f_count == 0 to avoid race in fdrop() */
213 	while (nfp != NULL) {
214 		count = nfp->f_count;
215 		if (count == 0) {
216 			nfp = LIST_NEXT(nfp, f_list);
217 			continue;
218 		}
219 		if (atomic_cas_uint(&nfp->f_count, count, count + 1) == count)
220 			break;
221 	}
222 	mtx_leave(&fhdlk);
223 
224 	if (fp != NULL)
225 		FRELE(fp, p);
226 
227 	return nfp;
228 }
229 
230 struct file *
231 fd_getfile(struct filedesc *fdp, int fd)
232 {
233 	struct file *fp;
234 
235 	vfs_stall_barrier();
236 
237 	if ((u_int)fd >= fdp->fd_nfiles)
238 		return (NULL);
239 
240 	mtx_enter(&fdp->fd_fplock);
241 	fp = fdp->fd_ofiles[fd];
242 	if (fp != NULL)
243 		atomic_inc_int(&fp->f_count);
244 	mtx_leave(&fdp->fd_fplock);
245 
246 	return (fp);
247 }
248 
249 struct file *
250 fd_getfile_mode(struct filedesc *fdp, int fd, int mode)
251 {
252 	struct file *fp;
253 
254 	KASSERT(mode != 0);
255 
256 	fp = fd_getfile(fdp, fd);
257 	if (fp == NULL)
258 		return (NULL);
259 
260 	if ((fp->f_flag & mode) == 0) {
261 		FRELE(fp, curproc);
262 		return (NULL);
263 	}
264 
265 	return (fp);
266 }
267 
268 int
269 fd_checkclosed(struct filedesc *fdp, int fd, struct file *fp)
270 {
271 	int closed;
272 
273 	mtx_enter(&fdp->fd_fplock);
274 	KASSERT(fd < fdp->fd_nfiles);
275 	closed = (fdp->fd_ofiles[fd] != fp);
276 	mtx_leave(&fdp->fd_fplock);
277 	return (closed);
278 }
279 
280 /*
281  * System calls on descriptors.
282  */
283 
284 /*
285  * Duplicate a file descriptor.
286  */
287 int
288 sys_dup(struct proc *p, void *v, register_t *retval)
289 {
290 	struct sys_dup_args /* {
291 		syscallarg(int) fd;
292 	} */ *uap = v;
293 	struct filedesc *fdp = p->p_fd;
294 	int old = SCARG(uap, fd);
295 	struct file *fp;
296 	int new;
297 	int error;
298 
299 restart:
300 	if ((fp = fd_getfile(fdp, old)) == NULL)
301 		return (EBADF);
302 	fdplock(fdp);
303 	if ((error = fdalloc(p, 0, &new)) != 0) {
304 		if (error == ENOSPC) {
305 			fdexpand(p);
306 			fdpunlock(fdp);
307 			FRELE(fp, p);
308 			goto restart;
309 		}
310 		fdpunlock(fdp);
311 		FRELE(fp, p);
312 		return (error);
313 	}
314 	/* No need for FRELE(), finishdup() uses current ref. */
315 	return (finishdup(p, fp, old, new, retval, 0));
316 }
317 
318 /*
319  * Duplicate a file descriptor to a particular value.
320  */
321 int
322 sys_dup2(struct proc *p, void *v, register_t *retval)
323 {
324 	struct sys_dup2_args /* {
325 		syscallarg(int) from;
326 		syscallarg(int) to;
327 	} */ *uap = v;
328 
329 	return (dodup3(p, SCARG(uap, from), SCARG(uap, to), 0, retval));
330 }
331 
332 int
333 sys_dup3(struct proc *p, void *v, register_t *retval)
334 {
335 	struct sys_dup3_args /* {
336 		syscallarg(int) from;
337 		syscallarg(int) to;
338 		syscallarg(int) flags;
339 	} */ *uap = v;
340 
341 	if (SCARG(uap, from) == SCARG(uap, to))
342 		return (EINVAL);
343 	if (SCARG(uap, flags) & ~O_CLOEXEC)
344 		return (EINVAL);
345 	return (dodup3(p, SCARG(uap, from), SCARG(uap, to),
346 	    SCARG(uap, flags), retval));
347 }
348 
349 int
350 dodup3(struct proc *p, int old, int new, int flags, register_t *retval)
351 {
352 	struct filedesc *fdp = p->p_fd;
353 	struct file *fp;
354 	int dupflags, error, i;
355 
356 restart:
357 	if ((fp = fd_getfile(fdp, old)) == NULL)
358 		return (EBADF);
359 	if (old == new) {
360 		/*
361 		 * NOTE! This doesn't clear the close-on-exec flag. This might
362 		 * or might not be the intended behavior from the start, but
363 		 * this is what everyone else does.
364 		 */
365 		*retval = new;
366 		FRELE(fp, p);
367 		return (0);
368 	}
369 	if ((u_int)new >= lim_cur(RLIMIT_NOFILE) ||
370 	    (u_int)new >= maxfiles) {
371 		FRELE(fp, p);
372 		return (EBADF);
373 	}
374 	fdplock(fdp);
375 	if (new >= fdp->fd_nfiles) {
376 		if ((error = fdalloc(p, new, &i)) != 0) {
377 			if (error == ENOSPC) {
378 				fdexpand(p);
379 				fdpunlock(fdp);
380 				FRELE(fp, p);
381 				goto restart;
382 			}
383 			fdpunlock(fdp);
384 			FRELE(fp, p);
385 			return (error);
386 		}
387 		if (new != i)
388 			panic("dup2: fdalloc");
389 		fd_unused(fdp, new);
390 	}
391 
392 	dupflags = DUPF_DUP2;
393 	if (flags & O_CLOEXEC)
394 		dupflags |= DUPF_CLOEXEC;
395 
396 	/* No need for FRELE(), finishdup() uses current ref. */
397 	return (finishdup(p, fp, old, new, retval, dupflags));
398 }
399 
400 /*
401  * The file control system call.
402  */
403 int
404 sys_fcntl(struct proc *p, void *v, register_t *retval)
405 {
406 	struct sys_fcntl_args /* {
407 		syscallarg(int) fd;
408 		syscallarg(int) cmd;
409 		syscallarg(void *) arg;
410 	} */ *uap = v;
411 	int fd = SCARG(uap, fd);
412 	struct filedesc *fdp = p->p_fd;
413 	struct file *fp;
414 	struct vnode *vp;
415 	int i, prev, tmp, newmin, flg = F_POSIX;
416 	struct flock fl;
417 	int error = 0;
418 
419 	error = pledge_fcntl(p, SCARG(uap, cmd));
420 	if (error)
421 		return (error);
422 
423 restart:
424 	if ((fp = fd_getfile(fdp, fd)) == NULL)
425 		return (EBADF);
426 	switch (SCARG(uap, cmd)) {
427 
428 	case F_DUPFD:
429 	case F_DUPFD_CLOEXEC:
430 		newmin = (long)SCARG(uap, arg);
431 		if ((u_int)newmin >= lim_cur(RLIMIT_NOFILE) ||
432 		    (u_int)newmin >= maxfiles) {
433 			error = EINVAL;
434 			break;
435 		}
436 		fdplock(fdp);
437 		if ((error = fdalloc(p, newmin, &i)) != 0) {
438 			if (error == ENOSPC) {
439 				fdexpand(p);
440 				fdpunlock(fdp);
441 				FRELE(fp, p);
442 				goto restart;
443 			}
444 			fdpunlock(fdp);
445 			FRELE(fp, p);
446 		} else {
447 			int dupflags = 0;
448 
449 			if (SCARG(uap, cmd) == F_DUPFD_CLOEXEC)
450 				dupflags |= DUPF_CLOEXEC;
451 
452 			/* No need for FRELE(), finishdup() uses current ref. */
453 			error = finishdup(p, fp, fd, i, retval, dupflags);
454 		}
455 		return (error);
456 
457 	case F_GETFD:
458 		fdplock(fdp);
459 		*retval = fdp->fd_ofileflags[fd] & UF_EXCLOSE ? 1 : 0;
460 		fdpunlock(fdp);
461 		break;
462 
463 	case F_SETFD:
464 		fdplock(fdp);
465 		if ((long)SCARG(uap, arg) & 1)
466 			fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
467 		else
468 			fdp->fd_ofileflags[fd] &= ~UF_EXCLOSE;
469 		fdpunlock(fdp);
470 		break;
471 
472 	case F_GETFL:
473 		*retval = OFLAGS(fp->f_flag);
474 		break;
475 
476 	case F_ISATTY:
477 		vp = fp->f_data;
478 	        if (fp->f_type == DTYPE_VNODE && (vp->v_flag & VISTTY))
479 			*retval = 1;
480 		else {
481 			*retval = 0;
482 			error = ENOTTY;
483 		}
484 		break;
485 
486 	case F_SETFL:
487 		do {
488 			tmp = prev = fp->f_flag;
489 			tmp &= ~FCNTLFLAGS;
490 			tmp |= FFLAGS((long)SCARG(uap, arg)) & FCNTLFLAGS;
491 		} while (atomic_cas_uint(&fp->f_flag, prev, tmp) != prev);
492 		tmp = fp->f_flag & FNONBLOCK;
493 		error = (*fp->f_ops->fo_ioctl)(fp, FIONBIO, (caddr_t)&tmp, p);
494 		if (error)
495 			break;
496 		tmp = fp->f_flag & FASYNC;
497 		error = (*fp->f_ops->fo_ioctl)(fp, FIOASYNC, (caddr_t)&tmp, p);
498 		if (!error)
499 			break;
500 		atomic_clearbits_int(&fp->f_flag, FNONBLOCK);
501 		tmp = 0;
502 		(void) (*fp->f_ops->fo_ioctl)(fp, FIONBIO, (caddr_t)&tmp, p);
503 		break;
504 
505 	case F_GETOWN:
506 		tmp = 0;
507 		error = (*fp->f_ops->fo_ioctl)
508 			(fp, FIOGETOWN, (caddr_t)&tmp, p);
509 		*retval = tmp;
510 		break;
511 
512 	case F_SETOWN:
513 		tmp = (long)SCARG(uap, arg);
514 		error = ((*fp->f_ops->fo_ioctl)
515 			(fp, FIOSETOWN, (caddr_t)&tmp, p));
516 		break;
517 
518 	case F_SETLKW:
519 		flg |= F_WAIT;
520 		/* FALLTHROUGH */
521 
522 	case F_SETLK:
523 		error = pledge_flock(p);
524 		if (error != 0)
525 			break;
526 
527 		if (fp->f_type != DTYPE_VNODE) {
528 			error = EINVAL;
529 			break;
530 		}
531 		vp = fp->f_data;
532 		/* Copy in the lock structure */
533 		error = copyin((caddr_t)SCARG(uap, arg), (caddr_t)&fl,
534 		    sizeof (fl));
535 		if (error)
536 			break;
537 #ifdef KTRACE
538 		if (KTRPOINT(p, KTR_STRUCT))
539 			ktrflock(p, &fl);
540 #endif
541 		if (fl.l_whence == SEEK_CUR) {
542 			off_t offset = foffset(fp);
543 
544 			if (fl.l_start == 0 && fl.l_len < 0) {
545 				/* lockf(3) compliance hack */
546 				fl.l_len = -fl.l_len;
547 				fl.l_start = offset - fl.l_len;
548 			} else
549 				fl.l_start += offset;
550 		}
551 		switch (fl.l_type) {
552 
553 		case F_RDLCK:
554 			if ((fp->f_flag & FREAD) == 0) {
555 				error = EBADF;
556 				goto out;
557 			}
558 			atomic_setbits_int(&fdp->fd_flags, FD_ADVLOCK);
559 			error = VOP_ADVLOCK(vp, fdp, F_SETLK, &fl, flg);
560 			break;
561 
562 		case F_WRLCK:
563 			if ((fp->f_flag & FWRITE) == 0) {
564 				error = EBADF;
565 				goto out;
566 			}
567 			atomic_setbits_int(&fdp->fd_flags, FD_ADVLOCK);
568 			error = VOP_ADVLOCK(vp, fdp, F_SETLK, &fl, flg);
569 			break;
570 
571 		case F_UNLCK:
572 			error = VOP_ADVLOCK(vp, fdp, F_UNLCK, &fl, F_POSIX);
573 			goto out;
574 
575 		default:
576 			error = EINVAL;
577 			goto out;
578 		}
579 
580 		if (fd_checkclosed(fdp, fd, fp)) {
581 			/*
582 			 * We have lost the race with close() or dup2();
583 			 * unlock, pretend that we've won the race and that
584 			 * lock had been removed by close()
585 			 */
586 			fl.l_whence = SEEK_SET;
587 			fl.l_start = 0;
588 			fl.l_len = 0;
589 			VOP_ADVLOCK(vp, fdp, F_UNLCK, &fl, F_POSIX);
590 			fl.l_type = F_UNLCK;
591 		}
592 		goto out;
593 
594 
595 	case F_GETLK:
596 		error = pledge_flock(p);
597 		if (error != 0)
598 			break;
599 
600 		if (fp->f_type != DTYPE_VNODE) {
601 			error = EINVAL;
602 			break;
603 		}
604 		vp = fp->f_data;
605 		/* Copy in the lock structure */
606 		error = copyin((caddr_t)SCARG(uap, arg), (caddr_t)&fl,
607 		    sizeof (fl));
608 		if (error)
609 			break;
610 		if (fl.l_whence == SEEK_CUR) {
611 			off_t offset = foffset(fp);
612 
613 			if (fl.l_start == 0 && fl.l_len < 0) {
614 				/* lockf(3) compliance hack */
615 				fl.l_len = -fl.l_len;
616 				fl.l_start = offset - fl.l_len;
617 			} else
618 				fl.l_start += offset;
619 		}
620 		if (fl.l_type != F_RDLCK &&
621 		    fl.l_type != F_WRLCK &&
622 		    fl.l_type != F_UNLCK &&
623 		    fl.l_type != 0) {
624 			error = EINVAL;
625 			break;
626 		}
627 		error = VOP_ADVLOCK(vp, fdp, F_GETLK, &fl, F_POSIX);
628 		if (error)
629 			break;
630 #ifdef KTRACE
631 		if (KTRPOINT(p, KTR_STRUCT))
632 			ktrflock(p, &fl);
633 #endif
634 		error = (copyout((caddr_t)&fl, (caddr_t)SCARG(uap, arg),
635 		    sizeof (fl)));
636 		break;
637 
638 	default:
639 		error = EINVAL;
640 		break;
641 	}
642 out:
643 	FRELE(fp, p);
644 	return (error);
645 }
646 
647 /*
648  * Common code for dup, dup2, and fcntl(F_DUPFD).
649  */
650 int
651 finishdup(struct proc *p, struct file *fp, int old, int new,
652     register_t *retval, int dupflags)
653 {
654 	struct file *oldfp;
655 	struct filedesc *fdp = p->p_fd;
656 	int error;
657 
658 	fdpassertlocked(fdp);
659 	KASSERT(fp->f_iflags & FIF_INSERTED);
660 
661 	if (fp->f_count >= FDUP_MAX_COUNT) {
662 		error = EDEADLK;
663 		goto fail;
664 	}
665 
666 	oldfp = fd_getfile(fdp, new);
667 	if ((dupflags & DUPF_DUP2) && oldfp == NULL) {
668 		if (fd_inuse(fdp, new)) {
669 			error = EBUSY;
670 			goto fail;
671 		}
672 		fd_used(fdp, new);
673 	}
674 
675 	/*
676 	 * Use `fd_fplock' to synchronize with fd_getfile() so that
677 	 * the function no longer creates a new reference to the old file.
678 	 */
679 	mtx_enter(&fdp->fd_fplock);
680 	fdp->fd_ofiles[new] = fp;
681 	mtx_leave(&fdp->fd_fplock);
682 
683 	fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] & ~UF_EXCLOSE;
684 	if (dupflags & DUPF_CLOEXEC)
685 		fdp->fd_ofileflags[new] |= UF_EXCLOSE;
686 	*retval = new;
687 
688 	if (oldfp != NULL) {
689 		knote_fdclose(p, new);
690 		fdpunlock(fdp);
691 		closef(oldfp, p);
692 	} else {
693 		fdpunlock(fdp);
694 	}
695 
696 	return (0);
697 
698 fail:
699 	fdpunlock(fdp);
700 	FRELE(fp, p);
701 	return (error);
702 }
703 
704 void
705 fdinsert(struct filedesc *fdp, int fd, int flags, struct file *fp)
706 {
707 	struct file *fq;
708 
709 	fdpassertlocked(fdp);
710 
711 	mtx_enter(&fhdlk);
712 	if ((fp->f_iflags & FIF_INSERTED) == 0) {
713 		atomic_setbits_int(&fp->f_iflags, FIF_INSERTED);
714 		if ((fq = fdp->fd_ofiles[0]) != NULL) {
715 			LIST_INSERT_AFTER(fq, fp, f_list);
716 		} else {
717 			LIST_INSERT_HEAD(&filehead, fp, f_list);
718 		}
719 	}
720 	mtx_leave(&fhdlk);
721 
722 	mtx_enter(&fdp->fd_fplock);
723 	KASSERT(fdp->fd_ofiles[fd] == NULL);
724 	fdp->fd_ofiles[fd] = fp;
725 	mtx_leave(&fdp->fd_fplock);
726 
727 	fdp->fd_ofileflags[fd] |= (flags & UF_EXCLOSE);
728 }
729 
730 void
731 fdremove(struct filedesc *fdp, int fd)
732 {
733 	fdpassertlocked(fdp);
734 
735 	/*
736 	 * Use `fd_fplock' to synchronize with fd_getfile() so that
737 	 * the function no longer creates a new reference to the file.
738 	 */
739 	mtx_enter(&fdp->fd_fplock);
740 	fdp->fd_ofiles[fd] = NULL;
741 	mtx_leave(&fdp->fd_fplock);
742 
743 	fdp->fd_ofileflags[fd] = 0;
744 
745 	fd_unused(fdp, fd);
746 }
747 
748 int
749 fdrelease(struct proc *p, int fd)
750 {
751 	struct filedesc *fdp = p->p_fd;
752 	struct file *fp;
753 
754 	fdpassertlocked(fdp);
755 
756 	fp = fd_getfile(fdp, fd);
757 	if (fp == NULL) {
758 		fdpunlock(fdp);
759 		return (EBADF);
760 	}
761 	fdremove(fdp, fd);
762 	knote_fdclose(p, fd);
763 	fdpunlock(fdp);
764 	return (closef(fp, p));
765 }
766 
767 /*
768  * Close a file descriptor.
769  */
770 int
771 sys_close(struct proc *p, void *v, register_t *retval)
772 {
773 	struct sys_close_args /* {
774 		syscallarg(int) fd;
775 	} */ *uap = v;
776 	int fd = SCARG(uap, fd), error;
777 	struct filedesc *fdp = p->p_fd;
778 
779 	fdplock(fdp);
780 	/* fdrelease unlocks fdp. */
781 	error = fdrelease(p, fd);
782 
783 	return (error);
784 }
785 
786 /*
787  * Return status information about a file descriptor.
788  */
789 int
790 sys_fstat(struct proc *p, void *v, register_t *retval)
791 {
792 	struct sys_fstat_args /* {
793 		syscallarg(int) fd;
794 		syscallarg(struct stat *) sb;
795 	} */ *uap = v;
796 	int fd = SCARG(uap, fd);
797 	struct filedesc *fdp = p->p_fd;
798 	struct file *fp;
799 	struct stat ub;
800 	int error;
801 
802 	if ((fp = fd_getfile(fdp, fd)) == NULL)
803 		return (EBADF);
804 	error = (*fp->f_ops->fo_stat)(fp, &ub, p);
805 	FRELE(fp, p);
806 	if (error == 0) {
807 		/*
808 		 * Don't let non-root see generation numbers
809 		 * (for NFS security)
810 		 */
811 		if (suser(p))
812 			ub.st_gen = 0;
813 		error = copyout((caddr_t)&ub, (caddr_t)SCARG(uap, sb),
814 		    sizeof (ub));
815 	}
816 #ifdef KTRACE
817 	if (error == 0 && KTRPOINT(p, KTR_STRUCT))
818 		ktrstat(p, &ub);
819 #endif
820 	return (error);
821 }
822 
823 /*
824  * Return pathconf information about a file descriptor.
825  */
826 int
827 sys_fpathconf(struct proc *p, void *v, register_t *retval)
828 {
829 	struct sys_fpathconf_args /* {
830 		syscallarg(int) fd;
831 		syscallarg(int) name;
832 	} */ *uap = v;
833 	int fd = SCARG(uap, fd);
834 	struct filedesc *fdp = p->p_fd;
835 	struct file *fp;
836 	struct vnode *vp;
837 	int error;
838 
839 	if ((fp = fd_getfile(fdp, fd)) == NULL)
840 		return (EBADF);
841 	switch (fp->f_type) {
842 	case DTYPE_PIPE:
843 	case DTYPE_SOCKET:
844 		if (SCARG(uap, name) != _PC_PIPE_BUF) {
845 			error = EINVAL;
846 			break;
847 		}
848 		*retval = PIPE_BUF;
849 		error = 0;
850 		break;
851 
852 	case DTYPE_VNODE:
853 		vp = fp->f_data;
854 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
855 		error = VOP_PATHCONF(vp, SCARG(uap, name), retval);
856 		VOP_UNLOCK(vp);
857 		break;
858 
859 	default:
860 		error = EOPNOTSUPP;
861 		break;
862 	}
863 	FRELE(fp, p);
864 	return (error);
865 }
866 
867 /*
868  * Allocate a file descriptor for the process.
869  */
870 int
871 fdalloc(struct proc *p, int want, int *result)
872 {
873 	struct filedesc *fdp = p->p_fd;
874 	int lim, last, i;
875 	u_int new, off;
876 
877 	fdpassertlocked(fdp);
878 
879 	/*
880 	 * Search for a free descriptor starting at the higher
881 	 * of want or fd_freefile.  If that fails, consider
882 	 * expanding the ofile array.
883 	 */
884 restart:
885 	lim = min((int)lim_cur(RLIMIT_NOFILE), maxfiles);
886 	last = min(fdp->fd_nfiles, lim);
887 	if ((i = want) < fdp->fd_freefile)
888 		i = fdp->fd_freefile;
889 	off = i >> NDENTRYSHIFT;
890 	new = find_next_zero(fdp->fd_himap, off,
891 	    (last + NDENTRIES - 1) >> NDENTRYSHIFT);
892 	if (new != -1) {
893 		i = find_next_zero(&fdp->fd_lomap[new],
894 				   new > off ? 0 : i & NDENTRYMASK,
895 				   NDENTRIES);
896 		if (i == -1) {
897 			/*
898 			 * Free file descriptor in this block was
899 			 * below want, try again with higher want.
900 			 */
901 			want = (new + 1) << NDENTRYSHIFT;
902 			goto restart;
903 		}
904 		i += (new << NDENTRYSHIFT);
905 		if (i < last) {
906 			fd_used(fdp, i);
907 			if (want <= fdp->fd_freefile)
908 				fdp->fd_freefile = i;
909 			*result = i;
910 			fdp->fd_ofileflags[i] = 0;
911 			if (ISSET(p->p_p->ps_flags, PS_PLEDGE))
912 				fdp->fd_ofileflags[i] |= UF_PLEDGED;
913 			return (0);
914 		}
915 	}
916 	if (fdp->fd_nfiles >= lim)
917 		return (EMFILE);
918 
919 	return (ENOSPC);
920 }
921 
922 void
923 fdexpand(struct proc *p)
924 {
925 	struct filedesc *fdp = p->p_fd;
926 	int nfiles, oldnfiles;
927 	size_t copylen;
928 	struct file **newofile, **oldofile;
929 	char *newofileflags;
930 	u_int *newhimap, *newlomap;
931 
932 	fdpassertlocked(fdp);
933 
934 	oldnfiles = fdp->fd_nfiles;
935 	oldofile = fdp->fd_ofiles;
936 
937 	/*
938 	 * No space in current array.
939 	 */
940 	if (fdp->fd_nfiles < NDEXTENT)
941 		nfiles = NDEXTENT;
942 	else
943 		nfiles = 2 * fdp->fd_nfiles;
944 
945 	newofile = mallocarray(nfiles, OFILESIZE, M_FILEDESC, M_WAITOK);
946 	/*
947 	 * Allocate all required chunks before calling free(9) to make
948 	 * sure that ``fd_ofiles'' stays valid if we go to sleep.
949 	 */
950 	if (NDHISLOTS(nfiles) > NDHISLOTS(fdp->fd_nfiles)) {
951 		newhimap = mallocarray(NDHISLOTS(nfiles), sizeof(u_int),
952 		    M_FILEDESC, M_WAITOK);
953 		newlomap = mallocarray(NDLOSLOTS(nfiles), sizeof(u_int),
954 		    M_FILEDESC, M_WAITOK);
955 	}
956 	newofileflags = (char *) &newofile[nfiles];
957 
958 	/*
959 	 * Copy the existing ofile and ofileflags arrays
960 	 * and zero the new portion of each array.
961 	 */
962 	copylen = sizeof(struct file *) * fdp->fd_nfiles;
963 	memcpy(newofile, fdp->fd_ofiles, copylen);
964 	memset((char *)newofile + copylen, 0,
965 	    nfiles * sizeof(struct file *) - copylen);
966 	copylen = sizeof(char) * fdp->fd_nfiles;
967 	memcpy(newofileflags, fdp->fd_ofileflags, copylen);
968 	memset(newofileflags + copylen, 0, nfiles * sizeof(char) - copylen);
969 
970 	if (NDHISLOTS(nfiles) > NDHISLOTS(fdp->fd_nfiles)) {
971 		copylen = NDHISLOTS(fdp->fd_nfiles) * sizeof(u_int);
972 		memcpy(newhimap, fdp->fd_himap, copylen);
973 		memset((char *)newhimap + copylen, 0,
974 		    NDHISLOTS(nfiles) * sizeof(u_int) - copylen);
975 
976 		copylen = NDLOSLOTS(fdp->fd_nfiles) * sizeof(u_int);
977 		memcpy(newlomap, fdp->fd_lomap, copylen);
978 		memset((char *)newlomap + copylen, 0,
979 		    NDLOSLOTS(nfiles) * sizeof(u_int) - copylen);
980 
981 		if (NDHISLOTS(fdp->fd_nfiles) > NDHISLOTS(NDFILE)) {
982 			free(fdp->fd_himap, M_FILEDESC,
983 			    NDHISLOTS(fdp->fd_nfiles) * sizeof(u_int));
984 			free(fdp->fd_lomap, M_FILEDESC,
985 			    NDLOSLOTS(fdp->fd_nfiles) * sizeof(u_int));
986 		}
987 		fdp->fd_himap = newhimap;
988 		fdp->fd_lomap = newlomap;
989 	}
990 
991 	mtx_enter(&fdp->fd_fplock);
992 	fdp->fd_ofiles = newofile;
993 	mtx_leave(&fdp->fd_fplock);
994 
995 	fdp->fd_ofileflags = newofileflags;
996 	fdp->fd_nfiles = nfiles;
997 
998 	if (oldnfiles > NDFILE)
999 		free(oldofile, M_FILEDESC, oldnfiles * OFILESIZE);
1000 }
1001 
1002 /*
1003  * Create a new open file structure and allocate
1004  * a file descriptor for the process that refers to it.
1005  */
1006 int
1007 falloc(struct proc *p, struct file **resultfp, int *resultfd)
1008 {
1009 	struct file *fp;
1010 	int error, i;
1011 
1012 	KASSERT(resultfp != NULL);
1013 	KASSERT(resultfd != NULL);
1014 
1015 	fdpassertlocked(p->p_fd);
1016 restart:
1017 	if ((error = fdalloc(p, 0, &i)) != 0) {
1018 		if (error == ENOSPC) {
1019 			fdexpand(p);
1020 			goto restart;
1021 		}
1022 		return (error);
1023 	}
1024 
1025 	fp = fnew(p);
1026 	if (fp == NULL) {
1027 		fd_unused(p->p_fd, i);
1028 		return (ENFILE);
1029 	}
1030 
1031 	FREF(fp);
1032 	*resultfp = fp;
1033 	*resultfd = i;
1034 
1035 	return (0);
1036 }
1037 
1038 struct file *
1039 fnew(struct proc *p)
1040 {
1041 	struct file *fp;
1042 	int nfiles;
1043 
1044 	nfiles = atomic_inc_int_nv(&numfiles);
1045 	if (nfiles > maxfiles) {
1046 		atomic_dec_int(&numfiles);
1047 		tablefull("file");
1048 		return (NULL);
1049 	}
1050 
1051 	fp = pool_get(&file_pool, PR_WAITOK|PR_ZERO);
1052 	/*
1053 	 * We need to block interrupts as long as `f_mtx' is being taken
1054 	 * with and without the KERNEL_LOCK().
1055 	 */
1056 	mtx_init(&fp->f_mtx, IPL_MPFLOOR);
1057 	fp->f_count = 1;
1058 	fp->f_cred = p->p_ucred;
1059 	crhold(fp->f_cred);
1060 
1061 	return (fp);
1062 }
1063 
1064 /*
1065  * Build a new filedesc structure.
1066  */
1067 struct filedesc *
1068 fdinit(void)
1069 {
1070 	struct filedesc0 *newfdp;
1071 
1072 	newfdp = pool_get(&fdesc_pool, PR_WAITOK|PR_ZERO);
1073 	rw_init(&newfdp->fd_fd.fd_lock, "fdlock");
1074 	mtx_init(&newfdp->fd_fd.fd_fplock, IPL_MPFLOOR);
1075 	LIST_INIT(&newfdp->fd_fd.fd_kqlist);
1076 
1077 	/* Create the file descriptor table. */
1078 	newfdp->fd_fd.fd_refcnt = 1;
1079 	newfdp->fd_fd.fd_cmask = S_IWGRP|S_IWOTH;
1080 	newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1081 	newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1082 	newfdp->fd_fd.fd_nfiles = NDFILE;
1083 	newfdp->fd_fd.fd_himap = newfdp->fd_dhimap;
1084 	newfdp->fd_fd.fd_lomap = newfdp->fd_dlomap;
1085 
1086 	newfdp->fd_fd.fd_freefile = 0;
1087 	newfdp->fd_fd.fd_lastfile = 0;
1088 
1089 	return (&newfdp->fd_fd);
1090 }
1091 
1092 /*
1093  * Share a filedesc structure.
1094  */
1095 struct filedesc *
1096 fdshare(struct process *pr)
1097 {
1098 	pr->ps_fd->fd_refcnt++;
1099 	return (pr->ps_fd);
1100 }
1101 
1102 /*
1103  * Copy a filedesc structure.
1104  */
1105 struct filedesc *
1106 fdcopy(struct process *pr)
1107 {
1108 	struct filedesc *newfdp, *fdp = pr->ps_fd;
1109 	int i;
1110 
1111 	newfdp = fdinit();
1112 
1113 	fdplock(fdp);
1114 	if (fdp->fd_cdir) {
1115 		vref(fdp->fd_cdir);
1116 		newfdp->fd_cdir = fdp->fd_cdir;
1117 	}
1118 	if (fdp->fd_rdir) {
1119 		vref(fdp->fd_rdir);
1120 		newfdp->fd_rdir = fdp->fd_rdir;
1121 	}
1122 
1123 	/*
1124 	 * If the number of open files fits in the internal arrays
1125 	 * of the open file structure, use them, otherwise allocate
1126 	 * additional memory for the number of descriptors currently
1127 	 * in use.
1128 	 */
1129 	if (fdp->fd_lastfile >= NDFILE) {
1130 		/*
1131 		 * Compute the smallest multiple of NDEXTENT needed
1132 		 * for the file descriptors currently in use,
1133 		 * allowing the table to shrink.
1134 		 */
1135 		i = fdp->fd_nfiles;
1136 		while (i >= 2 * NDEXTENT && i > fdp->fd_lastfile * 2)
1137 			i /= 2;
1138 		newfdp->fd_ofiles = mallocarray(i, OFILESIZE, M_FILEDESC,
1139 		    M_WAITOK | M_ZERO);
1140 		newfdp->fd_ofileflags = (char *) &newfdp->fd_ofiles[i];
1141 		newfdp->fd_nfiles = i;
1142 	}
1143 	if (NDHISLOTS(newfdp->fd_nfiles) > NDHISLOTS(NDFILE)) {
1144 		newfdp->fd_himap = mallocarray(NDHISLOTS(newfdp->fd_nfiles),
1145 		    sizeof(u_int), M_FILEDESC, M_WAITOK | M_ZERO);
1146 		newfdp->fd_lomap = mallocarray(NDLOSLOTS(newfdp->fd_nfiles),
1147 		    sizeof(u_int), M_FILEDESC, M_WAITOK | M_ZERO);
1148 	}
1149 	newfdp->fd_freefile = fdp->fd_freefile;
1150 	newfdp->fd_flags = fdp->fd_flags;
1151 	newfdp->fd_cmask = fdp->fd_cmask;
1152 
1153 	for (i = 0; i <= fdp->fd_lastfile; i++) {
1154 		struct file *fp = fdp->fd_ofiles[i];
1155 
1156 		if (fp != NULL) {
1157 			/*
1158 			 * XXX Gruesome hack. If count gets too high, fail
1159 			 * to copy an fd, since fdcopy()'s callers do not
1160 			 * permit it to indicate failure yet.
1161 			 * Meanwhile, kqueue files have to be
1162 			 * tied to the process that opened them to enforce
1163 			 * their internal consistency, so close them here.
1164 			 */
1165 			if (fp->f_count >= FDUP_MAX_COUNT ||
1166 			    fp->f_type == DTYPE_KQUEUE) {
1167 				if (i < newfdp->fd_freefile)
1168 					newfdp->fd_freefile = i;
1169 				continue;
1170 			}
1171 
1172 			FREF(fp);
1173 			newfdp->fd_ofiles[i] = fp;
1174 			newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1175 			fd_used(newfdp, i);
1176 		}
1177 	}
1178 	fdpunlock(fdp);
1179 
1180 	return (newfdp);
1181 }
1182 
1183 /*
1184  * Release a filedesc structure.
1185  */
1186 void
1187 fdfree(struct proc *p)
1188 {
1189 	struct filedesc *fdp = p->p_fd;
1190 	struct file *fp;
1191 	int fd;
1192 
1193 	if (--fdp->fd_refcnt > 0)
1194 		return;
1195 	for (fd = 0; fd <= fdp->fd_lastfile; fd++) {
1196 		fp = fdp->fd_ofiles[fd];
1197 		if (fp != NULL) {
1198 			fdp->fd_ofiles[fd] = NULL;
1199 			knote_fdclose(p, fd);
1200 			 /* closef() expects a refcount of 2 */
1201 			FREF(fp);
1202 			(void) closef(fp, p);
1203 		}
1204 	}
1205 	p->p_fd = NULL;
1206 	if (fdp->fd_nfiles > NDFILE)
1207 		free(fdp->fd_ofiles, M_FILEDESC, fdp->fd_nfiles * OFILESIZE);
1208 	if (NDHISLOTS(fdp->fd_nfiles) > NDHISLOTS(NDFILE)) {
1209 		free(fdp->fd_himap, M_FILEDESC,
1210 		    NDHISLOTS(fdp->fd_nfiles) * sizeof(u_int));
1211 		free(fdp->fd_lomap, M_FILEDESC,
1212 		    NDLOSLOTS(fdp->fd_nfiles) * sizeof(u_int));
1213 	}
1214 	if (fdp->fd_cdir)
1215 		vrele(fdp->fd_cdir);
1216 	if (fdp->fd_rdir)
1217 		vrele(fdp->fd_rdir);
1218 	pool_put(&fdesc_pool, fdp);
1219 }
1220 
1221 /*
1222  * Internal form of close.
1223  * Decrement reference count on file structure.
1224  * Note: p may be NULL when closing a file
1225  * that was being passed in a message.
1226  *
1227  * The fp must have its usecount bumped and will be FRELEd here.
1228  */
1229 int
1230 closef(struct file *fp, struct proc *p)
1231 {
1232 	struct filedesc *fdp;
1233 
1234 	if (fp == NULL)
1235 		return (0);
1236 
1237 	KASSERTMSG(fp->f_count >= 2, "count (%u) < 2", fp->f_count);
1238 
1239 	atomic_dec_int(&fp->f_count);
1240 
1241 	/*
1242 	 * POSIX record locking dictates that any close releases ALL
1243 	 * locks owned by this process.  This is handled by setting
1244 	 * a flag in the unlock to free ONLY locks obeying POSIX
1245 	 * semantics, and not to free BSD-style file locks.
1246 	 * If the descriptor was in a message, POSIX-style locks
1247 	 * aren't passed with the descriptor.
1248 	 */
1249 
1250 	if (p && ((fdp = p->p_fd) != NULL) &&
1251 	    (fdp->fd_flags & FD_ADVLOCK) &&
1252 	    fp->f_type == DTYPE_VNODE) {
1253 		struct vnode *vp = fp->f_data;
1254 		struct flock lf;
1255 
1256 		lf.l_whence = SEEK_SET;
1257 		lf.l_start = 0;
1258 		lf.l_len = 0;
1259 		lf.l_type = F_UNLCK;
1260 		(void) VOP_ADVLOCK(vp, fdp, F_UNLCK, &lf, F_POSIX);
1261 	}
1262 
1263 	return (FRELE(fp, p));
1264 }
1265 
1266 int
1267 fdrop(struct file *fp, struct proc *p)
1268 {
1269 	int error;
1270 
1271 	KASSERTMSG(fp->f_count == 0, "count (%u) != 0", fp->f_count);
1272 
1273 	mtx_enter(&fhdlk);
1274 	if (fp->f_iflags & FIF_INSERTED)
1275 		LIST_REMOVE(fp, f_list);
1276 	mtx_leave(&fhdlk);
1277 
1278 	if (fp->f_ops)
1279 		error = (*fp->f_ops->fo_close)(fp, p);
1280 	else
1281 		error = 0;
1282 
1283 	crfree(fp->f_cred);
1284 	atomic_dec_int(&numfiles);
1285 	pool_put(&file_pool, fp);
1286 
1287 	return (error);
1288 }
1289 
1290 /*
1291  * Apply an advisory lock on a file descriptor.
1292  *
1293  * Just attempt to get a record lock of the requested type on
1294  * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
1295  */
1296 int
1297 sys_flock(struct proc *p, void *v, register_t *retval)
1298 {
1299 	struct sys_flock_args /* {
1300 		syscallarg(int) fd;
1301 		syscallarg(int) how;
1302 	} */ *uap = v;
1303 	int fd = SCARG(uap, fd);
1304 	int how = SCARG(uap, how);
1305 	struct filedesc *fdp = p->p_fd;
1306 	struct file *fp;
1307 	struct vnode *vp;
1308 	struct flock lf;
1309 	int error;
1310 
1311 	if ((fp = fd_getfile(fdp, fd)) == NULL)
1312 		return (EBADF);
1313 	if (fp->f_type != DTYPE_VNODE) {
1314 		error = EOPNOTSUPP;
1315 		goto out;
1316 	}
1317 	vp = fp->f_data;
1318 	lf.l_whence = SEEK_SET;
1319 	lf.l_start = 0;
1320 	lf.l_len = 0;
1321 	if (how & LOCK_UN) {
1322 		lf.l_type = F_UNLCK;
1323 		atomic_clearbits_int(&fp->f_iflags, FIF_HASLOCK);
1324 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
1325 		goto out;
1326 	}
1327 	if (how & LOCK_EX)
1328 		lf.l_type = F_WRLCK;
1329 	else if (how & LOCK_SH)
1330 		lf.l_type = F_RDLCK;
1331 	else {
1332 		error = EINVAL;
1333 		goto out;
1334 	}
1335 	atomic_setbits_int(&fp->f_iflags, FIF_HASLOCK);
1336 	if (how & LOCK_NB)
1337 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK);
1338 	else
1339 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK|F_WAIT);
1340 out:
1341 	FRELE(fp, p);
1342 	return (error);
1343 }
1344 
1345 /*
1346  * File Descriptor pseudo-device driver (/dev/fd/).
1347  *
1348  * Opening minor device N dup()s the file (if any) connected to file
1349  * descriptor N belonging to the calling process.  Note that this driver
1350  * consists of only the ``open()'' routine, because all subsequent
1351  * references to this file will be direct to the other driver.
1352  */
1353 int
1354 filedescopen(dev_t dev, int mode, int type, struct proc *p)
1355 {
1356 
1357 	/*
1358 	 * XXX Kludge: set curproc->p_dupfd to contain the value of the
1359 	 * the file descriptor being sought for duplication. The error
1360 	 * return ensures that the vnode for this device will be released
1361 	 * by vn_open. Open will detect this special error and take the
1362 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
1363 	 * will simply report the error.
1364 	 */
1365 	p->p_dupfd = minor(dev);
1366 	return (ENODEV);
1367 }
1368 
1369 /*
1370  * Duplicate the specified descriptor to a free descriptor.
1371  */
1372 int
1373 dupfdopen(struct proc *p, int indx, int mode)
1374 {
1375 	struct filedesc *fdp = p->p_fd;
1376 	int dupfd = p->p_dupfd;
1377 	struct file *wfp;
1378 
1379 	fdpassertlocked(fdp);
1380 
1381 	/*
1382 	 * Assume that the filename was user-specified; applications do
1383 	 * not tend to open /dev/fd/# when they can just call dup()
1384 	 */
1385 	if ((p->p_p->ps_flags & (PS_SUGIDEXEC | PS_SUGID))) {
1386 		if (p->p_descfd == 255)
1387 			return (EPERM);
1388 		if (p->p_descfd != dupfd)
1389 			return (EPERM);
1390 	}
1391 
1392 	/*
1393 	 * If the to-be-dup'd fd number is greater than the allowed number
1394 	 * of file descriptors, or the fd to be dup'd has already been
1395 	 * closed, reject. Note, there is no need to check for new == old
1396 	 * because fd_getfile will return NULL if the file at indx is
1397 	 * newly created by falloc.
1398 	 */
1399 	if ((wfp = fd_getfile(fdp, dupfd)) == NULL)
1400 		return (EBADF);
1401 
1402 	/*
1403 	 * Check that the mode the file is being opened for is a
1404 	 * subset of the mode of the existing descriptor.
1405 	 */
1406 	if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
1407 		FRELE(wfp, p);
1408 		return (EACCES);
1409 	}
1410 	if (wfp->f_count >= FDUP_MAX_COUNT) {
1411 		FRELE(wfp, p);
1412 		return (EDEADLK);
1413 	}
1414 
1415 	KASSERT(wfp->f_iflags & FIF_INSERTED);
1416 
1417 	mtx_enter(&fdp->fd_fplock);
1418 	KASSERT(fdp->fd_ofiles[indx] == NULL);
1419 	fdp->fd_ofiles[indx] = wfp;
1420 	mtx_leave(&fdp->fd_fplock);
1421 
1422 	fdp->fd_ofileflags[indx] = (fdp->fd_ofileflags[indx] & UF_EXCLOSE) |
1423 	    (fdp->fd_ofileflags[dupfd] & ~UF_EXCLOSE);
1424 
1425 	return (0);
1426 }
1427 
1428 /*
1429  * Close any files on exec?
1430  */
1431 void
1432 fdcloseexec(struct proc *p)
1433 {
1434 	struct filedesc *fdp = p->p_fd;
1435 	int fd;
1436 
1437 	fdplock(fdp);
1438 	for (fd = 0; fd <= fdp->fd_lastfile; fd++) {
1439 		fdp->fd_ofileflags[fd] &= ~UF_PLEDGED;
1440 		if (fdp->fd_ofileflags[fd] & UF_EXCLOSE) {
1441 			/* fdrelease() unlocks fdp. */
1442 			(void) fdrelease(p, fd);
1443 			fdplock(fdp);
1444 		}
1445 	}
1446 	fdpunlock(fdp);
1447 }
1448 
1449 int
1450 sys_closefrom(struct proc *p, void *v, register_t *retval)
1451 {
1452 	struct sys_closefrom_args *uap = v;
1453 	struct filedesc *fdp = p->p_fd;
1454 	u_int startfd, i;
1455 
1456 	startfd = SCARG(uap, fd);
1457 	fdplock(fdp);
1458 
1459 	if (startfd > fdp->fd_lastfile) {
1460 		fdpunlock(fdp);
1461 		return (EBADF);
1462 	}
1463 
1464 	for (i = startfd; i <= fdp->fd_lastfile; i++) {
1465 		/* fdrelease() unlocks fdp. */
1466 		fdrelease(p, i);
1467 		fdplock(fdp);
1468 	}
1469 
1470 	fdpunlock(fdp);
1471 	return (0);
1472 }
1473 
1474 int
1475 sys_getdtablecount(struct proc *p, void *v, register_t *retval)
1476 {
1477 	*retval = p->p_fd->fd_openfd;
1478 	return (0);
1479 }
1480