kern_descrip.c revision 1.251.10.2 1 /* $NetBSD: kern_descrip.c,v 1.251.10.2 2024/08/07 10:04:47 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.2 2024/08/07 10:04:47 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 fdtab_t *dt;
767 int error;
768
769 while ((error = fd_alloc(p, minfd, newp)) != 0) {
770 if (error != ENOSPC) {
771 return error;
772 }
773 fd_tryexpand(p);
774 }
775
776 dt = atomic_load_consume(&curlwp->l_fd->fd_dt);
777 dt->dt_ff[*newp]->ff_exclose = exclose;
778 fd_affix(p, fp, *newp);
779 return 0;
780 }
781
782 /*
783 * dup2 operation.
784 */
785 int
786 fd_dup2(file_t *fp, unsigned newfd, int flags)
787 {
788 filedesc_t *fdp = curlwp->l_fd;
789 fdfile_t *ff;
790 fdtab_t *dt;
791
792 if (flags & ~(O_CLOEXEC|O_NONBLOCK|O_NOSIGPIPE))
793 return EINVAL;
794 /*
795 * Ensure there are enough slots in the descriptor table,
796 * and allocate an fdfile_t up front in case we need it.
797 */
798 while (newfd >= atomic_load_consume(&fdp->fd_dt)->dt_nfiles) {
799 fd_tryexpand(curproc);
800 }
801 ff = pool_cache_get(fdfile_cache, PR_WAITOK);
802
803 /*
804 * If there is already a file open, close it. If the file is
805 * half open, wait for it to be constructed before closing it.
806 * XXX Potential for deadlock here?
807 */
808 mutex_enter(&fdp->fd_lock);
809 while (fd_isused(fdp, newfd)) {
810 mutex_exit(&fdp->fd_lock);
811 if (fd_getfile(newfd) != NULL) {
812 (void)fd_close(newfd);
813 } else {
814 /*
815 * Crummy, but unlikely to happen.
816 * Can occur if we interrupt another
817 * thread while it is opening a file.
818 */
819 kpause("dup2", false, 1, NULL);
820 }
821 mutex_enter(&fdp->fd_lock);
822 }
823 dt = fdp->fd_dt;
824 if (dt->dt_ff[newfd] == NULL) {
825 KASSERT(newfd >= NDFDFILE);
826 dt->dt_ff[newfd] = ff;
827 ff = NULL;
828 }
829 fd_used(fdp, newfd);
830 mutex_exit(&fdp->fd_lock);
831
832 dt->dt_ff[newfd]->ff_exclose = (flags & O_CLOEXEC) != 0;
833 fp->f_flag |= flags & (FNONBLOCK|FNOSIGPIPE);
834 /* Slot is now allocated. Insert copy of the file. */
835 fd_affix(curproc, fp, newfd);
836 if (ff != NULL) {
837 pool_cache_put(fdfile_cache, ff);
838 }
839 return 0;
840 }
841
842 /*
843 * Drop reference to a file structure.
844 */
845 int
846 closef(file_t *fp)
847 {
848 struct flock lf;
849 int error;
850
851 /*
852 * Drop reference. If referenced elsewhere it's still open
853 * and we have nothing more to do.
854 */
855 mutex_enter(&fp->f_lock);
856 KASSERT(fp->f_count > 0);
857 if (--fp->f_count > 0) {
858 mutex_exit(&fp->f_lock);
859 return 0;
860 }
861 KASSERT(fp->f_count == 0);
862 mutex_exit(&fp->f_lock);
863
864 /* We held the last reference - release locks, close and free. */
865 if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
866 lf.l_whence = SEEK_SET;
867 lf.l_start = 0;
868 lf.l_len = 0;
869 lf.l_type = F_UNLCK;
870 (void)VOP_ADVLOCK(fp->f_vnode, fp, F_UNLCK, &lf, F_FLOCK);
871 }
872 if (fp->f_ops != NULL) {
873 error = (*fp->f_ops->fo_close)(fp);
874 } else {
875 error = 0;
876 }
877 KASSERT(fp->f_count == 0);
878 KASSERT(fp->f_cred != NULL);
879 pool_cache_put(file_cache, fp);
880
881 return error;
882 }
883
884 /*
885 * Allocate a file descriptor for the process.
886 */
887 int
888 fd_alloc(proc_t *p, int want, int *result)
889 {
890 filedesc_t *fdp = p->p_fd;
891 int i, lim, last, error, hi;
892 u_int off;
893 fdtab_t *dt;
894
895 KASSERT(p == curproc || p == &proc0);
896
897 /*
898 * Search for a free descriptor starting at the higher
899 * of want or fd_freefile.
900 */
901 mutex_enter(&fdp->fd_lock);
902 fd_checkmaps(fdp);
903 dt = fdp->fd_dt;
904 KASSERT(dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
905 lim = uimin((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
906 last = uimin(dt->dt_nfiles, lim);
907 for (;;) {
908 if ((i = want) < fdp->fd_freefile)
909 i = fdp->fd_freefile;
910 off = i >> NDENTRYSHIFT;
911 hi = fd_next_zero(fdp, fdp->fd_himap, off,
912 (last + NDENTRIES - 1) >> NDENTRYSHIFT);
913 if (hi == -1)
914 break;
915 i = fd_next_zero(fdp, &fdp->fd_lomap[hi],
916 hi > off ? 0 : i & NDENTRYMASK, NDENTRIES);
917 if (i == -1) {
918 /*
919 * Free file descriptor in this block was
920 * below want, try again with higher want.
921 */
922 want = (hi + 1) << NDENTRYSHIFT;
923 continue;
924 }
925 i += (hi << NDENTRYSHIFT);
926 if (i >= last) {
927 break;
928 }
929 if (dt->dt_ff[i] == NULL) {
930 KASSERT(i >= NDFDFILE);
931 dt->dt_ff[i] = pool_cache_get(fdfile_cache, PR_WAITOK);
932 }
933 KASSERT(dt->dt_ff[i]->ff_file == NULL);
934 fd_used(fdp, i);
935 if (want <= fdp->fd_freefile) {
936 fdp->fd_freefile = i;
937 }
938 *result = i;
939 KASSERT(i >= NDFDFILE ||
940 dt->dt_ff[i] == (fdfile_t *)fdp->fd_dfdfile[i]);
941 fd_checkmaps(fdp);
942 mutex_exit(&fdp->fd_lock);
943 return 0;
944 }
945
946 /* No space in current array. Let the caller expand and retry. */
947 error = (dt->dt_nfiles >= lim) ? EMFILE : ENOSPC;
948 mutex_exit(&fdp->fd_lock);
949 return error;
950 }
951
952 /*
953 * Allocate memory for a descriptor table.
954 */
955 static fdtab_t *
956 fd_dtab_alloc(int n)
957 {
958 fdtab_t *dt;
959 size_t sz;
960
961 KASSERT(n > NDFILE);
962
963 sz = sizeof(*dt) + (n - NDFILE) * sizeof(dt->dt_ff[0]);
964 dt = kmem_alloc(sz, KM_SLEEP);
965 #ifdef DIAGNOSTIC
966 memset(dt, 0xff, sz);
967 #endif
968 dt->dt_nfiles = n;
969 dt->dt_link = NULL;
970 return dt;
971 }
972
973 /*
974 * Free a descriptor table, and all tables linked for deferred free.
975 */
976 static void
977 fd_dtab_free(fdtab_t *dt)
978 {
979 fdtab_t *next;
980 size_t sz;
981
982 do {
983 next = dt->dt_link;
984 KASSERT(dt->dt_nfiles > NDFILE);
985 sz = sizeof(*dt) +
986 (dt->dt_nfiles - NDFILE) * sizeof(dt->dt_ff[0]);
987 #ifdef DIAGNOSTIC
988 memset(dt, 0xff, sz);
989 #endif
990 kmem_free(dt, sz);
991 dt = next;
992 } while (dt != NULL);
993 }
994
995 /*
996 * Allocate descriptor bitmap.
997 */
998 static void
999 fd_map_alloc(int n, uint32_t **lo, uint32_t **hi)
1000 {
1001 uint8_t *ptr;
1002 size_t szlo, szhi;
1003
1004 KASSERT(n > NDENTRIES);
1005
1006 szlo = NDLOSLOTS(n) * sizeof(uint32_t);
1007 szhi = NDHISLOTS(n) * sizeof(uint32_t);
1008 ptr = kmem_alloc(szlo + szhi, KM_SLEEP);
1009 *lo = (uint32_t *)ptr;
1010 *hi = (uint32_t *)(ptr + szlo);
1011 }
1012
1013 /*
1014 * Free descriptor bitmap.
1015 */
1016 static void
1017 fd_map_free(int n, uint32_t *lo, uint32_t *hi)
1018 {
1019 size_t szlo, szhi;
1020
1021 KASSERT(n > NDENTRIES);
1022
1023 szlo = NDLOSLOTS(n) * sizeof(uint32_t);
1024 szhi = NDHISLOTS(n) * sizeof(uint32_t);
1025 KASSERT(hi == (uint32_t *)((uint8_t *)lo + szlo));
1026 kmem_free(lo, szlo + szhi);
1027 }
1028
1029 /*
1030 * Expand a process' descriptor table.
1031 */
1032 void
1033 fd_tryexpand(proc_t *p)
1034 {
1035 filedesc_t *fdp;
1036 int i, numfiles, oldnfiles;
1037 fdtab_t *newdt, *dt;
1038 uint32_t *newhimap, *newlomap;
1039
1040 KASSERT(p == curproc || p == &proc0);
1041
1042 fdp = p->p_fd;
1043 newhimap = NULL;
1044 newlomap = NULL;
1045 oldnfiles = atomic_load_consume(&fdp->fd_dt)->dt_nfiles;
1046
1047 if (oldnfiles < NDEXTENT)
1048 numfiles = NDEXTENT;
1049 else
1050 numfiles = 2 * oldnfiles;
1051
1052 newdt = fd_dtab_alloc(numfiles);
1053 if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
1054 fd_map_alloc(numfiles, &newlomap, &newhimap);
1055 }
1056
1057 mutex_enter(&fdp->fd_lock);
1058 dt = fdp->fd_dt;
1059 KASSERT(dt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
1060 if (dt->dt_nfiles != oldnfiles) {
1061 /* fdp changed; caller must retry */
1062 mutex_exit(&fdp->fd_lock);
1063 fd_dtab_free(newdt);
1064 if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
1065 fd_map_free(numfiles, newlomap, newhimap);
1066 }
1067 return;
1068 }
1069
1070 /* Copy the existing descriptor table and zero the new portion. */
1071 i = sizeof(fdfile_t *) * oldnfiles;
1072 memcpy(newdt->dt_ff, dt->dt_ff, i);
1073 memset((uint8_t *)newdt->dt_ff + i, 0,
1074 numfiles * sizeof(fdfile_t *) - i);
1075
1076 /*
1077 * Link old descriptor array into list to be discarded. We defer
1078 * freeing until the last reference to the descriptor table goes
1079 * away (usually process exit). This allows us to do lockless
1080 * lookups in fd_getfile().
1081 */
1082 if (oldnfiles > NDFILE) {
1083 if (fdp->fd_refcnt > 1) {
1084 newdt->dt_link = dt;
1085 } else {
1086 fd_dtab_free(dt);
1087 }
1088 }
1089
1090 if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
1091 i = NDHISLOTS(oldnfiles) * sizeof(uint32_t);
1092 memcpy(newhimap, fdp->fd_himap, i);
1093 memset((uint8_t *)newhimap + i, 0,
1094 NDHISLOTS(numfiles) * sizeof(uint32_t) - i);
1095
1096 i = NDLOSLOTS(oldnfiles) * sizeof(uint32_t);
1097 memcpy(newlomap, fdp->fd_lomap, i);
1098 memset((uint8_t *)newlomap + i, 0,
1099 NDLOSLOTS(numfiles) * sizeof(uint32_t) - i);
1100
1101 if (NDHISLOTS(oldnfiles) > NDHISLOTS(NDFILE)) {
1102 fd_map_free(oldnfiles, fdp->fd_lomap, fdp->fd_himap);
1103 }
1104 fdp->fd_himap = newhimap;
1105 fdp->fd_lomap = newlomap;
1106 }
1107
1108 /*
1109 * All other modifications must become globally visible before
1110 * the change to fd_dt. See fd_getfile().
1111 */
1112 atomic_store_release(&fdp->fd_dt, newdt);
1113 KASSERT(newdt->dt_ff[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
1114 fd_checkmaps(fdp);
1115 mutex_exit(&fdp->fd_lock);
1116 }
1117
1118 /*
1119 * Create a new open file structure and allocate a file descriptor
1120 * for the current process.
1121 */
1122 int
1123 fd_allocfile(file_t **resultfp, int *resultfd)
1124 {
1125 proc_t *p = curproc;
1126 kauth_cred_t cred;
1127 file_t *fp;
1128 int error;
1129
1130 while ((error = fd_alloc(p, 0, resultfd)) != 0) {
1131 if (error != ENOSPC) {
1132 return error;
1133 }
1134 fd_tryexpand(p);
1135 }
1136
1137 fp = pool_cache_get(file_cache, PR_WAITOK);
1138 if (fp == NULL) {
1139 fd_abort(p, NULL, *resultfd);
1140 return ENFILE;
1141 }
1142 KASSERT(fp->f_count == 0);
1143 KASSERT(fp->f_msgcount == 0);
1144 KASSERT(fp->f_unpcount == 0);
1145
1146 /* Replace cached credentials if not what we need. */
1147 cred = curlwp->l_cred;
1148 if (__predict_false(cred != fp->f_cred)) {
1149 kauth_cred_free(fp->f_cred);
1150 kauth_cred_hold(cred);
1151 fp->f_cred = cred;
1152 }
1153
1154 /*
1155 * Don't allow recycled files to be scanned.
1156 * See uipc_usrreq.c.
1157 */
1158 if (__predict_false((fp->f_flag & FSCAN) != 0)) {
1159 mutex_enter(&fp->f_lock);
1160 atomic_and_uint(&fp->f_flag, ~FSCAN);
1161 mutex_exit(&fp->f_lock);
1162 }
1163
1164 fp->f_advice = 0;
1165 fp->f_offset = 0;
1166 *resultfp = fp;
1167
1168 return 0;
1169 }
1170
1171 /*
1172 * Successful creation of a new descriptor: make visible to the process.
1173 */
1174 void
1175 fd_affix(proc_t *p, file_t *fp, unsigned fd)
1176 {
1177 fdfile_t *ff;
1178 filedesc_t *fdp;
1179 fdtab_t *dt;
1180
1181 KASSERT(p == curproc || p == &proc0);
1182
1183 /* Add a reference to the file structure. */
1184 mutex_enter(&fp->f_lock);
1185 fp->f_count++;
1186 mutex_exit(&fp->f_lock);
1187
1188 /*
1189 * Insert the new file into the descriptor slot.
1190 */
1191 fdp = p->p_fd;
1192 dt = atomic_load_consume(&fdp->fd_dt);
1193 ff = dt->dt_ff[fd];
1194
1195 KASSERT(ff != NULL);
1196 KASSERT(ff->ff_file == NULL);
1197 KASSERT(ff->ff_allocated);
1198 KASSERT(fd_isused(fdp, fd));
1199 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
1200
1201 /* No need to lock in order to make file initially visible. */
1202 atomic_store_release(&ff->ff_file, fp);
1203 }
1204
1205 /*
1206 * Abort creation of a new descriptor: free descriptor slot and file.
1207 */
1208 void
1209 fd_abort(proc_t *p, file_t *fp, unsigned fd)
1210 {
1211 filedesc_t *fdp;
1212 fdfile_t *ff;
1213
1214 KASSERT(p == curproc || p == &proc0);
1215
1216 fdp = p->p_fd;
1217 ff = atomic_load_consume(&fdp->fd_dt)->dt_ff[fd];
1218 ff->ff_exclose = false;
1219
1220 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
1221
1222 mutex_enter(&fdp->fd_lock);
1223 KASSERT(fd_isused(fdp, fd));
1224 fd_unused(fdp, fd);
1225 mutex_exit(&fdp->fd_lock);
1226
1227 if (fp != NULL) {
1228 KASSERT(fp->f_count == 0);
1229 KASSERT(fp->f_cred != NULL);
1230 pool_cache_put(file_cache, fp);
1231 }
1232 }
1233
1234 static int
1235 file_ctor(void *arg, void *obj, int flags)
1236 {
1237 file_t *fp = obj;
1238
1239 memset(fp, 0, sizeof(*fp));
1240
1241 mutex_enter(&filelist_lock);
1242 if (__predict_false(nfiles >= maxfiles)) {
1243 mutex_exit(&filelist_lock);
1244 tablefull("file", "increase kern.maxfiles or MAXFILES");
1245 return ENFILE;
1246 }
1247 nfiles++;
1248 LIST_INSERT_HEAD(&filehead, fp, f_list);
1249 mutex_init(&fp->f_lock, MUTEX_DEFAULT, IPL_NONE);
1250 fp->f_cred = curlwp->l_cred;
1251 kauth_cred_hold(fp->f_cred);
1252 mutex_exit(&filelist_lock);
1253
1254 return 0;
1255 }
1256
1257 static void
1258 file_dtor(void *arg, void *obj)
1259 {
1260 file_t *fp = obj;
1261
1262 mutex_enter(&filelist_lock);
1263 nfiles--;
1264 LIST_REMOVE(fp, f_list);
1265 mutex_exit(&filelist_lock);
1266
1267 KASSERT(fp->f_count == 0);
1268 kauth_cred_free(fp->f_cred);
1269 mutex_destroy(&fp->f_lock);
1270 }
1271
1272 static int
1273 fdfile_ctor(void *arg, void *obj, int flags)
1274 {
1275 fdfile_t *ff = obj;
1276
1277 memset(ff, 0, sizeof(*ff));
1278 cv_init(&ff->ff_closing, "fdclose");
1279
1280 return 0;
1281 }
1282
1283 static void
1284 fdfile_dtor(void *arg, void *obj)
1285 {
1286 fdfile_t *ff = obj;
1287
1288 cv_destroy(&ff->ff_closing);
1289 }
1290
1291 file_t *
1292 fgetdummy(void)
1293 {
1294 file_t *fp;
1295
1296 fp = kmem_zalloc(sizeof(*fp), KM_SLEEP);
1297 mutex_init(&fp->f_lock, MUTEX_DEFAULT, IPL_NONE);
1298 return fp;
1299 }
1300
1301 void
1302 fputdummy(file_t *fp)
1303 {
1304
1305 mutex_destroy(&fp->f_lock);
1306 kmem_free(fp, sizeof(*fp));
1307 }
1308
1309 /*
1310 * Create an initial filedesc structure.
1311 */
1312 filedesc_t *
1313 fd_init(filedesc_t *fdp)
1314 {
1315 #ifdef DIAGNOSTIC
1316 unsigned fd;
1317 #endif
1318
1319 if (__predict_true(fdp == NULL)) {
1320 fdp = pool_cache_get(filedesc_cache, PR_WAITOK);
1321 } else {
1322 KASSERT(fdp == &filedesc0);
1323 filedesc_ctor(NULL, fdp, PR_WAITOK);
1324 }
1325
1326 #ifdef DIAGNOSTIC
1327 KASSERT(fdp->fd_lastfile == -1);
1328 KASSERT(fdp->fd_lastkqfile == -1);
1329 KASSERT(fdp->fd_knhash == NULL);
1330 KASSERT(fdp->fd_freefile == 0);
1331 KASSERT(fdp->fd_exclose == false);
1332 KASSERT(fdp->fd_dt == &fdp->fd_dtbuiltin);
1333 KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
1334 for (fd = 0; fd < NDFDFILE; fd++) {
1335 KASSERT(fdp->fd_dtbuiltin.dt_ff[fd] ==
1336 (fdfile_t *)fdp->fd_dfdfile[fd]);
1337 }
1338 for (fd = NDFDFILE; fd < NDFILE; fd++) {
1339 KASSERT(fdp->fd_dtbuiltin.dt_ff[fd] == NULL);
1340 }
1341 KASSERT(fdp->fd_himap == fdp->fd_dhimap);
1342 KASSERT(fdp->fd_lomap == fdp->fd_dlomap);
1343 #endif /* DIAGNOSTIC */
1344
1345 fdp->fd_refcnt = 1;
1346 fd_checkmaps(fdp);
1347
1348 return fdp;
1349 }
1350
1351 /*
1352 * Initialize a file descriptor table.
1353 */
1354 static int
1355 filedesc_ctor(void *arg, void *obj, int flag)
1356 {
1357 filedesc_t *fdp = obj;
1358 fdfile_t **ffp;
1359 int i;
1360
1361 memset(fdp, 0, sizeof(*fdp));
1362 mutex_init(&fdp->fd_lock, MUTEX_DEFAULT, IPL_NONE);
1363 fdp->fd_lastfile = -1;
1364 fdp->fd_lastkqfile = -1;
1365 fdp->fd_dt = &fdp->fd_dtbuiltin;
1366 fdp->fd_dtbuiltin.dt_nfiles = NDFILE;
1367 fdp->fd_himap = fdp->fd_dhimap;
1368 fdp->fd_lomap = fdp->fd_dlomap;
1369
1370 CTASSERT(sizeof(fdp->fd_dfdfile[0]) >= sizeof(fdfile_t));
1371 for (i = 0, ffp = fdp->fd_dt->dt_ff; i < NDFDFILE; i++, ffp++) {
1372 *ffp = (fdfile_t *)fdp->fd_dfdfile[i];
1373 (void)fdfile_ctor(NULL, fdp->fd_dfdfile[i], PR_WAITOK);
1374 }
1375
1376 return 0;
1377 }
1378
1379 static void
1380 filedesc_dtor(void *arg, void *obj)
1381 {
1382 filedesc_t *fdp = obj;
1383 int i;
1384
1385 for (i = 0; i < NDFDFILE; i++) {
1386 fdfile_dtor(NULL, fdp->fd_dfdfile[i]);
1387 }
1388
1389 mutex_destroy(&fdp->fd_lock);
1390 }
1391
1392 /*
1393 * Make p share curproc's filedesc structure.
1394 */
1395 void
1396 fd_share(struct proc *p)
1397 {
1398 filedesc_t *fdp;
1399
1400 fdp = curlwp->l_fd;
1401 p->p_fd = fdp;
1402 atomic_inc_uint(&fdp->fd_refcnt);
1403 }
1404
1405 /*
1406 * Acquire a hold on a filedesc structure.
1407 */
1408 void
1409 fd_hold(lwp_t *l)
1410 {
1411 filedesc_t *fdp = l->l_fd;
1412
1413 atomic_inc_uint(&fdp->fd_refcnt);
1414 }
1415
1416 /*
1417 * Copy a filedesc structure.
1418 */
1419 filedesc_t *
1420 fd_copy(void)
1421 {
1422 filedesc_t *newfdp, *fdp;
1423 fdfile_t *ff, **ffp, **nffp, *ff2;
1424 int i, j, numfiles, lastfile, newlast;
1425 file_t *fp;
1426 fdtab_t *newdt;
1427
1428 fdp = curproc->p_fd;
1429 newfdp = pool_cache_get(filedesc_cache, PR_WAITOK);
1430 newfdp->fd_refcnt = 1;
1431
1432 #ifdef DIAGNOSTIC
1433 KASSERT(newfdp->fd_lastfile == -1);
1434 KASSERT(newfdp->fd_lastkqfile == -1);
1435 KASSERT(newfdp->fd_knhash == NULL);
1436 KASSERT(newfdp->fd_freefile == 0);
1437 KASSERT(newfdp->fd_exclose == false);
1438 KASSERT(newfdp->fd_dt == &newfdp->fd_dtbuiltin);
1439 KASSERT(newfdp->fd_dtbuiltin.dt_nfiles == NDFILE);
1440 for (i = 0; i < NDFDFILE; i++) {
1441 KASSERT(newfdp->fd_dtbuiltin.dt_ff[i] ==
1442 (fdfile_t *)&newfdp->fd_dfdfile[i]);
1443 }
1444 for (i = NDFDFILE; i < NDFILE; i++) {
1445 KASSERT(newfdp->fd_dtbuiltin.dt_ff[i] == NULL);
1446 }
1447 #endif /* DIAGNOSTIC */
1448
1449 mutex_enter(&fdp->fd_lock);
1450 fd_checkmaps(fdp);
1451 numfiles = fdp->fd_dt->dt_nfiles;
1452 lastfile = fdp->fd_lastfile;
1453
1454 /*
1455 * If the number of open files fits in the internal arrays
1456 * of the open file structure, use them, otherwise allocate
1457 * additional memory for the number of descriptors currently
1458 * in use.
1459 */
1460 if (lastfile < NDFILE) {
1461 i = NDFILE;
1462 newdt = newfdp->fd_dt;
1463 KASSERT(newfdp->fd_dt == &newfdp->fd_dtbuiltin);
1464 } else {
1465 /*
1466 * Compute the smallest multiple of NDEXTENT needed
1467 * for the file descriptors currently in use,
1468 * allowing the table to shrink.
1469 */
1470 i = numfiles;
1471 while (i >= 2 * NDEXTENT && i > lastfile * 2) {
1472 i /= 2;
1473 }
1474 KASSERT(i > NDFILE);
1475 newdt = fd_dtab_alloc(i);
1476 newfdp->fd_dt = newdt;
1477 memcpy(newdt->dt_ff, newfdp->fd_dtbuiltin.dt_ff,
1478 NDFDFILE * sizeof(fdfile_t **));
1479 memset(newdt->dt_ff + NDFDFILE, 0,
1480 (i - NDFDFILE) * sizeof(fdfile_t **));
1481 }
1482 if (NDHISLOTS(i) <= NDHISLOTS(NDFILE)) {
1483 newfdp->fd_himap = newfdp->fd_dhimap;
1484 newfdp->fd_lomap = newfdp->fd_dlomap;
1485 } else {
1486 fd_map_alloc(i, &newfdp->fd_lomap, &newfdp->fd_himap);
1487 KASSERT(i >= NDENTRIES * NDENTRIES);
1488 memset(newfdp->fd_himap, 0, NDHISLOTS(i)*sizeof(uint32_t));
1489 memset(newfdp->fd_lomap, 0, NDLOSLOTS(i)*sizeof(uint32_t));
1490 }
1491 newfdp->fd_freefile = fdp->fd_freefile;
1492 newfdp->fd_exclose = fdp->fd_exclose;
1493
1494 ffp = fdp->fd_dt->dt_ff;
1495 nffp = newdt->dt_ff;
1496 newlast = -1;
1497 for (i = 0; i <= lastfile; i++, ffp++, nffp++) {
1498 KASSERT(i >= NDFDFILE ||
1499 *nffp == (fdfile_t *)newfdp->fd_dfdfile[i]);
1500 ff = *ffp;
1501 if (ff == NULL ||
1502 (fp = atomic_load_consume(&ff->ff_file)) == NULL) {
1503 /* Descriptor unused, or descriptor half open. */
1504 KASSERT(!fd_isused(newfdp, i));
1505 continue;
1506 }
1507 if (__predict_false(fp->f_type == DTYPE_KQUEUE)) {
1508 /* kqueue descriptors cannot be copied. */
1509 if (i < newfdp->fd_freefile) {
1510 newfdp->fd_freefile = i;
1511 }
1512 continue;
1513 }
1514 /* It's active: add a reference to the file. */
1515 mutex_enter(&fp->f_lock);
1516 fp->f_count++;
1517 mutex_exit(&fp->f_lock);
1518
1519 /* Allocate an fdfile_t to represent it. */
1520 if (i >= NDFDFILE) {
1521 ff2 = pool_cache_get(fdfile_cache, PR_WAITOK);
1522 *nffp = ff2;
1523 } else {
1524 ff2 = newdt->dt_ff[i];
1525 }
1526 ff2->ff_file = fp;
1527 ff2->ff_exclose = ff->ff_exclose;
1528 ff2->ff_allocated = true;
1529
1530 /* Fix up bitmaps. */
1531 j = i >> NDENTRYSHIFT;
1532 KASSERT((newfdp->fd_lomap[j] & (1U << (i & NDENTRYMASK))) == 0);
1533 newfdp->fd_lomap[j] |= 1U << (i & NDENTRYMASK);
1534 if (__predict_false(newfdp->fd_lomap[j] == ~0)) {
1535 KASSERT((newfdp->fd_himap[j >> NDENTRYSHIFT] &
1536 (1U << (j & NDENTRYMASK))) == 0);
1537 newfdp->fd_himap[j >> NDENTRYSHIFT] |=
1538 1U << (j & NDENTRYMASK);
1539 }
1540 newlast = i;
1541 }
1542 KASSERT(newdt->dt_ff[0] == (fdfile_t *)newfdp->fd_dfdfile[0]);
1543 newfdp->fd_lastfile = newlast;
1544 fd_checkmaps(newfdp);
1545 mutex_exit(&fdp->fd_lock);
1546
1547 return newfdp;
1548 }
1549
1550 /*
1551 * Release a filedesc structure.
1552 */
1553 void
1554 fd_free(void)
1555 {
1556 fdfile_t *ff;
1557 file_t *fp;
1558 int fd, nf;
1559 fdtab_t *dt;
1560 lwp_t * const l = curlwp;
1561 filedesc_t * const fdp = l->l_fd;
1562 const bool noadvlock = (l->l_proc->p_flag & PK_ADVLOCK) == 0;
1563
1564 KASSERT(atomic_load_consume(&fdp->fd_dt)->dt_ff[0] ==
1565 (fdfile_t *)fdp->fd_dfdfile[0]);
1566 KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
1567 KASSERT(fdp->fd_dtbuiltin.dt_link == NULL);
1568
1569 #ifndef __HAVE_ATOMIC_AS_MEMBAR
1570 membar_release();
1571 #endif
1572 if (atomic_dec_uint_nv(&fdp->fd_refcnt) > 0)
1573 return;
1574 #ifndef __HAVE_ATOMIC_AS_MEMBAR
1575 membar_acquire();
1576 #endif
1577
1578 /*
1579 * Close any files that the process holds open.
1580 */
1581 dt = fdp->fd_dt;
1582 fd_checkmaps(fdp);
1583 #ifdef DEBUG
1584 fdp->fd_refcnt = -1; /* see fd_checkmaps */
1585 #endif
1586 for (fd = 0, nf = dt->dt_nfiles; fd < nf; fd++) {
1587 ff = dt->dt_ff[fd];
1588 KASSERT(fd >= NDFDFILE ||
1589 ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
1590 if (ff == NULL)
1591 continue;
1592 if ((fp = atomic_load_consume(&ff->ff_file)) != NULL) {
1593 /*
1594 * Must use fd_close() here if there is
1595 * a reference from kqueue or we might have posix
1596 * advisory locks.
1597 */
1598 if (__predict_true(ff->ff_refcnt == 0) &&
1599 (noadvlock || fp->f_type != DTYPE_VNODE)) {
1600 ff->ff_file = NULL;
1601 ff->ff_exclose = false;
1602 ff->ff_allocated = false;
1603 closef(fp);
1604 } else {
1605 ff->ff_refcnt++;
1606 fd_close(fd);
1607 }
1608 }
1609 KASSERT(ff->ff_refcnt == 0);
1610 KASSERT(ff->ff_file == NULL);
1611 KASSERT(!ff->ff_exclose);
1612 KASSERT(!ff->ff_allocated);
1613 if (fd >= NDFDFILE) {
1614 pool_cache_put(fdfile_cache, ff);
1615 dt->dt_ff[fd] = NULL;
1616 }
1617 }
1618
1619 /*
1620 * Clean out the descriptor table for the next user and return
1621 * to the cache.
1622 */
1623 if (__predict_false(dt != &fdp->fd_dtbuiltin)) {
1624 fd_dtab_free(fdp->fd_dt);
1625 /* Otherwise, done above. */
1626 memset(&fdp->fd_dtbuiltin.dt_ff[NDFDFILE], 0,
1627 (NDFILE - NDFDFILE) * sizeof(fdp->fd_dtbuiltin.dt_ff[0]));
1628 fdp->fd_dt = &fdp->fd_dtbuiltin;
1629 }
1630 if (__predict_false(NDHISLOTS(nf) > NDHISLOTS(NDFILE))) {
1631 KASSERT(fdp->fd_himap != fdp->fd_dhimap);
1632 KASSERT(fdp->fd_lomap != fdp->fd_dlomap);
1633 fd_map_free(nf, fdp->fd_lomap, fdp->fd_himap);
1634 }
1635 if (__predict_false(fdp->fd_knhash != NULL)) {
1636 hashdone(fdp->fd_knhash, HASH_LIST, fdp->fd_knhashmask);
1637 fdp->fd_knhash = NULL;
1638 fdp->fd_knhashmask = 0;
1639 } else {
1640 KASSERT(fdp->fd_knhashmask == 0);
1641 }
1642 fdp->fd_dt = &fdp->fd_dtbuiltin;
1643 fdp->fd_lastkqfile = -1;
1644 fdp->fd_lastfile = -1;
1645 fdp->fd_freefile = 0;
1646 fdp->fd_exclose = false;
1647 memset(&fdp->fd_startzero, 0, sizeof(*fdp) -
1648 offsetof(filedesc_t, fd_startzero));
1649 fdp->fd_himap = fdp->fd_dhimap;
1650 fdp->fd_lomap = fdp->fd_dlomap;
1651 KASSERT(fdp->fd_dtbuiltin.dt_nfiles == NDFILE);
1652 KASSERT(fdp->fd_dtbuiltin.dt_link == NULL);
1653 KASSERT(fdp->fd_dt == &fdp->fd_dtbuiltin);
1654 #ifdef DEBUG
1655 fdp->fd_refcnt = 0; /* see fd_checkmaps */
1656 #endif
1657 fd_checkmaps(fdp);
1658 pool_cache_put(filedesc_cache, fdp);
1659 }
1660
1661 /*
1662 * File Descriptor pseudo-device driver (/dev/fd/).
1663 *
1664 * Opening minor device N dup()s the file (if any) connected to file
1665 * descriptor N belonging to the calling process. Note that this driver
1666 * consists of only the ``open()'' routine, because all subsequent
1667 * references to this file will be direct to the other driver.
1668 */
1669 static int
1670 filedescopen(dev_t dev, int mode, int type, lwp_t *l)
1671 {
1672
1673 /*
1674 * XXX Kludge: set dupfd to contain the value of the
1675 * the file descriptor being sought for duplication. The error
1676 * return ensures that the vnode for this device will be released
1677 * by vn_open. Open will detect this special error and take the
1678 * actions in fd_dupopen below. Other callers of vn_open or VOP_OPEN
1679 * will simply report the error.
1680 */
1681 l->l_dupfd = minor(dev); /* XXX */
1682 return EDUPFD;
1683 }
1684
1685 /*
1686 * Duplicate the specified descriptor to a free descriptor.
1687 *
1688 * old is the original fd.
1689 * moveit is true if we should move rather than duplicate.
1690 * flags are the open flags (converted from O_* to F*).
1691 * newp returns the new fd on success.
1692 *
1693 * These two cases are produced by the EDUPFD and EMOVEFD magic
1694 * errnos, but in the interest of removing that regrettable interface,
1695 * vn_open has been changed to intercept them. Now vn_open returns
1696 * either a vnode or a filehandle, and the filehandle is accompanied
1697 * by a boolean that says whether we should dup (moveit == false) or
1698 * move (moveit == true) the fd.
1699 *
1700 * The dup case is used by /dev/stderr, /proc/self/fd, and such. The
1701 * move case is used by cloner devices that allocate a fd of their
1702 * own (a layering violation that should go away eventually) that
1703 * then needs to be put in the place open() expects it.
1704 */
1705 int
1706 fd_dupopen(int old, bool moveit, int flags, int *newp)
1707 {
1708 filedesc_t *fdp;
1709 fdfile_t *ff;
1710 file_t *fp;
1711 fdtab_t *dt;
1712 int error;
1713
1714 if ((fp = fd_getfile(old)) == NULL) {
1715 return EBADF;
1716 }
1717 fdp = curlwp->l_fd;
1718 dt = atomic_load_consume(&fdp->fd_dt);
1719 ff = dt->dt_ff[old];
1720
1721 /*
1722 * There are two cases of interest here.
1723 *
1724 * 1. moveit == false (used to be the EDUPFD magic errno):
1725 * simply dup (old) to file descriptor (new) and return.
1726 *
1727 * 2. moveit == true (used to be the EMOVEFD magic errno):
1728 * steal away the file structure from (old) and store it in
1729 * (new). (old) is effectively closed by this operation.
1730 */
1731 if (moveit == false) {
1732 /*
1733 * Check that the mode the file is being opened for is a
1734 * subset of the mode of the existing descriptor.
1735 */
1736 if (((flags & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
1737 error = EACCES;
1738 goto out;
1739 }
1740
1741 /* Copy it. */
1742 error = fd_dup(fp, 0, newp, ff->ff_exclose);
1743 } else {
1744 /* Copy it. */
1745 error = fd_dup(fp, 0, newp, ff->ff_exclose);
1746 if (error != 0) {
1747 goto out;
1748 }
1749
1750 /* Steal away the file pointer from 'old'. */
1751 (void)fd_close(old);
1752 return 0;
1753 }
1754
1755 out:
1756 fd_putfile(old);
1757 return error;
1758 }
1759
1760 /*
1761 * Close open files on exec.
1762 */
1763 void
1764 fd_closeexec(void)
1765 {
1766 proc_t *p;
1767 filedesc_t *fdp;
1768 fdfile_t *ff;
1769 lwp_t *l;
1770 fdtab_t *dt;
1771 int fd;
1772
1773 l = curlwp;
1774 p = l->l_proc;
1775 fdp = p->p_fd;
1776
1777 if (fdp->fd_refcnt > 1) {
1778 fdp = fd_copy();
1779 fd_free();
1780 p->p_fd = fdp;
1781 l->l_fd = fdp;
1782 }
1783 if (!fdp->fd_exclose) {
1784 return;
1785 }
1786 fdp->fd_exclose = false;
1787 dt = atomic_load_consume(&fdp->fd_dt);
1788
1789 for (fd = 0; fd <= fdp->fd_lastfile; fd++) {
1790 if ((ff = dt->dt_ff[fd]) == NULL) {
1791 KASSERT(fd >= NDFDFILE);
1792 continue;
1793 }
1794 KASSERT(fd >= NDFDFILE ||
1795 ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
1796 if (ff->ff_file == NULL)
1797 continue;
1798 if (ff->ff_exclose) {
1799 /*
1800 * We need a reference to close the file.
1801 * No other threads can see the fdfile_t at
1802 * this point, so don't bother locking.
1803 */
1804 KASSERT((ff->ff_refcnt & FR_CLOSING) == 0);
1805 ff->ff_refcnt++;
1806 fd_close(fd);
1807 }
1808 }
1809 }
1810
1811 /*
1812 * Sets descriptor owner. If the owner is a process, 'pgid'
1813 * is set to positive value, process ID. If the owner is process group,
1814 * 'pgid' is set to -pg_id.
1815 */
1816 int
1817 fsetown(pid_t *pgid, u_long cmd, const void *data)
1818 {
1819 pid_t id = *(const pid_t *)data;
1820 int error;
1821
1822 if (id <= INT_MIN)
1823 return EINVAL;
1824
1825 switch (cmd) {
1826 case TIOCSPGRP:
1827 if (id < 0)
1828 return EINVAL;
1829 id = -id;
1830 break;
1831 default:
1832 break;
1833 }
1834 if (id > 0) {
1835 mutex_enter(&proc_lock);
1836 error = proc_find(id) ? 0 : ESRCH;
1837 mutex_exit(&proc_lock);
1838 } else if (id < 0) {
1839 error = pgid_in_session(curproc, -id);
1840 } else {
1841 error = 0;
1842 }
1843 if (!error) {
1844 *pgid = id;
1845 }
1846 return error;
1847 }
1848
1849 void
1850 fd_set_exclose(struct lwp *l, int fd, bool exclose)
1851 {
1852 filedesc_t *fdp = l->l_fd;
1853 fdfile_t *ff = atomic_load_consume(&fdp->fd_dt)->dt_ff[fd];
1854
1855 ff->ff_exclose = exclose;
1856 if (exclose)
1857 fdp->fd_exclose = true;
1858 }
1859
1860 /*
1861 * Return descriptor owner information. If the value is positive,
1862 * it's process ID. If it's negative, it's process group ID and
1863 * needs the sign removed before use.
1864 */
1865 int
1866 fgetown(pid_t pgid, u_long cmd, void *data)
1867 {
1868
1869 switch (cmd) {
1870 case TIOCGPGRP:
1871 KASSERT(pgid > INT_MIN);
1872 *(int *)data = -pgid;
1873 break;
1874 default:
1875 *(int *)data = pgid;
1876 break;
1877 }
1878 return 0;
1879 }
1880
1881 /*
1882 * Send signal to descriptor owner, either process or process group.
1883 */
1884 void
1885 fownsignal(pid_t pgid, int signo, int code, int band, void *fdescdata)
1886 {
1887 ksiginfo_t ksi;
1888
1889 KASSERT(!cpu_intr_p());
1890
1891 if (pgid == 0) {
1892 return;
1893 }
1894
1895 KSI_INIT(&ksi);
1896 ksi.ksi_signo = signo;
1897 ksi.ksi_code = code;
1898 ksi.ksi_band = band;
1899
1900 mutex_enter(&proc_lock);
1901 if (pgid > 0) {
1902 struct proc *p1;
1903
1904 p1 = proc_find(pgid);
1905 if (p1 != NULL) {
1906 kpsignal(p1, &ksi, fdescdata);
1907 }
1908 } else {
1909 struct pgrp *pgrp;
1910
1911 KASSERT(pgid < 0 && pgid > INT_MIN);
1912 pgrp = pgrp_find(-pgid);
1913 if (pgrp != NULL) {
1914 kpgsignal(pgrp, &ksi, fdescdata, 0);
1915 }
1916 }
1917 mutex_exit(&proc_lock);
1918 }
1919
1920 int
1921 fd_clone(file_t *fp, unsigned fd, int flag, const struct fileops *fops,
1922 void *data)
1923 {
1924 fdfile_t *ff;
1925 filedesc_t *fdp;
1926
1927 fp->f_flag = flag & FMASK;
1928 fdp = curproc->p_fd;
1929 ff = atomic_load_consume(&fdp->fd_dt)->dt_ff[fd];
1930 KASSERT(ff != NULL);
1931 ff->ff_exclose = (flag & O_CLOEXEC) != 0;
1932 fp->f_type = DTYPE_MISC;
1933 fp->f_ops = fops;
1934 fp->f_data = data;
1935 curlwp->l_dupfd = fd;
1936 fd_affix(curproc, fp, fd);
1937
1938 return EMOVEFD;
1939 }
1940
1941 int
1942 fnullop_fcntl(file_t *fp, u_int cmd, void *data)
1943 {
1944
1945 if (cmd == F_SETFL)
1946 return 0;
1947
1948 return EOPNOTSUPP;
1949 }
1950
1951 int
1952 fnullop_poll(file_t *fp, int which)
1953 {
1954
1955 return 0;
1956 }
1957
1958 int
1959 fnullop_kqfilter(file_t *fp, struct knote *kn)
1960 {
1961
1962 return EOPNOTSUPP;
1963 }
1964
1965 void
1966 fnullop_restart(file_t *fp)
1967 {
1968
1969 }
1970
1971 int
1972 fbadop_read(file_t *fp, off_t *offset, struct uio *uio,
1973 kauth_cred_t cred, int flags)
1974 {
1975
1976 return EOPNOTSUPP;
1977 }
1978
1979 int
1980 fbadop_write(file_t *fp, off_t *offset, struct uio *uio,
1981 kauth_cred_t cred, int flags)
1982 {
1983
1984 return EOPNOTSUPP;
1985 }
1986
1987 int
1988 fbadop_ioctl(file_t *fp, u_long com, void *data)
1989 {
1990
1991 return EOPNOTSUPP;
1992 }
1993
1994 int
1995 fbadop_stat(file_t *fp, struct stat *sb)
1996 {
1997
1998 return EOPNOTSUPP;
1999 }
2000
2001 int
2002 fbadop_close(file_t *fp)
2003 {
2004
2005 return EOPNOTSUPP;
2006 }
2007
2008 /*
2009 * sysctl routines pertaining to file descriptors
2010 */
2011
2012 /* Initialized in sysctl_init() for now... */
2013 extern kmutex_t sysctl_file_marker_lock;
2014 static u_int sysctl_file_marker = 1;
2015
2016 /*
2017 * Expects to be called with proc_lock and sysctl_file_marker_lock locked.
2018 */
2019 static void
2020 sysctl_file_marker_reset(void)
2021 {
2022 struct proc *p;
2023
2024 PROCLIST_FOREACH(p, &allproc) {
2025 struct filedesc *fd = p->p_fd;
2026 fdtab_t *dt;
2027 u_int i;
2028
2029 mutex_enter(&fd->fd_lock);
2030 dt = fd->fd_dt;
2031 for (i = 0; i < dt->dt_nfiles; i++) {
2032 struct file *fp;
2033 fdfile_t *ff;
2034
2035 if ((ff = dt->dt_ff[i]) == NULL) {
2036 continue;
2037 }
2038 if ((fp = atomic_load_consume(&ff->ff_file)) == NULL) {
2039 continue;
2040 }
2041 fp->f_marker = 0;
2042 }
2043 mutex_exit(&fd->fd_lock);
2044 }
2045 }
2046
2047 /*
2048 * sysctl helper routine for kern.file pseudo-subtree.
2049 */
2050 static int
2051 sysctl_kern_file(SYSCTLFN_ARGS)
2052 {
2053 const bool allowaddr = get_expose_address(curproc);
2054 struct filelist flist;
2055 int error;
2056 size_t buflen;
2057 struct file *fp, fbuf;
2058 char *start, *where;
2059 struct proc *p;
2060
2061 start = where = oldp;
2062 buflen = *oldlenp;
2063
2064 if (where == NULL) {
2065 /*
2066 * overestimate by 10 files
2067 */
2068 *oldlenp = sizeof(filehead) + (nfiles + 10) *
2069 sizeof(struct file);
2070 return 0;
2071 }
2072
2073 /*
2074 * first sysctl_copyout filehead
2075 */
2076 if (buflen < sizeof(filehead)) {
2077 *oldlenp = 0;
2078 return 0;
2079 }
2080 sysctl_unlock();
2081 if (allowaddr) {
2082 memcpy(&flist, &filehead, sizeof(flist));
2083 } else {
2084 memset(&flist, 0, sizeof(flist));
2085 }
2086 error = sysctl_copyout(l, &flist, where, sizeof(flist));
2087 if (error) {
2088 sysctl_relock();
2089 return error;
2090 }
2091 buflen -= sizeof(flist);
2092 where += sizeof(flist);
2093
2094 /*
2095 * followed by an array of file structures
2096 */
2097 mutex_enter(&sysctl_file_marker_lock);
2098 mutex_enter(&proc_lock);
2099 PROCLIST_FOREACH(p, &allproc) {
2100 struct filedesc *fd;
2101 fdtab_t *dt;
2102 u_int i;
2103
2104 if (p->p_stat == SIDL) {
2105 /* skip embryonic processes */
2106 continue;
2107 }
2108 mutex_enter(p->p_lock);
2109 error = kauth_authorize_process(l->l_cred,
2110 KAUTH_PROCESS_CANSEE, p,
2111 KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_OPENFILES),
2112 NULL, NULL);
2113 mutex_exit(p->p_lock);
2114 if (error != 0) {
2115 /*
2116 * Don't leak kauth retval if we're silently
2117 * skipping this entry.
2118 */
2119 error = 0;
2120 continue;
2121 }
2122
2123 /*
2124 * Grab a hold on the process.
2125 */
2126 if (!rw_tryenter(&p->p_reflock, RW_READER)) {
2127 continue;
2128 }
2129 mutex_exit(&proc_lock);
2130
2131 fd = p->p_fd;
2132 mutex_enter(&fd->fd_lock);
2133 dt = fd->fd_dt;
2134 for (i = 0; i < dt->dt_nfiles; i++) {
2135 fdfile_t *ff;
2136
2137 if ((ff = dt->dt_ff[i]) == NULL) {
2138 continue;
2139 }
2140 if ((fp = atomic_load_consume(&ff->ff_file)) == NULL) {
2141 continue;
2142 }
2143
2144 mutex_enter(&fp->f_lock);
2145
2146 if ((fp->f_count == 0) ||
2147 (fp->f_marker == sysctl_file_marker)) {
2148 mutex_exit(&fp->f_lock);
2149 continue;
2150 }
2151
2152 /* Check that we have enough space. */
2153 if (buflen < sizeof(struct file)) {
2154 *oldlenp = where - start;
2155 mutex_exit(&fp->f_lock);
2156 error = ENOMEM;
2157 break;
2158 }
2159
2160 fill_file(&fbuf, fp);
2161 mutex_exit(&fp->f_lock);
2162 error = sysctl_copyout(l, &fbuf, where, sizeof(fbuf));
2163 if (error) {
2164 break;
2165 }
2166 buflen -= sizeof(struct file);
2167 where += sizeof(struct file);
2168
2169 fp->f_marker = sysctl_file_marker;
2170 }
2171 mutex_exit(&fd->fd_lock);
2172
2173 /*
2174 * Release reference to process.
2175 */
2176 mutex_enter(&proc_lock);
2177 rw_exit(&p->p_reflock);
2178
2179 if (error)
2180 break;
2181 }
2182
2183 sysctl_file_marker++;
2184 /* Reset all markers if wrapped. */
2185 if (sysctl_file_marker == 0) {
2186 sysctl_file_marker_reset();
2187 sysctl_file_marker++;
2188 }
2189
2190 mutex_exit(&proc_lock);
2191 mutex_exit(&sysctl_file_marker_lock);
2192
2193 *oldlenp = where - start;
2194 sysctl_relock();
2195 return error;
2196 }
2197
2198 /*
2199 * sysctl helper function for kern.file2
2200 */
2201 static int
2202 sysctl_kern_file2(SYSCTLFN_ARGS)
2203 {
2204 struct proc *p;
2205 struct file *fp;
2206 struct filedesc *fd;
2207 struct kinfo_file kf;
2208 char *dp;
2209 u_int i, op;
2210 size_t len, needed, elem_size, out_size;
2211 int error, arg, elem_count;
2212 fdfile_t *ff;
2213 fdtab_t *dt;
2214
2215 if (namelen == 1 && name[0] == CTL_QUERY)
2216 return sysctl_query(SYSCTLFN_CALL(rnode));
2217
2218 if (namelen != 4)
2219 return EINVAL;
2220
2221 error = 0;
2222 dp = oldp;
2223 len = (oldp != NULL) ? *oldlenp : 0;
2224 op = name[0];
2225 arg = name[1];
2226 elem_size = name[2];
2227 elem_count = name[3];
2228 out_size = MIN(sizeof(kf), elem_size);
2229 needed = 0;
2230
2231 if (elem_size < 1 || elem_count < 0)
2232 return EINVAL;
2233
2234 switch (op) {
2235 case KERN_FILE_BYFILE:
2236 case KERN_FILE_BYPID:
2237 /*
2238 * We're traversing the process list in both cases; the BYFILE
2239 * case does additional work of keeping track of files already
2240 * looked at.
2241 */
2242
2243 /* doesn't use arg so it must be zero */
2244 if ((op == KERN_FILE_BYFILE) && (arg != 0))
2245 return EINVAL;
2246
2247 if ((op == KERN_FILE_BYPID) && (arg < -1))
2248 /* -1 means all processes */
2249 return EINVAL;
2250
2251 sysctl_unlock();
2252 if (op == KERN_FILE_BYFILE)
2253 mutex_enter(&sysctl_file_marker_lock);
2254 mutex_enter(&proc_lock);
2255 PROCLIST_FOREACH(p, &allproc) {
2256 if (p->p_stat == SIDL) {
2257 /* skip embryonic processes */
2258 continue;
2259 }
2260 if (arg > 0 && p->p_pid != arg) {
2261 /* pick only the one we want */
2262 /* XXX want 0 to mean "kernel files" */
2263 continue;
2264 }
2265 mutex_enter(p->p_lock);
2266 error = kauth_authorize_process(l->l_cred,
2267 KAUTH_PROCESS_CANSEE, p,
2268 KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_OPENFILES),
2269 NULL, NULL);
2270 mutex_exit(p->p_lock);
2271 if (error != 0) {
2272 /*
2273 * Don't leak kauth retval if we're silently
2274 * skipping this entry.
2275 */
2276 error = 0;
2277 continue;
2278 }
2279
2280 /*
2281 * Grab a hold on the process.
2282 */
2283 if (!rw_tryenter(&p->p_reflock, RW_READER)) {
2284 continue;
2285 }
2286 mutex_exit(&proc_lock);
2287
2288 fd = p->p_fd;
2289 mutex_enter(&fd->fd_lock);
2290 dt = fd->fd_dt;
2291 for (i = 0; i < dt->dt_nfiles; i++) {
2292 if ((ff = dt->dt_ff[i]) == NULL) {
2293 continue;
2294 }
2295 if ((fp = atomic_load_consume(&ff->ff_file)) ==
2296 NULL) {
2297 continue;
2298 }
2299
2300 if ((op == KERN_FILE_BYFILE) &&
2301 (fp->f_marker == sysctl_file_marker)) {
2302 continue;
2303 }
2304 if (len >= elem_size && elem_count > 0) {
2305 mutex_enter(&fp->f_lock);
2306 fill_file2(&kf, fp, ff, i, p->p_pid);
2307 mutex_exit(&fp->f_lock);
2308 mutex_exit(&fd->fd_lock);
2309 error = sysctl_copyout(l,
2310 &kf, dp, out_size);
2311 mutex_enter(&fd->fd_lock);
2312 if (error)
2313 break;
2314 dp += elem_size;
2315 len -= elem_size;
2316 }
2317 if (op == KERN_FILE_BYFILE)
2318 fp->f_marker = sysctl_file_marker;
2319 needed += elem_size;
2320 if (elem_count > 0 && elem_count != INT_MAX)
2321 elem_count--;
2322 }
2323 mutex_exit(&fd->fd_lock);
2324
2325 /*
2326 * Release reference to process.
2327 */
2328 mutex_enter(&proc_lock);
2329 rw_exit(&p->p_reflock);
2330 }
2331 if (op == KERN_FILE_BYFILE) {
2332 sysctl_file_marker++;
2333
2334 /* Reset all markers if wrapped. */
2335 if (sysctl_file_marker == 0) {
2336 sysctl_file_marker_reset();
2337 sysctl_file_marker++;
2338 }
2339 }
2340 mutex_exit(&proc_lock);
2341 if (op == KERN_FILE_BYFILE)
2342 mutex_exit(&sysctl_file_marker_lock);
2343 sysctl_relock();
2344 break;
2345 default:
2346 return EINVAL;
2347 }
2348
2349 if (oldp == NULL)
2350 needed += KERN_FILESLOP * elem_size;
2351 *oldlenp = needed;
2352
2353 return error;
2354 }
2355
2356 static void
2357 fill_file(struct file *fp, const struct file *fpsrc)
2358 {
2359 const bool allowaddr = get_expose_address(curproc);
2360
2361 memset(fp, 0, sizeof(*fp));
2362
2363 fp->f_offset = fpsrc->f_offset;
2364 COND_SET_PTR(fp->f_cred, fpsrc->f_cred, allowaddr);
2365 COND_SET_CPTR(fp->f_ops, fpsrc->f_ops, allowaddr);
2366 COND_SET_STRUCT(fp->f_undata, fpsrc->f_undata, allowaddr);
2367 COND_SET_STRUCT(fp->f_list, fpsrc->f_list, allowaddr);
2368 fp->f_flag = fpsrc->f_flag;
2369 fp->f_marker = fpsrc->f_marker;
2370 fp->f_type = fpsrc->f_type;
2371 fp->f_advice = fpsrc->f_advice;
2372 fp->f_count = fpsrc->f_count;
2373 fp->f_msgcount = fpsrc->f_msgcount;
2374 fp->f_unpcount = fpsrc->f_unpcount;
2375 COND_SET_STRUCT(fp->f_unplist, fpsrc->f_unplist, allowaddr);
2376 }
2377
2378 static void
2379 fill_file2(struct kinfo_file *kp, const file_t *fp, const fdfile_t *ff,
2380 int i, pid_t pid)
2381 {
2382 const bool allowaddr = get_expose_address(curproc);
2383
2384 memset(kp, 0, sizeof(*kp));
2385
2386 COND_SET_VALUE(kp->ki_fileaddr, PTRTOUINT64(fp), allowaddr);
2387 kp->ki_flag = fp->f_flag;
2388 kp->ki_iflags = 0;
2389 kp->ki_ftype = fp->f_type;
2390 kp->ki_count = fp->f_count;
2391 kp->ki_msgcount = fp->f_msgcount;
2392 COND_SET_VALUE(kp->ki_fucred, PTRTOUINT64(fp->f_cred), allowaddr);
2393 kp->ki_fuid = kauth_cred_geteuid(fp->f_cred);
2394 kp->ki_fgid = kauth_cred_getegid(fp->f_cred);
2395 COND_SET_VALUE(kp->ki_fops, PTRTOUINT64(fp->f_ops), allowaddr);
2396 kp->ki_foffset = fp->f_offset;
2397 COND_SET_VALUE(kp->ki_fdata, PTRTOUINT64(fp->f_data), allowaddr);
2398
2399 /* vnode information to glue this file to something */
2400 if (fp->f_type == DTYPE_VNODE) {
2401 struct vnode *vp = fp->f_vnode;
2402
2403 COND_SET_VALUE(kp->ki_vun, PTRTOUINT64(vp->v_un.vu_socket),
2404 allowaddr);
2405 kp->ki_vsize = vp->v_size;
2406 kp->ki_vtype = vp->v_type;
2407 kp->ki_vtag = vp->v_tag;
2408 COND_SET_VALUE(kp->ki_vdata, PTRTOUINT64(vp->v_data),
2409 allowaddr);
2410 }
2411
2412 /* process information when retrieved via KERN_FILE_BYPID */
2413 if (ff != NULL) {
2414 kp->ki_pid = pid;
2415 kp->ki_fd = i;
2416 kp->ki_ofileflags = ff->ff_exclose;
2417 kp->ki_usecount = ff->ff_refcnt;
2418 }
2419 }
2420