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