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