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