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