kern_descrip.c revision 1.215 1 /* $NetBSD: kern_descrip.c,v 1.215 2011/06/26 16:42:41 christos 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.215 2011/06/26 16:42:41 christos 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 #include <sys/sysctl.h>
98 #include <sys/ktrace.h>
99
100 /*
101 * A list (head) of open files, counter, and lock protecting them.
102 */
103 struct filelist filehead __cacheline_aligned;
104 static u_int nfiles __cacheline_aligned;
105 kmutex_t filelist_lock __cacheline_aligned;
106
107 static pool_cache_t filedesc_cache __read_mostly;
108 static pool_cache_t file_cache __read_mostly;
109 static pool_cache_t fdfile_cache __read_mostly;
110
111 static int file_ctor(void *, void *, int);
112 static void file_dtor(void *, void *);
113 static int fdfile_ctor(void *, void *, int);
114 static void fdfile_dtor(void *, void *);
115 static int filedesc_ctor(void *, void *, int);
116 static void filedesc_dtor(void *, void *);
117 static int filedescopen(dev_t, int, int, lwp_t *);
118
119 static int sysctl_kern_file(SYSCTLFN_PROTO);
120 static int sysctl_kern_file2(SYSCTLFN_PROTO);
121 static void fill_file(struct kinfo_file *, const file_t *, const fdfile_t *,
122 int, pid_t);
123
124 const struct cdevsw filedesc_cdevsw = {
125 filedescopen, noclose, noread, nowrite, noioctl,
126 nostop, notty, nopoll, nommap, nokqfilter, D_OTHER | D_MPSAFE,
127 };
128
129 /* For ease of reading. */
130 __strong_alias(fd_putvnode,fd_putfile)
131 __strong_alias(fd_putsock,fd_putfile)
132
133 /*
134 * Initialize the descriptor system.
135 */
136 void
137 fd_sys_init(void)
138 {
139 static struct sysctllog *clog;
140
141 mutex_init(&filelist_lock, MUTEX_DEFAULT, IPL_NONE);
142
143 file_cache = pool_cache_init(sizeof(file_t), coherency_unit, 0,
144 0, "file", NULL, IPL_NONE, file_ctor, file_dtor, NULL);
145 KASSERT(file_cache != NULL);
146
147 fdfile_cache = pool_cache_init(sizeof(fdfile_t), coherency_unit, 0,
148 PR_LARGECACHE, "fdfile", NULL, IPL_NONE, fdfile_ctor, fdfile_dtor,
149 NULL);
150 KASSERT(fdfile_cache != NULL);
151
152 filedesc_cache = pool_cache_init(sizeof(filedesc_t), coherency_unit,
153 0, 0, "filedesc", NULL, IPL_NONE, filedesc_ctor, filedesc_dtor,
154 NULL);
155 KASSERT(filedesc_cache != NULL);
156
157 sysctl_createv(&clog, 0, NULL, NULL,
158 CTLFLAG_PERMANENT, CTLTYPE_NODE, "kern", NULL,
159 NULL, 0, NULL, 0, CTL_KERN, CTL_EOL);
160 sysctl_createv(&clog, 0, NULL, NULL,
161 CTLFLAG_PERMANENT,
162 CTLTYPE_STRUCT, "file",
163 SYSCTL_DESCR("System open file table"),
164 sysctl_kern_file, 0, NULL, 0,
165 CTL_KERN, KERN_FILE, CTL_EOL);
166 sysctl_createv(&clog, 0, NULL, NULL,
167 CTLFLAG_PERMANENT,
168 CTLTYPE_STRUCT, "file2",
169 SYSCTL_DESCR("System open file table"),
170 sysctl_kern_file2, 0, NULL, 0,
171 CTL_KERN, KERN_FILE2, CTL_EOL);
172 }
173
174 static bool
175 fd_isused(filedesc_t *fdp, unsigned fd)
176 {
177 u_int off = fd >> NDENTRYSHIFT;
178
179 KASSERT(fd < fdp->fd_dt->dt_nfiles);
180
181 return (fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) != 0;
182 }
183
184 /*
185 * Verify that the bitmaps match the descriptor table.
186 */
187 static inline void
188 fd_checkmaps(filedesc_t *fdp)
189 {
190 #ifdef DEBUG
191 fdtab_t *dt;
192 u_int fd;
193
194 dt = fdp->fd_dt;
195 if (fdp->fd_refcnt == -1) {
196 /*
197 * fd_free tears down the table without maintaining its bitmap.
198 */
199 return;
200 }
201 for (fd = 0; fd < dt->dt_nfiles; fd++) {
202 if (fd < NDFDFILE) {
203 KASSERT(dt->dt_ff[fd] ==
204 (fdfile_t *)fdp->fd_dfdfile[fd]);
205 }
206 if (dt->dt_ff[fd] == NULL) {
207 KASSERT(!fd_isused(fdp, fd));
208 } else if (dt->dt_ff[fd]->ff_file != NULL) {
209 KASSERT(fd_isused(fdp, fd));
210 }
211 }
212 #endif
213 }
214
215 static int
216 fd_next_zero(filedesc_t *fdp, uint32_t *bitmap, int want, u_int bits)
217 {
218 int i, off, maxoff;
219 uint32_t sub;
220
221 KASSERT(mutex_owned(&fdp->fd_lock));
222
223 fd_checkmaps(fdp);
224
225 if (want > bits)
226 return -1;
227
228 off = want >> NDENTRYSHIFT;
229 i = want & NDENTRYMASK;
230 if (i) {
231 sub = bitmap[off] | ((u_int)~0 >> (NDENTRIES - i));
232 if (sub != ~0)
233 goto found;
234 off++;
235 }
236
237 maxoff = NDLOSLOTS(bits);
238 while (off < maxoff) {
239 if ((sub = bitmap[off]) != ~0)
240 goto found;
241 off++;
242 }
243
244 return -1;
245
246 found:
247 return (off << NDENTRYSHIFT) + ffs(~sub) - 1;
248 }
249
250 static int
251 fd_last_set(filedesc_t *fd, int last)
252 {
253 int off, i;
254 fdfile_t **ff = fd->fd_dt->dt_ff;
255 uint32_t *bitmap = fd->fd_lomap;
256
257 KASSERT(mutex_owned(&fd->fd_lock));
258
259 fd_checkmaps(fd);
260
261 off = (last - 1) >> NDENTRYSHIFT;
262
263 while (off >= 0 && !bitmap[off])
264 off--;
265
266 if (off < 0)
267 return -1;
268
269 i = ((off + 1) << NDENTRYSHIFT) - 1;
270 if (i >= last)
271 i = last - 1;
272
273 /* XXX should use bitmap */
274 while (i > 0 && (ff[i] == NULL || !ff[i]->ff_allocated))
275 i--;
276
277 return i;
278 }
279
280 static inline void
281 fd_used(filedesc_t *fdp, unsigned fd)
282 {
283 u_int off = fd >> NDENTRYSHIFT;
284 fdfile_t *ff;
285
286 ff = fdp->fd_dt->dt_ff[fd];
287
288 KASSERT(mutex_owned(&fdp->fd_lock));
289 KASSERT((fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) == 0);
290 KASSERT(ff != NULL);
291 KASSERT(ff->ff_file == NULL);
292 KASSERT(!ff->ff_allocated);
293
294 ff->ff_allocated = 1;
295 fdp->fd_lomap[off] |= 1 << (fd & NDENTRYMASK);
296 if (__predict_false(fdp->fd_lomap[off] == ~0)) {
297 KASSERT((fdp->fd_himap[off >> NDENTRYSHIFT] &
298 (1 << (off & NDENTRYMASK))) == 0);
299 fdp->fd_himap[off >> NDENTRYSHIFT] |= 1 << (off & NDENTRYMASK);
300 }
301
302 if ((int)fd > fdp->fd_lastfile) {
303 fdp->fd_lastfile = fd;
304 }
305
306 fd_checkmaps(fdp);
307 }
308
309 static inline void
310 fd_unused(filedesc_t *fdp, unsigned fd)
311 {
312 u_int off = fd >> NDENTRYSHIFT;
313 fdfile_t *ff;
314
315 ff = fdp->fd_dt->dt_ff[fd];
316
317 /*
318 * Don't assert the lock is held here, as we may be copying
319 * the table during exec() and it is not needed there.
320 * procfs and sysctl are locked out by proc::p_reflock.
321 *
322 * KASSERT(mutex_owned(&fdp->fd_lock));
323 */
324 KASSERT(ff != NULL);
325 KASSERT(ff->ff_file == NULL);
326 KASSERT(ff->ff_allocated);
327
328 if (fd < fdp->fd_freefile) {
329 fdp->fd_freefile = fd;
330 }
331
332 if (fdp->fd_lomap[off] == ~0) {
333 KASSERT((fdp->fd_himap[off >> NDENTRYSHIFT] &
334 (1 << (off & NDENTRYMASK))) != 0);
335 fdp->fd_himap[off >> NDENTRYSHIFT] &=
336 ~(1 << (off & NDENTRYMASK));
337 }
338 KASSERT((fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) != 0);
339 fdp->fd_lomap[off] &= ~(1 << (fd & NDENTRYMASK));
340 ff->ff_allocated = 0;
341
342 KASSERT(fd <= fdp->fd_lastfile);
343 if (fd == fdp->fd_lastfile) {
344 fdp->fd_lastfile = fd_last_set(fdp, fd);
345 }
346 fd_checkmaps(fdp);
347 }
348
349 /*
350 * Look up the file structure corresponding to a file descriptor
351 * and return the file, holding a reference on the descriptor.
352 */
353 file_t *
354 fd_getfile(unsigned fd)
355 {
356 filedesc_t *fdp;
357 fdfile_t *ff;
358 file_t *fp;
359 fdtab_t *dt;
360
361 /*
362 * Look up the fdfile structure representing this descriptor.
363 * We are doing this unlocked. See fd_tryexpand().
364 */
365 fdp = curlwp->l_fd;
366 dt = fdp->fd_dt;
367 if (__predict_false(fd >= dt->dt_nfiles)) {
368 return NULL;
369 }
370 ff = dt->dt_ff[fd];
371 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
372 if (__predict_false(ff == NULL)) {
373 return NULL;
374 }
375
376 /* Now get a reference to the descriptor. */
377 if (fdp->fd_refcnt == 1) {
378 /*
379 * Single threaded: don't need to worry about concurrent
380 * access (other than earlier calls to kqueue, which may
381 * hold a reference to the descriptor).
382 */
383 ff->ff_refcnt++;
384 } else {
385 /*
386 * Multi threaded: issue a memory barrier to ensure that we
387 * acquire the file pointer _after_ adding a reference. If
388 * no memory barrier, we could fetch a stale pointer.
389 */
390 atomic_inc_uint(&ff->ff_refcnt);
391 #ifndef __HAVE_ATOMIC_AS_MEMBAR
392 membar_enter();
393 #endif
394 }
395
396 /*
397 * If the file is not open or is being closed then put the
398 * reference back.
399 */
400 fp = ff->ff_file;
401 if (__predict_true(fp != NULL)) {
402 return fp;
403 }
404 fd_putfile(fd);
405 return NULL;
406 }
407
408 /*
409 * Release a reference to a file descriptor acquired with fd_getfile().
410 */
411 void
412 fd_putfile(unsigned fd)
413 {
414 filedesc_t *fdp;
415 fdfile_t *ff;
416 u_int u, v;
417
418 fdp = curlwp->l_fd;
419 ff = fdp->fd_dt->dt_ff[fd];
420
421 KASSERT(fd < fdp->fd_dt->dt_nfiles);
422 KASSERT(ff != NULL);
423 KASSERT((ff->ff_refcnt & FR_MASK) > 0);
424 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
425
426 if (fdp->fd_refcnt == 1) {
427 /*
428 * Single threaded: don't need to worry about concurrent
429 * access (other than earlier calls to kqueue, which may
430 * hold a reference to the descriptor).
431 */
432 if (__predict_false((ff->ff_refcnt & FR_CLOSING) != 0)) {
433 fd_close(fd);
434 return;
435 }
436 ff->ff_refcnt--;
437 return;
438 }
439
440 /*
441 * Ensure that any use of the file is complete and globally
442 * visible before dropping the final reference. If no membar,
443 * the current CPU could still access memory associated with
444 * the file after it has been freed or recycled by another
445 * CPU.
446 */
447 #ifndef __HAVE_ATOMIC_AS_MEMBAR
448 membar_exit();
449 #endif
450
451 /*
452 * Be optimistic and start out with the assumption that no other
453 * threads are trying to close the descriptor. If the CAS fails,
454 * we lost a race and/or it's being closed.
455 */
456 for (u = ff->ff_refcnt & FR_MASK;; u = v) {
457 v = atomic_cas_uint(&ff->ff_refcnt, u, u - 1);
458 if (__predict_true(u == v)) {
459 return;
460 }
461 if (__predict_false((v & FR_CLOSING) != 0)) {
462 break;
463 }
464 }
465
466 /* Another thread is waiting to close the file: join it. */
467 (void)fd_close(fd);
468 }
469
470 /*
471 * Convenience wrapper around fd_getfile() that returns reference
472 * to a vnode.
473 */
474 int
475 fd_getvnode(unsigned fd, file_t **fpp)
476 {
477 vnode_t *vp;
478 file_t *fp;
479
480 fp = fd_getfile(fd);
481 if (__predict_false(fp == NULL)) {
482 return EBADF;
483 }
484 if (__predict_false(fp->f_type != DTYPE_VNODE)) {
485 fd_putfile(fd);
486 return EINVAL;
487 }
488 vp = fp->f_data;
489 if (__predict_false(vp->v_type == VBAD)) {
490 /* XXX Is this case really necessary? */
491 fd_putfile(fd);
492 return EBADF;
493 }
494 *fpp = fp;
495 return 0;
496 }
497
498 /*
499 * Convenience wrapper around fd_getfile() that returns reference
500 * to a socket.
501 */
502 int
503 fd_getsock(unsigned fd, struct socket **sop)
504 {
505 file_t *fp;
506
507 fp = fd_getfile(fd);
508 if (__predict_false(fp == NULL)) {
509 return EBADF;
510 }
511 if (__predict_false(fp->f_type != DTYPE_SOCKET)) {
512 fd_putfile(fd);
513 return ENOTSOCK;
514 }
515 *sop = fp->f_data;
516 return 0;
517 }
518
519 /*
520 * Look up the file structure corresponding to a file descriptor
521 * and return it with a reference held on the file, not the
522 * descriptor.
523 *
524 * This is heavyweight and only used when accessing descriptors
525 * from a foreign process. The caller must ensure that `p' does
526 * not exit or fork across this call.
527 *
528 * To release the file (not descriptor) reference, use closef().
529 */
530 file_t *
531 fd_getfile2(proc_t *p, unsigned fd)
532 {
533 filedesc_t *fdp;
534 fdfile_t *ff;
535 file_t *fp;
536 fdtab_t *dt;
537
538 fdp = p->p_fd;
539 mutex_enter(&fdp->fd_lock);
540 dt = fdp->fd_dt;
541 if (fd >= dt->dt_nfiles) {
542 mutex_exit(&fdp->fd_lock);
543 return NULL;
544 }
545 if ((ff = dt->dt_ff[fd]) == NULL) {
546 mutex_exit(&fdp->fd_lock);
547 return NULL;
548 }
549 if ((fp = ff->ff_file) == NULL) {
550 mutex_exit(&fdp->fd_lock);
551 return NULL;
552 }
553 mutex_enter(&fp->f_lock);
554 fp->f_count++;
555 mutex_exit(&fp->f_lock);
556 mutex_exit(&fdp->fd_lock);
557
558 return fp;
559 }
560
561 /*
562 * Internal form of close. Must be called with a reference to the
563 * descriptor, and will drop the reference. When all descriptor
564 * references are dropped, releases the descriptor slot and a single
565 * reference to the file structure.
566 */
567 int
568 fd_close(unsigned fd)
569 {
570 struct flock lf;
571 filedesc_t *fdp;
572 fdfile_t *ff;
573 file_t *fp;
574 proc_t *p;
575 lwp_t *l;
576 u_int refcnt;
577
578 l = curlwp;
579 p = l->l_proc;
580 fdp = l->l_fd;
581 ff = fdp->fd_dt->dt_ff[fd];
582
583 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
584
585 mutex_enter(&fdp->fd_lock);
586 KASSERT((ff->ff_refcnt & FR_MASK) > 0);
587 if (__predict_false(ff->ff_file == NULL)) {
588 /*
589 * Another user of the file is already closing, and is
590 * waiting for other users of the file to drain. Release
591 * our reference, and wake up the closer.
592 */
593 atomic_dec_uint(&ff->ff_refcnt);
594 cv_broadcast(&ff->ff_closing);
595 mutex_exit(&fdp->fd_lock);
596
597 /*
598 * An application error, so pretend that the descriptor
599 * was already closed. We can't safely wait for it to
600 * be closed without potentially deadlocking.
601 */
602 return (EBADF);
603 }
604 KASSERT((ff->ff_refcnt & FR_CLOSING) == 0);
605
606 /*
607 * There may be multiple users of this file within the process.
608 * Notify existing and new users that the file is closing. This
609 * will prevent them from adding additional uses to this file
610 * while we are closing it.
611 */
612 fp = ff->ff_file;
613 ff->ff_file = NULL;
614 ff->ff_exclose = false;
615
616 /*
617 * We expect the caller to hold a descriptor reference - drop it.
618 * The reference count may increase beyond zero at this point due
619 * to an erroneous descriptor reference by an application, but
620 * fd_getfile() will notice that the file is being closed and drop
621 * the reference again.
622 */
623 if (fdp->fd_refcnt == 1) {
624 /* Single threaded. */
625 refcnt = --(ff->ff_refcnt);
626 } else {
627 /* Multi threaded. */
628 #ifndef __HAVE_ATOMIC_AS_MEMBAR
629 membar_producer();
630 #endif
631 refcnt = atomic_dec_uint_nv(&ff->ff_refcnt);
632 }
633 if (__predict_false(refcnt != 0)) {
634 /*
635 * Wait for other references to drain. This is typically
636 * an application error - the descriptor is being closed
637 * while still in use.
638 * (Or just a threaded application trying to unblock its
639 * thread that sleeps in (say) accept()).
640 */
641 atomic_or_uint(&ff->ff_refcnt, FR_CLOSING);
642
643 /*
644 * Remove any knotes attached to the file. A knote
645 * attached to the descriptor can hold references on it.
646 */
647 mutex_exit(&fdp->fd_lock);
648 if (!SLIST_EMPTY(&ff->ff_knlist)) {
649 knote_fdclose(fd);
650 }
651
652 /*
653 * Since the file system code doesn't know which fd
654 * each request came from (think dup()), we have to
655 * ask it to return ERESTART for any long-term blocks.
656 * The re-entry through read/write/etc will detect the
657 * closed fd and return EBAFD.
658 * Blocked partial writes may return a short length.
659 */
660 (*fp->f_ops->fo_restart)(fp);
661 mutex_enter(&fdp->fd_lock);
662
663 /*
664 * We need to see the count drop to zero at least once,
665 * in order to ensure that all pre-existing references
666 * have been drained. New references past this point are
667 * of no interest.
668 * XXX (dsl) this may need to call fo_restart() after a
669 * timeout to guarantee that all the system calls exit.
670 */
671 while ((ff->ff_refcnt & FR_MASK) != 0) {
672 cv_wait(&ff->ff_closing, &fdp->fd_lock);
673 }
674 atomic_and_uint(&ff->ff_refcnt, ~FR_CLOSING);
675 } else {
676 /* If no references, there must be no knotes. */
677 KASSERT(SLIST_EMPTY(&ff->ff_knlist));
678 }
679
680 /*
681 * POSIX record locking dictates that any close releases ALL
682 * locks owned by this process. This is handled by setting
683 * a flag in the unlock to free ONLY locks obeying POSIX
684 * semantics, and not to free BSD-style file locks.
685 * If the descriptor was in a message, POSIX-style locks
686 * aren't passed with the descriptor.
687 */
688 if (__predict_false((p->p_flag & PK_ADVLOCK) != 0 &&
689 fp->f_type == DTYPE_VNODE)) {
690 lf.l_whence = SEEK_SET;
691 lf.l_start = 0;
692 lf.l_len = 0;
693 lf.l_type = F_UNLCK;
694 mutex_exit(&fdp->fd_lock);
695 (void)VOP_ADVLOCK(fp->f_data, p, F_UNLCK, &lf, F_POSIX);
696 mutex_enter(&fdp->fd_lock);
697 }
698
699 /* Free descriptor slot. */
700 fd_unused(fdp, fd);
701 mutex_exit(&fdp->fd_lock);
702
703 /* Now drop reference to the file itself. */
704 return closef(fp);
705 }
706
707 /*
708 * Duplicate a file descriptor.
709 */
710 int
711 fd_dup(file_t *fp, int minfd, int *newp, bool exclose)
712 {
713 proc_t *p = curproc;
714 int error;
715
716 while ((error = fd_alloc(p, minfd, newp)) != 0) {
717 if (error != ENOSPC) {
718 return error;
719 }
720 fd_tryexpand(p);
721 }
722
723 curlwp->l_fd->fd_dt->dt_ff[*newp]->ff_exclose = exclose;
724 fd_affix(p, fp, *newp);
725 return 0;
726 }
727
728 /*
729 * dup2 operation.
730 */
731 int
732 fd_dup2(file_t *fp, unsigned new, int flags)
733 {
734 filedesc_t *fdp = curlwp->l_fd;
735 fdfile_t *ff;
736 fdtab_t *dt;
737
738 /*
739 * Ensure there are enough slots in the descriptor table,
740 * and allocate an fdfile_t up front in case we need it.
741 */
742 while (new >= fdp->fd_dt->dt_nfiles) {
743 fd_tryexpand(curproc);
744 }
745 ff = pool_cache_get(fdfile_cache, PR_WAITOK);
746
747 /*
748 * If there is already a file open, close it. If the file is
749 * half open, wait for it to be constructed before closing it.
750 * XXX Potential for deadlock here?
751 */
752 mutex_enter(&fdp->fd_lock);
753 while (fd_isused(fdp, new)) {
754 mutex_exit(&fdp->fd_lock);
755 if (fd_getfile(new) != NULL) {
756 (void)fd_close(new);
757 } else {
758 /*
759 * Crummy, but unlikely to happen.
760 * Can occur if we interrupt another
761 * thread while it is opening a file.
762 */
763 kpause("dup2", false, 1, NULL);
764 }
765 mutex_enter(&fdp->fd_lock);
766 }
767 dt = fdp->fd_dt;
768 if (dt->dt_ff[new] == NULL) {
769 KASSERT(new >= NDFDFILE);
770 dt->dt_ff[new] = ff;
771 ff = NULL;
772 }
773 fd_used(fdp, new);
774 mutex_exit(&fdp->fd_lock);
775
776 dt->dt_ff[new]->ff_exclose = (flags & O_CLOEXEC) != 0;
777 fp->f_flag |= flags & FNONBLOCK;
778 /* Slot is now allocated. Insert copy of the file. */
779 fd_affix(curproc, fp, new);
780 if (ff != NULL) {
781 pool_cache_put(fdfile_cache, ff);
782 }
783 return 0;
784 }
785
786 /*
787 * Drop reference to a file structure.
788 */
789 int
790 closef(file_t *fp)
791 {
792 struct flock lf;
793 int error;
794
795 /*
796 * Drop reference. If referenced elsewhere it's still open
797 * and we have nothing more to do.
798 */
799 mutex_enter(&fp->f_lock);
800 KASSERT(fp->f_count > 0);
801 if (--fp->f_count > 0) {
802 mutex_exit(&fp->f_lock);
803 return 0;
804 }
805 KASSERT(fp->f_count == 0);
806 mutex_exit(&fp->f_lock);
807
808 /* We held the last reference - release locks, close and free. */
809 if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
810 lf.l_whence = SEEK_SET;
811 lf.l_start = 0;
812 lf.l_len = 0;
813 lf.l_type = F_UNLCK;
814 (void)VOP_ADVLOCK(fp->f_data, fp, F_UNLCK, &lf, F_FLOCK);
815 }
816 if (fp->f_ops != NULL) {
817 error = (*fp->f_ops->fo_close)(fp);
818 } else {
819 error = 0;
820 }
821 KASSERT(fp->f_count == 0);
822 KASSERT(fp->f_cred != NULL);
823 pool_cache_put(file_cache, fp);
824
825 return error;
826 }
827
828 /*
829 * Allocate a file descriptor for the process.
830 */
831 int
832 fd_alloc(proc_t *p, int want, int *result)
833 {
834 filedesc_t *fdp = p->p_fd;
835 int i, lim, last, error;
836 u_int off, new;
837 fdtab_t *dt;
838
839 KASSERT(p == curproc || p == &proc0);
840
841 /*
842 * Search for a free descriptor starting at the higher
843 * of want or fd_freefile.
844 */
845 mutex_enter(&fdp->fd_lock);
846 fd_checkmaps(fdp);
847 dt = fdp->fd_dt;
848 KASSERT(dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
849 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
850 last = min(dt->dt_nfiles, lim);
851 for (;;) {
852 if ((i = want) < fdp->fd_freefile)
853 i = fdp->fd_freefile;
854 off = i >> NDENTRYSHIFT;
855 new = fd_next_zero(fdp, fdp->fd_himap, off,
856 (last + NDENTRIES - 1) >> NDENTRYSHIFT);
857 if (new == -1)
858 break;
859 i = fd_next_zero(fdp, &fdp->fd_lomap[new],
860 new > off ? 0 : i & NDENTRYMASK, NDENTRIES);
861 if (i == -1) {
862 /*
863 * Free file descriptor in this block was
864 * below want, try again with higher want.
865 */
866 want = (new + 1) << NDENTRYSHIFT;
867 continue;
868 }
869 i += (new << NDENTRYSHIFT);
870 if (i >= last) {
871 break;
872 }
873 if (dt->dt_ff[i] == NULL) {
874 KASSERT(i >= NDFDFILE);
875 dt->dt_ff[i] = pool_cache_get(fdfile_cache, PR_WAITOK);
876 }
877 KASSERT(dt->dt_ff[i]->ff_file == NULL);
878 fd_used(fdp, i);
879 if (want <= fdp->fd_freefile) {
880 fdp->fd_freefile = i;
881 }
882 *result = i;
883 KASSERT(i >= NDFDFILE ||
884 dt->dt_ff[i] == (fdfile_t *)fdp->fd_dfdfile[i]);
885 fd_checkmaps(fdp);
886 mutex_exit(&fdp->fd_lock);
887 return 0;
888 }
889
890 /* No space in current array. Let the caller expand and retry. */
891 error = (dt->dt_nfiles >= lim) ? EMFILE : ENOSPC;
892 mutex_exit(&fdp->fd_lock);
893 return error;
894 }
895
896 /*
897 * Allocate memory for a descriptor table.
898 */
899 static fdtab_t *
900 fd_dtab_alloc(int n)
901 {
902 fdtab_t *dt;
903 size_t sz;
904
905 KASSERT(n > NDFILE);
906
907 sz = sizeof(*dt) + (n - NDFILE) * sizeof(dt->dt_ff[0]);
908 dt = kmem_alloc(sz, KM_SLEEP);
909 #ifdef DIAGNOSTIC
910 memset(dt, 0xff, sz);
911 #endif
912 dt->dt_nfiles = n;
913 dt->dt_link = NULL;
914 return dt;
915 }
916
917 /*
918 * Free a descriptor table, and all tables linked for deferred free.
919 */
920 static void
921 fd_dtab_free(fdtab_t *dt)
922 {
923 fdtab_t *next;
924 size_t sz;
925
926 do {
927 next = dt->dt_link;
928 KASSERT(dt->dt_nfiles > NDFILE);
929 sz = sizeof(*dt) +
930 (dt->dt_nfiles - NDFILE) * sizeof(dt->dt_ff[0]);
931 #ifdef DIAGNOSTIC
932 memset(dt, 0xff, sz);
933 #endif
934 kmem_free(dt, sz);
935 dt = next;
936 } while (dt != NULL);
937 }
938
939 /*
940 * Allocate descriptor bitmap.
941 */
942 static void
943 fd_map_alloc(int n, uint32_t **lo, uint32_t **hi)
944 {
945 uint8_t *ptr;
946 size_t szlo, szhi;
947
948 KASSERT(n > NDENTRIES);
949
950 szlo = NDLOSLOTS(n) * sizeof(uint32_t);
951 szhi = NDHISLOTS(n) * sizeof(uint32_t);
952 ptr = kmem_alloc(szlo + szhi, KM_SLEEP);
953 *lo = (uint32_t *)ptr;
954 *hi = (uint32_t *)(ptr + szlo);
955 }
956
957 /*
958 * Free descriptor bitmap.
959 */
960 static void
961 fd_map_free(int n, uint32_t *lo, uint32_t *hi)
962 {
963 size_t szlo, szhi;
964
965 KASSERT(n > NDENTRIES);
966
967 szlo = NDLOSLOTS(n) * sizeof(uint32_t);
968 szhi = NDHISLOTS(n) * sizeof(uint32_t);
969 KASSERT(hi == (uint32_t *)((uint8_t *)lo + szlo));
970 kmem_free(lo, szlo + szhi);
971 }
972
973 /*
974 * Expand a process' descriptor table.
975 */
976 void
977 fd_tryexpand(proc_t *p)
978 {
979 filedesc_t *fdp;
980 int i, numfiles, oldnfiles;
981 fdtab_t *newdt, *dt;
982 uint32_t *newhimap, *newlomap;
983
984 KASSERT(p == curproc || p == &proc0);
985
986 fdp = p->p_fd;
987 newhimap = NULL;
988 newlomap = NULL;
989 oldnfiles = fdp->fd_dt->dt_nfiles;
990
991 if (oldnfiles < NDEXTENT)
992 numfiles = NDEXTENT;
993 else
994 numfiles = 2 * oldnfiles;
995
996 newdt = fd_dtab_alloc(numfiles);
997 if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
998 fd_map_alloc(numfiles, &newlomap, &newhimap);
999 }
1000
1001 mutex_enter(&fdp->fd_lock);
1002 dt = fdp->fd_dt;
1003 KASSERT(dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
1004 if (dt->dt_nfiles != oldnfiles) {
1005 /* fdp changed; caller must retry */
1006 mutex_exit(&fdp->fd_lock);
1007 fd_dtab_free(newdt);
1008 if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
1009 fd_map_free(numfiles, newlomap, newhimap);
1010 }
1011 return;
1012 }
1013
1014 /* Copy the existing descriptor table and zero the new portion. */
1015 i = sizeof(fdfile_t *) * oldnfiles;
1016 memcpy(newdt->dt_ff, dt->dt_ff, i);
1017 memset((uint8_t *)newdt->dt_ff + i, 0,
1018 numfiles * sizeof(fdfile_t *) - i);
1019
1020 /*
1021 * Link old descriptor array into list to be discarded. We defer
1022 * freeing until the last reference to the descriptor table goes
1023 * away (usually process exit). This allows us to do lockless
1024 * lookups in fd_getfile().
1025 */
1026 if (oldnfiles > NDFILE) {
1027 if (fdp->fd_refcnt > 1) {
1028 newdt->dt_link = dt;
1029 } else {
1030 fd_dtab_free(dt);
1031 }
1032 }
1033
1034 if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
1035 i = NDHISLOTS(oldnfiles) * sizeof(uint32_t);
1036 memcpy(newhimap, fdp->fd_himap, i);
1037 memset((uint8_t *)newhimap + i, 0,
1038 NDHISLOTS(numfiles) * sizeof(uint32_t) - i);
1039
1040 i = NDLOSLOTS(oldnfiles) * sizeof(uint32_t);
1041 memcpy(newlomap, fdp->fd_lomap, i);
1042 memset((uint8_t *)newlomap + i, 0,
1043 NDLOSLOTS(numfiles) * sizeof(uint32_t) - i);
1044
1045 if (NDHISLOTS(oldnfiles) > NDHISLOTS(NDFILE)) {
1046 fd_map_free(oldnfiles, fdp->fd_lomap, fdp->fd_himap);
1047 }
1048 fdp->fd_himap = newhimap;
1049 fdp->fd_lomap = newlomap;
1050 }
1051
1052 /*
1053 * All other modifications must become globally visible before
1054 * the change to fd_dt. See fd_getfile().
1055 */
1056 membar_producer();
1057 fdp->fd_dt = newdt;
1058 KASSERT(newdt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
1059 fd_checkmaps(fdp);
1060 mutex_exit(&fdp->fd_lock);
1061 }
1062
1063 /*
1064 * Create a new open file structure and allocate a file descriptor
1065 * for the current process.
1066 */
1067 int
1068 fd_allocfile(file_t **resultfp, int *resultfd)
1069 {
1070 proc_t *p = curproc;
1071 kauth_cred_t cred;
1072 file_t *fp;
1073 int error;
1074
1075 while ((error = fd_alloc(p, 0, resultfd)) != 0) {
1076 if (error != ENOSPC) {
1077 return error;
1078 }
1079 fd_tryexpand(p);
1080 }
1081
1082 fp = pool_cache_get(file_cache, PR_WAITOK);
1083 if (fp == NULL) {
1084 return ENFILE;
1085 }
1086 KASSERT(fp->f_count == 0);
1087 KASSERT(fp->f_msgcount == 0);
1088 KASSERT(fp->f_unpcount == 0);
1089
1090 /* Replace cached credentials if not what we need. */
1091 cred = curlwp->l_cred;
1092 if (__predict_false(cred != fp->f_cred)) {
1093 kauth_cred_free(fp->f_cred);
1094 kauth_cred_hold(cred);
1095 fp->f_cred = cred;
1096 }
1097
1098 /*
1099 * Don't allow recycled files to be scanned.
1100 * See uipc_usrreq.c.
1101 */
1102 if (__predict_false((fp->f_flag & FSCAN) != 0)) {
1103 mutex_enter(&fp->f_lock);
1104 atomic_and_uint(&fp->f_flag, ~FSCAN);
1105 mutex_exit(&fp->f_lock);
1106 }
1107
1108 fp->f_advice = 0;
1109 fp->f_offset = 0;
1110 *resultfp = fp;
1111
1112 return 0;
1113 }
1114
1115 /*
1116 * Successful creation of a new descriptor: make visible to the process.
1117 */
1118 void
1119 fd_affix(proc_t *p, file_t *fp, unsigned fd)
1120 {
1121 fdfile_t *ff;
1122 filedesc_t *fdp;
1123
1124 KASSERT(p == curproc || p == &proc0);
1125
1126 /* Add a reference to the file structure. */
1127 mutex_enter(&fp->f_lock);
1128 fp->f_count++;
1129 mutex_exit(&fp->f_lock);
1130
1131 /*
1132 * Insert the new file into the descriptor slot.
1133 *
1134 * The memory barriers provided by lock activity in this routine
1135 * ensure that any updates to the file structure become globally
1136 * visible before the file becomes visible to other LWPs in the
1137 * current process.
1138 */
1139 fdp = p->p_fd;
1140 ff = fdp->fd_dt->dt_ff[fd];
1141
1142 KASSERT(ff != NULL);
1143 KASSERT(ff->ff_file == NULL);
1144 KASSERT(ff->ff_allocated);
1145 KASSERT(fd_isused(fdp, fd));
1146 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
1147
1148 /* No need to lock in order to make file initially visible. */
1149 ff->ff_file = fp;
1150 }
1151
1152 /*
1153 * Abort creation of a new descriptor: free descriptor slot and file.
1154 */
1155 void
1156 fd_abort(proc_t *p, file_t *fp, unsigned fd)
1157 {
1158 filedesc_t *fdp;
1159 fdfile_t *ff;
1160
1161 KASSERT(p == curproc || p == &proc0);
1162
1163 fdp = p->p_fd;
1164 ff = fdp->fd_dt->dt_ff[fd];
1165
1166 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
1167
1168 mutex_enter(&fdp->fd_lock);
1169 KASSERT(fd_isused(fdp, fd));
1170 fd_unused(fdp, fd);
1171 mutex_exit(&fdp->fd_lock);
1172
1173 if (fp != NULL) {
1174 KASSERT(fp->f_count == 0);
1175 KASSERT(fp->f_cred != NULL);
1176 pool_cache_put(file_cache, fp);
1177 }
1178 }
1179
1180 static int
1181 file_ctor(void *arg, void *obj, int flags)
1182 {
1183 file_t *fp = obj;
1184
1185 memset(fp, 0, sizeof(*fp));
1186
1187 mutex_enter(&filelist_lock);
1188 if (__predict_false(nfiles >= maxfiles)) {
1189 mutex_exit(&filelist_lock);
1190 tablefull("file", "increase kern.maxfiles or MAXFILES");
1191 return ENFILE;
1192 }
1193 nfiles++;
1194 LIST_INSERT_HEAD(&filehead, fp, f_list);
1195 mutex_init(&fp->f_lock, MUTEX_DEFAULT, IPL_NONE);
1196 fp->f_cred = curlwp->l_cred;
1197 kauth_cred_hold(fp->f_cred);
1198 mutex_exit(&filelist_lock);
1199
1200 return 0;
1201 }
1202
1203 static void
1204 file_dtor(void *arg, void *obj)
1205 {
1206 file_t *fp = obj;
1207
1208 mutex_enter(&filelist_lock);
1209 nfiles--;
1210 LIST_REMOVE(fp, f_list);
1211 mutex_exit(&filelist_lock);
1212
1213 kauth_cred_free(fp->f_cred);
1214 mutex_destroy(&fp->f_lock);
1215 }
1216
1217 static int
1218 fdfile_ctor(void *arg, void *obj, int flags)
1219 {
1220 fdfile_t *ff = obj;
1221
1222 memset(ff, 0, sizeof(*ff));
1223 cv_init(&ff->ff_closing, "fdclose");
1224
1225 return 0;
1226 }
1227
1228 static void
1229 fdfile_dtor(void *arg, void *obj)
1230 {
1231 fdfile_t *ff = obj;
1232
1233 cv_destroy(&ff->ff_closing);
1234 }
1235
1236 file_t *
1237 fgetdummy(void)
1238 {
1239 file_t *fp;
1240
1241 fp = kmem_zalloc(sizeof(*fp), KM_SLEEP);
1242 if (fp != NULL) {
1243 mutex_init(&fp->f_lock, MUTEX_DEFAULT, IPL_NONE);
1244 }
1245 return fp;
1246 }
1247
1248 void
1249 fputdummy(file_t *fp)
1250 {
1251
1252 mutex_destroy(&fp->f_lock);
1253 kmem_free(fp, sizeof(*fp));
1254 }
1255
1256 /*
1257 * Create an initial filedesc structure.
1258 */
1259 filedesc_t *
1260 fd_init(filedesc_t *fdp)
1261 {
1262 #ifdef DIAGNOSTIC
1263 unsigned fd;
1264 #endif
1265
1266 if (__predict_true(fdp == NULL)) {
1267 fdp = pool_cache_get(filedesc_cache, PR_WAITOK);
1268 } else {
1269 KASSERT(fdp == &filedesc0);
1270 filedesc_ctor(NULL, fdp, PR_WAITOK);
1271 }
1272
1273 #ifdef DIAGNOSTIC
1274 KASSERT(fdp->fd_lastfile == -1);
1275 KASSERT(fdp->fd_lastkqfile == -1);
1276 KASSERT(fdp->fd_knhash == NULL);
1277 KASSERT(fdp->fd_freefile == 0);
1278 KASSERT(fdp->fd_exclose == false);
1279 KASSERT(fdp->fd_dt == &fdp->fd_dtbuiltin);
1280 KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
1281 for (fd = 0; fd < NDFDFILE; fd++) {
1282 KASSERT(fdp->fd_dtbuiltin.dt_ff[fd] ==
1283 (fdfile_t *)fdp->fd_dfdfile[fd]);
1284 }
1285 for (fd = NDFDFILE; fd < NDFILE; fd++) {
1286 KASSERT(fdp->fd_dtbuiltin.dt_ff[fd] == NULL);
1287 }
1288 KASSERT(fdp->fd_himap == fdp->fd_dhimap);
1289 KASSERT(fdp->fd_lomap == fdp->fd_dlomap);
1290 #endif /* DIAGNOSTIC */
1291
1292 fdp->fd_refcnt = 1;
1293 fd_checkmaps(fdp);
1294
1295 return fdp;
1296 }
1297
1298 /*
1299 * Initialize a file descriptor table.
1300 */
1301 static int
1302 filedesc_ctor(void *arg, void *obj, int flag)
1303 {
1304 filedesc_t *fdp = obj;
1305 fdfile_t **ffp;
1306 int i;
1307
1308 memset(fdp, 0, sizeof(*fdp));
1309 mutex_init(&fdp->fd_lock, MUTEX_DEFAULT, IPL_NONE);
1310 fdp->fd_lastfile = -1;
1311 fdp->fd_lastkqfile = -1;
1312 fdp->fd_dt = &fdp->fd_dtbuiltin;
1313 fdp->fd_dtbuiltin.dt_nfiles = NDFILE;
1314 fdp->fd_himap = fdp->fd_dhimap;
1315 fdp->fd_lomap = fdp->fd_dlomap;
1316
1317 CTASSERT(sizeof(fdp->fd_dfdfile[0]) >= sizeof(fdfile_t));
1318 for (i = 0, ffp = fdp->fd_dt->dt_ff; i < NDFDFILE; i++, ffp++) {
1319 *ffp = (fdfile_t *)fdp->fd_dfdfile[i];
1320 (void)fdfile_ctor(NULL, fdp->fd_dfdfile[i], PR_WAITOK);
1321 }
1322
1323 return 0;
1324 }
1325
1326 static void
1327 filedesc_dtor(void *arg, void *obj)
1328 {
1329 filedesc_t *fdp = obj;
1330 int i;
1331
1332 for (i = 0; i < NDFDFILE; i++) {
1333 fdfile_dtor(NULL, fdp->fd_dfdfile[i]);
1334 }
1335
1336 mutex_destroy(&fdp->fd_lock);
1337 }
1338
1339 /*
1340 * Make p share curproc's filedesc structure.
1341 */
1342 void
1343 fd_share(struct proc *p)
1344 {
1345 filedesc_t *fdp;
1346
1347 fdp = curlwp->l_fd;
1348 p->p_fd = fdp;
1349 atomic_inc_uint(&fdp->fd_refcnt);
1350 }
1351
1352 /*
1353 * Acquire a hold on a filedesc structure.
1354 */
1355 void
1356 fd_hold(lwp_t *l)
1357 {
1358 filedesc_t *fdp = l->l_fd;
1359
1360 atomic_inc_uint(&fdp->fd_refcnt);
1361 }
1362
1363 /*
1364 * Copy a filedesc structure.
1365 */
1366 filedesc_t *
1367 fd_copy(void)
1368 {
1369 filedesc_t *newfdp, *fdp;
1370 fdfile_t *ff, **ffp, **nffp, *ff2;
1371 int i, j, numfiles, lastfile, newlast;
1372 file_t *fp;
1373 fdtab_t *newdt;
1374
1375 fdp = curproc->p_fd;
1376 newfdp = pool_cache_get(filedesc_cache, PR_WAITOK);
1377 newfdp->fd_refcnt = 1;
1378
1379 #ifdef DIAGNOSTIC
1380 KASSERT(newfdp->fd_lastfile == -1);
1381 KASSERT(newfdp->fd_lastkqfile == -1);
1382 KASSERT(newfdp->fd_knhash == NULL);
1383 KASSERT(newfdp->fd_freefile == 0);
1384 KASSERT(newfdp->fd_exclose == false);
1385 KASSERT(newfdp->fd_dt == &newfdp->fd_dtbuiltin);
1386 KASSERT(newfdp->fd_dtbuiltin.dt_nfiles == NDFILE);
1387 for (i = 0; i < NDFDFILE; i++) {
1388 KASSERT(newfdp->fd_dtbuiltin.dt_ff[i] ==
1389 (fdfile_t *)&newfdp->fd_dfdfile[i]);
1390 }
1391 for (i = NDFDFILE; i < NDFILE; i++) {
1392 KASSERT(newfdp->fd_dtbuiltin.dt_ff[i] == NULL);
1393 }
1394 #endif /* DIAGNOSTIC */
1395
1396 mutex_enter(&fdp->fd_lock);
1397 fd_checkmaps(fdp);
1398 numfiles = fdp->fd_dt->dt_nfiles;
1399 lastfile = fdp->fd_lastfile;
1400
1401 /*
1402 * If the number of open files fits in the internal arrays
1403 * of the open file structure, use them, otherwise allocate
1404 * additional memory for the number of descriptors currently
1405 * in use.
1406 */
1407 if (lastfile < NDFILE) {
1408 i = NDFILE;
1409 newdt = newfdp->fd_dt;
1410 KASSERT(newfdp->fd_dt == &newfdp->fd_dtbuiltin);
1411 } else {
1412 /*
1413 * Compute the smallest multiple of NDEXTENT needed
1414 * for the file descriptors currently in use,
1415 * allowing the table to shrink.
1416 */
1417 i = numfiles;
1418 while (i >= 2 * NDEXTENT && i > lastfile * 2) {
1419 i /= 2;
1420 }
1421 KASSERT(i > NDFILE);
1422 newdt = fd_dtab_alloc(i);
1423 newfdp->fd_dt = newdt;
1424 memcpy(newdt->dt_ff, newfdp->fd_dtbuiltin.dt_ff,
1425 NDFDFILE * sizeof(fdfile_t **));
1426 memset(newdt->dt_ff + NDFDFILE, 0,
1427 (i - NDFDFILE) * sizeof(fdfile_t **));
1428 }
1429 if (NDHISLOTS(i) <= NDHISLOTS(NDFILE)) {
1430 newfdp->fd_himap = newfdp->fd_dhimap;
1431 newfdp->fd_lomap = newfdp->fd_dlomap;
1432 } else {
1433 fd_map_alloc(i, &newfdp->fd_lomap, &newfdp->fd_himap);
1434 KASSERT(i >= NDENTRIES * NDENTRIES);
1435 memset(newfdp->fd_himap, 0, NDHISLOTS(i)*sizeof(uint32_t));
1436 memset(newfdp->fd_lomap, 0, NDLOSLOTS(i)*sizeof(uint32_t));
1437 }
1438 newfdp->fd_freefile = fdp->fd_freefile;
1439 newfdp->fd_exclose = fdp->fd_exclose;
1440
1441 ffp = fdp->fd_dt->dt_ff;
1442 nffp = newdt->dt_ff;
1443 newlast = -1;
1444 for (i = 0; i <= (int)lastfile; i++, ffp++, nffp++) {
1445 KASSERT(i >= NDFDFILE ||
1446 *nffp == (fdfile_t *)newfdp->fd_dfdfile[i]);
1447 ff = *ffp;
1448 if (ff == NULL || (fp = ff->ff_file) == NULL) {
1449 /* Descriptor unused, or descriptor half open. */
1450 KASSERT(!fd_isused(newfdp, i));
1451 continue;
1452 }
1453 if (__predict_false(fp->f_type == DTYPE_KQUEUE)) {
1454 /* kqueue descriptors cannot be copied. */
1455 if (i < newfdp->fd_freefile) {
1456 newfdp->fd_freefile = i;
1457 }
1458 continue;
1459 }
1460 /* It's active: add a reference to the file. */
1461 mutex_enter(&fp->f_lock);
1462 fp->f_count++;
1463 mutex_exit(&fp->f_lock);
1464
1465 /* Allocate an fdfile_t to represent it. */
1466 if (i >= NDFDFILE) {
1467 ff2 = pool_cache_get(fdfile_cache, PR_WAITOK);
1468 *nffp = ff2;
1469 } else {
1470 ff2 = newdt->dt_ff[i];
1471 }
1472 ff2->ff_file = fp;
1473 ff2->ff_exclose = ff->ff_exclose;
1474 ff2->ff_allocated = true;
1475
1476 /* Fix up bitmaps. */
1477 j = i >> NDENTRYSHIFT;
1478 KASSERT((newfdp->fd_lomap[j] & (1 << (i & NDENTRYMASK))) == 0);
1479 newfdp->fd_lomap[j] |= 1 << (i & NDENTRYMASK);
1480 if (__predict_false(newfdp->fd_lomap[j] == ~0)) {
1481 KASSERT((newfdp->fd_himap[j >> NDENTRYSHIFT] &
1482 (1 << (j & NDENTRYMASK))) == 0);
1483 newfdp->fd_himap[j >> NDENTRYSHIFT] |=
1484 1 << (j & NDENTRYMASK);
1485 }
1486 newlast = i;
1487 }
1488 KASSERT(newdt->dt_ff[0] == (fdfile_t *)newfdp->fd_dfdfile[0]);
1489 newfdp->fd_lastfile = newlast;
1490 fd_checkmaps(newfdp);
1491 mutex_exit(&fdp->fd_lock);
1492
1493 return newfdp;
1494 }
1495
1496 /*
1497 * Release a filedesc structure.
1498 */
1499 void
1500 fd_free(void)
1501 {
1502 fdfile_t *ff;
1503 file_t *fp;
1504 int fd, nf;
1505 fdtab_t *dt;
1506 lwp_t * const l = curlwp;
1507 filedesc_t * const fdp = l->l_fd;
1508 const bool noadvlock = (l->l_proc->p_flag & PK_ADVLOCK) == 0;
1509
1510 KASSERT(fdp->fd_dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
1511 KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
1512 KASSERT(fdp->fd_dtbuiltin.dt_link == NULL);
1513
1514 #ifndef __HAVE_ATOMIC_AS_MEMBAR
1515 membar_exit();
1516 #endif
1517 if (atomic_dec_uint_nv(&fdp->fd_refcnt) > 0)
1518 return;
1519
1520 /*
1521 * Close any files that the process holds open.
1522 */
1523 dt = fdp->fd_dt;
1524 fd_checkmaps(fdp);
1525 #ifdef DEBUG
1526 fdp->fd_refcnt = -1; /* see fd_checkmaps */
1527 #endif
1528 for (fd = 0, nf = dt->dt_nfiles; fd < nf; fd++) {
1529 ff = dt->dt_ff[fd];
1530 KASSERT(fd >= NDFDFILE ||
1531 ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
1532 if (ff == NULL)
1533 continue;
1534 if ((fp = ff->ff_file) != NULL) {
1535 /*
1536 * Must use fd_close() here if there is
1537 * a reference from kqueue or we might have posix
1538 * advisory locks.
1539 */
1540 if (__predict_true(ff->ff_refcnt == 0) &&
1541 (noadvlock || fp->f_type != DTYPE_VNODE)) {
1542 ff->ff_file = NULL;
1543 ff->ff_exclose = false;
1544 ff->ff_allocated = false;
1545 closef(fp);
1546 } else {
1547 ff->ff_refcnt++;
1548 fd_close(fd);
1549 }
1550 }
1551 KASSERT(ff->ff_refcnt == 0);
1552 KASSERT(ff->ff_file == NULL);
1553 KASSERT(!ff->ff_exclose);
1554 KASSERT(!ff->ff_allocated);
1555 if (fd >= NDFDFILE) {
1556 pool_cache_put(fdfile_cache, ff);
1557 dt->dt_ff[fd] = NULL;
1558 }
1559 }
1560
1561 /*
1562 * Clean out the descriptor table for the next user and return
1563 * to the cache.
1564 */
1565 if (__predict_false(dt != &fdp->fd_dtbuiltin)) {
1566 fd_dtab_free(fdp->fd_dt);
1567 /* Otherwise, done above. */
1568 memset(&fdp->fd_dtbuiltin.dt_ff[NDFDFILE], 0,
1569 (NDFILE - NDFDFILE) * sizeof(fdp->fd_dtbuiltin.dt_ff[0]));
1570 fdp->fd_dt = &fdp->fd_dtbuiltin;
1571 }
1572 if (__predict_false(NDHISLOTS(nf) > NDHISLOTS(NDFILE))) {
1573 KASSERT(fdp->fd_himap != fdp->fd_dhimap);
1574 KASSERT(fdp->fd_lomap != fdp->fd_dlomap);
1575 fd_map_free(nf, fdp->fd_lomap, fdp->fd_himap);
1576 }
1577 if (__predict_false(fdp->fd_knhash != NULL)) {
1578 hashdone(fdp->fd_knhash, HASH_LIST, fdp->fd_knhashmask);
1579 fdp->fd_knhash = NULL;
1580 fdp->fd_knhashmask = 0;
1581 } else {
1582 KASSERT(fdp->fd_knhashmask == 0);
1583 }
1584 fdp->fd_dt = &fdp->fd_dtbuiltin;
1585 fdp->fd_lastkqfile = -1;
1586 fdp->fd_lastfile = -1;
1587 fdp->fd_freefile = 0;
1588 fdp->fd_exclose = false;
1589 memset(&fdp->fd_startzero, 0, sizeof(*fdp) -
1590 offsetof(filedesc_t, fd_startzero));
1591 fdp->fd_himap = fdp->fd_dhimap;
1592 fdp->fd_lomap = fdp->fd_dlomap;
1593 KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
1594 KASSERT(fdp->fd_dtbuiltin.dt_link == NULL);
1595 KASSERT(fdp->fd_dt == &fdp->fd_dtbuiltin);
1596 #ifdef DEBUG
1597 fdp->fd_refcnt = 0; /* see fd_checkmaps */
1598 #endif
1599 fd_checkmaps(fdp);
1600 pool_cache_put(filedesc_cache, fdp);
1601 }
1602
1603 /*
1604 * File Descriptor pseudo-device driver (/dev/fd/).
1605 *
1606 * Opening minor device N dup()s the file (if any) connected to file
1607 * descriptor N belonging to the calling process. Note that this driver
1608 * consists of only the ``open()'' routine, because all subsequent
1609 * references to this file will be direct to the other driver.
1610 */
1611 static int
1612 filedescopen(dev_t dev, int mode, int type, lwp_t *l)
1613 {
1614
1615 /*
1616 * XXX Kludge: set dupfd to contain the value of the
1617 * the file descriptor being sought for duplication. The error
1618 * return ensures that the vnode for this device will be released
1619 * by vn_open. Open will detect this special error and take the
1620 * actions in fd_dupopen below. Other callers of vn_open or VOP_OPEN
1621 * will simply report the error.
1622 */
1623 l->l_dupfd = minor(dev); /* XXX */
1624 return EDUPFD;
1625 }
1626
1627 /*
1628 * Duplicate the specified descriptor to a free descriptor.
1629 */
1630 int
1631 fd_dupopen(int old, int *new, int mode, int error)
1632 {
1633 filedesc_t *fdp;
1634 fdfile_t *ff;
1635 file_t *fp;
1636 fdtab_t *dt;
1637
1638 if ((fp = fd_getfile(old)) == NULL) {
1639 return EBADF;
1640 }
1641 fdp = curlwp->l_fd;
1642 dt = fdp->fd_dt;
1643 ff = dt->dt_ff[old];
1644
1645 /*
1646 * There are two cases of interest here.
1647 *
1648 * For EDUPFD simply dup (old) to file descriptor
1649 * (new) and return.
1650 *
1651 * For EMOVEFD steal away the file structure from (old) and
1652 * store it in (new). (old) is effectively closed by
1653 * this operation.
1654 *
1655 * Any other error code is just returned.
1656 */
1657 switch (error) {
1658 case EDUPFD:
1659 /*
1660 * Check that the mode the file is being opened for is a
1661 * subset of the mode of the existing descriptor.
1662 */
1663 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
1664 error = EACCES;
1665 break;
1666 }
1667
1668 /* Copy it. */
1669 error = fd_dup(fp, 0, new, ff->ff_exclose);
1670 break;
1671
1672 case EMOVEFD:
1673 /* Copy it. */
1674 error = fd_dup(fp, 0, new, ff->ff_exclose);
1675 if (error != 0) {
1676 break;
1677 }
1678
1679 /* Steal away the file pointer from 'old'. */
1680 (void)fd_close(old);
1681 return 0;
1682 }
1683
1684 fd_putfile(old);
1685 return error;
1686 }
1687
1688 /*
1689 * Close open files on exec.
1690 */
1691 void
1692 fd_closeexec(void)
1693 {
1694 proc_t *p;
1695 filedesc_t *fdp;
1696 fdfile_t *ff;
1697 lwp_t *l;
1698 fdtab_t *dt;
1699 int fd;
1700
1701 l = curlwp;
1702 p = l->l_proc;
1703 fdp = p->p_fd;
1704
1705 if (fdp->fd_refcnt > 1) {
1706 fdp = fd_copy();
1707 fd_free();
1708 p->p_fd = fdp;
1709 l->l_fd = fdp;
1710 }
1711 if (!fdp->fd_exclose) {
1712 return;
1713 }
1714 fdp->fd_exclose = false;
1715 dt = fdp->fd_dt;
1716
1717 for (fd = 0; fd <= fdp->fd_lastfile; fd++) {
1718 if ((ff = dt->dt_ff[fd]) == NULL) {
1719 KASSERT(fd >= NDFDFILE);
1720 continue;
1721 }
1722 KASSERT(fd >= NDFDFILE ||
1723 ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
1724 if (ff->ff_file == NULL)
1725 continue;
1726 if (ff->ff_exclose) {
1727 /*
1728 * We need a reference to close the file.
1729 * No other threads can see the fdfile_t at
1730 * this point, so don't bother locking.
1731 */
1732 KASSERT((ff->ff_refcnt & FR_CLOSING) == 0);
1733 ff->ff_refcnt++;
1734 fd_close(fd);
1735 }
1736 }
1737 }
1738
1739 /*
1740 * Sets descriptor owner. If the owner is a process, 'pgid'
1741 * is set to positive value, process ID. If the owner is process group,
1742 * 'pgid' is set to -pg_id.
1743 */
1744 int
1745 fsetown(pid_t *pgid, u_long cmd, const void *data)
1746 {
1747 pid_t id = *(const pid_t *)data;
1748 int error;
1749
1750 switch (cmd) {
1751 case TIOCSPGRP:
1752 if (id < 0)
1753 return EINVAL;
1754 id = -id;
1755 break;
1756 default:
1757 break;
1758 }
1759 if (id > 0) {
1760 mutex_enter(proc_lock);
1761 error = proc_find(id) ? 0 : ESRCH;
1762 mutex_exit(proc_lock);
1763 } else if (id < 0) {
1764 error = pgid_in_session(curproc, -id);
1765 } else {
1766 error = 0;
1767 }
1768 if (!error) {
1769 *pgid = id;
1770 }
1771 return error;
1772 }
1773
1774 void
1775 fd_set_exclose(struct lwp *l, int fd, bool exclose)
1776 {
1777 filedesc_t *fdp = l->l_fd;
1778 fdfile_t *ff = fdp->fd_dt->dt_ff[fd];
1779
1780 ff->ff_exclose = exclose;
1781 if (exclose)
1782 fdp->fd_exclose = true;
1783 }
1784
1785 /*
1786 * Return descriptor owner information. If the value is positive,
1787 * it's process ID. If it's negative, it's process group ID and
1788 * needs the sign removed before use.
1789 */
1790 int
1791 fgetown(pid_t pgid, u_long cmd, void *data)
1792 {
1793
1794 switch (cmd) {
1795 case TIOCGPGRP:
1796 *(int *)data = -pgid;
1797 break;
1798 default:
1799 *(int *)data = pgid;
1800 break;
1801 }
1802 return 0;
1803 }
1804
1805 /*
1806 * Send signal to descriptor owner, either process or process group.
1807 */
1808 void
1809 fownsignal(pid_t pgid, int signo, int code, int band, void *fdescdata)
1810 {
1811 ksiginfo_t ksi;
1812
1813 KASSERT(!cpu_intr_p());
1814
1815 if (pgid == 0) {
1816 return;
1817 }
1818
1819 KSI_INIT(&ksi);
1820 ksi.ksi_signo = signo;
1821 ksi.ksi_code = code;
1822 ksi.ksi_band = band;
1823
1824 mutex_enter(proc_lock);
1825 if (pgid > 0) {
1826 struct proc *p1;
1827
1828 p1 = proc_find(pgid);
1829 if (p1 != NULL) {
1830 kpsignal(p1, &ksi, fdescdata);
1831 }
1832 } else {
1833 struct pgrp *pgrp;
1834
1835 KASSERT(pgid < 0);
1836 pgrp = pgrp_find(-pgid);
1837 if (pgrp != NULL) {
1838 kpgsignal(pgrp, &ksi, fdescdata, 0);
1839 }
1840 }
1841 mutex_exit(proc_lock);
1842 }
1843
1844 int
1845 fd_clone(file_t *fp, unsigned fd, int flag, const struct fileops *fops,
1846 void *data)
1847 {
1848
1849 fp->f_flag = flag;
1850 fp->f_type = DTYPE_MISC;
1851 fp->f_ops = fops;
1852 fp->f_data = data;
1853 curlwp->l_dupfd = fd;
1854 fd_affix(curproc, fp, fd);
1855
1856 return EMOVEFD;
1857 }
1858
1859 int
1860 fnullop_fcntl(file_t *fp, u_int cmd, void *data)
1861 {
1862
1863 if (cmd == F_SETFL)
1864 return 0;
1865
1866 return EOPNOTSUPP;
1867 }
1868
1869 int
1870 fnullop_poll(file_t *fp, int which)
1871 {
1872
1873 return 0;
1874 }
1875
1876 int
1877 fnullop_kqfilter(file_t *fp, struct knote *kn)
1878 {
1879
1880 return 0;
1881 }
1882
1883 void
1884 fnullop_restart(file_t *fp)
1885 {
1886
1887 }
1888
1889 int
1890 fbadop_read(file_t *fp, off_t *offset, struct uio *uio,
1891 kauth_cred_t cred, int flags)
1892 {
1893
1894 return EOPNOTSUPP;
1895 }
1896
1897 int
1898 fbadop_write(file_t *fp, off_t *offset, struct uio *uio,
1899 kauth_cred_t cred, int flags)
1900 {
1901
1902 return EOPNOTSUPP;
1903 }
1904
1905 int
1906 fbadop_ioctl(file_t *fp, u_long com, void *data)
1907 {
1908
1909 return EOPNOTSUPP;
1910 }
1911
1912 int
1913 fbadop_stat(file_t *fp, struct stat *sb)
1914 {
1915
1916 return EOPNOTSUPP;
1917 }
1918
1919 int
1920 fbadop_close(file_t *fp)
1921 {
1922
1923 return EOPNOTSUPP;
1924 }
1925
1926 /*
1927 * sysctl routines pertaining to file descriptors
1928 */
1929
1930 /* Initialized in sysctl_init() for now... */
1931 extern kmutex_t sysctl_file_marker_lock;
1932 static u_int sysctl_file_marker = 1;
1933
1934 /*
1935 * Expects to be called with proc_lock and sysctl_file_marker_lock locked.
1936 */
1937 static void
1938 sysctl_file_marker_reset(void)
1939 {
1940 struct proc *p;
1941
1942 PROCLIST_FOREACH(p, &allproc) {
1943 struct filedesc *fd = p->p_fd;
1944 fdtab_t *dt;
1945 u_int i;
1946
1947 mutex_enter(&fd->fd_lock);
1948 dt = fd->fd_dt;
1949 for (i = 0; i < dt->dt_nfiles; i++) {
1950 struct file *fp;
1951 fdfile_t *ff;
1952
1953 if ((ff = dt->dt_ff[i]) == NULL) {
1954 continue;
1955 }
1956 if ((fp = ff->ff_file) == NULL) {
1957 continue;
1958 }
1959 fp->f_marker = 0;
1960 }
1961 mutex_exit(&fd->fd_lock);
1962 }
1963 }
1964
1965 /*
1966 * sysctl helper routine for kern.file pseudo-subtree.
1967 */
1968 static int
1969 sysctl_kern_file(SYSCTLFN_ARGS)
1970 {
1971 int error;
1972 size_t buflen;
1973 struct file *fp, fbuf;
1974 char *start, *where;
1975 struct proc *p;
1976
1977 start = where = oldp;
1978 buflen = *oldlenp;
1979
1980 if (where == NULL) {
1981 /*
1982 * overestimate by 10 files
1983 */
1984 *oldlenp = sizeof(filehead) + (nfiles + 10) *
1985 sizeof(struct file);
1986 return 0;
1987 }
1988
1989 /*
1990 * first sysctl_copyout filehead
1991 */
1992 if (buflen < sizeof(filehead)) {
1993 *oldlenp = 0;
1994 return 0;
1995 }
1996 sysctl_unlock();
1997 error = sysctl_copyout(l, &filehead, where, sizeof(filehead));
1998 if (error) {
1999 sysctl_relock();
2000 return error;
2001 }
2002 buflen -= sizeof(filehead);
2003 where += sizeof(filehead);
2004
2005 /*
2006 * followed by an array of file structures
2007 */
2008 mutex_enter(&sysctl_file_marker_lock);
2009 mutex_enter(proc_lock);
2010 PROCLIST_FOREACH(p, &allproc) {
2011 struct filedesc *fd;
2012 fdtab_t *dt;
2013 u_int i;
2014
2015 if (p->p_stat == SIDL) {
2016 /* skip embryonic processes */
2017 continue;
2018 }
2019 mutex_enter(p->p_lock);
2020 error = kauth_authorize_process(l->l_cred,
2021 KAUTH_PROCESS_CANSEE, p,
2022 KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_OPENFILES),
2023 NULL, NULL);
2024 mutex_exit(p->p_lock);
2025 if (error != 0) {
2026 /*
2027 * Don't leak kauth retval if we're silently
2028 * skipping this entry.
2029 */
2030 error = 0;
2031 continue;
2032 }
2033
2034 /*
2035 * Grab a hold on the process.
2036 */
2037 if (!rw_tryenter(&p->p_reflock, RW_READER)) {
2038 continue;
2039 }
2040 mutex_exit(proc_lock);
2041
2042 fd = p->p_fd;
2043 mutex_enter(&fd->fd_lock);
2044 dt = fd->fd_dt;
2045 for (i = 0; i < dt->dt_nfiles; i++) {
2046 fdfile_t *ff;
2047
2048 if ((ff = dt->dt_ff[i]) == NULL) {
2049 continue;
2050 }
2051 if ((fp = ff->ff_file) == NULL) {
2052 continue;
2053 }
2054
2055 mutex_enter(&fp->f_lock);
2056
2057 if ((fp->f_count == 0) ||
2058 (fp->f_marker == sysctl_file_marker)) {
2059 mutex_exit(&fp->f_lock);
2060 continue;
2061 }
2062
2063 /* Check that we have enough space. */
2064 if (buflen < sizeof(struct file)) {
2065 *oldlenp = where - start;
2066 mutex_exit(&fp->f_lock);
2067 error = ENOMEM;
2068 break;
2069 }
2070
2071 memcpy(&fbuf, fp, sizeof(fbuf));
2072 mutex_exit(&fp->f_lock);
2073 error = sysctl_copyout(l, &fbuf, where, sizeof(fbuf));
2074 if (error) {
2075 break;
2076 }
2077 buflen -= sizeof(struct file);
2078 where += sizeof(struct file);
2079
2080 fp->f_marker = sysctl_file_marker;
2081 }
2082 mutex_exit(&fd->fd_lock);
2083
2084 /*
2085 * Release reference to process.
2086 */
2087 mutex_enter(proc_lock);
2088 rw_exit(&p->p_reflock);
2089
2090 if (error)
2091 break;
2092 }
2093
2094 sysctl_file_marker++;
2095 /* Reset all markers if wrapped. */
2096 if (sysctl_file_marker == 0) {
2097 sysctl_file_marker_reset();
2098 sysctl_file_marker++;
2099 }
2100
2101 mutex_exit(proc_lock);
2102 mutex_exit(&sysctl_file_marker_lock);
2103
2104 *oldlenp = where - start;
2105 sysctl_relock();
2106 return error;
2107 }
2108
2109 /*
2110 * sysctl helper function for kern.file2
2111 */
2112 static int
2113 sysctl_kern_file2(SYSCTLFN_ARGS)
2114 {
2115 struct proc *p;
2116 struct file *fp;
2117 struct filedesc *fd;
2118 struct kinfo_file kf;
2119 char *dp;
2120 u_int i, op;
2121 size_t len, needed, elem_size, out_size;
2122 int error, arg, elem_count;
2123 fdfile_t *ff;
2124 fdtab_t *dt;
2125
2126 if (namelen == 1 && name[0] == CTL_QUERY)
2127 return sysctl_query(SYSCTLFN_CALL(rnode));
2128
2129 if (namelen != 4)
2130 return EINVAL;
2131
2132 error = 0;
2133 dp = oldp;
2134 len = (oldp != NULL) ? *oldlenp : 0;
2135 op = name[0];
2136 arg = name[1];
2137 elem_size = name[2];
2138 elem_count = name[3];
2139 out_size = MIN(sizeof(kf), elem_size);
2140 needed = 0;
2141
2142 if (elem_size < 1 || elem_count < 0)
2143 return EINVAL;
2144
2145 switch (op) {
2146 case KERN_FILE_BYFILE:
2147 case KERN_FILE_BYPID:
2148 /*
2149 * We're traversing the process list in both cases; the BYFILE
2150 * case does additional work of keeping track of files already
2151 * looked at.
2152 */
2153
2154 /* doesn't use arg so it must be zero */
2155 if ((op == KERN_FILE_BYFILE) && (arg != 0))
2156 return EINVAL;
2157
2158 if ((op == KERN_FILE_BYPID) && (arg < -1))
2159 /* -1 means all processes */
2160 return EINVAL;
2161
2162 sysctl_unlock();
2163 if (op == KERN_FILE_BYFILE)
2164 mutex_enter(&sysctl_file_marker_lock);
2165 mutex_enter(proc_lock);
2166 PROCLIST_FOREACH(p, &allproc) {
2167 if (p->p_stat == SIDL) {
2168 /* skip embryonic processes */
2169 continue;
2170 }
2171 if (arg > 0 && p->p_pid != arg) {
2172 /* pick only the one we want */
2173 /* XXX want 0 to mean "kernel files" */
2174 continue;
2175 }
2176 mutex_enter(p->p_lock);
2177 error = kauth_authorize_process(l->l_cred,
2178 KAUTH_PROCESS_CANSEE, p,
2179 KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_OPENFILES),
2180 NULL, NULL);
2181 mutex_exit(p->p_lock);
2182 if (error != 0) {
2183 /*
2184 * Don't leak kauth retval if we're silently
2185 * skipping this entry.
2186 */
2187 error = 0;
2188 continue;
2189 }
2190
2191 /*
2192 * Grab a hold on the process.
2193 */
2194 if (!rw_tryenter(&p->p_reflock, RW_READER)) {
2195 continue;
2196 }
2197 mutex_exit(proc_lock);
2198
2199 fd = p->p_fd;
2200 mutex_enter(&fd->fd_lock);
2201 dt = fd->fd_dt;
2202 for (i = 0; i < dt->dt_nfiles; i++) {
2203 if ((ff = dt->dt_ff[i]) == NULL) {
2204 continue;
2205 }
2206 if ((fp = ff->ff_file) == NULL) {
2207 continue;
2208 }
2209
2210 if ((op == KERN_FILE_BYFILE) &&
2211 (fp->f_marker == sysctl_file_marker)) {
2212 continue;
2213 }
2214 if (len >= elem_size && elem_count > 0) {
2215 mutex_enter(&fp->f_lock);
2216 fill_file(&kf, fp, ff, i, p->p_pid);
2217 mutex_exit(&fp->f_lock);
2218 mutex_exit(&fd->fd_lock);
2219 error = sysctl_copyout(l,
2220 &kf, dp, out_size);
2221 mutex_enter(&fd->fd_lock);
2222 if (error)
2223 break;
2224 dp += elem_size;
2225 len -= elem_size;
2226 }
2227 if (op == KERN_FILE_BYFILE)
2228 fp->f_marker = sysctl_file_marker;
2229 needed += elem_size;
2230 if (elem_count > 0 && elem_count != INT_MAX)
2231 elem_count--;
2232 }
2233 mutex_exit(&fd->fd_lock);
2234
2235 /*
2236 * Release reference to process.
2237 */
2238 mutex_enter(proc_lock);
2239 rw_exit(&p->p_reflock);
2240 }
2241 if (op == KERN_FILE_BYFILE) {
2242 sysctl_file_marker++;
2243
2244 /* Reset all markers if wrapped. */
2245 if (sysctl_file_marker == 0) {
2246 sysctl_file_marker_reset();
2247 sysctl_file_marker++;
2248 }
2249 }
2250 mutex_exit(proc_lock);
2251 if (op == KERN_FILE_BYFILE)
2252 mutex_exit(&sysctl_file_marker_lock);
2253 sysctl_relock();
2254 break;
2255 default:
2256 return EINVAL;
2257 }
2258
2259 if (oldp == NULL)
2260 needed += KERN_FILESLOP * elem_size;
2261 *oldlenp = needed;
2262
2263 return error;
2264 }
2265
2266 static void
2267 fill_file(struct kinfo_file *kp, const file_t *fp, const fdfile_t *ff,
2268 int i, pid_t pid)
2269 {
2270
2271 memset(kp, 0, sizeof(*kp));
2272
2273 kp->ki_fileaddr = PTRTOUINT64(fp);
2274 kp->ki_flag = fp->f_flag;
2275 kp->ki_iflags = 0;
2276 kp->ki_ftype = fp->f_type;
2277 kp->ki_count = fp->f_count;
2278 kp->ki_msgcount = fp->f_msgcount;
2279 kp->ki_fucred = PTRTOUINT64(fp->f_cred);
2280 kp->ki_fuid = kauth_cred_geteuid(fp->f_cred);
2281 kp->ki_fgid = kauth_cred_getegid(fp->f_cred);
2282 kp->ki_fops = PTRTOUINT64(fp->f_ops);
2283 kp->ki_foffset = fp->f_offset;
2284 kp->ki_fdata = PTRTOUINT64(fp->f_data);
2285
2286 /* vnode information to glue this file to something */
2287 if (fp->f_type == DTYPE_VNODE) {
2288 struct vnode *vp = (struct vnode *)fp->f_data;
2289
2290 kp->ki_vun = PTRTOUINT64(vp->v_un.vu_socket);
2291 kp->ki_vsize = vp->v_size;
2292 kp->ki_vtype = vp->v_type;
2293 kp->ki_vtag = vp->v_tag;
2294 kp->ki_vdata = PTRTOUINT64(vp->v_data);
2295 }
2296
2297 /* process information when retrieved via KERN_FILE_BYPID */
2298 if (ff != NULL) {
2299 kp->ki_pid = pid;
2300 kp->ki_fd = i;
2301 kp->ki_ofileflags = ff->ff_exclose;
2302 kp->ki_usecount = ff->ff_refcnt;
2303 }
2304 }
2305