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