kern_descrip.c revision 1.199 1 /* $NetBSD: kern_descrip.c,v 1.199 2009/08/16 11:00:20 yamt Exp $ */
2
3 /*-
4 * Copyright (c) 2008, 2009 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Andrew Doran.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 /*
33 * Copyright (c) 1982, 1986, 1989, 1991, 1993
34 * The Regents of the University of California. All rights reserved.
35 * (c) UNIX System Laboratories, Inc.
36 * All or some portions of this file are derived from material licensed
37 * to the University of California by American Telephone and Telegraph
38 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
39 * the permission of UNIX System Laboratories, Inc.
40 *
41 * Redistribution and use in source and binary forms, with or without
42 * modification, are permitted provided that the following conditions
43 * are met:
44 * 1. Redistributions of source code must retain the above copyright
45 * notice, this list of conditions and the following disclaimer.
46 * 2. Redistributions in binary form must reproduce the above copyright
47 * notice, this list of conditions and the following disclaimer in the
48 * documentation and/or other materials provided with the distribution.
49 * 3. Neither the name of the University nor the names of its contributors
50 * may be used to endorse or promote products derived from this software
51 * without specific prior written permission.
52 *
53 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63 * SUCH DAMAGE.
64 *
65 * @(#)kern_descrip.c 8.8 (Berkeley) 2/14/95
66 */
67
68 /*
69 * File descriptor management.
70 */
71
72 #include <sys/cdefs.h>
73 __KERNEL_RCSID(0, "$NetBSD: kern_descrip.c,v 1.199 2009/08/16 11:00:20 yamt Exp $");
74
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/filedesc.h>
78 #include <sys/kernel.h>
79 #include <sys/proc.h>
80 #include <sys/file.h>
81 #include <sys/socket.h>
82 #include <sys/socketvar.h>
83 #include <sys/stat.h>
84 #include <sys/ioctl.h>
85 #include <sys/fcntl.h>
86 #include <sys/pool.h>
87 #include <sys/unistd.h>
88 #include <sys/resourcevar.h>
89 #include <sys/conf.h>
90 #include <sys/event.h>
91 #include <sys/kauth.h>
92 #include <sys/atomic.h>
93 #include <sys/syscallargs.h>
94 #include <sys/cpu.h>
95 #include <sys/kmem.h>
96 #include <sys/vnode.h>
97
98 static int file_ctor(void *, void *, int);
99 static void file_dtor(void *, void *);
100 static int fdfile_ctor(void *, void *, int);
101 static void fdfile_dtor(void *, void *);
102 static int filedesc_ctor(void *, void *, int);
103 static void filedesc_dtor(void *, void *);
104 static int filedescopen(dev_t, int, int, lwp_t *);
105
106 kmutex_t filelist_lock; /* lock on filehead */
107 struct filelist filehead; /* head of list of open files */
108 u_int nfiles; /* actual number of open files */
109
110 static pool_cache_t filedesc_cache;
111 static pool_cache_t file_cache;
112 static pool_cache_t fdfile_cache;
113
114 const struct cdevsw filedesc_cdevsw = {
115 filedescopen, noclose, noread, nowrite, noioctl,
116 nostop, notty, nopoll, nommap, nokqfilter, D_OTHER | D_MPSAFE,
117 };
118
119 /* For ease of reading. */
120 __strong_alias(fd_putvnode,fd_putfile)
121 __strong_alias(fd_putsock,fd_putfile)
122
123 /*
124 * Initialize the descriptor system.
125 */
126 void
127 fd_sys_init(void)
128 {
129
130 mutex_init(&filelist_lock, MUTEX_DEFAULT, IPL_NONE);
131
132 file_cache = pool_cache_init(sizeof(file_t), coherency_unit, 0,
133 0, "file", NULL, IPL_NONE, file_ctor, file_dtor, NULL);
134 KASSERT(file_cache != NULL);
135
136 fdfile_cache = pool_cache_init(sizeof(fdfile_t), coherency_unit, 0,
137 PR_LARGECACHE, "fdfile", NULL, IPL_NONE, fdfile_ctor, fdfile_dtor,
138 NULL);
139 KASSERT(fdfile_cache != NULL);
140
141 filedesc_cache = pool_cache_init(sizeof(filedesc_t), coherency_unit,
142 0, 0, "filedesc", NULL, IPL_NONE, filedesc_ctor, filedesc_dtor,
143 NULL);
144 KASSERT(filedesc_cache != NULL);
145 }
146
147 static bool
148 fd_isused(filedesc_t *fdp, unsigned fd)
149 {
150 u_int off = fd >> NDENTRYSHIFT;
151
152 KASSERT(fd < fdp->fd_dt->dt_nfiles);
153
154 return (fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) != 0;
155 }
156
157 /*
158 * Verify that the bitmaps match the descriptor table.
159 */
160 static inline void
161 fd_checkmaps(filedesc_t *fdp)
162 {
163 #ifdef DEBUG
164 fdtab_t *dt;
165 u_int fd;
166
167 dt = fdp->fd_dt;
168 if (fdp->fd_refcnt == -1) {
169 /*
170 * fd_free tears down the table without maintaining its bitmap.
171 */
172 return;
173 }
174 for (fd = 0; fd < dt->dt_nfiles; fd++) {
175 if (fd < NDFDFILE) {
176 KASSERT(dt->dt_ff[fd] ==
177 (fdfile_t *)fdp->fd_dfdfile[fd]);
178 }
179 if (dt->dt_ff[fd] == NULL) {
180 KASSERT(!fd_isused(fdp, fd));
181 } else if (dt->dt_ff[fd]->ff_file != NULL) {
182 KASSERT(fd_isused(fdp, fd));
183 }
184 }
185 #else /* DEBUG */
186 /* nothing */
187 #endif /* DEBUG */
188 }
189
190 static int
191 fd_next_zero(filedesc_t *fdp, uint32_t *bitmap, int want, u_int bits)
192 {
193 int i, off, maxoff;
194 uint32_t sub;
195
196 KASSERT(mutex_owned(&fdp->fd_lock));
197
198 fd_checkmaps(fdp);
199
200 if (want > bits)
201 return -1;
202
203 off = want >> NDENTRYSHIFT;
204 i = want & NDENTRYMASK;
205 if (i) {
206 sub = bitmap[off] | ((u_int)~0 >> (NDENTRIES - i));
207 if (sub != ~0)
208 goto found;
209 off++;
210 }
211
212 maxoff = NDLOSLOTS(bits);
213 while (off < maxoff) {
214 if ((sub = bitmap[off]) != ~0)
215 goto found;
216 off++;
217 }
218
219 return (-1);
220
221 found:
222 return (off << NDENTRYSHIFT) + ffs(~sub) - 1;
223 }
224
225 static int
226 fd_last_set(filedesc_t *fd, int last)
227 {
228 int off, i;
229 fdfile_t **ff = fd->fd_dt->dt_ff;
230 uint32_t *bitmap = fd->fd_lomap;
231
232 KASSERT(mutex_owned(&fd->fd_lock));
233
234 fd_checkmaps(fd);
235
236 off = (last - 1) >> NDENTRYSHIFT;
237
238 while (off >= 0 && !bitmap[off])
239 off--;
240
241 if (off < 0)
242 return (-1);
243
244 i = ((off + 1) << NDENTRYSHIFT) - 1;
245 if (i >= last)
246 i = last - 1;
247
248 /* XXX should use bitmap */
249 while (i > 0 && (ff[i] == NULL || !ff[i]->ff_allocated))
250 i--;
251
252 return (i);
253 }
254
255 static inline void
256 fd_used(filedesc_t *fdp, unsigned fd)
257 {
258 u_int off = fd >> NDENTRYSHIFT;
259 fdfile_t *ff;
260
261 ff = fdp->fd_dt->dt_ff[fd];
262
263 KASSERT(mutex_owned(&fdp->fd_lock));
264 KASSERT((fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) == 0);
265 KASSERT(ff != NULL);
266 KASSERT(ff->ff_file == NULL);
267 KASSERT(!ff->ff_allocated);
268
269 ff->ff_allocated = 1;
270 fdp->fd_lomap[off] |= 1 << (fd & NDENTRYMASK);
271 if (__predict_false(fdp->fd_lomap[off] == ~0)) {
272 KASSERT((fdp->fd_himap[off >> NDENTRYSHIFT] &
273 (1 << (off & NDENTRYMASK))) == 0);
274 fdp->fd_himap[off >> NDENTRYSHIFT] |= 1 << (off & NDENTRYMASK);
275 }
276
277 if ((int)fd > fdp->fd_lastfile) {
278 fdp->fd_lastfile = fd;
279 }
280
281 fd_checkmaps(fdp);
282 }
283
284 static inline void
285 fd_unused(filedesc_t *fdp, unsigned fd)
286 {
287 u_int off = fd >> NDENTRYSHIFT;
288 fdfile_t *ff;
289
290 ff = fdp->fd_dt->dt_ff[fd];
291
292 /*
293 * Don't assert the lock is held here, as we may be copying
294 * the table during exec() and it is not needed there.
295 * procfs and sysctl are locked out by proc::p_reflock.
296 *
297 * KASSERT(mutex_owned(&fdp->fd_lock));
298 */
299 KASSERT(ff != NULL);
300 KASSERT(ff->ff_file == NULL);
301 KASSERT(ff->ff_allocated);
302
303 if (fd < fdp->fd_freefile) {
304 fdp->fd_freefile = fd;
305 }
306
307 if (fdp->fd_lomap[off] == ~0) {
308 KASSERT((fdp->fd_himap[off >> NDENTRYSHIFT] &
309 (1 << (off & NDENTRYMASK))) != 0);
310 fdp->fd_himap[off >> NDENTRYSHIFT] &=
311 ~(1 << (off & NDENTRYMASK));
312 }
313 KASSERT((fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) != 0);
314 fdp->fd_lomap[off] &= ~(1 << (fd & NDENTRYMASK));
315 ff->ff_allocated = 0;
316
317 KASSERT(fd <= fdp->fd_lastfile);
318 if (fd == fdp->fd_lastfile) {
319 fdp->fd_lastfile = fd_last_set(fdp, fd);
320 }
321 fd_checkmaps(fdp);
322 }
323
324 /*
325 * Look up the file structure corresponding to a file descriptor
326 * and return the file, holding a reference on the descriptor.
327 */
328 inline file_t *
329 fd_getfile(unsigned fd)
330 {
331 filedesc_t *fdp;
332 fdfile_t *ff;
333 file_t *fp;
334 fdtab_t *dt;
335
336 /*
337 * Look up the fdfile structure representing this descriptor.
338 * We are doing this unlocked. See fd_tryexpand().
339 */
340 fdp = curlwp->l_fd;
341 dt = fdp->fd_dt;
342 if (__predict_false(fd >= dt->dt_nfiles)) {
343 return NULL;
344 }
345 ff = dt->dt_ff[fd];
346 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
347 if (__predict_false(ff == NULL)) {
348 return NULL;
349 }
350
351 /* Now get a reference to the descriptor. */
352 if (fdp->fd_refcnt == 1) {
353 /*
354 * Single threaded: don't need to worry about concurrent
355 * access (other than earlier calls to kqueue, which may
356 * hold a reference to the descriptor).
357 */
358 ff->ff_refcnt++;
359 } else {
360 /*
361 * Multi threaded: issue a memory barrier to ensure that we
362 * acquire the file pointer _after_ adding a reference. If
363 * no memory barrier, we could fetch a stale pointer.
364 */
365 atomic_inc_uint(&ff->ff_refcnt);
366 #ifndef __HAVE_ATOMIC_AS_MEMBAR
367 membar_enter();
368 #endif
369 }
370
371 /*
372 * If the file is not open or is being closed then put the
373 * reference back.
374 */
375 fp = ff->ff_file;
376 if (__predict_true(fp != NULL)) {
377 return fp;
378 }
379 fd_putfile(fd);
380 return NULL;
381 }
382
383 /*
384 * Release a reference to a file descriptor acquired with fd_getfile().
385 */
386 void
387 fd_putfile(unsigned fd)
388 {
389 filedesc_t *fdp;
390 fdfile_t *ff;
391 u_int u, v;
392
393 fdp = curlwp->l_fd;
394 ff = fdp->fd_dt->dt_ff[fd];
395
396 KASSERT(fd < fdp->fd_dt->dt_nfiles);
397 KASSERT(ff != NULL);
398 KASSERT((ff->ff_refcnt & FR_MASK) > 0);
399 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
400
401 if (fdp->fd_refcnt == 1) {
402 /*
403 * Single threaded: don't need to worry about concurrent
404 * access (other than earlier calls to kqueue, which may
405 * hold a reference to the descriptor).
406 */
407 if (__predict_false((ff->ff_refcnt & FR_CLOSING) != 0)) {
408 fd_close(fd);
409 return;
410 }
411 ff->ff_refcnt--;
412 return;
413 }
414
415 /*
416 * Ensure that any use of the file is complete and globally
417 * visible before dropping the final reference. If no membar,
418 * the current CPU could still access memory associated with
419 * the file after it has been freed or recycled by another
420 * CPU.
421 */
422 #ifndef __HAVE_ATOMIC_AS_MEMBAR
423 membar_exit();
424 #endif
425
426 /*
427 * Be optimistic and start out with the assumption that no other
428 * threads are trying to close the descriptor. If the CAS fails,
429 * we lost a race and/or it's being closed.
430 */
431 for (u = ff->ff_refcnt & FR_MASK;; u = v) {
432 v = atomic_cas_uint(&ff->ff_refcnt, u, u - 1);
433 if (__predict_true(u == v)) {
434 return;
435 }
436 if (__predict_false((v & FR_CLOSING) != 0)) {
437 break;
438 }
439 }
440
441 /* Another thread is waiting to close the file: join it. */
442 (void)fd_close(fd);
443 }
444
445 /*
446 * Convenience wrapper around fd_getfile() that returns reference
447 * to a vnode.
448 */
449 int
450 fd_getvnode(unsigned fd, file_t **fpp)
451 {
452 vnode_t *vp;
453 file_t *fp;
454
455 fp = fd_getfile(fd);
456 if (__predict_false(fp == NULL)) {
457 return EBADF;
458 }
459 if (__predict_false(fp->f_type != DTYPE_VNODE)) {
460 fd_putfile(fd);
461 return EINVAL;
462 }
463 vp = fp->f_data;
464 if (__predict_false(vp->v_type == VBAD)) {
465 /* XXX Is this case really necessary? */
466 fd_putfile(fd);
467 return EBADF;
468 }
469 *fpp = fp;
470 return 0;
471 }
472
473 /*
474 * Convenience wrapper around fd_getfile() that returns reference
475 * to a socket.
476 */
477 int
478 fd_getsock(unsigned fd, struct socket **sop)
479 {
480 file_t *fp;
481
482 fp = fd_getfile(fd);
483 if (__predict_false(fp == NULL)) {
484 return EBADF;
485 }
486 if (__predict_false(fp->f_type != DTYPE_SOCKET)) {
487 fd_putfile(fd);
488 return ENOTSOCK;
489 }
490 *sop = fp->f_data;
491 return 0;
492 }
493
494 /*
495 * Look up the file structure corresponding to a file descriptor
496 * and return it with a reference held on the file, not the
497 * descriptor.
498 *
499 * This is heavyweight and only used when accessing descriptors
500 * from a foreign process. The caller must ensure that `p' does
501 * not exit or fork across this call.
502 *
503 * To release the file (not descriptor) reference, use closef().
504 */
505 file_t *
506 fd_getfile2(proc_t *p, unsigned fd)
507 {
508 filedesc_t *fdp;
509 fdfile_t *ff;
510 file_t *fp;
511 fdtab_t *dt;
512
513 fdp = p->p_fd;
514 mutex_enter(&fdp->fd_lock);
515 dt = fdp->fd_dt;
516 if (fd >= dt->dt_nfiles) {
517 mutex_exit(&fdp->fd_lock);
518 return NULL;
519 }
520 if ((ff = dt->dt_ff[fd]) == NULL) {
521 mutex_exit(&fdp->fd_lock);
522 return NULL;
523 }
524 if ((fp = ff->ff_file) == NULL) {
525 mutex_exit(&fdp->fd_lock);
526 return NULL;
527 }
528 mutex_enter(&fp->f_lock);
529 fp->f_count++;
530 mutex_exit(&fp->f_lock);
531 mutex_exit(&fdp->fd_lock);
532
533 return fp;
534 }
535
536 /*
537 * Internal form of close. Must be called with a reference to the
538 * descriptor, and will drop the reference. When all descriptor
539 * references are dropped, releases the descriptor slot and a single
540 * reference to the file structure.
541 */
542 int
543 fd_close(unsigned fd)
544 {
545 struct flock lf;
546 filedesc_t *fdp;
547 fdfile_t *ff;
548 file_t *fp;
549 proc_t *p;
550 lwp_t *l;
551 u_int refcnt;
552
553 l = curlwp;
554 p = l->l_proc;
555 fdp = l->l_fd;
556 ff = fdp->fd_dt->dt_ff[fd];
557
558 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
559
560 mutex_enter(&fdp->fd_lock);
561 KASSERT((ff->ff_refcnt & FR_MASK) > 0);
562 if (__predict_false(ff->ff_file == NULL)) {
563 /*
564 * Another user of the file is already closing, and is
565 * waiting for other users of the file to drain. Release
566 * our reference, and wake up the closer.
567 */
568 atomic_dec_uint(&ff->ff_refcnt);
569 cv_broadcast(&ff->ff_closing);
570 mutex_exit(&fdp->fd_lock);
571
572 /*
573 * An application error, so pretend that the descriptor
574 * was already closed. We can't safely wait for it to
575 * be closed without potentially deadlocking.
576 */
577 return (EBADF);
578 }
579 KASSERT((ff->ff_refcnt & FR_CLOSING) == 0);
580
581 /*
582 * There may be multiple users of this file within the process.
583 * Notify existing and new users that the file is closing. This
584 * will prevent them from adding additional uses to this file
585 * while we are closing it.
586 */
587 fp = ff->ff_file;
588 ff->ff_file = NULL;
589 ff->ff_exclose = false;
590
591 /*
592 * We expect the caller to hold a descriptor reference - drop it.
593 * The reference count may increase beyond zero at this point due
594 * to an erroneous descriptor reference by an application, but
595 * fd_getfile() will notice that the file is being closed and drop
596 * the reference again.
597 */
598 if (fdp->fd_refcnt == 1) {
599 /* Single threaded. */
600 refcnt = --(ff->ff_refcnt);
601 } else {
602 /* Multi threaded. */
603 #ifndef __HAVE_ATOMIC_AS_MEMBAR
604 membar_producer();
605 #endif
606 refcnt = atomic_dec_uint_nv(&ff->ff_refcnt);
607 }
608 if (__predict_false(refcnt != 0)) {
609 /*
610 * Wait for other references to drain. This is typically
611 * an application error - the descriptor is being closed
612 * while still in use.
613 *
614 */
615 atomic_or_uint(&ff->ff_refcnt, FR_CLOSING);
616
617 /*
618 * Remove any knotes attached to the file. A knote
619 * attached to the descriptor can hold references on it.
620 */
621 mutex_exit(&fdp->fd_lock);
622 if (!SLIST_EMPTY(&ff->ff_knlist)) {
623 knote_fdclose(fd);
624 }
625
626 /* Try to drain out descriptor references. */
627 (*fp->f_ops->fo_drain)(fp);
628 mutex_enter(&fdp->fd_lock);
629
630 /*
631 * We need to see the count drop to zero at least once,
632 * in order to ensure that all pre-existing references
633 * have been drained. New references past this point are
634 * of no interest.
635 */
636 while ((ff->ff_refcnt & FR_MASK) != 0) {
637 cv_wait(&ff->ff_closing, &fdp->fd_lock);
638 }
639 atomic_and_uint(&ff->ff_refcnt, ~FR_CLOSING);
640 } else {
641 /* If no references, there must be no knotes. */
642 KASSERT(SLIST_EMPTY(&ff->ff_knlist));
643 }
644
645 /*
646 * POSIX record locking dictates that any close releases ALL
647 * locks owned by this process. This is handled by setting
648 * a flag in the unlock to free ONLY locks obeying POSIX
649 * semantics, and not to free BSD-style file locks.
650 * If the descriptor was in a message, POSIX-style locks
651 * aren't passed with the descriptor.
652 */
653 if (__predict_false((p->p_flag & PK_ADVLOCK) != 0 &&
654 fp->f_type == DTYPE_VNODE)) {
655 lf.l_whence = SEEK_SET;
656 lf.l_start = 0;
657 lf.l_len = 0;
658 lf.l_type = F_UNLCK;
659 mutex_exit(&fdp->fd_lock);
660 (void)VOP_ADVLOCK(fp->f_data, p, F_UNLCK, &lf, F_POSIX);
661 mutex_enter(&fdp->fd_lock);
662 }
663
664 /* Free descriptor slot. */
665 fd_unused(fdp, fd);
666 mutex_exit(&fdp->fd_lock);
667
668 /* Now drop reference to the file itself. */
669 return closef(fp);
670 }
671
672 /*
673 * Duplicate a file descriptor.
674 */
675 int
676 fd_dup(file_t *fp, int minfd, int *newp, bool exclose)
677 {
678 proc_t *p;
679 int error;
680
681 p = curproc;
682
683 while ((error = fd_alloc(p, minfd, newp)) != 0) {
684 if (error != ENOSPC) {
685 return error;
686 }
687 fd_tryexpand(p);
688 }
689
690 curlwp->l_fd->fd_dt->dt_ff[*newp]->ff_exclose = exclose;
691 fd_affix(p, fp, *newp);
692 return 0;
693 }
694
695 /*
696 * dup2 operation.
697 */
698 int
699 fd_dup2(file_t *fp, unsigned new)
700 {
701 filedesc_t *fdp;
702 fdfile_t *ff;
703 fdtab_t *dt;
704
705 fdp = curlwp->l_fd;
706
707 /*
708 * Ensure there are enough slots in the descriptor table,
709 * and allocate an fdfile_t up front in case we need it.
710 */
711 while (new >= fdp->fd_dt->dt_nfiles) {
712 fd_tryexpand(curproc);
713 }
714 ff = pool_cache_get(fdfile_cache, PR_WAITOK);
715
716 /*
717 * If there is already a file open, close it. If the file is
718 * half open, wait for it to be constructed before closing it.
719 * XXX Potential for deadlock here?
720 */
721 mutex_enter(&fdp->fd_lock);
722 while (fd_isused(fdp, new)) {
723 mutex_exit(&fdp->fd_lock);
724 if (fd_getfile(new) != NULL) {
725 (void)fd_close(new);
726 } else {
727 /*
728 * Crummy, but unlikely to happen.
729 * Can occur if we interrupt another
730 * thread while it is opening a file.
731 */
732 kpause("dup2", false, 1, NULL);
733 }
734 mutex_enter(&fdp->fd_lock);
735 }
736 dt = fdp->fd_dt;
737 if (dt->dt_ff[new] == NULL) {
738 KASSERT(new >= NDFDFILE);
739 dt->dt_ff[new] = ff;
740 ff = NULL;
741 }
742 fd_used(fdp, new);
743 mutex_exit(&fdp->fd_lock);
744
745 /* Slot is now allocated. Insert copy of the file. */
746 fd_affix(curproc, fp, new);
747 if (ff != NULL) {
748 pool_cache_put(fdfile_cache, ff);
749 }
750 return 0;
751 }
752
753 /*
754 * Drop reference to a file structure.
755 */
756 int
757 closef(file_t *fp)
758 {
759 struct flock lf;
760 int error;
761
762 /*
763 * Drop reference. If referenced elsewhere it's still open
764 * and we have nothing more to do.
765 */
766 mutex_enter(&fp->f_lock);
767 KASSERT(fp->f_count > 0);
768 if (--fp->f_count > 0) {
769 mutex_exit(&fp->f_lock);
770 return 0;
771 }
772 KASSERT(fp->f_count == 0);
773 mutex_exit(&fp->f_lock);
774
775 /* We held the last reference - release locks, close and free. */
776 if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
777 lf.l_whence = SEEK_SET;
778 lf.l_start = 0;
779 lf.l_len = 0;
780 lf.l_type = F_UNLCK;
781 (void)VOP_ADVLOCK(fp->f_data, fp, F_UNLCK, &lf, F_FLOCK);
782 }
783 if (fp->f_ops != NULL) {
784 error = (*fp->f_ops->fo_close)(fp);
785 } else {
786 error = 0;
787 }
788 KASSERT(fp->f_count == 0);
789 KASSERT(fp->f_cred != NULL);
790 pool_cache_put(file_cache, fp);
791
792 return error;
793 }
794
795 /*
796 * Allocate a file descriptor for the process.
797 */
798 int
799 fd_alloc(proc_t *p, int want, int *result)
800 {
801 filedesc_t *fdp;
802 int i, lim, last, error;
803 u_int off, new;
804 fdtab_t *dt;
805
806 KASSERT(p == curproc || p == &proc0);
807
808 fdp = p->p_fd;
809
810 /*
811 * Search for a free descriptor starting at the higher
812 * of want or fd_freefile.
813 */
814 mutex_enter(&fdp->fd_lock);
815 fd_checkmaps(fdp);
816 dt = fdp->fd_dt;
817 KASSERT(dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
818 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
819 last = min(dt->dt_nfiles, lim);
820 for (;;) {
821 if ((i = want) < fdp->fd_freefile)
822 i = fdp->fd_freefile;
823 off = i >> NDENTRYSHIFT;
824 new = fd_next_zero(fdp, fdp->fd_himap, off,
825 (last + NDENTRIES - 1) >> NDENTRYSHIFT);
826 if (new == -1)
827 break;
828 i = fd_next_zero(fdp, &fdp->fd_lomap[new],
829 new > off ? 0 : i & NDENTRYMASK, NDENTRIES);
830 if (i == -1) {
831 /*
832 * Free file descriptor in this block was
833 * below want, try again with higher want.
834 */
835 want = (new + 1) << NDENTRYSHIFT;
836 continue;
837 }
838 i += (new << NDENTRYSHIFT);
839 if (i >= last) {
840 break;
841 }
842 if (dt->dt_ff[i] == NULL) {
843 KASSERT(i >= NDFDFILE);
844 dt->dt_ff[i] = pool_cache_get(fdfile_cache, PR_WAITOK);
845 }
846 KASSERT(dt->dt_ff[i]->ff_refcnt == 0);
847 KASSERT(dt->dt_ff[i]->ff_file == NULL);
848 fd_used(fdp, i);
849 if (want <= fdp->fd_freefile) {
850 fdp->fd_freefile = i;
851 }
852 *result = i;
853 KASSERT(i >= NDFDFILE ||
854 dt->dt_ff[i] == (fdfile_t *)fdp->fd_dfdfile[i]);
855 fd_checkmaps(fdp);
856 mutex_exit(&fdp->fd_lock);
857 return 0;
858 }
859
860 /* No space in current array. Let the caller expand and retry. */
861 error = (dt->dt_nfiles >= lim) ? EMFILE : ENOSPC;
862 mutex_exit(&fdp->fd_lock);
863 return error;
864 }
865
866 /*
867 * Allocate memory for a descriptor table.
868 */
869 static fdtab_t *
870 fd_dtab_alloc(int n)
871 {
872 fdtab_t *dt;
873 size_t sz;
874
875 KASSERT(n > NDFILE);
876
877 sz = sizeof(*dt) + (n - NDFILE) * sizeof(dt->dt_ff[0]);
878 dt = kmem_alloc(sz, KM_SLEEP);
879 #ifdef DIAGNOSTIC
880 memset(dt, 0xff, sz);
881 #endif
882 dt->dt_nfiles = n;
883 dt->dt_link = NULL;
884 return dt;
885 }
886
887 /*
888 * Free a descriptor table, and all tables linked for deferred free.
889 */
890 static void
891 fd_dtab_free(fdtab_t *dt)
892 {
893 fdtab_t *next;
894 size_t sz;
895
896 do {
897 next = dt->dt_link;
898 KASSERT(dt->dt_nfiles > NDFILE);
899 sz = sizeof(*dt) +
900 (dt->dt_nfiles - NDFILE) * sizeof(dt->dt_ff[0]);
901 #ifdef DIAGNOSTIC
902 memset(dt, 0xff, sz);
903 #endif
904 kmem_free(dt, sz);
905 dt = next;
906 } while (dt != NULL);
907 }
908
909 /*
910 * Allocate descriptor bitmap.
911 */
912 static void
913 fd_map_alloc(int n, uint32_t **lo, uint32_t **hi)
914 {
915 uint8_t *ptr;
916 size_t szlo, szhi;
917
918 KASSERT(n > NDENTRIES);
919
920 szlo = NDLOSLOTS(n) * sizeof(uint32_t);
921 szhi = NDHISLOTS(n) * sizeof(uint32_t);
922 ptr = kmem_alloc(szlo + szhi, KM_SLEEP);
923 *lo = (uint32_t *)ptr;
924 *hi = (uint32_t *)(ptr + szlo);
925 }
926
927 /*
928 * Free descriptor bitmap.
929 */
930 static void
931 fd_map_free(int n, uint32_t *lo, uint32_t *hi)
932 {
933 size_t szlo, szhi;
934
935 KASSERT(n > NDENTRIES);
936
937 szlo = NDLOSLOTS(n) * sizeof(uint32_t);
938 szhi = NDHISLOTS(n) * sizeof(uint32_t);
939 KASSERT(hi == (uint32_t *)((uint8_t *)lo + szlo));
940 kmem_free(lo, szlo + szhi);
941 }
942
943 /*
944 * Expand a process' descriptor table.
945 */
946 void
947 fd_tryexpand(proc_t *p)
948 {
949 filedesc_t *fdp;
950 int i, numfiles, oldnfiles;
951 fdtab_t *newdt, *dt;
952 uint32_t *newhimap, *newlomap;
953
954 KASSERT(p == curproc || p == &proc0);
955
956 fdp = p->p_fd;
957 newhimap = NULL;
958 newlomap = NULL;
959 oldnfiles = fdp->fd_dt->dt_nfiles;
960
961 if (oldnfiles < NDEXTENT)
962 numfiles = NDEXTENT;
963 else
964 numfiles = 2 * oldnfiles;
965
966 newdt = fd_dtab_alloc(numfiles);
967 if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
968 fd_map_alloc(numfiles, &newlomap, &newhimap);
969 }
970
971 mutex_enter(&fdp->fd_lock);
972 dt = fdp->fd_dt;
973 KASSERT(dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
974 if (dt->dt_nfiles != oldnfiles) {
975 /* fdp changed; caller must retry */
976 mutex_exit(&fdp->fd_lock);
977 fd_dtab_free(newdt);
978 if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
979 fd_map_free(numfiles, newlomap, newhimap);
980 }
981 return;
982 }
983
984 /* Copy the existing descriptor table and zero the new portion. */
985 i = sizeof(fdfile_t *) * oldnfiles;
986 memcpy(newdt->dt_ff, dt->dt_ff, i);
987 memset((uint8_t *)newdt->dt_ff + i, 0,
988 numfiles * sizeof(fdfile_t *) - i);
989
990 /*
991 * Link old descriptor array into list to be discarded. We defer
992 * freeing until the last reference to the descriptor table goes
993 * away (usually process exit). This allows us to do lockless
994 * lookups in fd_getfile().
995 */
996 if (oldnfiles > NDFILE) {
997 if (fdp->fd_refcnt > 1) {
998 newdt->dt_link = dt;
999 } else {
1000 fd_dtab_free(dt);
1001 }
1002 }
1003
1004 if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
1005 i = NDHISLOTS(oldnfiles) * sizeof(uint32_t);
1006 memcpy(newhimap, fdp->fd_himap, i);
1007 memset((uint8_t *)newhimap + i, 0,
1008 NDHISLOTS(numfiles) * sizeof(uint32_t) - i);
1009
1010 i = NDLOSLOTS(oldnfiles) * sizeof(uint32_t);
1011 memcpy(newlomap, fdp->fd_lomap, i);
1012 memset((uint8_t *)newlomap + i, 0,
1013 NDLOSLOTS(numfiles) * sizeof(uint32_t) - i);
1014
1015 if (NDHISLOTS(oldnfiles) > NDHISLOTS(NDFILE)) {
1016 fd_map_free(oldnfiles, fdp->fd_lomap, fdp->fd_himap);
1017 }
1018 fdp->fd_himap = newhimap;
1019 fdp->fd_lomap = newlomap;
1020 }
1021
1022 /*
1023 * All other modifications must become globally visible before
1024 * the change to fd_dt. See fd_getfile().
1025 */
1026 membar_producer();
1027 fdp->fd_dt = newdt;
1028 KASSERT(newdt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
1029 fd_checkmaps(fdp);
1030 mutex_exit(&fdp->fd_lock);
1031 }
1032
1033 /*
1034 * Create a new open file structure and allocate a file descriptor
1035 * for the current process.
1036 */
1037 int
1038 fd_allocfile(file_t **resultfp, int *resultfd)
1039 {
1040 kauth_cred_t cred;
1041 file_t *fp;
1042 proc_t *p;
1043 int error;
1044
1045 p = curproc;
1046
1047 while ((error = fd_alloc(p, 0, resultfd)) != 0) {
1048 if (error != ENOSPC) {
1049 return error;
1050 }
1051 fd_tryexpand(p);
1052 }
1053
1054 fp = pool_cache_get(file_cache, PR_WAITOK);
1055 if (fp == NULL) {
1056 return ENFILE;
1057 }
1058 KASSERT(fp->f_count == 0);
1059 KASSERT(fp->f_msgcount == 0);
1060 KASSERT(fp->f_unpcount == 0);
1061
1062 /* Replace cached credentials if not what we need. */
1063 cred = curlwp->l_cred;
1064 if (__predict_false(cred != fp->f_cred)) {
1065 kauth_cred_free(fp->f_cred);
1066 kauth_cred_hold(cred);
1067 fp->f_cred = cred;
1068 }
1069
1070 /*
1071 * Don't allow recycled files to be scanned.
1072 * See uipc_usrreq.c.
1073 */
1074 if (__predict_false((fp->f_flag & FSCAN) != 0)) {
1075 mutex_enter(&fp->f_lock);
1076 atomic_and_uint(&fp->f_flag, ~FSCAN);
1077 mutex_exit(&fp->f_lock);
1078 }
1079
1080 fp->f_advice = 0;
1081 fp->f_offset = 0;
1082 *resultfp = fp;
1083
1084 return 0;
1085 }
1086
1087 /*
1088 * Successful creation of a new descriptor: make visible to the process.
1089 */
1090 void
1091 fd_affix(proc_t *p, file_t *fp, unsigned fd)
1092 {
1093 fdfile_t *ff;
1094 filedesc_t *fdp;
1095
1096 KASSERT(p == curproc || p == &proc0);
1097
1098 /* Add a reference to the file structure. */
1099 mutex_enter(&fp->f_lock);
1100 fp->f_count++;
1101 mutex_exit(&fp->f_lock);
1102
1103 /*
1104 * Insert the new file into the descriptor slot.
1105 *
1106 * The memory barriers provided by lock activity in this routine
1107 * ensure that any updates to the file structure become globally
1108 * visible before the file becomes visible to other LWPs in the
1109 * current process.
1110 */
1111 fdp = p->p_fd;
1112 ff = fdp->fd_dt->dt_ff[fd];
1113
1114 KASSERT(ff != NULL);
1115 KASSERT(ff->ff_file == NULL);
1116 KASSERT(ff->ff_allocated);
1117 KASSERT(fd_isused(fdp, fd));
1118 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
1119
1120 /* No need to lock in order to make file initially visible. */
1121 ff->ff_file = fp;
1122 }
1123
1124 /*
1125 * Abort creation of a new descriptor: free descriptor slot and file.
1126 */
1127 void
1128 fd_abort(proc_t *p, file_t *fp, unsigned fd)
1129 {
1130 filedesc_t *fdp;
1131 fdfile_t *ff;
1132
1133 KASSERT(p == curproc || p == &proc0);
1134
1135 fdp = p->p_fd;
1136 ff = fdp->fd_dt->dt_ff[fd];
1137
1138 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
1139
1140 mutex_enter(&fdp->fd_lock);
1141 KASSERT(fd_isused(fdp, fd));
1142 fd_unused(fdp, fd);
1143 mutex_exit(&fdp->fd_lock);
1144
1145 if (fp != NULL) {
1146 KASSERT(fp->f_count == 0);
1147 KASSERT(fp->f_cred != NULL);
1148 pool_cache_put(file_cache, fp);
1149 }
1150 }
1151
1152 static int
1153 file_ctor(void *arg, void *obj, int flags)
1154 {
1155 file_t *fp = obj;
1156
1157 memset(fp, 0, sizeof(*fp));
1158
1159 mutex_enter(&filelist_lock);
1160 if (__predict_false(nfiles >= maxfiles)) {
1161 mutex_exit(&filelist_lock);
1162 tablefull("file", "increase kern.maxfiles or MAXFILES");
1163 return ENFILE;
1164 }
1165 nfiles++;
1166 LIST_INSERT_HEAD(&filehead, fp, f_list);
1167 mutex_init(&fp->f_lock, MUTEX_DEFAULT, IPL_NONE);
1168 fp->f_cred = curlwp->l_cred;
1169 kauth_cred_hold(fp->f_cred);
1170 mutex_exit(&filelist_lock);
1171
1172 return 0;
1173 }
1174
1175 static void
1176 file_dtor(void *arg, void *obj)
1177 {
1178 file_t *fp = obj;
1179
1180 mutex_enter(&filelist_lock);
1181 nfiles--;
1182 LIST_REMOVE(fp, f_list);
1183 mutex_exit(&filelist_lock);
1184
1185 kauth_cred_free(fp->f_cred);
1186 mutex_destroy(&fp->f_lock);
1187 }
1188
1189 static int
1190 fdfile_ctor(void *arg, void *obj, int flags)
1191 {
1192 fdfile_t *ff = obj;
1193
1194 memset(ff, 0, sizeof(*ff));
1195 cv_init(&ff->ff_closing, "fdclose");
1196
1197 return 0;
1198 }
1199
1200 static void
1201 fdfile_dtor(void *arg, void *obj)
1202 {
1203 fdfile_t *ff = obj;
1204
1205 cv_destroy(&ff->ff_closing);
1206 }
1207
1208 file_t *
1209 fgetdummy(void)
1210 {
1211 file_t *fp;
1212
1213 fp = kmem_alloc(sizeof(*fp), KM_SLEEP);
1214 if (fp != NULL) {
1215 memset(fp, 0, sizeof(*fp));
1216 mutex_init(&fp->f_lock, MUTEX_DEFAULT, IPL_NONE);
1217 }
1218 return fp;
1219 }
1220
1221 void
1222 fputdummy(file_t *fp)
1223 {
1224
1225 mutex_destroy(&fp->f_lock);
1226 kmem_free(fp, sizeof(*fp));
1227 }
1228
1229 /*
1230 * Create an initial filedesc structure.
1231 */
1232 filedesc_t *
1233 fd_init(filedesc_t *fdp)
1234 {
1235 #ifdef DIAGNOSTIC
1236 unsigned fd;
1237 #endif
1238
1239 if (__predict_true(fdp == NULL)) {
1240 fdp = pool_cache_get(filedesc_cache, PR_WAITOK);
1241 } else {
1242 /* XXXRUMP KASSERT(fdp == &filedesc0); */
1243 filedesc_ctor(NULL, fdp, PR_WAITOK);
1244 }
1245
1246 #ifdef DIAGNOSTIC
1247 KASSERT(fdp->fd_lastfile == -1);
1248 KASSERT(fdp->fd_lastkqfile == -1);
1249 KASSERT(fdp->fd_knhash == NULL);
1250 KASSERT(fdp->fd_freefile == 0);
1251 KASSERT(fdp->fd_exclose == false);
1252 KASSERT(fdp->fd_dt == &fdp->fd_dtbuiltin);
1253 KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
1254 for (fd = 0; fd < NDFDFILE; fd++) {
1255 KASSERT(fdp->fd_dtbuiltin.dt_ff[fd] ==
1256 (fdfile_t *)fdp->fd_dfdfile[fd]);
1257 }
1258 for (fd = NDFDFILE; fd < NDFILE; fd++) {
1259 KASSERT(fdp->fd_dtbuiltin.dt_ff[fd] == NULL);
1260 }
1261 KASSERT(fdp->fd_himap == fdp->fd_dhimap);
1262 KASSERT(fdp->fd_lomap == fdp->fd_dlomap);
1263 #endif /* DIAGNOSTIC */
1264
1265 fdp->fd_refcnt = 1;
1266 fd_checkmaps(fdp);
1267
1268 return fdp;
1269 }
1270
1271 /*
1272 * Initialize a file descriptor table.
1273 */
1274 static int
1275 filedesc_ctor(void *arg, void *obj, int flag)
1276 {
1277 filedesc_t *fdp = obj;
1278 fdfile_t **ffp;
1279 int i;
1280
1281 memset(fdp, 0, sizeof(*fdp));
1282 mutex_init(&fdp->fd_lock, MUTEX_DEFAULT, IPL_NONE);
1283 fdp->fd_lastfile = -1;
1284 fdp->fd_lastkqfile = -1;
1285 fdp->fd_dt = &fdp->fd_dtbuiltin;
1286 fdp->fd_dtbuiltin.dt_nfiles = NDFILE;
1287 fdp->fd_himap = fdp->fd_dhimap;
1288 fdp->fd_lomap = fdp->fd_dlomap;
1289
1290 CTASSERT(sizeof(fdp->fd_dfdfile[0]) >= sizeof(fdfile_t));
1291 for (i = 0, ffp = fdp->fd_dt->dt_ff; i < NDFDFILE; i++, ffp++) {
1292 *ffp = (fdfile_t *)fdp->fd_dfdfile[i];
1293 (void)fdfile_ctor(NULL, fdp->fd_dfdfile[i], PR_WAITOK);
1294 }
1295
1296 return 0;
1297 }
1298
1299 static void
1300 filedesc_dtor(void *arg, void *obj)
1301 {
1302 filedesc_t *fdp = obj;
1303 int i;
1304
1305 for (i = 0; i < NDFDFILE; i++) {
1306 fdfile_dtor(NULL, fdp->fd_dfdfile[i]);
1307 }
1308
1309 mutex_destroy(&fdp->fd_lock);
1310 }
1311
1312 /*
1313 * Make p2 share p1's filedesc structure.
1314 */
1315 void
1316 fd_share(struct proc *p2)
1317 {
1318 filedesc_t *fdp;
1319
1320 fdp = curlwp->l_fd;
1321 p2->p_fd = fdp;
1322 atomic_inc_uint(&fdp->fd_refcnt);
1323 }
1324
1325 /*
1326 * Acquire a hold on a filedesc structure.
1327 */
1328 void
1329 fd_hold(void)
1330 {
1331
1332 atomic_inc_uint(&curlwp->l_fd->fd_refcnt);
1333 }
1334
1335 /*
1336 * Copy a filedesc structure.
1337 */
1338 filedesc_t *
1339 fd_copy(void)
1340 {
1341 filedesc_t *newfdp, *fdp;
1342 fdfile_t *ff, **ffp, **nffp, *ff2;
1343 int i, j, numfiles, lastfile, newlast;
1344 file_t *fp;
1345 fdtab_t *newdt;
1346
1347 fdp = curproc->p_fd;
1348 newfdp = pool_cache_get(filedesc_cache, PR_WAITOK);
1349 newfdp->fd_refcnt = 1;
1350
1351 #ifdef DIAGNOSTIC
1352 KASSERT(newfdp->fd_lastfile == -1);
1353 KASSERT(newfdp->fd_lastkqfile == -1);
1354 KASSERT(newfdp->fd_knhash == NULL);
1355 KASSERT(newfdp->fd_freefile == 0);
1356 KASSERT(newfdp->fd_exclose == false);
1357 KASSERT(newfdp->fd_dt == &newfdp->fd_dtbuiltin);
1358 KASSERT(newfdp->fd_dtbuiltin.dt_nfiles == NDFILE);
1359 for (i = 0; i < NDFDFILE; i++) {
1360 KASSERT(newfdp->fd_dtbuiltin.dt_ff[i] ==
1361 (fdfile_t *)&newfdp->fd_dfdfile[i]);
1362 }
1363 for (i = NDFDFILE; i < NDFILE; i++) {
1364 KASSERT(newfdp->fd_dtbuiltin.dt_ff[i] == NULL);
1365 }
1366 #endif /* DIAGNOSTIC */
1367
1368 mutex_enter(&fdp->fd_lock);
1369 fd_checkmaps(fdp);
1370 numfiles = fdp->fd_dt->dt_nfiles;
1371 lastfile = fdp->fd_lastfile;
1372
1373 /*
1374 * If the number of open files fits in the internal arrays
1375 * of the open file structure, use them, otherwise allocate
1376 * additional memory for the number of descriptors currently
1377 * in use.
1378 */
1379 if (lastfile < NDFILE) {
1380 i = NDFILE;
1381 newdt = newfdp->fd_dt;
1382 KASSERT(newfdp->fd_dt == &newfdp->fd_dtbuiltin);
1383 } else {
1384 /*
1385 * Compute the smallest multiple of NDEXTENT needed
1386 * for the file descriptors currently in use,
1387 * allowing the table to shrink.
1388 */
1389 i = numfiles;
1390 while (i >= 2 * NDEXTENT && i > lastfile * 2) {
1391 i /= 2;
1392 }
1393 KASSERT(i > NDFILE);
1394 newdt = fd_dtab_alloc(i);
1395 newfdp->fd_dt = newdt;
1396 memcpy(newdt->dt_ff, newfdp->fd_dtbuiltin.dt_ff,
1397 NDFDFILE * sizeof(fdfile_t **));
1398 memset(newdt->dt_ff + NDFDFILE, 0,
1399 (i - NDFDFILE) * sizeof(fdfile_t **));
1400 }
1401 if (NDHISLOTS(i) <= NDHISLOTS(NDFILE)) {
1402 newfdp->fd_himap = newfdp->fd_dhimap;
1403 newfdp->fd_lomap = newfdp->fd_dlomap;
1404 } else {
1405 fd_map_alloc(i, &newfdp->fd_lomap, &newfdp->fd_himap);
1406 KASSERT(i >= NDENTRIES * NDENTRIES);
1407 memset(newfdp->fd_himap, 0, NDHISLOTS(i)*sizeof(uint32_t));
1408 memset(newfdp->fd_lomap, 0, NDLOSLOTS(i)*sizeof(uint32_t));
1409 }
1410 newfdp->fd_freefile = fdp->fd_freefile;
1411 newfdp->fd_exclose = fdp->fd_exclose;
1412
1413 ffp = fdp->fd_dt->dt_ff;
1414 nffp = newdt->dt_ff;
1415 newlast = -1;
1416 for (i = 0; i <= (int)lastfile; i++, ffp++, nffp++) {
1417 KASSERT(i >= NDFDFILE ||
1418 *nffp == (fdfile_t *)newfdp->fd_dfdfile[i]);
1419 ff = *ffp;
1420 if (ff == NULL || (fp = ff->ff_file) == NULL) {
1421 /* Descriptor unused, or descriptor half open. */
1422 KASSERT(!fd_isused(newfdp, i));
1423 continue;
1424 }
1425 if (__predict_false(fp->f_type == DTYPE_KQUEUE)) {
1426 /* kqueue descriptors cannot be copied. */
1427 if (i < newfdp->fd_freefile)
1428 newfdp->fd_freefile = i;
1429 continue;
1430 }
1431 /* It's active: add a reference to the file. */
1432 mutex_enter(&fp->f_lock);
1433 fp->f_count++;
1434 mutex_exit(&fp->f_lock);
1435
1436 /* Allocate an fdfile_t to represent it. */
1437 if (i >= NDFDFILE) {
1438 ff2 = pool_cache_get(fdfile_cache, PR_WAITOK);
1439 *nffp = ff2;
1440 } else {
1441 ff2 = newdt->dt_ff[i];
1442 }
1443 ff2->ff_file = fp;
1444 ff2->ff_exclose = ff->ff_exclose;
1445 ff2->ff_allocated = true;
1446
1447 /* Fix up bitmaps. */
1448 j = i >> NDENTRYSHIFT;
1449 KASSERT((newfdp->fd_lomap[j] & (1 << (i & NDENTRYMASK))) == 0);
1450 newfdp->fd_lomap[j] |= 1 << (i & NDENTRYMASK);
1451 if (__predict_false(newfdp->fd_lomap[j] == ~0)) {
1452 KASSERT((newfdp->fd_himap[j >> NDENTRYSHIFT] &
1453 (1 << (j & NDENTRYMASK))) == 0);
1454 newfdp->fd_himap[j >> NDENTRYSHIFT] |=
1455 1 << (j & NDENTRYMASK);
1456 }
1457 newlast = i;
1458 }
1459 KASSERT(newdt->dt_ff[0] == (fdfile_t *)newfdp->fd_dfdfile[0]);
1460 newfdp->fd_lastfile = newlast;
1461 fd_checkmaps(newfdp);
1462 mutex_exit(&fdp->fd_lock);
1463
1464 return (newfdp);
1465 }
1466
1467 /*
1468 * Release a filedesc structure.
1469 */
1470 void
1471 fd_free(void)
1472 {
1473 fdfile_t *ff;
1474 file_t *fp;
1475 int fd, nf;
1476 fdtab_t *dt;
1477 lwp_t * const l = curlwp;
1478 filedesc_t * const fdp = l->l_fd;
1479 const bool noadvlock = (l->l_proc->p_flag & PK_ADVLOCK) == 0;
1480
1481 KASSERT(fdp->fd_dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
1482 KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
1483 KASSERT(fdp->fd_dtbuiltin.dt_link == NULL);
1484
1485 #ifndef __HAVE_ATOMIC_AS_MEMBAR
1486 membar_exit();
1487 #endif
1488 if (atomic_dec_uint_nv(&fdp->fd_refcnt) > 0)
1489 return;
1490
1491 /*
1492 * Close any files that the process holds open.
1493 */
1494 dt = fdp->fd_dt;
1495 fd_checkmaps(fdp);
1496 #ifdef DEBUG
1497 fdp->fd_refcnt = -1; /* see fd_checkmaps */
1498 #endif
1499 for (fd = 0, nf = dt->dt_nfiles; fd < nf; fd++) {
1500 ff = dt->dt_ff[fd];
1501 KASSERT(fd >= NDFDFILE ||
1502 ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
1503 if (ff == NULL)
1504 continue;
1505 if ((fp = ff->ff_file) != NULL) {
1506 /*
1507 * Must use fd_close() here if there is
1508 * a reference from kqueue or we might have posix
1509 * advisory locks.
1510 */
1511 if (__predict_true(ff->ff_refcnt == 0) &&
1512 (noadvlock || fp->f_type != DTYPE_VNODE)) {
1513 ff->ff_file = NULL;
1514 ff->ff_exclose = false;
1515 ff->ff_allocated = false;
1516 closef(fp);
1517 } else {
1518 ff->ff_refcnt++;
1519 fd_close(fd);
1520 }
1521 }
1522 KASSERT(ff->ff_refcnt == 0);
1523 KASSERT(ff->ff_file == NULL);
1524 KASSERT(!ff->ff_exclose);
1525 KASSERT(!ff->ff_allocated);
1526 if (fd >= NDFDFILE) {
1527 pool_cache_put(fdfile_cache, ff);
1528 dt->dt_ff[fd] = NULL;
1529 }
1530 }
1531
1532 /*
1533 * Clean out the descriptor table for the next user and return
1534 * to the cache.
1535 */
1536 if (__predict_false(dt != &fdp->fd_dtbuiltin)) {
1537 fd_dtab_free(fdp->fd_dt);
1538 /* Otherwise, done above. */
1539 memset(&fdp->fd_dtbuiltin.dt_ff[NDFDFILE], 0,
1540 (NDFILE - NDFDFILE) * sizeof(fdp->fd_dtbuiltin.dt_ff[0]));
1541 fdp->fd_dt = &fdp->fd_dtbuiltin;
1542 }
1543 if (__predict_false(NDHISLOTS(nf) > NDHISLOTS(NDFILE))) {
1544 KASSERT(fdp->fd_himap != fdp->fd_dhimap);
1545 KASSERT(fdp->fd_lomap != fdp->fd_dlomap);
1546 fd_map_free(nf, fdp->fd_lomap, fdp->fd_himap);
1547 }
1548 if (__predict_false(fdp->fd_knhash != NULL)) {
1549 hashdone(fdp->fd_knhash, HASH_LIST, fdp->fd_knhashmask);
1550 fdp->fd_knhash = NULL;
1551 fdp->fd_knhashmask = 0;
1552 } else {
1553 KASSERT(fdp->fd_knhashmask == 0);
1554 }
1555 fdp->fd_dt = &fdp->fd_dtbuiltin;
1556 fdp->fd_lastkqfile = -1;
1557 fdp->fd_lastfile = -1;
1558 fdp->fd_freefile = 0;
1559 fdp->fd_exclose = false;
1560 memset(&fdp->fd_startzero, 0, sizeof(*fdp) -
1561 offsetof(filedesc_t, fd_startzero));
1562 fdp->fd_himap = fdp->fd_dhimap;
1563 fdp->fd_lomap = fdp->fd_dlomap;
1564 KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
1565 KASSERT(fdp->fd_dtbuiltin.dt_link == NULL);
1566 KASSERT(fdp->fd_dt == &fdp->fd_dtbuiltin);
1567 #ifdef DEBUG
1568 fdp->fd_refcnt = 0; /* see fd_checkmaps */
1569 #endif
1570 fd_checkmaps(fdp);
1571 pool_cache_put(filedesc_cache, fdp);
1572 }
1573
1574 /*
1575 * File Descriptor pseudo-device driver (/dev/fd/).
1576 *
1577 * Opening minor device N dup()s the file (if any) connected to file
1578 * descriptor N belonging to the calling process. Note that this driver
1579 * consists of only the ``open()'' routine, because all subsequent
1580 * references to this file will be direct to the other driver.
1581 */
1582 static int
1583 filedescopen(dev_t dev, int mode, int type, lwp_t *l)
1584 {
1585
1586 /*
1587 * XXX Kludge: set dupfd to contain the value of the
1588 * the file descriptor being sought for duplication. The error
1589 * return ensures that the vnode for this device will be released
1590 * by vn_open. Open will detect this special error and take the
1591 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
1592 * will simply report the error.
1593 */
1594 l->l_dupfd = minor(dev); /* XXX */
1595 return EDUPFD;
1596 }
1597
1598 /*
1599 * Duplicate the specified descriptor to a free descriptor.
1600 */
1601 int
1602 fd_dupopen(int old, int *new, int mode, int error)
1603 {
1604 filedesc_t *fdp;
1605 fdfile_t *ff;
1606 file_t *fp;
1607 fdtab_t *dt;
1608
1609 if ((fp = fd_getfile(old)) == NULL) {
1610 return EBADF;
1611 }
1612 fdp = curlwp->l_fd;
1613 dt = fdp->fd_dt;
1614 ff = dt->dt_ff[old];
1615
1616 /*
1617 * There are two cases of interest here.
1618 *
1619 * For EDUPFD simply dup (dfd) to file descriptor
1620 * (indx) and return.
1621 *
1622 * For EMOVEFD steal away the file structure from (dfd) and
1623 * store it in (indx). (dfd) is effectively closed by
1624 * this operation.
1625 *
1626 * Any other error code is just returned.
1627 */
1628 switch (error) {
1629 case EDUPFD:
1630 /*
1631 * Check that the mode the file is being opened for is a
1632 * subset of the mode of the existing descriptor.
1633 */
1634 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
1635 error = EACCES;
1636 break;
1637 }
1638
1639 /* Copy it. */
1640 error = fd_dup(fp, 0, new, ff->ff_exclose);
1641 break;
1642
1643 case EMOVEFD:
1644 /* Copy it. */
1645 error = fd_dup(fp, 0, new, ff->ff_exclose);
1646 if (error != 0) {
1647 break;
1648 }
1649
1650 /* Steal away the file pointer from 'old'. */
1651 (void)fd_close(old);
1652 return 0;
1653 }
1654
1655 fd_putfile(old);
1656 return error;
1657 }
1658
1659 /*
1660 * Sets descriptor owner. If the owner is a process, 'pgid'
1661 * is set to positive value, process ID. If the owner is process group,
1662 * 'pgid' is set to -pg_id.
1663 */
1664 int
1665 fsetown(pid_t *pgid, u_long cmd, const void *data)
1666 {
1667 int id = *(const int *)data;
1668 int error;
1669
1670 switch (cmd) {
1671 case TIOCSPGRP:
1672 if (id < 0)
1673 return (EINVAL);
1674 id = -id;
1675 break;
1676 default:
1677 break;
1678 }
1679
1680 if (id > 0 && !pfind(id))
1681 return (ESRCH);
1682 else if (id < 0 && (error = pgid_in_session(curproc, -id)))
1683 return (error);
1684
1685 *pgid = id;
1686 return (0);
1687 }
1688
1689 /*
1690 * Return descriptor owner information. If the value is positive,
1691 * it's process ID. If it's negative, it's process group ID and
1692 * needs the sign removed before use.
1693 */
1694 int
1695 fgetown(pid_t pgid, u_long cmd, void *data)
1696 {
1697
1698 switch (cmd) {
1699 case TIOCGPGRP:
1700 *(int *)data = -pgid;
1701 break;
1702 default:
1703 *(int *)data = pgid;
1704 break;
1705 }
1706 return (0);
1707 }
1708
1709 /*
1710 * Send signal to descriptor owner, either process or process group.
1711 */
1712 void
1713 fownsignal(pid_t pgid, int signo, int code, int band, void *fdescdata)
1714 {
1715 ksiginfo_t ksi;
1716
1717 KASSERT(!cpu_intr_p());
1718
1719 if (pgid == 0) {
1720 return;
1721 }
1722
1723 KSI_INIT(&ksi);
1724 ksi.ksi_signo = signo;
1725 ksi.ksi_code = code;
1726 ksi.ksi_band = band;
1727
1728 mutex_enter(proc_lock);
1729 if (pgid > 0) {
1730 struct proc *p1;
1731
1732 p1 = p_find(pgid, PFIND_LOCKED);
1733 if (p1 != NULL) {
1734 kpsignal(p1, &ksi, fdescdata);
1735 }
1736 } else {
1737 struct pgrp *pgrp;
1738
1739 KASSERT(pgid < 0);
1740 pgrp = pg_find(-pgid, PFIND_LOCKED);
1741 if (pgrp != NULL) {
1742 kpgsignal(pgrp, &ksi, fdescdata, 0);
1743 }
1744 }
1745 mutex_exit(proc_lock);
1746 }
1747
1748 int
1749 fd_clone(file_t *fp, unsigned fd, int flag, const struct fileops *fops,
1750 void *data)
1751 {
1752
1753 fp->f_flag = flag;
1754 fp->f_type = DTYPE_MISC;
1755 fp->f_ops = fops;
1756 fp->f_data = data;
1757 curlwp->l_dupfd = fd;
1758 fd_affix(curproc, fp, fd);
1759
1760 return EMOVEFD;
1761 }
1762
1763 int
1764 fnullop_fcntl(file_t *fp, u_int cmd, void *data)
1765 {
1766
1767 if (cmd == F_SETFL)
1768 return 0;
1769
1770 return EOPNOTSUPP;
1771 }
1772
1773 int
1774 fnullop_poll(file_t *fp, int which)
1775 {
1776
1777 return 0;
1778 }
1779
1780 int
1781 fnullop_kqfilter(file_t *fp, struct knote *kn)
1782 {
1783
1784 return 0;
1785 }
1786
1787 void
1788 fnullop_drain(file_t *fp)
1789 {
1790
1791 }
1792
1793 int
1794 fbadop_read(file_t *fp, off_t *offset, struct uio *uio,
1795 kauth_cred_t cred, int flags)
1796 {
1797
1798 return EOPNOTSUPP;
1799 }
1800
1801 int
1802 fbadop_write(file_t *fp, off_t *offset, struct uio *uio,
1803 kauth_cred_t cred, int flags)
1804 {
1805
1806 return EOPNOTSUPP;
1807 }
1808
1809 int
1810 fbadop_ioctl(file_t *fp, u_long com, void *data)
1811 {
1812
1813 return EOPNOTSUPP;
1814 }
1815
1816 int
1817 fbadop_stat(file_t *fp, struct stat *sb)
1818 {
1819
1820 return EOPNOTSUPP;
1821 }
1822
1823 int
1824 fbadop_close(file_t *fp)
1825 {
1826
1827 return EOPNOTSUPP;
1828 }
1829