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