1 /*-
2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
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 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 *
34 * @(#)kern_descrip.c 8.6 (Berkeley) 4/19/94
35 */
36
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD: releng/6.2/sys/kern/kern_descrip.c 176272 2008-02-14 11:47:39Z simon $");
39
40 #include "opt_compat.h"
41 #include "opt_ddb.h"
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45
46 #include <sys/conf.h>
47 #include <sys/fcntl.h>
48 #include <sys/file.h>
49 #include <sys/filedesc.h>
50 #include <sys/filio.h>
51 #include <sys/jail.h>
52 #include <sys/kernel.h>
53 #include <sys/limits.h>
54 #include <sys/lock.h>
55 #include <sys/malloc.h>
56 #include <sys/mount.h>
57 #include <sys/mutex.h>
58 #include <sys/namei.h>
59 #include <sys/proc.h>
60 #include <sys/resourcevar.h>
61 #include <sys/signalvar.h>
62 #include <sys/socketvar.h>
63 #include <sys/stat.h>
64 #include <sys/sx.h>
65 #include <sys/syscallsubr.h>
66 #include <sys/sysctl.h>
67 #include <sys/sysproto.h>
68 #include <sys/unistd.h>
69 #include <sys/vnode.h>
70
71 #include <security/audit/audit.h>
72
73 #include <vm/uma.h>
74
75 #include <ddb/ddb.h>
76
77 static MALLOC_DEFINE(M_FILEDESC, "file desc", "Open file descriptor table");
78 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "file desc to leader",
79 "file desc to leader structures");
80 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
81
82 static uma_zone_t file_zone;
83
84
85 /* How to treat 'new' parameter when allocating a fd for do_dup(). */
86 enum dup_type { DUP_VARIABLE, DUP_FIXED };
87
88 static int do_dup(struct thread *td, enum dup_type type, int old, int new,
89 register_t *retval);
90 static int fd_first_free(struct filedesc *, int, int);
91 static int fd_last_used(struct filedesc *, int, int);
92 static void fdgrowtable(struct filedesc *, int);
93 static int fdrop_locked(struct file *fp, struct thread *td);
94 static void fdunused(struct filedesc *fdp, int fd);
95 static void fdused(struct filedesc *fdp, int fd);
96
97 /*
98 * A process is initially started out with NDFILE descriptors stored within
99 * this structure, selected to be enough for typical applications based on
100 * the historical limit of 20 open files (and the usage of descriptors by
101 * shells). If these descriptors are exhausted, a larger descriptor table
102 * may be allocated, up to a process' resource limit; the internal arrays
103 * are then unused.
104 */
105 #define NDFILE 20
106 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
107 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
108 #define NDSLOT(x) ((x) / NDENTRIES)
109 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
110 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
111
112 /*
113 * Storage required per open file descriptor.
114 */
115 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
116
117 /*
118 * Basic allocation of descriptors:
119 * one of the above, plus arrays for NDFILE descriptors.
120 */
121 struct filedesc0 {
122 struct filedesc fd_fd;
123 /*
124 * These arrays are used when the number of open files is
125 * <= NDFILE, and are then pointed to by the pointers above.
126 */
127 struct file *fd_dfiles[NDFILE];
128 char fd_dfileflags[NDFILE];
129 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
130 };
131
132 /*
133 * Descriptor management.
134 */
135 struct filelist filehead; /* head of list of open files */
136 int openfiles; /* actual number of open files */
137 struct sx filelist_lock; /* sx to protect filelist */
138 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
139
140 /* A mutex to protect the association between a proc and filedesc. */
141 static struct mtx fdesc_mtx;
142
143 /*
144 * Find the first zero bit in the given bitmap, starting at low and not
145 * exceeding size - 1.
146 */
147 static int
148 fd_first_free(struct filedesc *fdp, int low, int size)
149 {
150 NDSLOTTYPE *map = fdp->fd_map;
151 NDSLOTTYPE mask;
152 int off, maxoff;
153
154 if (low >= size)
155 return (low);
156
157 off = NDSLOT(low);
158 if (low % NDENTRIES) {
159 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
160 if ((mask &= ~map[off]) != 0UL)
161 return (off * NDENTRIES + ffsl(mask) - 1);
162 ++off;
163 }
164 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
165 if (map[off] != ~0UL)
166 return (off * NDENTRIES + ffsl(~map[off]) - 1);
167 return (size);
168 }
169
170 /*
171 * Find the highest non-zero bit in the given bitmap, starting at low and
172 * not exceeding size - 1.
173 */
174 static int
175 fd_last_used(struct filedesc *fdp, int low, int size)
176 {
177 NDSLOTTYPE *map = fdp->fd_map;
178 NDSLOTTYPE mask;
179 int off, minoff;
180
181 if (low >= size)
182 return (-1);
183
184 off = NDSLOT(size);
185 if (size % NDENTRIES) {
186 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
187 if ((mask &= map[off]) != 0)
188 return (off * NDENTRIES + flsl(mask) - 1);
189 --off;
190 }
191 for (minoff = NDSLOT(low); off >= minoff; --off)
192 if (map[off] != 0)
193 return (off * NDENTRIES + flsl(map[off]) - 1);
194 return (low - 1);
195 }
196
197 static int
198 fdisused(struct filedesc *fdp, int fd)
199 {
200 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
201 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
202 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
203 }
204
205 /*
206 * Mark a file descriptor as used.
207 */
208 static void
209 fdused(struct filedesc *fdp, int fd)
210 {
211 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
212 KASSERT(!fdisused(fdp, fd),
213 ("fd already used"));
214 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
215 if (fd > fdp->fd_lastfile)
216 fdp->fd_lastfile = fd;
217 if (fd == fdp->fd_freefile)
218 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
219 }
220
221 /*
222 * Mark a file descriptor as unused.
223 */
224 static void
225 fdunused(struct filedesc *fdp, int fd)
226 {
227 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
228 KASSERT(fdisused(fdp, fd),
229 ("fd is already unused"));
230 KASSERT(fdp->fd_ofiles[fd] == NULL,
231 ("fd is still in use"));
232 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
233 if (fd < fdp->fd_freefile)
234 fdp->fd_freefile = fd;
235 if (fd == fdp->fd_lastfile)
236 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
237 }
238
239 /*
240 * System calls on descriptors.
241 */
242 #ifndef _SYS_SYSPROTO_H_
243 struct getdtablesize_args {
244 int dummy;
245 };
246 #endif
247 /*
248 * MPSAFE
249 */
250 /* ARGSUSED */
251 int
252 getdtablesize(struct thread *td, struct getdtablesize_args *uap)
253 {
254 struct proc *p = td->td_proc;
255
256 PROC_LOCK(p);
257 td->td_retval[0] =
258 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
259 PROC_UNLOCK(p);
260 return (0);
261 }
262
263 /*
264 * Duplicate a file descriptor to a particular value.
265 *
266 * note: keep in mind that a potential race condition exists when closing
267 * descriptors from a shared descriptor table (via rfork).
268 */
269 #ifndef _SYS_SYSPROTO_H_
270 struct dup2_args {
271 u_int from;
272 u_int to;
273 };
274 #endif
275 /*
276 * MPSAFE
277 */
278 /* ARGSUSED */
279 int
280 dup2(struct thread *td, struct dup2_args *uap)
281 {
282
283 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
284 td->td_retval));
285 }
286
287 /*
288 * Duplicate a file descriptor.
289 */
290 #ifndef _SYS_SYSPROTO_H_
291 struct dup_args {
292 u_int fd;
293 };
294 #endif
295 /*
296 * MPSAFE
297 */
298 /* ARGSUSED */
299 int
300 dup(struct thread *td, struct dup_args *uap)
301 {
302
303 return (do_dup(td, DUP_VARIABLE, (int)uap->fd, 0, td->td_retval));
304 }
305
306 /*
307 * The file control system call.
308 */
309 #ifndef _SYS_SYSPROTO_H_
310 struct fcntl_args {
311 int fd;
312 int cmd;
313 long arg;
314 };
315 #endif
316 /*
317 * MPSAFE
318 */
319 /* ARGSUSED */
320 int
321 fcntl(struct thread *td, struct fcntl_args *uap)
322 {
323 struct flock fl;
324 intptr_t arg;
325 int error;
326
327 error = 0;
328 switch (uap->cmd) {
329 case F_GETLK:
330 case F_SETLK:
331 case F_SETLKW:
332 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
333 arg = (intptr_t)&fl;
334 break;
335 default:
336 arg = uap->arg;
337 break;
338 }
339 if (error)
340 return (error);
341 error = kern_fcntl(td, uap->fd, uap->cmd, arg);
342 if (error)
343 return (error);
344 if (uap->cmd == F_GETLK)
345 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
346 return (error);
347 }
348
349 int
350 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
351 {
352 struct filedesc *fdp;
353 struct flock *flp;
354 struct file *fp;
355 struct proc *p;
356 char *pop;
357 struct vnode *vp;
358 u_int newmin;
359 int error, flg, tmp;
360 int giant_locked;
361
362 /*
363 * XXXRW: Some fcntl() calls require Giant -- others don't. Try to
364 * avoid grabbing Giant for calls we know don't need it.
365 */
366 switch (cmd) {
367 case F_DUPFD:
368 case F_GETFD:
369 case F_SETFD:
370 case F_GETFL:
371 giant_locked = 0;
372 break;
373
374 default:
375 giant_locked = 1;
376 mtx_lock(&Giant);
377 }
378
379 error = 0;
380 flg = F_POSIX;
381 p = td->td_proc;
382 fdp = p->p_fd;
383 FILEDESC_LOCK(fdp);
384 if ((unsigned)fd >= fdp->fd_nfiles ||
385 (fp = fdp->fd_ofiles[fd]) == NULL) {
386 FILEDESC_UNLOCK(fdp);
387 error = EBADF;
388 goto done2;
389 }
390 pop = &fdp->fd_ofileflags[fd];
391
392 switch (cmd) {
393 case F_DUPFD:
394 /* mtx_assert(&Giant, MA_NOTOWNED); */
395 FILEDESC_UNLOCK(fdp);
396 newmin = arg;
397 PROC_LOCK(p);
398 if (newmin >= lim_cur(p, RLIMIT_NOFILE) ||
399 newmin >= maxfilesperproc) {
400 PROC_UNLOCK(p);
401 error = EINVAL;
402 break;
403 }
404 PROC_UNLOCK(p);
405 error = do_dup(td, DUP_VARIABLE, fd, newmin, td->td_retval);
406 break;
407
408 case F_GETFD:
409 /* mtx_assert(&Giant, MA_NOTOWNED); */
410 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
411 FILEDESC_UNLOCK(fdp);
412 break;
413
414 case F_SETFD:
415 /* mtx_assert(&Giant, MA_NOTOWNED); */
416 *pop = (*pop &~ UF_EXCLOSE) |
417 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
418 FILEDESC_UNLOCK(fdp);
419 break;
420
421 case F_GETFL:
422 /* mtx_assert(&Giant, MA_NOTOWNED); */
423 FILE_LOCK(fp);
424 td->td_retval[0] = OFLAGS(fp->f_flag);
425 FILE_UNLOCK(fp);
426 FILEDESC_UNLOCK(fdp);
427 break;
428
429 case F_SETFL:
430 mtx_assert(&Giant, MA_OWNED);
431 FILE_LOCK(fp);
432 fhold_locked(fp);
433 fp->f_flag &= ~FCNTLFLAGS;
434 fp->f_flag |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
435 FILE_UNLOCK(fp);
436 FILEDESC_UNLOCK(fdp);
437 tmp = fp->f_flag & FNONBLOCK;
438 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
439 if (error) {
440 fdrop(fp, td);
441 break;
442 }
443 tmp = fp->f_flag & FASYNC;
444 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
445 if (error == 0) {
446 fdrop(fp, td);
447 break;
448 }
449 FILE_LOCK(fp);
450 fp->f_flag &= ~FNONBLOCK;
451 FILE_UNLOCK(fp);
452 tmp = 0;
453 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
454 fdrop(fp, td);
455 break;
456
457 case F_GETOWN:
458 mtx_assert(&Giant, MA_OWNED);
459 fhold(fp);
460 FILEDESC_UNLOCK(fdp);
461 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
462 if (error == 0)
463 td->td_retval[0] = tmp;
464 fdrop(fp, td);
465 break;
466
467 case F_SETOWN:
468 mtx_assert(&Giant, MA_OWNED);
469 fhold(fp);
470 FILEDESC_UNLOCK(fdp);
471 tmp = arg;
472 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
473 fdrop(fp, td);
474 break;
475
476 case F_SETLKW:
477 mtx_assert(&Giant, MA_OWNED);
478 flg |= F_WAIT;
479 /* FALLTHROUGH F_SETLK */
480
481 case F_SETLK:
482 mtx_assert(&Giant, MA_OWNED);
483 if (fp->f_type != DTYPE_VNODE) {
484 FILEDESC_UNLOCK(fdp);
485 error = EBADF;
486 break;
487 }
488
489 flp = (struct flock *)arg;
490 if (flp->l_whence == SEEK_CUR) {
491 if (fp->f_offset < 0 ||
492 (flp->l_start > 0 &&
493 fp->f_offset > OFF_MAX - flp->l_start)) {
494 FILEDESC_UNLOCK(fdp);
495 error = EOVERFLOW;
496 break;
497 }
498 flp->l_start += fp->f_offset;
499 }
500
501 /*
502 * VOP_ADVLOCK() may block.
503 */
504 fhold(fp);
505 FILEDESC_UNLOCK(fdp);
506 vp = fp->f_vnode;
507
508 switch (flp->l_type) {
509 case F_RDLCK:
510 if ((fp->f_flag & FREAD) == 0) {
511 error = EBADF;
512 break;
513 }
514 PROC_LOCK(p->p_leader);
515 p->p_leader->p_flag |= P_ADVLOCK;
516 PROC_UNLOCK(p->p_leader);
517 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
518 flp, flg);
519 break;
520 case F_WRLCK:
521 if ((fp->f_flag & FWRITE) == 0) {
522 error = EBADF;
523 break;
524 }
525 PROC_LOCK(p->p_leader);
526 p->p_leader->p_flag |= P_ADVLOCK;
527 PROC_UNLOCK(p->p_leader);
528 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
529 flp, flg);
530 break;
531 case F_UNLCK:
532 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
533 flp, F_POSIX);
534 break;
535 default:
536 error = EINVAL;
537 break;
538 }
539 /* Check for race with close */
540 FILEDESC_LOCK_FAST(fdp);
541 if ((unsigned) fd >= fdp->fd_nfiles ||
542 fp != fdp->fd_ofiles[fd]) {
543 FILEDESC_UNLOCK_FAST(fdp);
544 flp->l_whence = SEEK_SET;
545 flp->l_start = 0;
546 flp->l_len = 0;
547 flp->l_type = F_UNLCK;
548 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
549 F_UNLCK, flp, F_POSIX);
550 } else
551 FILEDESC_UNLOCK_FAST(fdp);
552 fdrop(fp, td);
553 break;
554
555 case F_GETLK:
556 mtx_assert(&Giant, MA_OWNED);
557 if (fp->f_type != DTYPE_VNODE) {
558 FILEDESC_UNLOCK(fdp);
559 error = EBADF;
560 break;
561 }
562 flp = (struct flock *)arg;
563 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
564 flp->l_type != F_UNLCK) {
565 FILEDESC_UNLOCK(fdp);
566 error = EINVAL;
567 break;
568 }
569 if (flp->l_whence == SEEK_CUR) {
570 if ((flp->l_start > 0 &&
571 fp->f_offset > OFF_MAX - flp->l_start) ||
572 (flp->l_start < 0 &&
573 fp->f_offset < OFF_MIN - flp->l_start)) {
574 FILEDESC_UNLOCK(fdp);
575 error = EOVERFLOW;
576 break;
577 }
578 flp->l_start += fp->f_offset;
579 }
580 /*
581 * VOP_ADVLOCK() may block.
582 */
583 fhold(fp);
584 FILEDESC_UNLOCK(fdp);
585 vp = fp->f_vnode;
586 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
587 F_POSIX);
588 fdrop(fp, td);
589 break;
590 default:
591 FILEDESC_UNLOCK(fdp);
592 error = EINVAL;
593 break;
594 }
595 done2:
596 if (giant_locked)
597 mtx_unlock(&Giant);
598 return (error);
599 }
600
601 /*
602 * Common code for dup, dup2, and fcntl(F_DUPFD).
603 */
604 static int
605 do_dup(struct thread *td, enum dup_type type, int old, int new, register_t *retval)
606 {
607 struct filedesc *fdp;
608 struct proc *p;
609 struct file *fp;
610 struct file *delfp;
611 int error, holdleaders, maxfd;
612
613 KASSERT((type == DUP_VARIABLE || type == DUP_FIXED),
614 ("invalid dup type %d", type));
615
616 p = td->td_proc;
617 fdp = p->p_fd;
618
619 /*
620 * Verify we have a valid descriptor to dup from and possibly to
621 * dup to.
622 */
623 if (old < 0 || new < 0)
624 return (EBADF);
625 PROC_LOCK(p);
626 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
627 PROC_UNLOCK(p);
628 if (new >= maxfd)
629 return (EMFILE);
630
631 FILEDESC_LOCK(fdp);
632 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
633 FILEDESC_UNLOCK(fdp);
634 return (EBADF);
635 }
636 if (type == DUP_FIXED && old == new) {
637 *retval = new;
638 FILEDESC_UNLOCK(fdp);
639 return (0);
640 }
641 fp = fdp->fd_ofiles[old];
642 fhold(fp);
643
644 /*
645 * If the caller specified a file descriptor, make sure the file
646 * table is large enough to hold it, and grab it. Otherwise, just
647 * allocate a new descriptor the usual way. Since the filedesc
648 * lock may be temporarily dropped in the process, we have to look
649 * out for a race.
650 */
651 if (type == DUP_FIXED) {
652 if (new >= fdp->fd_nfiles)
653 fdgrowtable(fdp, new + 1);
654 if (fdp->fd_ofiles[new] == NULL)
655 fdused(fdp, new);
656 } else {
657 if ((error = fdalloc(td, new, &new)) != 0) {
658 FILEDESC_UNLOCK(fdp);
659 fdrop(fp, td);
660 return (error);
661 }
662 }
663
664 /*
665 * If the old file changed out from under us then treat it as a
666 * bad file descriptor. Userland should do its own locking to
667 * avoid this case.
668 */
669 if (fdp->fd_ofiles[old] != fp) {
670 /* we've allocated a descriptor which we won't use */
671 if (fdp->fd_ofiles[new] == NULL)
672 fdunused(fdp, new);
673 FILEDESC_UNLOCK(fdp);
674 fdrop(fp, td);
675 return (EBADF);
676 }
677 KASSERT(old != new,
678 ("new fd is same as old"));
679
680 /*
681 * Save info on the descriptor being overwritten. We cannot close
682 * it without introducing an ownership race for the slot, since we
683 * need to drop the filedesc lock to call closef().
684 *
685 * XXX this duplicates parts of close().
686 */
687 delfp = fdp->fd_ofiles[new];
688 holdleaders = 0;
689 if (delfp != NULL) {
690 if (td->td_proc->p_fdtol != NULL) {
691 /*
692 * Ask fdfree() to sleep to ensure that all relevant
693 * process leaders can be traversed in closef().
694 */
695 fdp->fd_holdleaderscount++;
696 holdleaders = 1;
697 }
698 }
699
700 /*
701 * Duplicate the source descriptor
702 */
703 fdp->fd_ofiles[new] = fp;
704 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
705 if (new > fdp->fd_lastfile)
706 fdp->fd_lastfile = new;
707 *retval = new;
708
709 /*
710 * If we dup'd over a valid file, we now own the reference to it
711 * and must dispose of it using closef() semantics (as if a
712 * close() were performed on it).
713 *
714 * XXX this duplicates parts of close().
715 */
716 if (delfp != NULL) {
717 knote_fdclose(td, new);
718 FILEDESC_UNLOCK(fdp);
719 (void) closef(delfp, td);
720 if (holdleaders) {
721 FILEDESC_LOCK_FAST(fdp);
722 fdp->fd_holdleaderscount--;
723 if (fdp->fd_holdleaderscount == 0 &&
724 fdp->fd_holdleaderswakeup != 0) {
725 fdp->fd_holdleaderswakeup = 0;
726 wakeup(&fdp->fd_holdleaderscount);
727 }
728 FILEDESC_UNLOCK_FAST(fdp);
729 }
730 } else {
731 FILEDESC_UNLOCK(fdp);
732 }
733 return (0);
734 }
735
736 /*
737 * If sigio is on the list associated with a process or process group,
738 * disable signalling from the device, remove sigio from the list and
739 * free sigio.
740 */
741 void
742 funsetown(struct sigio **sigiop)
743 {
744 struct sigio *sigio;
745
746 SIGIO_LOCK();
747 sigio = *sigiop;
748 if (sigio == NULL) {
749 SIGIO_UNLOCK();
750 return;
751 }
752 *(sigio->sio_myref) = NULL;
753 if ((sigio)->sio_pgid < 0) {
754 struct pgrp *pg = (sigio)->sio_pgrp;
755 PGRP_LOCK(pg);
756 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
757 sigio, sio_pgsigio);
758 PGRP_UNLOCK(pg);
759 } else {
760 struct proc *p = (sigio)->sio_proc;
761 PROC_LOCK(p);
762 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
763 sigio, sio_pgsigio);
764 PROC_UNLOCK(p);
765 }
766 SIGIO_UNLOCK();
767 crfree(sigio->sio_ucred);
768 FREE(sigio, M_SIGIO);
769 }
770
771 /*
772 * Free a list of sigio structures.
773 * We only need to lock the SIGIO_LOCK because we have made ourselves
774 * inaccessible to callers of fsetown and therefore do not need to lock
775 * the proc or pgrp struct for the list manipulation.
776 */
777 void
778 funsetownlst(struct sigiolst *sigiolst)
779 {
780 struct proc *p;
781 struct pgrp *pg;
782 struct sigio *sigio;
783
784 sigio = SLIST_FIRST(sigiolst);
785 if (sigio == NULL)
786 return;
787 p = NULL;
788 pg = NULL;
789
790 /*
791 * Every entry of the list should belong
792 * to a single proc or pgrp.
793 */
794 if (sigio->sio_pgid < 0) {
795 pg = sigio->sio_pgrp;
796 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
797 } else /* if (sigio->sio_pgid > 0) */ {
798 p = sigio->sio_proc;
799 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
800 }
801
802 SIGIO_LOCK();
803 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
804 *(sigio->sio_myref) = NULL;
805 if (pg != NULL) {
806 KASSERT(sigio->sio_pgid < 0,
807 ("Proc sigio in pgrp sigio list"));
808 KASSERT(sigio->sio_pgrp == pg,
809 ("Bogus pgrp in sigio list"));
810 PGRP_LOCK(pg);
811 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
812 sio_pgsigio);
813 PGRP_UNLOCK(pg);
814 } else /* if (p != NULL) */ {
815 KASSERT(sigio->sio_pgid > 0,
816 ("Pgrp sigio in proc sigio list"));
817 KASSERT(sigio->sio_proc == p,
818 ("Bogus proc in sigio list"));
819 PROC_LOCK(p);
820 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
821 sio_pgsigio);
822 PROC_UNLOCK(p);
823 }
824 SIGIO_UNLOCK();
825 crfree(sigio->sio_ucred);
826 FREE(sigio, M_SIGIO);
827 SIGIO_LOCK();
828 }
829 SIGIO_UNLOCK();
830 }
831
832 /*
833 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
834 *
835 * After permission checking, add a sigio structure to the sigio list for
836 * the process or process group.
837 */
838 int
839 fsetown(pid_t pgid, struct sigio **sigiop)
840 {
841 struct proc *proc;
842 struct pgrp *pgrp;
843 struct sigio *sigio;
844 int ret;
845
846 if (pgid == 0) {
847 funsetown(sigiop);
848 return (0);
849 }
850
851 ret = 0;
852
853 /* Allocate and fill in the new sigio out of locks. */
854 MALLOC(sigio, struct sigio *, sizeof(struct sigio), M_SIGIO, M_WAITOK);
855 sigio->sio_pgid = pgid;
856 sigio->sio_ucred = crhold(curthread->td_ucred);
857 sigio->sio_myref = sigiop;
858
859 sx_slock(&proctree_lock);
860 if (pgid > 0) {
861 proc = pfind(pgid);
862 if (proc == NULL) {
863 ret = ESRCH;
864 goto fail;
865 }
866
867 /*
868 * Policy - Don't allow a process to FSETOWN a process
869 * in another session.
870 *
871 * Remove this test to allow maximum flexibility or
872 * restrict FSETOWN to the current process or process
873 * group for maximum safety.
874 */
875 PROC_UNLOCK(proc);
876 if (proc->p_session != curthread->td_proc->p_session) {
877 ret = EPERM;
878 goto fail;
879 }
880
881 pgrp = NULL;
882 } else /* if (pgid < 0) */ {
883 pgrp = pgfind(-pgid);
884 if (pgrp == NULL) {
885 ret = ESRCH;
886 goto fail;
887 }
888 PGRP_UNLOCK(pgrp);
889
890 /*
891 * Policy - Don't allow a process to FSETOWN a process
892 * in another session.
893 *
894 * Remove this test to allow maximum flexibility or
895 * restrict FSETOWN to the current process or process
896 * group for maximum safety.
897 */
898 if (pgrp->pg_session != curthread->td_proc->p_session) {
899 ret = EPERM;
900 goto fail;
901 }
902
903 proc = NULL;
904 }
905 funsetown(sigiop);
906 if (pgid > 0) {
907 PROC_LOCK(proc);
908 /*
909 * Since funsetownlst() is called without the proctree
910 * locked, we need to check for P_WEXIT.
911 * XXX: is ESRCH correct?
912 */
913 if ((proc->p_flag & P_WEXIT) != 0) {
914 PROC_UNLOCK(proc);
915 ret = ESRCH;
916 goto fail;
917 }
918 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
919 sigio->sio_proc = proc;
920 PROC_UNLOCK(proc);
921 } else {
922 PGRP_LOCK(pgrp);
923 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
924 sigio->sio_pgrp = pgrp;
925 PGRP_UNLOCK(pgrp);
926 }
927 sx_sunlock(&proctree_lock);
928 SIGIO_LOCK();
929 *sigiop = sigio;
930 SIGIO_UNLOCK();
931 return (0);
932
933 fail:
934 sx_sunlock(&proctree_lock);
935 crfree(sigio->sio_ucred);
936 FREE(sigio, M_SIGIO);
937 return (ret);
938 }
939
940 /*
941 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
942 */
943 pid_t
944 fgetown(sigiop)
945 struct sigio **sigiop;
946 {
947 pid_t pgid;
948
949 SIGIO_LOCK();
950 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
951 SIGIO_UNLOCK();
952 return (pgid);
953 }
954
955 /*
956 * Close a file descriptor.
957 */
958 #ifndef _SYS_SYSPROTO_H_
959 struct close_args {
960 int fd;
961 };
962 #endif
963 /*
964 * MPSAFE
965 */
966 /* ARGSUSED */
967 int
968 close(td, uap)
969 struct thread *td;
970 struct close_args *uap;
971 {
972 struct filedesc *fdp;
973 struct file *fp;
974 int fd, error;
975 int holdleaders;
976
977 fd = uap->fd;
978 error = 0;
979 holdleaders = 0;
980 fdp = td->td_proc->p_fd;
981
982 AUDIT_SYSCLOSE(td, fd);
983
984 FILEDESC_LOCK(fdp);
985 if ((unsigned)fd >= fdp->fd_nfiles ||
986 (fp = fdp->fd_ofiles[fd]) == NULL) {
987 FILEDESC_UNLOCK(fdp);
988 return (EBADF);
989 }
990 fdp->fd_ofiles[fd] = NULL;
991 fdp->fd_ofileflags[fd] = 0;
992 fdunused(fdp, fd);
993 if (td->td_proc->p_fdtol != NULL) {
994 /*
995 * Ask fdfree() to sleep to ensure that all relevant
996 * process leaders can be traversed in closef().
997 */
998 fdp->fd_holdleaderscount++;
999 holdleaders = 1;
1000 }
1001
1002 /*
1003 * We now hold the fp reference that used to be owned by the descriptor
1004 * array.
1005 * We have to unlock the FILEDESC *AFTER* knote_fdclose to prevent a
1006 * race of the fd getting opened, a knote added, and deleteing a knote
1007 * for the new fd.
1008 */
1009 knote_fdclose(td, fd);
1010 FILEDESC_UNLOCK(fdp);
1011
1012 error = closef(fp, td);
1013 if (holdleaders) {
1014 FILEDESC_LOCK_FAST(fdp);
1015 fdp->fd_holdleaderscount--;
1016 if (fdp->fd_holdleaderscount == 0 &&
1017 fdp->fd_holdleaderswakeup != 0) {
1018 fdp->fd_holdleaderswakeup = 0;
1019 wakeup(&fdp->fd_holdleaderscount);
1020 }
1021 FILEDESC_UNLOCK_FAST(fdp);
1022 }
1023 return (error);
1024 }
1025
1026 #if defined(COMPAT_43)
1027 /*
1028 * Return status information about a file descriptor.
1029 */
1030 #ifndef _SYS_SYSPROTO_H_
1031 struct ofstat_args {
1032 int fd;
1033 struct ostat *sb;
1034 };
1035 #endif
1036 /*
1037 * MPSAFE
1038 */
1039 /* ARGSUSED */
1040 int
1041 ofstat(struct thread *td, struct ofstat_args *uap)
1042 {
1043 struct ostat oub;
1044 struct stat ub;
1045 int error;
1046
1047 error = kern_fstat(td, uap->fd, &ub);
1048 if (error == 0) {
1049 cvtstat(&ub, &oub);
1050 error = copyout(&oub, uap->sb, sizeof(oub));
1051 }
1052 return (error);
1053 }
1054 #endif /* COMPAT_43 */
1055
1056 /*
1057 * Return status information about a file descriptor.
1058 */
1059 #ifndef _SYS_SYSPROTO_H_
1060 struct fstat_args {
1061 int fd;
1062 struct stat *sb;
1063 };
1064 #endif
1065 /*
1066 * MPSAFE
1067 */
1068 /* ARGSUSED */
1069 int
1070 fstat(struct thread *td, struct fstat_args *uap)
1071 {
1072 struct stat ub;
1073 int error;
1074
1075 error = kern_fstat(td, uap->fd, &ub);
1076 if (error == 0)
1077 error = copyout(&ub, uap->sb, sizeof(ub));
1078 return (error);
1079 }
1080
1081 int
1082 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1083 {
1084 struct file *fp;
1085 int error;
1086
1087 AUDIT_ARG(fd, fd);
1088
1089 if ((error = fget(td, fd, &fp)) != 0)
1090 return (error);
1091
1092 AUDIT_ARG(file, td->td_proc, fp);
1093
1094 error = fo_stat(fp, sbp, td->td_ucred, td);
1095 fdrop(fp, td);
1096 return (error);
1097 }
1098
1099 /*
1100 * Return status information about a file descriptor.
1101 */
1102 #ifndef _SYS_SYSPROTO_H_
1103 struct nfstat_args {
1104 int fd;
1105 struct nstat *sb;
1106 };
1107 #endif
1108 /*
1109 * MPSAFE
1110 */
1111 /* ARGSUSED */
1112 int
1113 nfstat(struct thread *td, struct nfstat_args *uap)
1114 {
1115 struct nstat nub;
1116 struct stat ub;
1117 int error;
1118
1119 error = kern_fstat(td, uap->fd, &ub);
1120 if (error == 0) {
1121 cvtnstat(&ub, &nub);
1122 error = copyout(&nub, uap->sb, sizeof(nub));
1123 }
1124 return (error);
1125 }
1126
1127 /*
1128 * Return pathconf information about a file descriptor.
1129 */
1130 #ifndef _SYS_SYSPROTO_H_
1131 struct fpathconf_args {
1132 int fd;
1133 int name;
1134 };
1135 #endif
1136 /*
1137 * MPSAFE
1138 */
1139 /* ARGSUSED */
1140 int
1141 fpathconf(struct thread *td, struct fpathconf_args *uap)
1142 {
1143 struct file *fp;
1144 struct vnode *vp;
1145 int error;
1146
1147 if ((error = fget(td, uap->fd, &fp)) != 0)
1148 return (error);
1149
1150 /* If asynchronous I/O is available, it works for all descriptors. */
1151 if (uap->name == _PC_ASYNC_IO) {
1152 td->td_retval[0] = async_io_version;
1153 goto out;
1154 }
1155 vp = fp->f_vnode;
1156 if (vp != NULL) {
1157 int vfslocked;
1158 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1159 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
1160 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1161 VOP_UNLOCK(vp, 0, td);
1162 VFS_UNLOCK_GIANT(vfslocked);
1163 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1164 if (uap->name != _PC_PIPE_BUF) {
1165 error = EINVAL;
1166 } else {
1167 td->td_retval[0] = PIPE_BUF;
1168 error = 0;
1169 }
1170 } else {
1171 error = EOPNOTSUPP;
1172 }
1173 out:
1174 fdrop(fp, td);
1175 return (error);
1176 }
1177
1178 /*
1179 * Grow the file table to accomodate (at least) nfd descriptors. This may
1180 * block and drop the filedesc lock, but it will reacquire it before
1181 * returning.
1182 */
1183 static void
1184 fdgrowtable(struct filedesc *fdp, int nfd)
1185 {
1186 struct file **ntable;
1187 char *nfileflags;
1188 int nnfiles, onfiles;
1189 NDSLOTTYPE *nmap;
1190
1191 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1192
1193 KASSERT(fdp->fd_nfiles > 0,
1194 ("zero-length file table"));
1195
1196 /* compute the size of the new table */
1197 onfiles = fdp->fd_nfiles;
1198 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1199 if (nnfiles <= onfiles)
1200 /* the table is already large enough */
1201 return;
1202
1203 /* allocate a new table and (if required) new bitmaps */
1204 FILEDESC_UNLOCK(fdp);
1205 MALLOC(ntable, struct file **, nnfiles * OFILESIZE,
1206 M_FILEDESC, M_ZERO | M_WAITOK);
1207 nfileflags = (char *)&ntable[nnfiles];
1208 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1209 MALLOC(nmap, NDSLOTTYPE *, NDSLOTS(nnfiles) * NDSLOTSIZE,
1210 M_FILEDESC, M_ZERO | M_WAITOK);
1211 else
1212 nmap = NULL;
1213 FILEDESC_LOCK(fdp);
1214
1215 /*
1216 * We now have new tables ready to go. Since we dropped the
1217 * filedesc lock to call malloc(), watch out for a race.
1218 */
1219 onfiles = fdp->fd_nfiles;
1220 if (onfiles >= nnfiles) {
1221 /* we lost the race, but that's OK */
1222 free(ntable, M_FILEDESC);
1223 if (nmap != NULL)
1224 free(nmap, M_FILEDESC);
1225 return;
1226 }
1227 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1228 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1229 if (onfiles > NDFILE)
1230 free(fdp->fd_ofiles, M_FILEDESC);
1231 fdp->fd_ofiles = ntable;
1232 fdp->fd_ofileflags = nfileflags;
1233 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1234 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1235 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1236 free(fdp->fd_map, M_FILEDESC);
1237 fdp->fd_map = nmap;
1238 }
1239 fdp->fd_nfiles = nnfiles;
1240 }
1241
1242 /*
1243 * Allocate a file descriptor for the process.
1244 */
1245 int
1246 fdalloc(struct thread *td, int minfd, int *result)
1247 {
1248 struct proc *p = td->td_proc;
1249 struct filedesc *fdp = p->p_fd;
1250 int fd = -1, maxfd;
1251
1252 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1253
1254 if (fdp->fd_freefile > minfd)
1255 minfd = fdp->fd_freefile;
1256
1257 PROC_LOCK(p);
1258 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1259 PROC_UNLOCK(p);
1260
1261 /*
1262 * Search the bitmap for a free descriptor. If none is found, try
1263 * to grow the file table. Keep at it until we either get a file
1264 * descriptor or run into process or system limits; fdgrowtable()
1265 * may drop the filedesc lock, so we're in a race.
1266 */
1267 for (;;) {
1268 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1269 if (fd >= maxfd)
1270 return (EMFILE);
1271 if (fd < fdp->fd_nfiles)
1272 break;
1273 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1274 }
1275
1276 /*
1277 * Perform some sanity checks, then mark the file descriptor as
1278 * used and return it to the caller.
1279 */
1280 KASSERT(!fdisused(fdp, fd),
1281 ("fd_first_free() returned non-free descriptor"));
1282 KASSERT(fdp->fd_ofiles[fd] == NULL,
1283 ("free descriptor isn't"));
1284 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1285 fdused(fdp, fd);
1286 *result = fd;
1287 return (0);
1288 }
1289
1290 /*
1291 * Check to see whether n user file descriptors
1292 * are available to the process p.
1293 */
1294 int
1295 fdavail(struct thread *td, int n)
1296 {
1297 struct proc *p = td->td_proc;
1298 struct filedesc *fdp = td->td_proc->p_fd;
1299 struct file **fpp;
1300 int i, lim, last;
1301
1302 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1303
1304 PROC_LOCK(p);
1305 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1306 PROC_UNLOCK(p);
1307 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1308 return (1);
1309 last = min(fdp->fd_nfiles, lim);
1310 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1311 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1312 if (*fpp == NULL && --n <= 0)
1313 return (1);
1314 }
1315 return (0);
1316 }
1317
1318 /*
1319 * Create a new open file structure and allocate
1320 * a file decriptor for the process that refers to it.
1321 * We add one reference to the file for the descriptor table
1322 * and one reference for resultfp. This is to prevent us being
1323 * preempted and the entry in the descriptor table closed after
1324 * we release the FILEDESC lock.
1325 */
1326 int
1327 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1328 {
1329 struct proc *p = td->td_proc;
1330 struct file *fp, *fq;
1331 int error, i;
1332 int maxuserfiles = maxfiles - (maxfiles / 20);
1333 static struct timeval lastfail;
1334 static int curfail;
1335
1336 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1337 sx_xlock(&filelist_lock);
1338
1339 if ((openfiles >= maxuserfiles &&
1340 suser_cred(td->td_ucred, SUSER_RUID) != 0) ||
1341 openfiles >= maxfiles) {
1342 if (ppsratecheck(&lastfail, &curfail, 1)) {
1343 printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1344 td->td_ucred->cr_ruid);
1345 }
1346 sx_xunlock(&filelist_lock);
1347 uma_zfree(file_zone, fp);
1348 return (ENFILE);
1349 }
1350 openfiles++;
1351
1352 /*
1353 * If the process has file descriptor zero open, add the new file
1354 * descriptor to the list of open files at that point, otherwise
1355 * put it at the front of the list of open files.
1356 */
1357 fp->f_mtxp = mtx_pool_alloc(mtxpool_sleep);
1358 fp->f_count = 1;
1359 if (resultfp)
1360 fp->f_count++;
1361 fp->f_cred = crhold(td->td_ucred);
1362 fp->f_ops = &badfileops;
1363 fp->f_data = NULL;
1364 fp->f_vnode = NULL;
1365 FILEDESC_LOCK(p->p_fd);
1366 if ((fq = p->p_fd->fd_ofiles[0])) {
1367 LIST_INSERT_AFTER(fq, fp, f_list);
1368 } else {
1369 LIST_INSERT_HEAD(&filehead, fp, f_list);
1370 }
1371 sx_xunlock(&filelist_lock);
1372 if ((error = fdalloc(td, 0, &i))) {
1373 FILEDESC_UNLOCK(p->p_fd);
1374 fdrop(fp, td);
1375 if (resultfp)
1376 fdrop(fp, td);
1377 return (error);
1378 }
1379 p->p_fd->fd_ofiles[i] = fp;
1380 FILEDESC_UNLOCK(p->p_fd);
1381 if (resultfp)
1382 *resultfp = fp;
1383 if (resultfd)
1384 *resultfd = i;
1385 return (0);
1386 }
1387
1388 /*
1389 * Build a new filedesc structure from another.
1390 * Copy the current, root, and jail root vnode references.
1391 */
1392 struct filedesc *
1393 fdinit(struct filedesc *fdp)
1394 {
1395 struct filedesc0 *newfdp;
1396
1397 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1398 mtx_init(&newfdp->fd_fd.fd_mtx, FILEDESC_LOCK_DESC, NULL, MTX_DEF);
1399 if (fdp != NULL) {
1400 FILEDESC_LOCK(fdp);
1401 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1402 if (newfdp->fd_fd.fd_cdir)
1403 VREF(newfdp->fd_fd.fd_cdir);
1404 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1405 if (newfdp->fd_fd.fd_rdir)
1406 VREF(newfdp->fd_fd.fd_rdir);
1407 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1408 if (newfdp->fd_fd.fd_jdir)
1409 VREF(newfdp->fd_fd.fd_jdir);
1410 FILEDESC_UNLOCK(fdp);
1411 }
1412
1413 /* Create the file descriptor table. */
1414 newfdp->fd_fd.fd_refcnt = 1;
1415 newfdp->fd_fd.fd_holdcnt = 1;
1416 newfdp->fd_fd.fd_cmask = CMASK;
1417 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1418 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1419 newfdp->fd_fd.fd_nfiles = NDFILE;
1420 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1421 newfdp->fd_fd.fd_lastfile = -1;
1422 return (&newfdp->fd_fd);
1423 }
1424
1425 static struct filedesc *
1426 fdhold(struct proc *p)
1427 {
1428 struct filedesc *fdp;
1429
1430 mtx_lock(&fdesc_mtx);
1431 fdp = p->p_fd;
1432 if (fdp != NULL)
1433 fdp->fd_holdcnt++;
1434 mtx_unlock(&fdesc_mtx);
1435 return (fdp);
1436 }
1437
1438 static void
1439 fddrop(struct filedesc *fdp)
1440 {
1441 int i;
1442
1443 mtx_lock(&fdesc_mtx);
1444 i = --fdp->fd_holdcnt;
1445 mtx_unlock(&fdesc_mtx);
1446 if (i > 0)
1447 return;
1448
1449 mtx_destroy(&fdp->fd_mtx);
1450 FREE(fdp, M_FILEDESC);
1451 }
1452
1453 /*
1454 * Share a filedesc structure.
1455 */
1456 struct filedesc *
1457 fdshare(struct filedesc *fdp)
1458 {
1459 FILEDESC_LOCK_FAST(fdp);
1460 fdp->fd_refcnt++;
1461 FILEDESC_UNLOCK_FAST(fdp);
1462 return (fdp);
1463 }
1464
1465 /*
1466 * Unshare a filedesc structure, if necessary by making a copy
1467 */
1468 void
1469 fdunshare(struct proc *p, struct thread *td)
1470 {
1471
1472 FILEDESC_LOCK_FAST(p->p_fd);
1473 if (p->p_fd->fd_refcnt > 1) {
1474 struct filedesc *tmp;
1475
1476 FILEDESC_UNLOCK_FAST(p->p_fd);
1477 tmp = fdcopy(p->p_fd);
1478 fdfree(td);
1479 p->p_fd = tmp;
1480 } else
1481 FILEDESC_UNLOCK_FAST(p->p_fd);
1482 }
1483
1484 /*
1485 * Copy a filedesc structure.
1486 * A NULL pointer in returns a NULL reference, this is to ease callers,
1487 * not catch errors.
1488 */
1489 struct filedesc *
1490 fdcopy(struct filedesc *fdp)
1491 {
1492 struct filedesc *newfdp;
1493 int i;
1494
1495 /* Certain daemons might not have file descriptors. */
1496 if (fdp == NULL)
1497 return (NULL);
1498
1499 newfdp = fdinit(fdp);
1500 FILEDESC_LOCK_FAST(fdp);
1501 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1502 FILEDESC_UNLOCK_FAST(fdp);
1503 FILEDESC_LOCK(newfdp);
1504 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1505 FILEDESC_UNLOCK(newfdp);
1506 FILEDESC_LOCK_FAST(fdp);
1507 }
1508 /* copy everything except kqueue descriptors */
1509 newfdp->fd_freefile = -1;
1510 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1511 if (fdisused(fdp, i) &&
1512 fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE) {
1513 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1514 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1515 fhold(newfdp->fd_ofiles[i]);
1516 newfdp->fd_lastfile = i;
1517 } else {
1518 if (newfdp->fd_freefile == -1)
1519 newfdp->fd_freefile = i;
1520 }
1521 }
1522 FILEDESC_UNLOCK_FAST(fdp);
1523 FILEDESC_LOCK(newfdp);
1524 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1525 if (newfdp->fd_ofiles[i] != NULL)
1526 fdused(newfdp, i);
1527 FILEDESC_UNLOCK(newfdp);
1528 FILEDESC_LOCK_FAST(fdp);
1529 if (newfdp->fd_freefile == -1)
1530 newfdp->fd_freefile = i;
1531 newfdp->fd_cmask = fdp->fd_cmask;
1532 FILEDESC_UNLOCK_FAST(fdp);
1533 return (newfdp);
1534 }
1535
1536 /*
1537 * Release a filedesc structure.
1538 */
1539 void
1540 fdfree(struct thread *td)
1541 {
1542 struct filedesc *fdp;
1543 struct file **fpp;
1544 int i, locked;
1545 struct filedesc_to_leader *fdtol;
1546 struct file *fp;
1547 struct vnode *cdir, *jdir, *rdir, *vp;
1548 struct flock lf;
1549
1550 /* Certain daemons might not have file descriptors. */
1551 fdp = td->td_proc->p_fd;
1552 if (fdp == NULL)
1553 return;
1554
1555 /* Check for special need to clear POSIX style locks */
1556 fdtol = td->td_proc->p_fdtol;
1557 if (fdtol != NULL) {
1558 FILEDESC_LOCK(fdp);
1559 KASSERT(fdtol->fdl_refcount > 0,
1560 ("filedesc_to_refcount botch: fdl_refcount=%d",
1561 fdtol->fdl_refcount));
1562 if (fdtol->fdl_refcount == 1 &&
1563 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1564 for (i = 0, fpp = fdp->fd_ofiles;
1565 i <= fdp->fd_lastfile;
1566 i++, fpp++) {
1567 if (*fpp == NULL ||
1568 (*fpp)->f_type != DTYPE_VNODE)
1569 continue;
1570 fp = *fpp;
1571 fhold(fp);
1572 FILEDESC_UNLOCK(fdp);
1573 lf.l_whence = SEEK_SET;
1574 lf.l_start = 0;
1575 lf.l_len = 0;
1576 lf.l_type = F_UNLCK;
1577 vp = fp->f_vnode;
1578 locked = VFS_LOCK_GIANT(vp->v_mount);
1579 (void) VOP_ADVLOCK(vp,
1580 (caddr_t)td->td_proc->
1581 p_leader,
1582 F_UNLCK,
1583 &lf,
1584 F_POSIX);
1585 VFS_UNLOCK_GIANT(locked);
1586 FILEDESC_LOCK(fdp);
1587 fdrop(fp, td);
1588 fpp = fdp->fd_ofiles + i;
1589 }
1590 }
1591 retry:
1592 if (fdtol->fdl_refcount == 1) {
1593 if (fdp->fd_holdleaderscount > 0 &&
1594 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1595 /*
1596 * close() or do_dup() has cleared a reference
1597 * in a shared file descriptor table.
1598 */
1599 fdp->fd_holdleaderswakeup = 1;
1600 msleep(&fdp->fd_holdleaderscount, &fdp->fd_mtx,
1601 PLOCK, "fdlhold", 0);
1602 goto retry;
1603 }
1604 if (fdtol->fdl_holdcount > 0) {
1605 /*
1606 * Ensure that fdtol->fdl_leader
1607 * remains valid in closef().
1608 */
1609 fdtol->fdl_wakeup = 1;
1610 msleep(fdtol, &fdp->fd_mtx,
1611 PLOCK, "fdlhold", 0);
1612 goto retry;
1613 }
1614 }
1615 fdtol->fdl_refcount--;
1616 if (fdtol->fdl_refcount == 0 &&
1617 fdtol->fdl_holdcount == 0) {
1618 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1619 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1620 } else
1621 fdtol = NULL;
1622 td->td_proc->p_fdtol = NULL;
1623 FILEDESC_UNLOCK(fdp);
1624 if (fdtol != NULL)
1625 FREE(fdtol, M_FILEDESC_TO_LEADER);
1626 }
1627 FILEDESC_LOCK_FAST(fdp);
1628 i = --fdp->fd_refcnt;
1629 FILEDESC_UNLOCK_FAST(fdp);
1630 if (i > 0)
1631 return;
1632 /*
1633 * We are the last reference to the structure, so we can
1634 * safely assume it will not change out from under us.
1635 */
1636 fpp = fdp->fd_ofiles;
1637 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1638 if (*fpp)
1639 (void) closef(*fpp, td);
1640 }
1641 FILEDESC_LOCK(fdp);
1642
1643 /* XXX This should happen earlier. */
1644 mtx_lock(&fdesc_mtx);
1645 td->td_proc->p_fd = NULL;
1646 mtx_unlock(&fdesc_mtx);
1647
1648 if (fdp->fd_nfiles > NDFILE)
1649 FREE(fdp->fd_ofiles, M_FILEDESC);
1650 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1651 FREE(fdp->fd_map, M_FILEDESC);
1652
1653 fdp->fd_nfiles = 0;
1654
1655 cdir = fdp->fd_cdir;
1656 fdp->fd_cdir = NULL;
1657 rdir = fdp->fd_rdir;
1658 fdp->fd_rdir = NULL;
1659 jdir = fdp->fd_jdir;
1660 fdp->fd_jdir = NULL;
1661 FILEDESC_UNLOCK(fdp);
1662
1663 if (cdir) {
1664 locked = VFS_LOCK_GIANT(cdir->v_mount);
1665 vrele(cdir);
1666 VFS_UNLOCK_GIANT(locked);
1667 }
1668 if (rdir) {
1669 locked = VFS_LOCK_GIANT(rdir->v_mount);
1670 vrele(rdir);
1671 VFS_UNLOCK_GIANT(locked);
1672 }
1673 if (jdir) {
1674 locked = VFS_LOCK_GIANT(jdir->v_mount);
1675 vrele(jdir);
1676 VFS_UNLOCK_GIANT(locked);
1677 }
1678
1679 fddrop(fdp);
1680 }
1681
1682 /*
1683 * For setugid programs, we don't want to people to use that setugidness
1684 * to generate error messages which write to a file which otherwise would
1685 * otherwise be off-limits to the process. We check for filesystems where
1686 * the vnode can change out from under us after execve (like [lin]procfs).
1687 *
1688 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1689 * sufficient. We also don't check for setugidness since we know we are.
1690 */
1691 static int
1692 is_unsafe(struct file *fp)
1693 {
1694 if (fp->f_type == DTYPE_VNODE) {
1695 struct vnode *vp = fp->f_vnode;
1696
1697 if ((vp->v_vflag & VV_PROCDEP) != 0)
1698 return (1);
1699 }
1700 return (0);
1701 }
1702
1703 /*
1704 * Make this setguid thing safe, if at all possible.
1705 */
1706 void
1707 setugidsafety(struct thread *td)
1708 {
1709 struct filedesc *fdp;
1710 int i;
1711
1712 /* Certain daemons might not have file descriptors. */
1713 fdp = td->td_proc->p_fd;
1714 if (fdp == NULL)
1715 return;
1716
1717 /*
1718 * Note: fdp->fd_ofiles may be reallocated out from under us while
1719 * we are blocked in a close. Be careful!
1720 */
1721 FILEDESC_LOCK(fdp);
1722 for (i = 0; i <= fdp->fd_lastfile; i++) {
1723 if (i > 2)
1724 break;
1725 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1726 struct file *fp;
1727
1728 knote_fdclose(td, i);
1729 /*
1730 * NULL-out descriptor prior to close to avoid
1731 * a race while close blocks.
1732 */
1733 fp = fdp->fd_ofiles[i];
1734 fdp->fd_ofiles[i] = NULL;
1735 fdp->fd_ofileflags[i] = 0;
1736 fdunused(fdp, i);
1737 FILEDESC_UNLOCK(fdp);
1738 (void) closef(fp, td);
1739 FILEDESC_LOCK(fdp);
1740 }
1741 }
1742 FILEDESC_UNLOCK(fdp);
1743 }
1744
1745 void
1746 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1747 {
1748
1749 FILEDESC_LOCK(fdp);
1750 if (fdp->fd_ofiles[idx] == fp) {
1751 fdp->fd_ofiles[idx] = NULL;
1752 fdunused(fdp, idx);
1753 FILEDESC_UNLOCK(fdp);
1754 fdrop(fp, td);
1755 } else {
1756 FILEDESC_UNLOCK(fdp);
1757 }
1758 }
1759
1760 /*
1761 * Close any files on exec?
1762 */
1763 void
1764 fdcloseexec(struct thread *td)
1765 {
1766 struct filedesc *fdp;
1767 int i;
1768
1769 /* Certain daemons might not have file descriptors. */
1770 fdp = td->td_proc->p_fd;
1771 if (fdp == NULL)
1772 return;
1773
1774 FILEDESC_LOCK(fdp);
1775
1776 /*
1777 * We cannot cache fd_ofiles or fd_ofileflags since operations
1778 * may block and rip them out from under us.
1779 */
1780 for (i = 0; i <= fdp->fd_lastfile; i++) {
1781 if (fdp->fd_ofiles[i] != NULL &&
1782 (fdp->fd_ofileflags[i] & UF_EXCLOSE)) {
1783 struct file *fp;
1784
1785 knote_fdclose(td, i);
1786 /*
1787 * NULL-out descriptor prior to close to avoid
1788 * a race while close blocks.
1789 */
1790 fp = fdp->fd_ofiles[i];
1791 fdp->fd_ofiles[i] = NULL;
1792 fdp->fd_ofileflags[i] = 0;
1793 fdunused(fdp, i);
1794 FILEDESC_UNLOCK(fdp);
1795 (void) closef(fp, td);
1796 FILEDESC_LOCK(fdp);
1797 }
1798 }
1799 FILEDESC_UNLOCK(fdp);
1800 }
1801
1802 /*
1803 * It is unsafe for set[ug]id processes to be started with file
1804 * descriptors 0..2 closed, as these descriptors are given implicit
1805 * significance in the Standard C library. fdcheckstd() will create a
1806 * descriptor referencing /dev/null for each of stdin, stdout, and
1807 * stderr that is not already open.
1808 */
1809 int
1810 fdcheckstd(struct thread *td)
1811 {
1812 struct nameidata nd;
1813 struct filedesc *fdp;
1814 struct file *fp;
1815 register_t retval;
1816 int fd, i, error, flags, devnull;
1817
1818 fdp = td->td_proc->p_fd;
1819 if (fdp == NULL)
1820 return (0);
1821 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
1822 devnull = -1;
1823 error = 0;
1824 for (i = 0; i < 3; i++) {
1825 if (fdp->fd_ofiles[i] != NULL)
1826 continue;
1827 if (devnull < 0) {
1828 int vfslocked;
1829 error = falloc(td, &fp, &fd);
1830 if (error != 0)
1831 break;
1832 /* Note extra ref on `fp' held for us by falloc(). */
1833 KASSERT(fd == i, ("oof, we didn't get our fd"));
1834 NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE,
1835 "/dev/null", td);
1836 flags = FREAD | FWRITE;
1837 error = vn_open(&nd, &flags, 0, fd);
1838 if (error != 0) {
1839 /*
1840 * Someone may have closed the entry in the
1841 * file descriptor table, so check it hasn't
1842 * changed before dropping the reference count.
1843 */
1844 FILEDESC_LOCK(fdp);
1845 KASSERT(fdp->fd_ofiles[fd] == fp,
1846 ("table not shared, how did it change?"));
1847 fdp->fd_ofiles[fd] = NULL;
1848 fdunused(fdp, fd);
1849 FILEDESC_UNLOCK(fdp);
1850 fdrop(fp, td);
1851 fdrop(fp, td);
1852 break;
1853 }
1854 vfslocked = NDHASGIANT(&nd);
1855 NDFREE(&nd, NDF_ONLY_PNBUF);
1856 fp->f_flag = flags;
1857 fp->f_vnode = nd.ni_vp;
1858 if (fp->f_data == NULL)
1859 fp->f_data = nd.ni_vp;
1860 if (fp->f_ops == &badfileops)
1861 fp->f_ops = &vnops;
1862 fp->f_type = DTYPE_VNODE;
1863 VOP_UNLOCK(nd.ni_vp, 0, td);
1864 VFS_UNLOCK_GIANT(vfslocked);
1865 devnull = fd;
1866 fdrop(fp, td);
1867 } else {
1868 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
1869 if (error != 0)
1870 break;
1871 }
1872 }
1873 return (error);
1874 }
1875
1876 /*
1877 * Internal form of close.
1878 * Decrement reference count on file structure.
1879 * Note: td may be NULL when closing a file that was being passed in a
1880 * message.
1881 *
1882 * XXXRW: Giant is not required for the caller, but often will be held; this
1883 * makes it moderately likely the Giant will be recursed in the VFS case.
1884 */
1885 int
1886 closef(struct file *fp, struct thread *td)
1887 {
1888 struct vnode *vp;
1889 struct flock lf;
1890 struct filedesc_to_leader *fdtol;
1891 struct filedesc *fdp;
1892
1893 /*
1894 * POSIX record locking dictates that any close releases ALL
1895 * locks owned by this process. This is handled by setting
1896 * a flag in the unlock to free ONLY locks obeying POSIX
1897 * semantics, and not to free BSD-style file locks.
1898 * If the descriptor was in a message, POSIX-style locks
1899 * aren't passed with the descriptor, and the thread pointer
1900 * will be NULL. Callers should be careful only to pass a
1901 * NULL thread pointer when there really is no owning
1902 * context that might have locks, or the locks will be
1903 * leaked.
1904 */
1905 if (fp->f_type == DTYPE_VNODE && td != NULL) {
1906 int vfslocked;
1907
1908 vp = fp->f_vnode;
1909 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1910 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1911 lf.l_whence = SEEK_SET;
1912 lf.l_start = 0;
1913 lf.l_len = 0;
1914 lf.l_type = F_UNLCK;
1915 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
1916 F_UNLCK, &lf, F_POSIX);
1917 }
1918 fdtol = td->td_proc->p_fdtol;
1919 if (fdtol != NULL) {
1920 /*
1921 * Handle special case where file descriptor table
1922 * is shared between multiple process leaders.
1923 */
1924 fdp = td->td_proc->p_fd;
1925 FILEDESC_LOCK(fdp);
1926 for (fdtol = fdtol->fdl_next;
1927 fdtol != td->td_proc->p_fdtol;
1928 fdtol = fdtol->fdl_next) {
1929 if ((fdtol->fdl_leader->p_flag &
1930 P_ADVLOCK) == 0)
1931 continue;
1932 fdtol->fdl_holdcount++;
1933 FILEDESC_UNLOCK(fdp);
1934 lf.l_whence = SEEK_SET;
1935 lf.l_start = 0;
1936 lf.l_len = 0;
1937 lf.l_type = F_UNLCK;
1938 vp = fp->f_vnode;
1939 (void) VOP_ADVLOCK(vp,
1940 (caddr_t)fdtol->fdl_leader,
1941 F_UNLCK, &lf, F_POSIX);
1942 FILEDESC_LOCK(fdp);
1943 fdtol->fdl_holdcount--;
1944 if (fdtol->fdl_holdcount == 0 &&
1945 fdtol->fdl_wakeup != 0) {
1946 fdtol->fdl_wakeup = 0;
1947 wakeup(fdtol);
1948 }
1949 }
1950 FILEDESC_UNLOCK(fdp);
1951 }
1952 VFS_UNLOCK_GIANT(vfslocked);
1953 }
1954 return (fdrop(fp, td));
1955 }
1956
1957 /*
1958 * Extract the file pointer associated with the specified descriptor for
1959 * the current user process.
1960 *
1961 * If the descriptor doesn't exist, EBADF is returned.
1962 *
1963 * If the descriptor exists but doesn't match 'flags' then
1964 * return EBADF for read attempts and EINVAL for write attempts.
1965 *
1966 * If 'hold' is set (non-zero) the file's refcount will be bumped on return.
1967 * It should be dropped with fdrop().
1968 * If it is not set, then the refcount will not be bumped however the
1969 * thread's filedesc struct will be returned locked (for fgetsock).
1970 *
1971 * If an error occured the non-zero error is returned and *fpp is set to NULL.
1972 * Otherwise *fpp is set and zero is returned.
1973 */
1974 static __inline int
1975 _fget(struct thread *td, int fd, struct file **fpp, int flags, int hold)
1976 {
1977 struct filedesc *fdp;
1978 struct file *fp;
1979
1980 *fpp = NULL;
1981 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
1982 return (EBADF);
1983 FILEDESC_LOCK(fdp);
1984 if ((fp = fget_locked(fdp, fd)) == NULL || fp->f_ops == &badfileops) {
1985 FILEDESC_UNLOCK(fdp);
1986 return (EBADF);
1987 }
1988
1989 /*
1990 * Note: FREAD failure returns EBADF to maintain backwards
1991 * compatibility with what routines returned before.
1992 *
1993 * Only one flag, or 0, may be specified.
1994 */
1995 if (flags == FREAD && (fp->f_flag & FREAD) == 0) {
1996 FILEDESC_UNLOCK(fdp);
1997 return (EBADF);
1998 }
1999 if (flags == FWRITE && (fp->f_flag & FWRITE) == 0) {
2000 FILEDESC_UNLOCK(fdp);
2001 return (EINVAL);
2002 }
2003 if (hold) {
2004 fhold(fp);
2005 FILEDESC_UNLOCK(fdp);
2006 }
2007 *fpp = fp;
2008 return (0);
2009 }
2010
2011 int
2012 fget(struct thread *td, int fd, struct file **fpp)
2013 {
2014
2015 return(_fget(td, fd, fpp, 0, 1));
2016 }
2017
2018 int
2019 fget_read(struct thread *td, int fd, struct file **fpp)
2020 {
2021
2022 return(_fget(td, fd, fpp, FREAD, 1));
2023 }
2024
2025 int
2026 fget_write(struct thread *td, int fd, struct file **fpp)
2027 {
2028
2029 return(_fget(td, fd, fpp, FWRITE, 1));
2030 }
2031
2032 /*
2033 * Like fget() but loads the underlying vnode, or returns an error if
2034 * the descriptor does not represent a vnode. Note that pipes use vnodes
2035 * but never have VM objects. The returned vnode will be vref()d.
2036 *
2037 * XXX: what about the unused flags ?
2038 */
2039 static __inline int
2040 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2041 {
2042 struct file *fp;
2043 int error;
2044
2045 *vpp = NULL;
2046 if ((error = _fget(td, fd, &fp, flags, 0)) != 0)
2047 return (error);
2048 if (fp->f_vnode == NULL) {
2049 error = EINVAL;
2050 } else {
2051 *vpp = fp->f_vnode;
2052 vref(*vpp);
2053 }
2054 FILEDESC_UNLOCK(td->td_proc->p_fd);
2055 return (error);
2056 }
2057
2058 int
2059 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2060 {
2061
2062 return (_fgetvp(td, fd, vpp, 0));
2063 }
2064
2065 int
2066 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2067 {
2068
2069 return (_fgetvp(td, fd, vpp, FREAD));
2070 }
2071
2072 #ifdef notyet
2073 int
2074 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2075 {
2076
2077 return (_fgetvp(td, fd, vpp, FWRITE));
2078 }
2079 #endif
2080
2081 /*
2082 * Like fget() but loads the underlying socket, or returns an error if
2083 * the descriptor does not represent a socket.
2084 *
2085 * We bump the ref count on the returned socket. XXX Also obtain the SX
2086 * lock in the future.
2087 */
2088 int
2089 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2090 {
2091 struct file *fp;
2092 int error;
2093
2094 NET_ASSERT_GIANT();
2095
2096 *spp = NULL;
2097 if (fflagp != NULL)
2098 *fflagp = 0;
2099 if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
2100 return (error);
2101 if (fp->f_type != DTYPE_SOCKET) {
2102 error = ENOTSOCK;
2103 } else {
2104 *spp = fp->f_data;
2105 if (fflagp)
2106 *fflagp = fp->f_flag;
2107 SOCK_LOCK(*spp);
2108 soref(*spp);
2109 SOCK_UNLOCK(*spp);
2110 }
2111 FILEDESC_UNLOCK(td->td_proc->p_fd);
2112 return (error);
2113 }
2114
2115 /*
2116 * Drop the reference count on the socket and XXX release the SX lock in
2117 * the future. The last reference closes the socket.
2118 */
2119 void
2120 fputsock(struct socket *so)
2121 {
2122
2123 NET_ASSERT_GIANT();
2124 ACCEPT_LOCK();
2125 SOCK_LOCK(so);
2126 sorele(so);
2127 }
2128
2129 int
2130 fdrop(struct file *fp, struct thread *td)
2131 {
2132
2133 FILE_LOCK(fp);
2134 return (fdrop_locked(fp, td));
2135 }
2136
2137 /*
2138 * Drop reference on struct file passed in, may call closef if the
2139 * reference hits zero.
2140 * Expects struct file locked, and will unlock it.
2141 */
2142 static int
2143 fdrop_locked(struct file *fp, struct thread *td)
2144 {
2145 int error;
2146
2147 FILE_LOCK_ASSERT(fp, MA_OWNED);
2148
2149 if (--fp->f_count > 0) {
2150 FILE_UNLOCK(fp);
2151 return (0);
2152 }
2153 /* We have the last ref so we can proceed without the file lock. */
2154 FILE_UNLOCK(fp);
2155 if (fp->f_count < 0)
2156 panic("fdrop: count < 0");
2157 if (fp->f_ops != &badfileops)
2158 error = fo_close(fp, td);
2159 else
2160 error = 0;
2161
2162 sx_xlock(&filelist_lock);
2163 LIST_REMOVE(fp, f_list);
2164 openfiles--;
2165 sx_xunlock(&filelist_lock);
2166 crfree(fp->f_cred);
2167 uma_zfree(file_zone, fp);
2168
2169 return (error);
2170 }
2171
2172 /*
2173 * Apply an advisory lock on a file descriptor.
2174 *
2175 * Just attempt to get a record lock of the requested type on
2176 * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2177 */
2178 #ifndef _SYS_SYSPROTO_H_
2179 struct flock_args {
2180 int fd;
2181 int how;
2182 };
2183 #endif
2184 /*
2185 * MPSAFE
2186 */
2187 /* ARGSUSED */
2188 int
2189 flock(struct thread *td, struct flock_args *uap)
2190 {
2191 struct file *fp;
2192 struct vnode *vp;
2193 struct flock lf;
2194 int error;
2195
2196 if ((error = fget(td, uap->fd, &fp)) != 0)
2197 return (error);
2198 if (fp->f_type != DTYPE_VNODE) {
2199 fdrop(fp, td);
2200 return (EOPNOTSUPP);
2201 }
2202
2203 mtx_lock(&Giant);
2204 vp = fp->f_vnode;
2205 lf.l_whence = SEEK_SET;
2206 lf.l_start = 0;
2207 lf.l_len = 0;
2208 if (uap->how & LOCK_UN) {
2209 lf.l_type = F_UNLCK;
2210 FILE_LOCK(fp);
2211 fp->f_flag &= ~FHASLOCK;
2212 FILE_UNLOCK(fp);
2213 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2214 goto done2;
2215 }
2216 if (uap->how & LOCK_EX)
2217 lf.l_type = F_WRLCK;
2218 else if (uap->how & LOCK_SH)
2219 lf.l_type = F_RDLCK;
2220 else {
2221 error = EBADF;
2222 goto done2;
2223 }
2224 FILE_LOCK(fp);
2225 fp->f_flag |= FHASLOCK;
2226 FILE_UNLOCK(fp);
2227 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2228 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2229 done2:
2230 fdrop(fp, td);
2231 mtx_unlock(&Giant);
2232 return (error);
2233 }
2234 /*
2235 * Duplicate the specified descriptor to a free descriptor.
2236 */
2237 int
2238 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2239 {
2240 struct file *wfp;
2241 struct file *fp;
2242
2243 /*
2244 * If the to-be-dup'd fd number is greater than the allowed number
2245 * of file descriptors, or the fd to be dup'd has already been
2246 * closed, then reject.
2247 */
2248 FILEDESC_LOCK(fdp);
2249 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2250 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2251 FILEDESC_UNLOCK(fdp);
2252 return (EBADF);
2253 }
2254
2255 /*
2256 * There are two cases of interest here.
2257 *
2258 * For ENODEV simply dup (dfd) to file descriptor
2259 * (indx) and return.
2260 *
2261 * For ENXIO steal away the file structure from (dfd) and
2262 * store it in (indx). (dfd) is effectively closed by
2263 * this operation.
2264 *
2265 * Any other error code is just returned.
2266 */
2267 switch (error) {
2268 case ENODEV:
2269 /*
2270 * Check that the mode the file is being opened for is a
2271 * subset of the mode of the existing descriptor.
2272 */
2273 FILE_LOCK(wfp);
2274 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2275 FILE_UNLOCK(wfp);
2276 FILEDESC_UNLOCK(fdp);
2277 return (EACCES);
2278 }
2279 fp = fdp->fd_ofiles[indx];
2280 fdp->fd_ofiles[indx] = wfp;
2281 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2282 if (fp == NULL)
2283 fdused(fdp, indx);
2284 fhold_locked(wfp);
2285 FILE_UNLOCK(wfp);
2286 FILEDESC_UNLOCK(fdp);
2287 if (fp != NULL) {
2288 /*
2289 * We now own the reference to fp that the ofiles[]
2290 * array used to own. Release it.
2291 */
2292 FILE_LOCK(fp);
2293 fdrop_locked(fp, td);
2294 }
2295 return (0);
2296
2297 case ENXIO:
2298 /*
2299 * Steal away the file pointer from dfd and stuff it into indx.
2300 */
2301 fp = fdp->fd_ofiles[indx];
2302 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2303 fdp->fd_ofiles[dfd] = NULL;
2304 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2305 fdp->fd_ofileflags[dfd] = 0;
2306 fdunused(fdp, dfd);
2307 if (fp == NULL)
2308 fdused(fdp, indx);
2309 if (fp != NULL)
2310 FILE_LOCK(fp);
2311
2312 /*
2313 * We now own the reference to fp that the ofiles[] array
2314 * used to own. Release it.
2315 */
2316 if (fp != NULL)
2317 fdrop_locked(fp, td);
2318
2319 FILEDESC_UNLOCK(fdp);
2320
2321 return (0);
2322
2323 default:
2324 FILEDESC_UNLOCK(fdp);
2325 return (error);
2326 }
2327 /* NOTREACHED */
2328 }
2329
2330 /*
2331 * Scan all active processes to see if any of them have a current
2332 * or root directory of `olddp'. If so, replace them with the new
2333 * mount point.
2334 */
2335 void
2336 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2337 {
2338 struct filedesc *fdp;
2339 struct proc *p;
2340 int nrele;
2341
2342 if (vrefcnt(olddp) == 1)
2343 return;
2344 sx_slock(&allproc_lock);
2345 LIST_FOREACH(p, &allproc, p_list) {
2346 fdp = fdhold(p);
2347 if (fdp == NULL)
2348 continue;
2349 nrele = 0;
2350 FILEDESC_LOCK_FAST(fdp);
2351 if (fdp->fd_cdir == olddp) {
2352 vref(newdp);
2353 fdp->fd_cdir = newdp;
2354 nrele++;
2355 }
2356 if (fdp->fd_rdir == olddp) {
2357 vref(newdp);
2358 fdp->fd_rdir = newdp;
2359 nrele++;
2360 }
2361 FILEDESC_UNLOCK_FAST(fdp);
2362 fddrop(fdp);
2363 while (nrele--)
2364 vrele(olddp);
2365 }
2366 sx_sunlock(&allproc_lock);
2367 if (rootvnode == olddp) {
2368 vrele(rootvnode);
2369 vref(newdp);
2370 rootvnode = newdp;
2371 }
2372 }
2373
2374 struct filedesc_to_leader *
2375 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2376 {
2377 struct filedesc_to_leader *fdtol;
2378
2379 MALLOC(fdtol, struct filedesc_to_leader *,
2380 sizeof(struct filedesc_to_leader),
2381 M_FILEDESC_TO_LEADER,
2382 M_WAITOK);
2383 fdtol->fdl_refcount = 1;
2384 fdtol->fdl_holdcount = 0;
2385 fdtol->fdl_wakeup = 0;
2386 fdtol->fdl_leader = leader;
2387 if (old != NULL) {
2388 FILEDESC_LOCK(fdp);
2389 fdtol->fdl_next = old->fdl_next;
2390 fdtol->fdl_prev = old;
2391 old->fdl_next = fdtol;
2392 fdtol->fdl_next->fdl_prev = fdtol;
2393 FILEDESC_UNLOCK(fdp);
2394 } else {
2395 fdtol->fdl_next = fdtol;
2396 fdtol->fdl_prev = fdtol;
2397 }
2398 return (fdtol);
2399 }
2400
2401 /*
2402 * Get file structures.
2403 */
2404 static int
2405 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2406 {
2407 struct xfile xf;
2408 struct filedesc *fdp;
2409 struct file *fp;
2410 struct proc *p;
2411 int error, n;
2412
2413 /*
2414 * Note: because the number of file descriptors is calculated
2415 * in different ways for sizing vs returning the data,
2416 * there is information leakage from the first loop. However,
2417 * it is of a similar order of magnitude to the leakage from
2418 * global system statistics such as kern.openfiles.
2419 */
2420 error = sysctl_wire_old_buffer(req, 0);
2421 if (error != 0)
2422 return (error);
2423 if (req->oldptr == NULL) {
2424 n = 16; /* A slight overestimate. */
2425 sx_slock(&filelist_lock);
2426 LIST_FOREACH(fp, &filehead, f_list) {
2427 /*
2428 * We should grab the lock, but this is an
2429 * estimate, so does it really matter?
2430 */
2431 /* mtx_lock(fp->f_mtxp); */
2432 n += fp->f_count;
2433 /* mtx_unlock(f->f_mtxp); */
2434 }
2435 sx_sunlock(&filelist_lock);
2436 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2437 }
2438 error = 0;
2439 bzero(&xf, sizeof(xf));
2440 xf.xf_size = sizeof(xf);
2441 sx_slock(&allproc_lock);
2442 LIST_FOREACH(p, &allproc, p_list) {
2443 if (p->p_state == PRS_NEW)
2444 continue;
2445 PROC_LOCK(p);
2446 if (p_cansee(req->td, p) != 0) {
2447 PROC_UNLOCK(p);
2448 continue;
2449 }
2450 xf.xf_pid = p->p_pid;
2451 xf.xf_uid = p->p_ucred->cr_uid;
2452 PROC_UNLOCK(p);
2453 fdp = fdhold(p);
2454 if (fdp == NULL)
2455 continue;
2456 FILEDESC_LOCK_FAST(fdp);
2457 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2458 if ((fp = fdp->fd_ofiles[n]) == NULL)
2459 continue;
2460 xf.xf_fd = n;
2461 xf.xf_file = fp;
2462 xf.xf_data = fp->f_data;
2463 xf.xf_vnode = fp->f_vnode;
2464 xf.xf_type = fp->f_type;
2465 xf.xf_count = fp->f_count;
2466 xf.xf_msgcount = fp->f_msgcount;
2467 xf.xf_offset = fp->f_offset;
2468 xf.xf_flag = fp->f_flag;
2469 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2470 if (error)
2471 break;
2472 }
2473 FILEDESC_UNLOCK_FAST(fdp);
2474 fddrop(fdp);
2475 if (error)
2476 break;
2477 }
2478 sx_sunlock(&allproc_lock);
2479 return (error);
2480 }
2481
2482 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2483 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2484
2485 #ifdef DDB
2486 /*
2487 * For the purposes of debugging, generate a human-readable string for the
2488 * file type.
2489 */
2490 static const char *
2491 file_type_to_name(short type)
2492 {
2493
2494 switch (type) {
2495 case 0:
2496 return ("zero");
2497 case DTYPE_VNODE:
2498 return ("vnod");
2499 case DTYPE_SOCKET:
2500 return ("sock");
2501 case DTYPE_PIPE:
2502 return ("pipe");
2503 case DTYPE_FIFO:
2504 return ("fifo");
2505 case DTYPE_CRYPTO:
2506 return ("crpt");
2507 default:
2508 return ("unkn");
2509 }
2510 }
2511
2512 /*
2513 * For the purposes of debugging, identify a process (if any, perhaps one of
2514 * many) that references the passed file in its file descriptor array. Return
2515 * NULL if none.
2516 */
2517 static struct proc *
2518 file_to_first_proc(struct file *fp)
2519 {
2520 struct filedesc *fdp;
2521 struct proc *p;
2522 int n;
2523
2524 LIST_FOREACH(p, &allproc, p_list) {
2525 if (p->p_state == PRS_NEW)
2526 continue;
2527 fdp = p->p_fd;
2528 if (fdp == NULL)
2529 continue;
2530 for (n = 0; n < fdp->fd_nfiles; n++) {
2531 if (fp == fdp->fd_ofiles[n])
2532 return (p);
2533 }
2534 }
2535 return (NULL);
2536 }
2537
2538 DB_SHOW_COMMAND(files, db_show_files)
2539 {
2540 struct file *fp;
2541 struct proc *p;
2542
2543 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n", "File",
2544 "Type", "Data", "Flag", "GCFl", "Count", "MCount", "Vnode",
2545 "FPID", "FCmd");
2546 LIST_FOREACH(fp, &filehead, f_list) {
2547 p = file_to_first_proc(fp);
2548 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
2549 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
2550 fp->f_gcflag, fp->f_count, fp->f_msgcount, fp->f_vnode,
2551 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
2552 }
2553 }
2554 #endif
2555
2556 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
2557 &maxfilesperproc, 0, "Maximum files allowed open per process");
2558
2559 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
2560 &maxfiles, 0, "Maximum number of files");
2561
2562 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
2563 &openfiles, 0, "System-wide number of open files");
2564
2565 /* ARGSUSED*/
2566 static void
2567 filelistinit(void *dummy)
2568 {
2569
2570 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
2571 NULL, NULL, UMA_ALIGN_PTR, 0);
2572 sx_init(&filelist_lock, "filelist lock");
2573 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
2574 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
2575 }
2576 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL)
2577
2578 /*-------------------------------------------------------------------*/
2579
2580 static int
2581 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
2582 {
2583
2584 return (EBADF);
2585 }
2586
2587 static int
2588 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
2589 {
2590
2591 return (EBADF);
2592 }
2593
2594 static int
2595 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
2596 {
2597
2598 return (0);
2599 }
2600
2601 static int
2602 badfo_kqfilter(struct file *fp, struct knote *kn)
2603 {
2604
2605 return (EBADF);
2606 }
2607
2608 static int
2609 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
2610 {
2611
2612 return (EBADF);
2613 }
2614
2615 static int
2616 badfo_close(struct file *fp, struct thread *td)
2617 {
2618
2619 return (EBADF);
2620 }
2621
2622 struct fileops badfileops = {
2623 .fo_read = badfo_readwrite,
2624 .fo_write = badfo_readwrite,
2625 .fo_ioctl = badfo_ioctl,
2626 .fo_poll = badfo_poll,
2627 .fo_kqfilter = badfo_kqfilter,
2628 .fo_stat = badfo_stat,
2629 .fo_close = badfo_close,
2630 };
2631
2632
2633 /*-------------------------------------------------------------------*/
2634
2635 /*
2636 * File Descriptor pseudo-device driver (/dev/fd/).
2637 *
2638 * Opening minor device N dup()s the file (if any) connected to file
2639 * descriptor N belonging to the calling process. Note that this driver
2640 * consists of only the ``open()'' routine, because all subsequent
2641 * references to this file will be direct to the other driver.
2642 *
2643 * XXX: we could give this one a cloning event handler if necessary.
2644 */
2645
2646 /* ARGSUSED */
2647 static int
2648 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
2649 {
2650
2651 /*
2652 * XXX Kludge: set curthread->td_dupfd to contain the value of the
2653 * the file descriptor being sought for duplication. The error
2654 * return ensures that the vnode for this device will be released
2655 * by vn_open. Open will detect this special error and take the
2656 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
2657 * will simply report the error.
2658 */
2659 td->td_dupfd = dev2unit(dev);
2660 return (ENODEV);
2661 }
2662
2663 static struct cdevsw fildesc_cdevsw = {
2664 .d_version = D_VERSION,
2665 .d_flags = D_NEEDGIANT,
2666 .d_open = fdopen,
2667 .d_name = "FD",
2668 };
2669
2670 static void
2671 fildesc_drvinit(void *unused)
2672 {
2673 struct cdev *dev;
2674
2675 dev = make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "fd/0");
2676 make_dev_alias(dev, "stdin");
2677 dev = make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "fd/1");
2678 make_dev_alias(dev, "stdout");
2679 dev = make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "fd/2");
2680 make_dev_alias(dev, "stderr");
2681 }
2682
2683 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL)
Cache object: 7c747863582c2ee97e9a97f5b48c3864
|