kern_descrip.c revision 1.182.6.2 1 /* $NetBSD: kern_descrip.c,v 1.182.6.2 2009/03/02 20:56:14 snj Exp $ */
2
3 /*-
4 * Copyright (c) 2008 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
17 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
18 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
20 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 * POSSIBILITY OF SUCH DAMAGE.
27 */
28
29 /*
30 * Copyright (c) 1982, 1986, 1989, 1991, 1993
31 * The Regents of the University of California. All rights reserved.
32 * (c) UNIX System Laboratories, Inc.
33 * All or some portions of this file are derived from material licensed
34 * to the University of California by American Telephone and Telegraph
35 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
36 * the permission of UNIX System Laboratories, Inc.
37 *
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
40 * are met:
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. Neither the name of the University nor the names of its contributors
47 * may be used to endorse or promote products derived from this software
48 * without specific prior written permission.
49 *
50 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60 * SUCH DAMAGE.
61 *
62 * @(#)kern_descrip.c 8.8 (Berkeley) 2/14/95
63 */
64
65 /*
66 * File descriptor management.
67 */
68
69 #include <sys/cdefs.h>
70 __KERNEL_RCSID(0, "$NetBSD: kern_descrip.c,v 1.182.6.2 2009/03/02 20:56:14 snj Exp $");
71
72 #include <sys/param.h>
73 #include <sys/systm.h>
74 #include <sys/filedesc.h>
75 #include <sys/kernel.h>
76 #include <sys/vnode.h>
77 #include <sys/proc.h>
78 #include <sys/file.h>
79 #include <sys/namei.h>
80 #include <sys/socket.h>
81 #include <sys/socketvar.h>
82 #include <sys/stat.h>
83 #include <sys/ioctl.h>
84 #include <sys/fcntl.h>
85 #include <sys/pool.h>
86 #include <sys/syslog.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/mount.h>
94 #include <sys/syscallargs.h>
95 #include <sys/cpu.h>
96
97 static int cwdi_ctor(void *, void *, int);
98 static void cwdi_dtor(void *, void *);
99 static int file_ctor(void *, void *, int);
100 static void file_dtor(void *, void *);
101 static int fdfile_ctor(void *, void *, int);
102 static void fdfile_dtor(void *, void *);
103 static int filedesc_ctor(void *, void *, int);
104 static void filedesc_dtor(void *, void *);
105 static int filedescopen(dev_t, int, int, lwp_t *);
106
107 kmutex_t filelist_lock; /* lock on filehead */
108 struct filelist filehead; /* head of list of open files */
109 u_int nfiles; /* actual number of open files */
110
111 static pool_cache_t cwdi_cache;
112 static pool_cache_t filedesc_cache;
113 static pool_cache_t file_cache;
114 static pool_cache_t fdfile_cache;
115
116 const struct cdevsw filedesc_cdevsw = {
117 filedescopen, noclose, noread, nowrite, noioctl,
118 nostop, notty, nopoll, nommap, nokqfilter, D_OTHER | D_MPSAFE,
119 };
120
121 /* For ease of reading. */
122 __strong_alias(fd_putvnode,fd_putfile)
123 __strong_alias(fd_putsock,fd_putfile)
124
125 /*
126 * Initialize the descriptor system.
127 */
128 void
129 fd_sys_init(void)
130 {
131
132 mutex_init(&filelist_lock, MUTEX_DEFAULT, IPL_NONE);
133
134 file_cache = pool_cache_init(sizeof(file_t), coherency_unit, 0,
135 0, "file", NULL, IPL_NONE, file_ctor, file_dtor, NULL);
136 KASSERT(file_cache != NULL);
137
138 fdfile_cache = pool_cache_init(sizeof(fdfile_t), coherency_unit, 0,
139 PR_LARGECACHE, "fdfile", NULL, IPL_NONE, fdfile_ctor, fdfile_dtor,
140 NULL);
141 KASSERT(fdfile_cache != NULL);
142
143 cwdi_cache = pool_cache_init(sizeof(struct cwdinfo), coherency_unit,
144 0, 0, "cwdi", NULL, IPL_NONE, cwdi_ctor, cwdi_dtor, NULL);
145 KASSERT(cwdi_cache != NULL);
146
147 filedesc_cache = pool_cache_init(sizeof(filedesc_t), coherency_unit,
148 0, 0, "filedesc", NULL, IPL_NONE, filedesc_ctor, filedesc_dtor,
149 NULL);
150 KASSERT(filedesc_cache != NULL);
151 }
152
153 static int
154 fd_next_zero(filedesc_t *fdp, uint32_t *bitmap, int want, u_int bits)
155 {
156 int i, off, maxoff;
157 uint32_t sub;
158
159 KASSERT(mutex_owned(&fdp->fd_lock));
160
161 if (want > bits)
162 return -1;
163
164 off = want >> NDENTRYSHIFT;
165 i = want & NDENTRYMASK;
166 if (i) {
167 sub = bitmap[off] | ((u_int)~0 >> (NDENTRIES - i));
168 if (sub != ~0)
169 goto found;
170 off++;
171 }
172
173 maxoff = NDLOSLOTS(bits);
174 while (off < maxoff) {
175 if ((sub = bitmap[off]) != ~0)
176 goto found;
177 off++;
178 }
179
180 return (-1);
181
182 found:
183 return (off << NDENTRYSHIFT) + ffs(~sub) - 1;
184 }
185
186 static int
187 fd_last_set(filedesc_t *fd, int last)
188 {
189 int off, i;
190 fdfile_t **ofiles = fd->fd_ofiles;
191 uint32_t *bitmap = fd->fd_lomap;
192
193 KASSERT(mutex_owned(&fd->fd_lock));
194
195 off = (last - 1) >> NDENTRYSHIFT;
196
197 while (off >= 0 && !bitmap[off])
198 off--;
199
200 if (off < 0)
201 return (-1);
202
203 i = ((off + 1) << NDENTRYSHIFT) - 1;
204 if (i >= last)
205 i = last - 1;
206
207 /* XXX should use bitmap */
208 /* XXXAD does not work for fd_copy() */
209 while (i > 0 && (ofiles[i] == NULL || !ofiles[i]->ff_allocated))
210 i--;
211
212 return (i);
213 }
214
215 void
216 fd_used(filedesc_t *fdp, unsigned fd)
217 {
218 u_int off = fd >> NDENTRYSHIFT;
219 fdfile_t *ff;
220
221 ff = fdp->fd_ofiles[fd];
222
223 KASSERT(mutex_owned(&fdp->fd_lock));
224 KASSERT((fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) == 0);
225 KASSERT(ff != NULL);
226 KASSERT(ff->ff_file == NULL);
227 KASSERT(!ff->ff_allocated);
228
229 ff->ff_allocated = 1;
230 fdp->fd_lomap[off] |= 1 << (fd & NDENTRYMASK);
231 if (fdp->fd_lomap[off] == ~0) {
232 KASSERT((fdp->fd_himap[off >> NDENTRYSHIFT] &
233 (1 << (off & NDENTRYMASK))) == 0);
234 fdp->fd_himap[off >> NDENTRYSHIFT] |= 1 << (off & NDENTRYMASK);
235 }
236
237 if ((int)fd > fdp->fd_lastfile) {
238 fdp->fd_lastfile = fd;
239 }
240
241 if (fd >= NDFDFILE) {
242 fdp->fd_nused++;
243 } else {
244 KASSERT(ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
245 }
246 }
247
248 void
249 fd_unused(filedesc_t *fdp, unsigned fd)
250 {
251 u_int off = fd >> NDENTRYSHIFT;
252 fdfile_t *ff;
253
254 ff = fdp->fd_ofiles[fd];
255
256 /*
257 * Don't assert the lock is held here, as we may be copying
258 * the table during exec() and it is not needed there.
259 * procfs and sysctl are locked out by proc::p_reflock.
260 *
261 * KASSERT(mutex_owned(&fdp->fd_lock));
262 */
263 KASSERT(ff != NULL);
264 KASSERT(ff->ff_file == NULL);
265 KASSERT(ff->ff_allocated);
266
267 if (fd < fdp->fd_freefile) {
268 fdp->fd_freefile = fd;
269 }
270
271 if (fdp->fd_lomap[off] == ~0) {
272 KASSERT((fdp->fd_himap[off >> NDENTRYSHIFT] &
273 (1 << (off & NDENTRYMASK))) != 0);
274 fdp->fd_himap[off >> NDENTRYSHIFT] &=
275 ~(1 << (off & NDENTRYMASK));
276 }
277 KASSERT((fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) != 0);
278 fdp->fd_lomap[off] &= ~(1 << (fd & NDENTRYMASK));
279 ff->ff_allocated = 0;
280
281 KASSERT(fd <= fdp->fd_lastfile);
282 if (fd == fdp->fd_lastfile) {
283 fdp->fd_lastfile = fd_last_set(fdp, fd);
284 }
285
286 if (fd >= NDFDFILE) {
287 KASSERT(fdp->fd_nused > 0);
288 fdp->fd_nused--;
289 } else {
290 KASSERT(ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
291 }
292 }
293
294 /*
295 * Custom version of fd_unused() for fd_copy(), where the descriptor
296 * table is not yet fully initialized.
297 */
298 static inline void
299 fd_zap(filedesc_t *fdp, unsigned fd)
300 {
301 u_int off = fd >> NDENTRYSHIFT;
302
303 if (fd < fdp->fd_freefile) {
304 fdp->fd_freefile = fd;
305 }
306
307 if (fdp->fd_lomap[off] == ~0) {
308 KASSERT((fdp->fd_himap[off >> NDENTRYSHIFT] &
309 (1 << (off & NDENTRYMASK))) != 0);
310 fdp->fd_himap[off >> NDENTRYSHIFT] &=
311 ~(1 << (off & NDENTRYMASK));
312 }
313 KASSERT((fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) != 0);
314 fdp->fd_lomap[off] &= ~(1 << (fd & NDENTRYMASK));
315 }
316
317 bool
318 fd_isused(filedesc_t *fdp, unsigned fd)
319 {
320 u_int off = fd >> NDENTRYSHIFT;
321
322 KASSERT(fd < fdp->fd_nfiles);
323
324 return (fdp->fd_lomap[off] & (1 << (fd & NDENTRYMASK))) != 0;
325 }
326
327 /*
328 * Look up the file structure corresponding to a file descriptor
329 * and return the file, holding a reference on the descriptor.
330 */
331 inline file_t *
332 fd_getfile(unsigned fd)
333 {
334 filedesc_t *fdp;
335 fdfile_t *ff;
336 file_t *fp;
337
338 fdp = curlwp->l_fd;
339
340 /*
341 * Look up the fdfile structure representing this descriptor.
342 * Ensure that we see fd_nfiles before fd_ofiles since we
343 * are doing this unlocked. See fd_tryexpand().
344 */
345 if (__predict_false(fd >= fdp->fd_nfiles)) {
346 return NULL;
347 }
348 membar_consumer();
349 ff = fdp->fd_ofiles[fd];
350 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
351 if (__predict_false(ff == NULL)) {
352 return NULL;
353 }
354
355 /*
356 * Now get a reference to the descriptor. Issue a memory
357 * barrier to ensure that we acquire the file pointer _after_
358 * adding a reference. If no memory barrier, we could fetch
359 * a stale pointer.
360 */
361 atomic_inc_uint(&ff->ff_refcnt);
362 #ifndef __HAVE_ATOMIC_AS_MEMBAR
363 membar_enter();
364 #endif
365
366 /*
367 * If the file is not open or is being closed then put the
368 * reference back.
369 */
370 fp = ff->ff_file;
371 if (__predict_true(fp != NULL)) {
372 return fp;
373 }
374 fd_putfile(fd);
375 return NULL;
376 }
377
378 /*
379 * Release a reference to a file descriptor acquired with fd_getfile().
380 */
381 void
382 fd_putfile(unsigned fd)
383 {
384 filedesc_t *fdp;
385 fdfile_t *ff;
386 u_int u, v;
387
388 fdp = curlwp->l_fd;
389 ff = fdp->fd_ofiles[fd];
390
391 KASSERT(fd < fdp->fd_nfiles);
392 KASSERT(ff != NULL);
393 KASSERT((ff->ff_refcnt & FR_MASK) > 0);
394 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
395
396 /*
397 * Ensure that any use of the file is complete and globally
398 * visible before dropping the final reference. If no membar,
399 * the current CPU could still access memory associated with
400 * the file after it has been freed or recycled by another
401 * CPU.
402 */
403 #ifndef __HAVE_ATOMIC_AS_MEMBAR
404 membar_exit();
405 #endif
406
407 /*
408 * Be optimistic and start out with the assumption that no other
409 * threads are trying to close the descriptor. If the CAS fails,
410 * we lost a race and/or it's being closed.
411 */
412 for (u = ff->ff_refcnt & FR_MASK;; u = v) {
413 v = atomic_cas_uint(&ff->ff_refcnt, u, u - 1);
414 if (__predict_true(u == v)) {
415 return;
416 }
417 if (__predict_false((v & FR_CLOSING) != 0)) {
418 break;
419 }
420 }
421
422 /* Another thread is waiting to close the file: join it. */
423 (void)fd_close(fd);
424 }
425
426 /*
427 * Convenience wrapper around fd_getfile() that returns reference
428 * to a vnode.
429 */
430 int
431 fd_getvnode(unsigned fd, file_t **fpp)
432 {
433 vnode_t *vp;
434 file_t *fp;
435
436 fp = fd_getfile(fd);
437 if (__predict_false(fp == NULL)) {
438 return EBADF;
439 }
440 if (__predict_false(fp->f_type != DTYPE_VNODE)) {
441 fd_putfile(fd);
442 return EINVAL;
443 }
444 vp = fp->f_data;
445 if (__predict_false(vp->v_type == VBAD)) {
446 /* XXX Is this case really necessary? */
447 fd_putfile(fd);
448 return EBADF;
449 }
450 *fpp = fp;
451 return 0;
452 }
453
454 /*
455 * Convenience wrapper around fd_getfile() that returns reference
456 * to a socket.
457 */
458 int
459 fd_getsock(unsigned fd, struct socket **sop)
460 {
461 file_t *fp;
462
463 fp = fd_getfile(fd);
464 if (__predict_false(fp == NULL)) {
465 return EBADF;
466 }
467 if (__predict_false(fp->f_type != DTYPE_SOCKET)) {
468 fd_putfile(fd);
469 return ENOTSOCK;
470 }
471 *sop = fp->f_data;
472 return 0;
473 }
474
475 /*
476 * Look up the file structure corresponding to a file descriptor
477 * and return it with a reference held on the file, not the
478 * descriptor.
479 *
480 * This is heavyweight and only used when accessing descriptors
481 * from a foreign process. The caller must ensure that `p' does
482 * not exit or fork across this call.
483 *
484 * To release the file (not descriptor) reference, use closef().
485 */
486 file_t *
487 fd_getfile2(proc_t *p, unsigned fd)
488 {
489 filedesc_t *fdp;
490 fdfile_t *ff;
491 file_t *fp;
492
493 fdp = p->p_fd;
494 mutex_enter(&fdp->fd_lock);
495 if (fd > fdp->fd_nfiles) {
496 mutex_exit(&fdp->fd_lock);
497 return NULL;
498 }
499 if ((ff = fdp->fd_ofiles[fd]) == NULL) {
500 mutex_exit(&fdp->fd_lock);
501 return NULL;
502 }
503 mutex_enter(&ff->ff_lock);
504 if ((fp = ff->ff_file) == NULL) {
505 mutex_exit(&ff->ff_lock);
506 mutex_exit(&fdp->fd_lock);
507 return NULL;
508 }
509 mutex_enter(&fp->f_lock);
510 fp->f_count++;
511 mutex_exit(&fp->f_lock);
512 mutex_exit(&ff->ff_lock);
513 mutex_exit(&fdp->fd_lock);
514
515 return fp;
516 }
517
518 /*
519 * Internal form of close. Must be called with a reference to the
520 * descriptor, and will drop the reference. When all descriptor
521 * references are dropped, releases the descriptor slot and a single
522 * reference to the file structure.
523 */
524 int
525 fd_close(unsigned fd)
526 {
527 struct flock lf;
528 filedesc_t *fdp;
529 fdfile_t *ff;
530 file_t *fp;
531 proc_t *p;
532 lwp_t *l;
533
534 l = curlwp;
535 p = l->l_proc;
536 fdp = l->l_fd;
537 ff = fdp->fd_ofiles[fd];
538
539 KASSERT(fd >= NDFDFILE || ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
540
541 mutex_enter(&ff->ff_lock);
542 KASSERT((ff->ff_refcnt & FR_MASK) > 0);
543 if (ff->ff_file == NULL) {
544 /*
545 * Another user of the file is already closing, and is
546 * waiting for other users of the file to drain. Release
547 * our reference, and wake up the closer.
548 */
549 atomic_dec_uint(&ff->ff_refcnt);
550 cv_broadcast(&ff->ff_closing);
551 mutex_exit(&ff->ff_lock);
552
553 /*
554 * An application error, so pretend that the descriptor
555 * was already closed. We can't safely wait for it to
556 * be closed without potentially deadlocking.
557 */
558 return (EBADF);
559 }
560 KASSERT((ff->ff_refcnt & FR_CLOSING) == 0);
561
562 /*
563 * There may be multiple users of this file within the process.
564 * Notify existing and new users that the file is closing. This
565 * will prevent them from adding additional uses to this file
566 * while we are closing it.
567 */
568 fp = ff->ff_file;
569 ff->ff_file = NULL;
570 ff->ff_exclose = false;
571
572 /*
573 * We expect the caller to hold a descriptor reference - drop it.
574 * The reference count may increase beyond zero at this point due
575 * to an erroneous descriptor reference by an application, but
576 * fd_getfile() will notice that the file is being closed and drop
577 * the reference again.
578 */
579 #ifndef __HAVE_ATOMIC_AS_MEMBAR
580 membar_producer();
581 #endif
582 if (__predict_false(atomic_dec_uint_nv(&ff->ff_refcnt) != 0)) {
583 /*
584 * Wait for other references to drain. This is typically
585 * an application error - the descriptor is being closed
586 * while still in use.
587 *
588 */
589 atomic_or_uint(&ff->ff_refcnt, FR_CLOSING);
590 /*
591 * Remove any knotes attached to the file. A knote
592 * attached to the descriptor can hold references on it.
593 */
594 if (!SLIST_EMPTY(&ff->ff_knlist)) {
595 mutex_exit(&ff->ff_lock);
596 knote_fdclose(fd);
597 mutex_enter(&ff->ff_lock);
598 }
599 /*
600 * We need to see the count drop to zero at least once,
601 * in order to ensure that all pre-existing references
602 * have been drained. New references past this point are
603 * of no interest.
604 */
605 while ((ff->ff_refcnt & FR_MASK) != 0) {
606 cv_wait(&ff->ff_closing, &ff->ff_lock);
607 }
608 atomic_and_uint(&ff->ff_refcnt, ~FR_CLOSING);
609 } else {
610 /* If no references, there must be no knotes. */
611 KASSERT(SLIST_EMPTY(&ff->ff_knlist));
612 }
613 mutex_exit(&ff->ff_lock);
614
615 /*
616 * POSIX record locking dictates that any close releases ALL
617 * locks owned by this process. This is handled by setting
618 * a flag in the unlock to free ONLY locks obeying POSIX
619 * semantics, and not to free BSD-style file locks.
620 * If the descriptor was in a message, POSIX-style locks
621 * aren't passed with the descriptor.
622 */
623 if ((p->p_flag & PK_ADVLOCK) != 0 && fp->f_type == DTYPE_VNODE) {
624 lf.l_whence = SEEK_SET;
625 lf.l_start = 0;
626 lf.l_len = 0;
627 lf.l_type = F_UNLCK;
628 (void)VOP_ADVLOCK(fp->f_data, p, F_UNLCK, &lf, F_POSIX);
629 }
630
631
632 /* Free descriptor slot. */
633 mutex_enter(&fdp->fd_lock);
634 fd_unused(fdp, fd);
635 mutex_exit(&fdp->fd_lock);
636
637 /* Now drop reference to the file itself. */
638 return closef(fp);
639 }
640
641 /*
642 * Duplicate a file descriptor.
643 */
644 int
645 fd_dup(file_t *fp, int minfd, int *newp, bool exclose)
646 {
647 proc_t *p;
648 int error;
649
650 p = curproc;
651
652 while ((error = fd_alloc(p, minfd, newp)) != 0) {
653 if (error != ENOSPC) {
654 return error;
655 }
656 fd_tryexpand(p);
657 }
658
659 curlwp->l_fd->fd_ofiles[*newp]->ff_exclose = exclose;
660 fd_affix(p, fp, *newp);
661 return 0;
662 }
663
664 /*
665 * dup2 operation.
666 */
667 int
668 fd_dup2(file_t *fp, unsigned new)
669 {
670 filedesc_t *fdp;
671 fdfile_t *ff;
672
673 fdp = curlwp->l_fd;
674
675 /*
676 * Ensure there are enough slots in the descriptor table,
677 * and allocate an fdfile_t up front in case we need it.
678 */
679 while (new >= fdp->fd_nfiles) {
680 fd_tryexpand(curproc);
681 }
682 ff = pool_cache_get(fdfile_cache, PR_WAITOK);
683
684 /*
685 * If there is already a file open, close it. If the file is
686 * half open, wait for it to be constructed before closing it.
687 * XXX Potential for deadlock here?
688 */
689 mutex_enter(&fdp->fd_lock);
690 while (fd_isused(fdp, new)) {
691 mutex_exit(&fdp->fd_lock);
692 if (fd_getfile(new) != NULL) {
693 (void)fd_close(new);
694 } else {
695 /* XXX Crummy, but unlikely to happen. */
696 kpause("dup2", false, 1, NULL);
697 }
698 mutex_enter(&fdp->fd_lock);
699 }
700 if (fdp->fd_ofiles[new] == NULL) {
701 KASSERT(new >= NDFDFILE);
702 fdp->fd_ofiles[new] = ff;
703 ff = NULL;
704 }
705 fd_used(fdp, new);
706 mutex_exit(&fdp->fd_lock);
707
708 /* Slot is now allocated. Insert copy of the file. */
709 fd_affix(curproc, fp, new);
710 if (ff != NULL) {
711 pool_cache_put(fdfile_cache, ff);
712 }
713 return 0;
714 }
715
716 /*
717 * Drop reference to a file structure.
718 */
719 int
720 closef(file_t *fp)
721 {
722 struct flock lf;
723 int error;
724
725 /*
726 * Drop reference. If referenced elsewhere it's still open
727 * and we have nothing more to do.
728 */
729 mutex_enter(&fp->f_lock);
730 KASSERT(fp->f_count > 0);
731 if (--fp->f_count > 0) {
732 mutex_exit(&fp->f_lock);
733 return 0;
734 }
735 KASSERT(fp->f_count == 0);
736 mutex_exit(&fp->f_lock);
737
738 /* We held the last reference - release locks, close and free. */
739 if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
740 lf.l_whence = SEEK_SET;
741 lf.l_start = 0;
742 lf.l_len = 0;
743 lf.l_type = F_UNLCK;
744 (void)VOP_ADVLOCK(fp->f_data, fp, F_UNLCK, &lf, F_FLOCK);
745 }
746 if (fp->f_ops != NULL) {
747 error = (*fp->f_ops->fo_close)(fp);
748 } else {
749 error = 0;
750 }
751 ffree(fp);
752
753 return error;
754 }
755
756 /*
757 * Allocate a file descriptor for the process.
758 */
759 int
760 fd_alloc(proc_t *p, int want, int *result)
761 {
762 filedesc_t *fdp;
763 int i, lim, last, error;
764 u_int off, new;
765 fdfile_t *ff;
766
767 KASSERT(p == curproc || p == &proc0);
768
769 fdp = p->p_fd;
770 ff = pool_cache_get(fdfile_cache, PR_WAITOK);
771 KASSERT(ff->ff_refcnt == 0);
772 KASSERT(ff->ff_file == NULL);
773
774 /*
775 * Search for a free descriptor starting at the higher
776 * of want or fd_freefile.
777 */
778 mutex_enter(&fdp->fd_lock);
779 KASSERT(fdp->fd_ofiles[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
780 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
781 last = min(fdp->fd_nfiles, lim);
782 for (;;) {
783 if ((i = want) < fdp->fd_freefile)
784 i = fdp->fd_freefile;
785 off = i >> NDENTRYSHIFT;
786 new = fd_next_zero(fdp, fdp->fd_himap, off,
787 (last + NDENTRIES - 1) >> NDENTRYSHIFT);
788 if (new == -1)
789 break;
790 i = fd_next_zero(fdp, &fdp->fd_lomap[new],
791 new > off ? 0 : i & NDENTRYMASK, NDENTRIES);
792 if (i == -1) {
793 /*
794 * Free file descriptor in this block was
795 * below want, try again with higher want.
796 */
797 want = (new + 1) << NDENTRYSHIFT;
798 continue;
799 }
800 i += (new << NDENTRYSHIFT);
801 if (i >= last) {
802 break;
803 }
804 if (fdp->fd_ofiles[i] == NULL) {
805 KASSERT(i >= NDFDFILE);
806 fdp->fd_ofiles[i] = ff;
807 } else {
808 pool_cache_put(fdfile_cache, ff);
809 }
810 KASSERT(fdp->fd_ofiles[i]->ff_file == NULL);
811 fd_used(fdp, i);
812 if (want <= fdp->fd_freefile) {
813 fdp->fd_freefile = i;
814 }
815 *result = i;
816 mutex_exit(&fdp->fd_lock);
817 KASSERT(i >= NDFDFILE ||
818 fdp->fd_ofiles[i] == (fdfile_t *)fdp->fd_dfdfile[i]);
819 return 0;
820 }
821
822 /* No space in current array. Let the caller expand and retry. */
823 error = (fdp->fd_nfiles >= lim) ? EMFILE : ENOSPC;
824 mutex_exit(&fdp->fd_lock);
825 pool_cache_put(fdfile_cache, ff);
826 return error;
827 }
828
829 /*
830 * Allocate memory for the open files array.
831 */
832 static fdfile_t **
833 fd_ofile_alloc(int n)
834 {
835 uintptr_t *ptr, sz;
836
837 KASSERT(n > NDFILE);
838
839 sz = (n + 2) * sizeof(uintptr_t);
840 ptr = kmem_alloc((size_t)sz, KM_SLEEP);
841 ptr[1] = sz;
842
843 return (fdfile_t **)(ptr + 2);
844 }
845
846 /*
847 * Free an open files array.
848 */
849 static void
850 fd_ofile_free(int n, fdfile_t **of)
851 {
852 uintptr_t *ptr, sz;
853
854 KASSERT(n > NDFILE);
855
856 sz = (n + 2) * sizeof(uintptr_t);
857 ptr = (uintptr_t *)of - 2;
858 KASSERT(ptr[1] == sz);
859 kmem_free(ptr, sz);
860 }
861
862 /*
863 * Allocate descriptor bitmap.
864 */
865 static void
866 fd_map_alloc(int n, uint32_t **lo, uint32_t **hi)
867 {
868 uint8_t *ptr;
869 size_t szlo, szhi;
870
871 KASSERT(n > NDENTRIES);
872
873 szlo = NDLOSLOTS(n) * sizeof(uint32_t);
874 szhi = NDHISLOTS(n) * sizeof(uint32_t);
875 ptr = kmem_alloc(szlo + szhi, KM_SLEEP);
876 *lo = (uint32_t *)ptr;
877 *hi = (uint32_t *)(ptr + szlo);
878 }
879
880 /*
881 * Free descriptor bitmap.
882 */
883 static void
884 fd_map_free(int n, uint32_t *lo, uint32_t *hi)
885 {
886 size_t szlo, szhi;
887
888 KASSERT(n > NDENTRIES);
889
890 szlo = NDLOSLOTS(n) * sizeof(uint32_t);
891 szhi = NDHISLOTS(n) * sizeof(uint32_t);
892 KASSERT(hi == (uint32_t *)((uint8_t *)lo + szlo));
893 kmem_free(lo, szlo + szhi);
894 }
895
896 /*
897 * Expand a process' descriptor table.
898 */
899 void
900 fd_tryexpand(proc_t *p)
901 {
902 filedesc_t *fdp;
903 int i, numfiles, oldnfiles;
904 fdfile_t **newofile;
905 uint32_t *newhimap, *newlomap;
906
907 KASSERT(p == curproc || p == &proc0);
908
909 fdp = p->p_fd;
910 newhimap = NULL;
911 newlomap = NULL;
912 oldnfiles = fdp->fd_nfiles;
913
914 if (oldnfiles < NDEXTENT)
915 numfiles = NDEXTENT;
916 else
917 numfiles = 2 * oldnfiles;
918
919 newofile = fd_ofile_alloc(numfiles);
920 if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
921 fd_map_alloc(numfiles, &newlomap, &newhimap);
922 }
923
924 mutex_enter(&fdp->fd_lock);
925 KASSERT(fdp->fd_ofiles[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
926 if (fdp->fd_nfiles != oldnfiles) {
927 /* fdp changed; caller must retry */
928 mutex_exit(&fdp->fd_lock);
929 fd_ofile_free(numfiles, newofile);
930 if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
931 fd_map_free(numfiles, newlomap, newhimap);
932 }
933 return;
934 }
935
936 /* Copy the existing ofile array and zero the new portion. */
937 i = sizeof(fdfile_t *) * fdp->fd_nfiles;
938 memcpy(newofile, fdp->fd_ofiles, i);
939 memset((uint8_t *)newofile + i, 0, numfiles * sizeof(fdfile_t *) - i);
940
941 /*
942 * Link old ofiles array into list to be discarded. We defer
943 * freeing until process exit if the descriptor table is visble
944 * to other threads.
945 */
946 if (oldnfiles > NDFILE) {
947 if ((fdp->fd_refcnt | p->p_nlwps) > 1) {
948 fdp->fd_ofiles[-2] = (void *)fdp->fd_discard;
949 fdp->fd_discard = fdp->fd_ofiles - 2;
950 } else {
951 fd_ofile_free(oldnfiles, fdp->fd_ofiles);
952 }
953 }
954
955 if (NDHISLOTS(numfiles) > NDHISLOTS(oldnfiles)) {
956 i = NDHISLOTS(oldnfiles) * sizeof(uint32_t);
957 memcpy(newhimap, fdp->fd_himap, i);
958 memset((uint8_t *)newhimap + i, 0,
959 NDHISLOTS(numfiles) * sizeof(uint32_t) - i);
960
961 i = NDLOSLOTS(oldnfiles) * sizeof(uint32_t);
962 memcpy(newlomap, fdp->fd_lomap, i);
963 memset((uint8_t *)newlomap + i, 0,
964 NDLOSLOTS(numfiles) * sizeof(uint32_t) - i);
965
966 if (NDHISLOTS(oldnfiles) > NDHISLOTS(NDFILE)) {
967 fd_map_free(oldnfiles, fdp->fd_lomap, fdp->fd_himap);
968 }
969 fdp->fd_himap = newhimap;
970 fdp->fd_lomap = newlomap;
971 }
972
973 /*
974 * All other modifications must become globally visible before
975 * the change to fd_nfiles. See fd_getfile().
976 */
977 fdp->fd_ofiles = newofile;
978 membar_producer();
979 fdp->fd_nfiles = numfiles;
980 mutex_exit(&fdp->fd_lock);
981
982 KASSERT(fdp->fd_ofiles[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
983 }
984
985 /*
986 * Create a new open file structure and allocate a file descriptor
987 * for the current process.
988 */
989 int
990 fd_allocfile(file_t **resultfp, int *resultfd)
991 {
992 file_t *fp;
993 proc_t *p;
994 int error;
995
996 p = curproc;
997
998 while ((error = fd_alloc(p, 0, resultfd)) != 0) {
999 if (error != ENOSPC) {
1000 return error;
1001 }
1002 fd_tryexpand(p);
1003 }
1004
1005 fp = pool_cache_get(file_cache, PR_WAITOK);
1006 KASSERT(fp->f_count == 0);
1007 fp->f_cred = kauth_cred_get();
1008 kauth_cred_hold(fp->f_cred);
1009
1010 if (__predict_false(atomic_inc_uint_nv(&nfiles) >= maxfiles)) {
1011 fd_abort(p, fp, *resultfd);
1012 tablefull("file", "increase kern.maxfiles or MAXFILES");
1013 return ENFILE;
1014 }
1015
1016 fp->f_advice = 0;
1017 fp->f_msgcount = 0;
1018 fp->f_offset = 0;
1019 fp->f_iflags = 0;
1020 *resultfp = fp;
1021
1022 return 0;
1023 }
1024
1025 /*
1026 * Successful creation of a new descriptor: make visible to the process.
1027 */
1028 void
1029 fd_affix(proc_t *p, file_t *fp, unsigned fd)
1030 {
1031 fdfile_t *ff;
1032 filedesc_t *fdp;
1033
1034 KASSERT(p == curproc || p == &proc0);
1035
1036 /* Add a reference to the file structure. */
1037 mutex_enter(&fp->f_lock);
1038 fp->f_count++;
1039 mutex_exit(&fp->f_lock);
1040
1041 /*
1042 * Insert the new file into the descriptor slot.
1043 *
1044 * The memory barriers provided by lock activity in this routine
1045 * ensure that any updates to the file structure become globally
1046 * visible before the file becomes visible to other LWPs in the
1047 * current process.
1048 */
1049 fdp = p->p_fd;
1050 ff = fdp->fd_ofiles[fd];
1051
1052 KASSERT(ff != NULL);
1053 KASSERT(ff->ff_file == NULL);
1054 KASSERT(ff->ff_allocated);
1055 KASSERT(fd_isused(fdp, fd));
1056 KASSERT(fd >= NDFDFILE ||
1057 fdp->fd_ofiles[fd] == (fdfile_t *)fdp->fd_dfdfile[fd]);
1058
1059 /* No need to lock in order to make file initially visible. */
1060 ff->ff_file = fp;
1061 }
1062
1063 /*
1064 * Abort creation of a new descriptor: free descriptor slot and file.
1065 */
1066 void
1067 fd_abort(proc_t *p, file_t *fp, unsigned fd)
1068 {
1069 filedesc_t *fdp;
1070 fdfile_t *ff;
1071
1072 KASSERT(p == curproc || p == &proc0);
1073
1074 fdp = p->p_fd;
1075 ff = fdp->fd_ofiles[fd];
1076
1077 KASSERT(fd >= NDFDFILE ||
1078 fdp->fd_ofiles[fd] == (fdfile_t *)fdp->fd_dfdfile[fd]);
1079
1080 mutex_enter(&fdp->fd_lock);
1081 KASSERT(fd_isused(fdp, fd));
1082 fd_unused(fdp, fd);
1083 mutex_exit(&fdp->fd_lock);
1084
1085 if (fp != NULL) {
1086 ffree(fp);
1087 }
1088 }
1089
1090 /*
1091 * Free a file descriptor.
1092 */
1093 void
1094 ffree(file_t *fp)
1095 {
1096
1097 KASSERT(fp->f_count == 0);
1098
1099 atomic_dec_uint(&nfiles);
1100 kauth_cred_free(fp->f_cred);
1101 pool_cache_put(file_cache, fp);
1102 }
1103
1104 /*
1105 * Create an initial cwdinfo structure, using the same current and root
1106 * directories as curproc.
1107 */
1108 struct cwdinfo *
1109 cwdinit(void)
1110 {
1111 struct cwdinfo *cwdi;
1112 struct cwdinfo *copy;
1113
1114 cwdi = pool_cache_get(cwdi_cache, PR_WAITOK);
1115 copy = curproc->p_cwdi;
1116
1117 rw_enter(©->cwdi_lock, RW_READER);
1118 cwdi->cwdi_cdir = copy->cwdi_cdir;
1119 if (cwdi->cwdi_cdir)
1120 VREF(cwdi->cwdi_cdir);
1121 cwdi->cwdi_rdir = copy->cwdi_rdir;
1122 if (cwdi->cwdi_rdir)
1123 VREF(cwdi->cwdi_rdir);
1124 cwdi->cwdi_edir = copy->cwdi_edir;
1125 if (cwdi->cwdi_edir)
1126 VREF(cwdi->cwdi_edir);
1127 cwdi->cwdi_cmask = copy->cwdi_cmask;
1128 cwdi->cwdi_refcnt = 1;
1129 rw_exit(©->cwdi_lock);
1130
1131 return (cwdi);
1132 }
1133
1134 static int
1135 cwdi_ctor(void *arg, void *obj, int flags)
1136 {
1137 struct cwdinfo *cwdi = obj;
1138
1139 rw_init(&cwdi->cwdi_lock);
1140
1141 return 0;
1142 }
1143
1144 static void
1145 cwdi_dtor(void *arg, void *obj)
1146 {
1147 struct cwdinfo *cwdi = obj;
1148
1149 rw_destroy(&cwdi->cwdi_lock);
1150 }
1151
1152 static int
1153 file_ctor(void *arg, void *obj, int flags)
1154 {
1155 file_t *fp = obj;
1156
1157 memset(fp, 0, sizeof(*fp));
1158 mutex_init(&fp->f_lock, MUTEX_DEFAULT, IPL_NONE);
1159
1160 mutex_enter(&filelist_lock);
1161 LIST_INSERT_HEAD(&filehead, fp, f_list);
1162 mutex_exit(&filelist_lock);
1163
1164 return 0;
1165 }
1166
1167 static void
1168 file_dtor(void *arg, void *obj)
1169 {
1170 file_t *fp = obj;
1171
1172 mutex_enter(&filelist_lock);
1173 LIST_REMOVE(fp, f_list);
1174 mutex_exit(&filelist_lock);
1175
1176 mutex_destroy(&fp->f_lock);
1177 }
1178
1179 static int
1180 fdfile_ctor(void *arg, void *obj, int flags)
1181 {
1182 fdfile_t *ff = obj;
1183
1184 memset(ff, 0, sizeof(*ff));
1185 mutex_init(&ff->ff_lock, MUTEX_DEFAULT, IPL_NONE);
1186 cv_init(&ff->ff_closing, "fdclose");
1187
1188 return 0;
1189 }
1190
1191 static void
1192 fdfile_dtor(void *arg, void *obj)
1193 {
1194 fdfile_t *ff = obj;
1195
1196 mutex_destroy(&ff->ff_lock);
1197 cv_destroy(&ff->ff_closing);
1198 }
1199
1200 file_t *
1201 fgetdummy(void)
1202 {
1203 file_t *fp;
1204
1205 fp = kmem_alloc(sizeof(*fp), KM_SLEEP);
1206 if (fp != NULL) {
1207 memset(fp, 0, sizeof(*fp));
1208 mutex_init(&fp->f_lock, MUTEX_DEFAULT, IPL_NONE);
1209 }
1210 return fp;
1211 }
1212
1213 void
1214 fputdummy(file_t *fp)
1215 {
1216
1217 mutex_destroy(&fp->f_lock);
1218 kmem_free(fp, sizeof(*fp));
1219 }
1220
1221 /*
1222 * Make p2 share p1's cwdinfo.
1223 */
1224 void
1225 cwdshare(struct proc *p2)
1226 {
1227 struct cwdinfo *cwdi;
1228
1229 cwdi = curproc->p_cwdi;
1230
1231 atomic_inc_uint(&cwdi->cwdi_refcnt);
1232 p2->p_cwdi = cwdi;
1233 }
1234
1235 /*
1236 * Release a cwdinfo structure.
1237 */
1238 void
1239 cwdfree(struct cwdinfo *cwdi)
1240 {
1241
1242 if (atomic_dec_uint_nv(&cwdi->cwdi_refcnt) > 0)
1243 return;
1244
1245 vrele(cwdi->cwdi_cdir);
1246 if (cwdi->cwdi_rdir)
1247 vrele(cwdi->cwdi_rdir);
1248 if (cwdi->cwdi_edir)
1249 vrele(cwdi->cwdi_edir);
1250 pool_cache_put(cwdi_cache, cwdi);
1251 }
1252
1253 /*
1254 * Create an initial filedesc structure.
1255 */
1256 filedesc_t *
1257 fd_init(filedesc_t *fdp)
1258 {
1259 unsigned fd;
1260
1261 if (fdp == NULL) {
1262 fdp = pool_cache_get(filedesc_cache, PR_WAITOK);
1263 } else {
1264 filedesc_ctor(NULL, fdp, PR_WAITOK);
1265 }
1266
1267 fdp->fd_refcnt = 1;
1268 fdp->fd_ofiles = fdp->fd_dfiles;
1269 fdp->fd_nfiles = NDFILE;
1270 fdp->fd_himap = fdp->fd_dhimap;
1271 fdp->fd_lomap = fdp->fd_dlomap;
1272 KASSERT(fdp->fd_lastfile == -1);
1273 KASSERT(fdp->fd_lastkqfile == -1);
1274 KASSERT(fdp->fd_knhash == NULL);
1275
1276 memset(&fdp->fd_startzero, 0, sizeof(*fdp) -
1277 offsetof(filedesc_t, fd_startzero));
1278 for (fd = 0; fd < NDFDFILE; fd++) {
1279 fdp->fd_ofiles[fd] = (fdfile_t *)fdp->fd_dfdfile[fd];
1280 }
1281
1282 return fdp;
1283 }
1284
1285 /*
1286 * Initialize a file descriptor table.
1287 */
1288 static int
1289 filedesc_ctor(void *arg, void *obj, int flag)
1290 {
1291 filedesc_t *fdp = obj;
1292 int i;
1293
1294 memset(fdp, 0, sizeof(*fdp));
1295 mutex_init(&fdp->fd_lock, MUTEX_DEFAULT, IPL_NONE);
1296 fdp->fd_lastfile = -1;
1297 fdp->fd_lastkqfile = -1;
1298
1299 CTASSERT(sizeof(fdp->fd_dfdfile[0]) >= sizeof(fdfile_t));
1300 for (i = 0; i < NDFDFILE; i++) {
1301 fdfile_ctor(NULL, fdp->fd_dfdfile[i], PR_WAITOK);
1302 }
1303
1304 return 0;
1305 }
1306
1307 static void
1308 filedesc_dtor(void *arg, void *obj)
1309 {
1310 filedesc_t *fdp = obj;
1311 int i;
1312
1313 for (i = 0; i < NDFDFILE; i++) {
1314 fdfile_dtor(NULL, fdp->fd_dfdfile[i]);
1315 }
1316
1317 mutex_destroy(&fdp->fd_lock);
1318 }
1319
1320 /*
1321 * Make p2 share p1's filedesc structure.
1322 */
1323 void
1324 fd_share(struct proc *p2)
1325 {
1326 filedesc_t *fdp;
1327
1328 fdp = curlwp->l_fd;
1329 p2->p_fd = fdp;
1330 atomic_inc_uint(&fdp->fd_refcnt);
1331 }
1332
1333 /*
1334 * Copy a filedesc structure.
1335 */
1336 filedesc_t *
1337 fd_copy(void)
1338 {
1339 filedesc_t *newfdp, *fdp;
1340 fdfile_t *ff, *fflist, **ffp, **nffp, *ff2;
1341 int i, nused, numfiles, lastfile, j, newlast;
1342 file_t *fp;
1343
1344 fdp = curproc->p_fd;
1345 newfdp = pool_cache_get(filedesc_cache, PR_WAITOK);
1346 newfdp->fd_refcnt = 1;
1347
1348 KASSERT(newfdp->fd_knhash == NULL);
1349 KASSERT(newfdp->fd_knhashmask == 0);
1350 KASSERT(newfdp->fd_discard == NULL);
1351
1352 for (;;) {
1353 numfiles = fdp->fd_nfiles;
1354 lastfile = fdp->fd_lastfile;
1355
1356 /*
1357 * If the number of open files fits in the internal arrays
1358 * of the open file structure, use them, otherwise allocate
1359 * additional memory for the number of descriptors currently
1360 * in use.
1361 */
1362 if (lastfile < NDFILE) {
1363 i = NDFILE;
1364 newfdp->fd_ofiles = newfdp->fd_dfiles;
1365 } else {
1366 /*
1367 * Compute the smallest multiple of NDEXTENT needed
1368 * for the file descriptors currently in use,
1369 * allowing the table to shrink.
1370 */
1371 i = numfiles;
1372 while (i >= 2 * NDEXTENT && i > lastfile * 2) {
1373 i /= 2;
1374 }
1375 newfdp->fd_ofiles = fd_ofile_alloc(i);
1376 KASSERT(i > NDFILE);
1377 }
1378 if (NDHISLOTS(i) <= NDHISLOTS(NDFILE)) {
1379 newfdp->fd_himap = newfdp->fd_dhimap;
1380 newfdp->fd_lomap = newfdp->fd_dlomap;
1381 } else {
1382 fd_map_alloc(i, &newfdp->fd_lomap,
1383 &newfdp->fd_himap);
1384 }
1385
1386 /*
1387 * Allocate and string together fdfile structures.
1388 * We abuse fdfile_t::ff_file here, but it will be
1389 * cleared before this routine returns.
1390 */
1391 nused = fdp->fd_nused;
1392 fflist = NULL;
1393 for (j = nused; j != 0; j--) {
1394 ff = pool_cache_get(fdfile_cache, PR_WAITOK);
1395 ff->ff_file = (void *)fflist;
1396 fflist = ff;
1397 }
1398
1399 mutex_enter(&fdp->fd_lock);
1400 if (numfiles == fdp->fd_nfiles && nused == fdp->fd_nused &&
1401 lastfile == fdp->fd_lastfile) {
1402 break;
1403 }
1404 mutex_exit(&fdp->fd_lock);
1405 if (i > NDFILE) {
1406 fd_ofile_free(i, newfdp->fd_ofiles);
1407 }
1408 if (NDHISLOTS(i) > NDHISLOTS(NDFILE)) {
1409 fd_map_free(i, newfdp->fd_lomap, newfdp->fd_himap);
1410 }
1411 while (fflist != NULL) {
1412 ff = fflist;
1413 fflist = (void *)ff->ff_file;
1414 ff->ff_file = NULL;
1415 pool_cache_put(fdfile_cache, ff);
1416 }
1417 }
1418
1419 newfdp->fd_nfiles = i;
1420 newfdp->fd_freefile = fdp->fd_freefile;
1421 newfdp->fd_exclose = fdp->fd_exclose;
1422
1423 /*
1424 * Clear the entries that will not be copied over.
1425 * Avoid calling memset with 0 size.
1426 */
1427 if (lastfile < (i-1)) {
1428 memset(newfdp->fd_ofiles + lastfile + 1, 0,
1429 (i - lastfile - 1) * sizeof(file_t **));
1430 }
1431 if (i < NDENTRIES * NDENTRIES) {
1432 i = NDENTRIES * NDENTRIES; /* size of inlined bitmaps */
1433 }
1434 memcpy(newfdp->fd_himap, fdp->fd_himap, NDHISLOTS(i)*sizeof(uint32_t));
1435 memcpy(newfdp->fd_lomap, fdp->fd_lomap, NDLOSLOTS(i)*sizeof(uint32_t));
1436
1437 ffp = fdp->fd_ofiles;
1438 nffp = newfdp->fd_ofiles;
1439 j = imax(lastfile, (NDFDFILE - 1));
1440 newlast = -1;
1441 KASSERT(j < fdp->fd_nfiles);
1442 for (i = 0; i <= j; i++, ffp++, *nffp++ = ff2) {
1443 ff = *ffp;
1444 /* Install built-in fdfiles even if unused here. */
1445 if (i < NDFDFILE) {
1446 ff2 = (fdfile_t *)newfdp->fd_dfdfile[i];
1447 } else {
1448 ff2 = NULL;
1449 }
1450 /* Determine if descriptor is active in parent. */
1451 if (ff == NULL || !fd_isused(fdp, i)) {
1452 KASSERT(ff != NULL || i >= NDFDFILE);
1453 continue;
1454 }
1455 mutex_enter(&ff->ff_lock);
1456 fp = ff->ff_file;
1457 if (fp == NULL) {
1458 /* Descriptor is half-open: free slot. */
1459 fd_zap(newfdp, i);
1460 mutex_exit(&ff->ff_lock);
1461 continue;
1462 }
1463 if (fp->f_type == DTYPE_KQUEUE) {
1464 /* kqueue descriptors cannot be copied. */
1465 fd_zap(newfdp, i);
1466 mutex_exit(&ff->ff_lock);
1467 continue;
1468 }
1469 /* It's active: add a reference to the file. */
1470 mutex_enter(&fp->f_lock);
1471 fp->f_count++;
1472 mutex_exit(&fp->f_lock);
1473 /* Consume one fdfile_t to represent it. */
1474 if (i >= NDFDFILE) {
1475 ff2 = fflist;
1476 fflist = (void *)ff2->ff_file;
1477 }
1478 ff2->ff_file = fp;
1479 ff2->ff_exclose = ff->ff_exclose;
1480 ff2->ff_allocated = true;
1481 mutex_exit(&ff->ff_lock);
1482 if (i > newlast) {
1483 newlast = i;
1484 }
1485 }
1486 mutex_exit(&fdp->fd_lock);
1487
1488 /* Discard unused fdfile_t structures. */
1489 while (__predict_false(fflist != NULL)) {
1490 ff = fflist;
1491 fflist = (void *)ff->ff_file;
1492 ff->ff_file = NULL;
1493 pool_cache_put(fdfile_cache, ff);
1494 nused--;
1495 }
1496 KASSERT(nused >= 0);
1497 KASSERT(newfdp->fd_ofiles[0] == (fdfile_t *)newfdp->fd_dfdfile[0]);
1498
1499 newfdp->fd_nused = nused;
1500 newfdp->fd_lastfile = newlast;
1501
1502 return (newfdp);
1503 }
1504
1505 /*
1506 * Release a filedesc structure.
1507 */
1508 void
1509 fd_free(void)
1510 {
1511 filedesc_t *fdp;
1512 fdfile_t *ff;
1513 file_t *fp;
1514 int fd, lastfd;
1515 void **discard;
1516
1517 fdp = curlwp->l_fd;
1518
1519 KASSERT(fdp->fd_ofiles[0] == (fdfile_t *)fdp->fd_dfdfile[0]);
1520
1521 if (atomic_dec_uint_nv(&fdp->fd_refcnt) > 0)
1522 return;
1523
1524 /*
1525 * Close any files that the process holds open.
1526 */
1527 for (fd = 0, lastfd = fdp->fd_nfiles - 1; fd <= lastfd; fd++) {
1528 ff = fdp->fd_ofiles[fd];
1529 KASSERT(fd >= NDFDFILE ||
1530 ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
1531 if ((ff = fdp->fd_ofiles[fd]) == NULL)
1532 continue;
1533 if ((fp = ff->ff_file) != NULL) {
1534 /*
1535 * Must use fd_close() here as kqueue holds
1536 * long term references to descriptors.
1537 */
1538 ff->ff_refcnt++;
1539 fd_close(fd);
1540 }
1541 KASSERT(ff->ff_refcnt == 0);
1542 KASSERT(ff->ff_file == NULL);
1543 KASSERT(!ff->ff_exclose);
1544 KASSERT(!ff->ff_allocated);
1545 if (fd >= NDFDFILE) {
1546 pool_cache_put(fdfile_cache, ff);
1547 }
1548 }
1549
1550 /*
1551 * Clean out the descriptor table for the next user and return
1552 * to the cache.
1553 */
1554 while ((discard = fdp->fd_discard) != NULL) {
1555 fdp->fd_discard = discard[0];
1556 kmem_free(discard, (uintptr_t)discard[1]);
1557 }
1558 if (NDHISLOTS(fdp->fd_nfiles) > NDHISLOTS(NDFILE)) {
1559 KASSERT(fdp->fd_himap != fdp->fd_dhimap);
1560 KASSERT(fdp->fd_lomap != fdp->fd_dlomap);
1561 fd_map_free(fdp->fd_nfiles, fdp->fd_lomap, fdp->fd_himap);
1562 }
1563 if (fdp->fd_nfiles > NDFILE) {
1564 KASSERT(fdp->fd_ofiles != fdp->fd_dfiles);
1565 fd_ofile_free(fdp->fd_nfiles, fdp->fd_ofiles);
1566 }
1567 if (fdp->fd_knhash != NULL) {
1568 hashdone(fdp->fd_knhash, HASH_LIST, fdp->fd_knhashmask);
1569 fdp->fd_knhash = NULL;
1570 fdp->fd_knhashmask = 0;
1571 } else {
1572 KASSERT(fdp->fd_knhashmask == 0);
1573 }
1574 fdp->fd_lastkqfile = -1;
1575 pool_cache_put(filedesc_cache, fdp);
1576 }
1577
1578 /*
1579 * File Descriptor pseudo-device driver (/dev/fd/).
1580 *
1581 * Opening minor device N dup()s the file (if any) connected to file
1582 * descriptor N belonging to the calling process. Note that this driver
1583 * consists of only the ``open()'' routine, because all subsequent
1584 * references to this file will be direct to the other driver.
1585 */
1586 static int
1587 filedescopen(dev_t dev, int mode, int type, lwp_t *l)
1588 {
1589
1590 /*
1591 * XXX Kludge: set dupfd to contain the value of the
1592 * the file descriptor being sought for duplication. The error
1593 * return ensures that the vnode for this device will be released
1594 * by vn_open. Open will detect this special error and take the
1595 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
1596 * will simply report the error.
1597 */
1598 l->l_dupfd = minor(dev); /* XXX */
1599 return EDUPFD;
1600 }
1601
1602 /*
1603 * Duplicate the specified descriptor to a free descriptor.
1604 */
1605 int
1606 fd_dupopen(int old, int *new, int mode, int error)
1607 {
1608 filedesc_t *fdp;
1609 fdfile_t *ff;
1610 file_t *fp;
1611
1612 if ((fp = fd_getfile(old)) == NULL) {
1613 return EBADF;
1614 }
1615 fdp = curlwp->l_fd;
1616 ff = fdp->fd_ofiles[old];
1617
1618 /*
1619 * There are two cases of interest here.
1620 *
1621 * For EDUPFD simply dup (dfd) to file descriptor
1622 * (indx) and return.
1623 *
1624 * For EMOVEFD steal away the file structure from (dfd) and
1625 * store it in (indx). (dfd) is effectively closed by
1626 * this operation.
1627 *
1628 * Any other error code is just returned.
1629 */
1630 switch (error) {
1631 case EDUPFD:
1632 /*
1633 * Check that the mode the file is being opened for is a
1634 * subset of the mode of the existing descriptor.
1635 */
1636 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
1637 error = EACCES;
1638 break;
1639 }
1640
1641 /* Copy it. */
1642 error = fd_dup(fp, 0, new, fdp->fd_ofiles[old]->ff_exclose);
1643 break;
1644
1645 case EMOVEFD:
1646 /* Copy it. */
1647 error = fd_dup(fp, 0, new, fdp->fd_ofiles[old]->ff_exclose);
1648 if (error != 0) {
1649 break;
1650 }
1651
1652 /* Steal away the file pointer from 'old'. */
1653 (void)fd_close(old);
1654 return 0;
1655 }
1656
1657 fd_putfile(old);
1658 return error;
1659 }
1660
1661 /*
1662 * Close open files on exec.
1663 */
1664 void
1665 fd_closeexec(void)
1666 {
1667 struct cwdinfo *cwdi;
1668 proc_t *p;
1669 filedesc_t *fdp;
1670 fdfile_t *ff;
1671 lwp_t *l;
1672 int fd;
1673
1674 l = curlwp;
1675 p = l->l_proc;
1676 fdp = p->p_fd;
1677 cwdi = p->p_cwdi;
1678
1679 if (cwdi->cwdi_refcnt > 1) {
1680 cwdi = cwdinit();
1681 cwdfree(p->p_cwdi);
1682 p->p_cwdi = cwdi;
1683 }
1684 if (p->p_cwdi->cwdi_edir) {
1685 vrele(p->p_cwdi->cwdi_edir);
1686 }
1687
1688 if (fdp->fd_refcnt > 1) {
1689 fdp = fd_copy();
1690 fd_free();
1691 p->p_fd = fdp;
1692 l->l_fd = fdp;
1693 }
1694 if (!fdp->fd_exclose) {
1695 return;
1696 }
1697 fdp->fd_exclose = false;
1698
1699 for (fd = 0; fd <= fdp->fd_lastfile; fd++) {
1700 if ((ff = fdp->fd_ofiles[fd]) == NULL) {
1701 KASSERT(fd >= NDFDFILE);
1702 continue;
1703 }
1704 KASSERT(fd >= NDFDFILE ||
1705 ff == (fdfile_t *)fdp->fd_dfdfile[fd]);
1706 if (ff->ff_file == NULL)
1707 continue;
1708 if (ff->ff_exclose) {
1709 /*
1710 * We need a reference to close the file.
1711 * No other threads can see the fdfile_t at
1712 * this point, so don't bother locking.
1713 */
1714 KASSERT((ff->ff_refcnt & FR_CLOSING) == 0);
1715 ff->ff_refcnt++;
1716 fd_close(fd);
1717 }
1718 }
1719 }
1720
1721 /*
1722 * It is unsafe for set[ug]id processes to be started with file
1723 * descriptors 0..2 closed, as these descriptors are given implicit
1724 * significance in the Standard C library. fdcheckstd() will create a
1725 * descriptor referencing /dev/null for each of stdin, stdout, and
1726 * stderr that is not already open.
1727 */
1728 #define CHECK_UPTO 3
1729 int
1730 fd_checkstd(void)
1731 {
1732 struct proc *p;
1733 struct nameidata nd;
1734 filedesc_t *fdp;
1735 file_t *fp;
1736 struct proc *pp;
1737 int fd, i, error, flags = FREAD|FWRITE;
1738 char closed[CHECK_UPTO * 3 + 1], which[3 + 1];
1739
1740 p = curproc;
1741 closed[0] = '\0';
1742 if ((fdp = p->p_fd) == NULL)
1743 return (0);
1744 for (i = 0; i < CHECK_UPTO; i++) {
1745 KASSERT(i >= NDFDFILE ||
1746 fdp->fd_ofiles[i] == (fdfile_t *)fdp->fd_dfdfile[i]);
1747 if (fdp->fd_ofiles[i]->ff_file != NULL)
1748 continue;
1749 snprintf(which, sizeof(which), ",%d", i);
1750 strlcat(closed, which, sizeof(closed));
1751 if ((error = fd_allocfile(&fp, &fd)) != 0)
1752 return (error);
1753 KASSERT(fd < CHECK_UPTO);
1754 NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, "/dev/null");
1755 if ((error = vn_open(&nd, flags, 0)) != 0) {
1756 fd_abort(p, fp, fd);
1757 return (error);
1758 }
1759 fp->f_data = nd.ni_vp;
1760 fp->f_flag = flags;
1761 fp->f_ops = &vnops;
1762 fp->f_type = DTYPE_VNODE;
1763 VOP_UNLOCK(nd.ni_vp, 0);
1764 fd_affix(p, fp, fd);
1765 }
1766 if (closed[0] != '\0') {
1767 mutex_enter(proc_lock);
1768 pp = p->p_pptr;
1769 mutex_enter(pp->p_lock);
1770 log(LOG_WARNING, "set{u,g}id pid %d (%s) "
1771 "was invoked by uid %d ppid %d (%s) "
1772 "with fd %s closed\n",
1773 p->p_pid, p->p_comm, kauth_cred_geteuid(pp->p_cred),
1774 pp->p_pid, pp->p_comm, &closed[1]);
1775 mutex_exit(pp->p_lock);
1776 mutex_exit(proc_lock);
1777 }
1778 return (0);
1779 }
1780 #undef CHECK_UPTO
1781
1782 /*
1783 * Sets descriptor owner. If the owner is a process, 'pgid'
1784 * is set to positive value, process ID. If the owner is process group,
1785 * 'pgid' is set to -pg_id.
1786 */
1787 int
1788 fsetown(pid_t *pgid, u_long cmd, const void *data)
1789 {
1790 int id = *(const int *)data;
1791 int error;
1792
1793 switch (cmd) {
1794 case TIOCSPGRP:
1795 if (id < 0)
1796 return (EINVAL);
1797 id = -id;
1798 break;
1799 default:
1800 break;
1801 }
1802
1803 if (id > 0 && !pfind(id))
1804 return (ESRCH);
1805 else if (id < 0 && (error = pgid_in_session(curproc, -id)))
1806 return (error);
1807
1808 *pgid = id;
1809 return (0);
1810 }
1811
1812 /*
1813 * Return descriptor owner information. If the value is positive,
1814 * it's process ID. If it's negative, it's process group ID and
1815 * needs the sign removed before use.
1816 */
1817 int
1818 fgetown(pid_t pgid, u_long cmd, void *data)
1819 {
1820
1821 switch (cmd) {
1822 case TIOCGPGRP:
1823 *(int *)data = -pgid;
1824 break;
1825 default:
1826 *(int *)data = pgid;
1827 break;
1828 }
1829 return (0);
1830 }
1831
1832 /*
1833 * Send signal to descriptor owner, either process or process group.
1834 */
1835 void
1836 fownsignal(pid_t pgid, int signo, int code, int band, void *fdescdata)
1837 {
1838 struct proc *p1;
1839 struct pgrp *pgrp;
1840 ksiginfo_t ksi;
1841
1842 KASSERT(!cpu_intr_p());
1843
1844 KSI_INIT(&ksi);
1845 ksi.ksi_signo = signo;
1846 ksi.ksi_code = code;
1847 ksi.ksi_band = band;
1848
1849 mutex_enter(proc_lock);
1850 if (pgid > 0 && (p1 = p_find(pgid, PFIND_LOCKED)))
1851 kpsignal(p1, &ksi, fdescdata);
1852 else if (pgid < 0 && (pgrp = pg_find(-pgid, PFIND_LOCKED)))
1853 kpgsignal(pgrp, &ksi, fdescdata, 0);
1854 mutex_exit(proc_lock);
1855 }
1856
1857 int
1858 fd_clone(file_t *fp, unsigned fd, int flag, const struct fileops *fops,
1859 void *data)
1860 {
1861
1862 fp->f_flag = flag;
1863 fp->f_type = DTYPE_MISC;
1864 fp->f_ops = fops;
1865 fp->f_data = data;
1866 curlwp->l_dupfd = fd;
1867 fd_affix(curproc, fp, fd);
1868
1869 return EMOVEFD;
1870 }
1871
1872 int
1873 fnullop_fcntl(file_t *fp, u_int cmd, void *data)
1874 {
1875
1876 if (cmd == F_SETFL)
1877 return 0;
1878
1879 return EOPNOTSUPP;
1880 }
1881
1882 int
1883 fnullop_poll(file_t *fp, int which)
1884 {
1885
1886 return 0;
1887 }
1888
1889 int
1890 fnullop_kqfilter(file_t *fp, struct knote *kn)
1891 {
1892
1893 return 0;
1894 }
1895
1896 int
1897 fbadop_read(file_t *fp, off_t *offset, struct uio *uio,
1898 kauth_cred_t cred, int flags)
1899 {
1900
1901 return EOPNOTSUPP;
1902 }
1903
1904 int
1905 fbadop_write(file_t *fp, off_t *offset, struct uio *uio,
1906 kauth_cred_t cred, int flags)
1907 {
1908
1909 return EOPNOTSUPP;
1910 }
1911
1912 int
1913 fbadop_ioctl(file_t *fp, u_long com, void *data)
1914 {
1915
1916 return EOPNOTSUPP;
1917 }
1918
1919 int
1920 fbadop_stat(file_t *fp, struct stat *sb)
1921 {
1922
1923 return EOPNOTSUPP;
1924 }
1925
1926 int
1927 fbadop_close(file_t *fp)
1928 {
1929
1930 return EOPNOTSUPP;
1931 }
1932