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