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