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.3/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 (fdp->fd_ofileflags[old] & UF_OPENING) != 0 ||
671 (fdp->fd_ofileflags[new] & UF_OPENING) != 0) {
672 /* we've allocated a descriptor which we won't use */
673 if (fdp->fd_ofiles[new] == NULL)
674 fdunused(fdp, new);
675 FILEDESC_UNLOCK(fdp);
676 fdrop(fp, td);
677 return (EBADF);
678 }
679 KASSERT(old != new,
680 ("new fd is same as old"));
681
682 /*
683 * Save info on the descriptor being overwritten. We cannot close
684 * it without introducing an ownership race for the slot, since we
685 * need to drop the filedesc lock to call closef().
686 *
687 * XXX this duplicates parts of close().
688 */
689 delfp = fdp->fd_ofiles[new];
690 holdleaders = 0;
691 if (delfp != NULL) {
692 if (td->td_proc->p_fdtol != NULL) {
693 /*
694 * Ask fdfree() to sleep to ensure that all relevant
695 * process leaders can be traversed in closef().
696 */
697 fdp->fd_holdleaderscount++;
698 holdleaders = 1;
699 }
700 }
701
702 /*
703 * Duplicate the source descriptor
704 */
705 fdp->fd_ofiles[new] = fp;
706 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
707 if (new > fdp->fd_lastfile)
708 fdp->fd_lastfile = new;
709 *retval = new;
710
711 /*
712 * If we dup'd over a valid file, we now own the reference to it
713 * and must dispose of it using closef() semantics (as if a
714 * close() were performed on it).
715 *
716 * XXX this duplicates parts of close().
717 */
718 if (delfp != NULL) {
719 knote_fdclose(td, new);
720 FILEDESC_UNLOCK(fdp);
721 (void) closef(delfp, td);
722 if (holdleaders) {
723 FILEDESC_LOCK_FAST(fdp);
724 fdp->fd_holdleaderscount--;
725 if (fdp->fd_holdleaderscount == 0 &&
726 fdp->fd_holdleaderswakeup != 0) {
727 fdp->fd_holdleaderswakeup = 0;
728 wakeup(&fdp->fd_holdleaderscount);
729 }
730 FILEDESC_UNLOCK_FAST(fdp);
731 }
732 } else {
733 FILEDESC_UNLOCK(fdp);
734 }
735 return (0);
736 }
737
738 /*
739 * If sigio is on the list associated with a process or process group,
740 * disable signalling from the device, remove sigio from the list and
741 * free sigio.
742 */
743 void
744 funsetown(struct sigio **sigiop)
745 {
746 struct sigio *sigio;
747
748 SIGIO_LOCK();
749 sigio = *sigiop;
750 if (sigio == NULL) {
751 SIGIO_UNLOCK();
752 return;
753 }
754 *(sigio->sio_myref) = NULL;
755 if ((sigio)->sio_pgid < 0) {
756 struct pgrp *pg = (sigio)->sio_pgrp;
757 PGRP_LOCK(pg);
758 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
759 sigio, sio_pgsigio);
760 PGRP_UNLOCK(pg);
761 } else {
762 struct proc *p = (sigio)->sio_proc;
763 PROC_LOCK(p);
764 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
765 sigio, sio_pgsigio);
766 PROC_UNLOCK(p);
767 }
768 SIGIO_UNLOCK();
769 crfree(sigio->sio_ucred);
770 FREE(sigio, M_SIGIO);
771 }
772
773 /*
774 * Free a list of sigio structures.
775 * We only need to lock the SIGIO_LOCK because we have made ourselves
776 * inaccessible to callers of fsetown and therefore do not need to lock
777 * the proc or pgrp struct for the list manipulation.
778 */
779 void
780 funsetownlst(struct sigiolst *sigiolst)
781 {
782 struct proc *p;
783 struct pgrp *pg;
784 struct sigio *sigio;
785
786 sigio = SLIST_FIRST(sigiolst);
787 if (sigio == NULL)
788 return;
789 p = NULL;
790 pg = NULL;
791
792 /*
793 * Every entry of the list should belong
794 * to a single proc or pgrp.
795 */
796 if (sigio->sio_pgid < 0) {
797 pg = sigio->sio_pgrp;
798 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
799 } else /* if (sigio->sio_pgid > 0) */ {
800 p = sigio->sio_proc;
801 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
802 }
803
804 SIGIO_LOCK();
805 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
806 *(sigio->sio_myref) = NULL;
807 if (pg != NULL) {
808 KASSERT(sigio->sio_pgid < 0,
809 ("Proc sigio in pgrp sigio list"));
810 KASSERT(sigio->sio_pgrp == pg,
811 ("Bogus pgrp in sigio list"));
812 PGRP_LOCK(pg);
813 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
814 sio_pgsigio);
815 PGRP_UNLOCK(pg);
816 } else /* if (p != NULL) */ {
817 KASSERT(sigio->sio_pgid > 0,
818 ("Pgrp sigio in proc sigio list"));
819 KASSERT(sigio->sio_proc == p,
820 ("Bogus proc in sigio list"));
821 PROC_LOCK(p);
822 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
823 sio_pgsigio);
824 PROC_UNLOCK(p);
825 }
826 SIGIO_UNLOCK();
827 crfree(sigio->sio_ucred);
828 FREE(sigio, M_SIGIO);
829 SIGIO_LOCK();
830 }
831 SIGIO_UNLOCK();
832 }
833
834 /*
835 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
836 *
837 * After permission checking, add a sigio structure to the sigio list for
838 * the process or process group.
839 */
840 int
841 fsetown(pid_t pgid, struct sigio **sigiop)
842 {
843 struct proc *proc;
844 struct pgrp *pgrp;
845 struct sigio *sigio;
846 int ret;
847
848 if (pgid == 0) {
849 funsetown(sigiop);
850 return (0);
851 }
852
853 ret = 0;
854
855 /* Allocate and fill in the new sigio out of locks. */
856 MALLOC(sigio, struct sigio *, sizeof(struct sigio), M_SIGIO, M_WAITOK);
857 sigio->sio_pgid = pgid;
858 sigio->sio_ucred = crhold(curthread->td_ucred);
859 sigio->sio_myref = sigiop;
860
861 sx_slock(&proctree_lock);
862 if (pgid > 0) {
863 proc = pfind(pgid);
864 if (proc == NULL) {
865 ret = ESRCH;
866 goto fail;
867 }
868
869 /*
870 * Policy - Don't allow a process to FSETOWN a process
871 * in another session.
872 *
873 * Remove this test to allow maximum flexibility or
874 * restrict FSETOWN to the current process or process
875 * group for maximum safety.
876 */
877 PROC_UNLOCK(proc);
878 if (proc->p_session != curthread->td_proc->p_session) {
879 ret = EPERM;
880 goto fail;
881 }
882
883 pgrp = NULL;
884 } else /* if (pgid < 0) */ {
885 pgrp = pgfind(-pgid);
886 if (pgrp == NULL) {
887 ret = ESRCH;
888 goto fail;
889 }
890 PGRP_UNLOCK(pgrp);
891
892 /*
893 * Policy - Don't allow a process to FSETOWN a process
894 * in another session.
895 *
896 * Remove this test to allow maximum flexibility or
897 * restrict FSETOWN to the current process or process
898 * group for maximum safety.
899 */
900 if (pgrp->pg_session != curthread->td_proc->p_session) {
901 ret = EPERM;
902 goto fail;
903 }
904
905 proc = NULL;
906 }
907 funsetown(sigiop);
908 if (pgid > 0) {
909 PROC_LOCK(proc);
910 /*
911 * Since funsetownlst() is called without the proctree
912 * locked, we need to check for P_WEXIT.
913 * XXX: is ESRCH correct?
914 */
915 if ((proc->p_flag & P_WEXIT) != 0) {
916 PROC_UNLOCK(proc);
917 ret = ESRCH;
918 goto fail;
919 }
920 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
921 sigio->sio_proc = proc;
922 PROC_UNLOCK(proc);
923 } else {
924 PGRP_LOCK(pgrp);
925 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
926 sigio->sio_pgrp = pgrp;
927 PGRP_UNLOCK(pgrp);
928 }
929 sx_sunlock(&proctree_lock);
930 SIGIO_LOCK();
931 *sigiop = sigio;
932 SIGIO_UNLOCK();
933 return (0);
934
935 fail:
936 sx_sunlock(&proctree_lock);
937 crfree(sigio->sio_ucred);
938 FREE(sigio, M_SIGIO);
939 return (ret);
940 }
941
942 /*
943 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
944 */
945 pid_t
946 fgetown(sigiop)
947 struct sigio **sigiop;
948 {
949 pid_t pgid;
950
951 SIGIO_LOCK();
952 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
953 SIGIO_UNLOCK();
954 return (pgid);
955 }
956
957 /*
958 * Close a file descriptor.
959 */
960 #ifndef _SYS_SYSPROTO_H_
961 struct close_args {
962 int fd;
963 };
964 #endif
965 /*
966 * MPSAFE
967 */
968 /* ARGSUSED */
969 int
970 close(td, uap)
971 struct thread *td;
972 struct close_args *uap;
973 {
974
975 return (kern_close(td, uap->fd));
976 }
977
978 int
979 kern_close(td, fd)
980 struct thread *td;
981 int fd;
982 {
983 struct filedesc *fdp;
984 struct file *fp;
985 int error;
986 int holdleaders;
987
988 error = 0;
989 holdleaders = 0;
990 fdp = td->td_proc->p_fd;
991
992 AUDIT_SYSCLOSE(td, fd);
993
994 FILEDESC_LOCK(fdp);
995 if ((unsigned)fd >= fdp->fd_nfiles ||
996 (fp = fdp->fd_ofiles[fd]) == NULL ||
997 (fdp->fd_ofileflags[fd] & UF_OPENING) != 0) {
998 FILEDESC_UNLOCK(fdp);
999 return (EBADF);
1000 }
1001 fdp->fd_ofiles[fd] = NULL;
1002 fdp->fd_ofileflags[fd] = 0;
1003 fdunused(fdp, fd);
1004 if (td->td_proc->p_fdtol != NULL) {
1005 /*
1006 * Ask fdfree() to sleep to ensure that all relevant
1007 * process leaders can be traversed in closef().
1008 */
1009 fdp->fd_holdleaderscount++;
1010 holdleaders = 1;
1011 }
1012
1013 /*
1014 * We now hold the fp reference that used to be owned by the descriptor
1015 * array.
1016 * We have to unlock the FILEDESC *AFTER* knote_fdclose to prevent a
1017 * race of the fd getting opened, a knote added, and deleteing a knote
1018 * for the new fd.
1019 */
1020 knote_fdclose(td, fd);
1021 FILEDESC_UNLOCK(fdp);
1022
1023 error = closef(fp, td);
1024 if (holdleaders) {
1025 FILEDESC_LOCK_FAST(fdp);
1026 fdp->fd_holdleaderscount--;
1027 if (fdp->fd_holdleaderscount == 0 &&
1028 fdp->fd_holdleaderswakeup != 0) {
1029 fdp->fd_holdleaderswakeup = 0;
1030 wakeup(&fdp->fd_holdleaderscount);
1031 }
1032 FILEDESC_UNLOCK_FAST(fdp);
1033 }
1034 return (error);
1035 }
1036
1037 #if defined(COMPAT_43)
1038 /*
1039 * Return status information about a file descriptor.
1040 */
1041 #ifndef _SYS_SYSPROTO_H_
1042 struct ofstat_args {
1043 int fd;
1044 struct ostat *sb;
1045 };
1046 #endif
1047 /*
1048 * MPSAFE
1049 */
1050 /* ARGSUSED */
1051 int
1052 ofstat(struct thread *td, struct ofstat_args *uap)
1053 {
1054 struct ostat oub;
1055 struct stat ub;
1056 int error;
1057
1058 error = kern_fstat(td, uap->fd, &ub);
1059 if (error == 0) {
1060 cvtstat(&ub, &oub);
1061 error = copyout(&oub, uap->sb, sizeof(oub));
1062 }
1063 return (error);
1064 }
1065 #endif /* COMPAT_43 */
1066
1067 /*
1068 * Return status information about a file descriptor.
1069 */
1070 #ifndef _SYS_SYSPROTO_H_
1071 struct fstat_args {
1072 int fd;
1073 struct stat *sb;
1074 };
1075 #endif
1076 /*
1077 * MPSAFE
1078 */
1079 /* ARGSUSED */
1080 int
1081 fstat(struct thread *td, struct fstat_args *uap)
1082 {
1083 struct stat ub;
1084 int error;
1085
1086 error = kern_fstat(td, uap->fd, &ub);
1087 if (error == 0)
1088 error = copyout(&ub, uap->sb, sizeof(ub));
1089 return (error);
1090 }
1091
1092 int
1093 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1094 {
1095 struct file *fp;
1096 int error;
1097
1098 AUDIT_ARG(fd, fd);
1099
1100 if ((error = fget(td, fd, &fp)) != 0)
1101 return (error);
1102
1103 AUDIT_ARG(file, td->td_proc, fp);
1104
1105 error = fo_stat(fp, sbp, td->td_ucred, td);
1106 fdrop(fp, td);
1107 return (error);
1108 }
1109
1110 /*
1111 * Return status information about a file descriptor.
1112 */
1113 #ifndef _SYS_SYSPROTO_H_
1114 struct nfstat_args {
1115 int fd;
1116 struct nstat *sb;
1117 };
1118 #endif
1119 /*
1120 * MPSAFE
1121 */
1122 /* ARGSUSED */
1123 int
1124 nfstat(struct thread *td, struct nfstat_args *uap)
1125 {
1126 struct nstat nub;
1127 struct stat ub;
1128 int error;
1129
1130 error = kern_fstat(td, uap->fd, &ub);
1131 if (error == 0) {
1132 cvtnstat(&ub, &nub);
1133 error = copyout(&nub, uap->sb, sizeof(nub));
1134 }
1135 return (error);
1136 }
1137
1138 /*
1139 * Return pathconf information about a file descriptor.
1140 */
1141 #ifndef _SYS_SYSPROTO_H_
1142 struct fpathconf_args {
1143 int fd;
1144 int name;
1145 };
1146 #endif
1147 /*
1148 * MPSAFE
1149 */
1150 /* ARGSUSED */
1151 int
1152 fpathconf(struct thread *td, struct fpathconf_args *uap)
1153 {
1154 struct file *fp;
1155 struct vnode *vp;
1156 int error;
1157
1158 if ((error = fget(td, uap->fd, &fp)) != 0)
1159 return (error);
1160
1161 /* If asynchronous I/O is available, it works for all descriptors. */
1162 if (uap->name == _PC_ASYNC_IO) {
1163 td->td_retval[0] = async_io_version;
1164 goto out;
1165 }
1166 vp = fp->f_vnode;
1167 if (vp != NULL) {
1168 int vfslocked;
1169 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1170 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
1171 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1172 VOP_UNLOCK(vp, 0, td);
1173 VFS_UNLOCK_GIANT(vfslocked);
1174 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1175 if (uap->name != _PC_PIPE_BUF) {
1176 error = EINVAL;
1177 } else {
1178 td->td_retval[0] = PIPE_BUF;
1179 error = 0;
1180 }
1181 } else {
1182 error = EOPNOTSUPP;
1183 }
1184 out:
1185 fdrop(fp, td);
1186 return (error);
1187 }
1188
1189 /*
1190 * Grow the file table to accomodate (at least) nfd descriptors. This may
1191 * block and drop the filedesc lock, but it will reacquire it before
1192 * returning.
1193 */
1194 static void
1195 fdgrowtable(struct filedesc *fdp, int nfd)
1196 {
1197 struct file **ntable;
1198 char *nfileflags;
1199 int nnfiles, onfiles;
1200 NDSLOTTYPE *nmap;
1201
1202 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1203
1204 KASSERT(fdp->fd_nfiles > 0,
1205 ("zero-length file table"));
1206
1207 /* compute the size of the new table */
1208 onfiles = fdp->fd_nfiles;
1209 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1210 if (nnfiles <= onfiles)
1211 /* the table is already large enough */
1212 return;
1213
1214 /* allocate a new table and (if required) new bitmaps */
1215 FILEDESC_UNLOCK(fdp);
1216 MALLOC(ntable, struct file **, nnfiles * OFILESIZE,
1217 M_FILEDESC, M_ZERO | M_WAITOK);
1218 nfileflags = (char *)&ntable[nnfiles];
1219 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1220 MALLOC(nmap, NDSLOTTYPE *, NDSLOTS(nnfiles) * NDSLOTSIZE,
1221 M_FILEDESC, M_ZERO | M_WAITOK);
1222 else
1223 nmap = NULL;
1224 FILEDESC_LOCK(fdp);
1225
1226 /*
1227 * We now have new tables ready to go. Since we dropped the
1228 * filedesc lock to call malloc(), watch out for a race.
1229 */
1230 onfiles = fdp->fd_nfiles;
1231 if (onfiles >= nnfiles) {
1232 /* we lost the race, but that's OK */
1233 free(ntable, M_FILEDESC);
1234 if (nmap != NULL)
1235 free(nmap, M_FILEDESC);
1236 return;
1237 }
1238 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1239 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1240 if (onfiles > NDFILE)
1241 free(fdp->fd_ofiles, M_FILEDESC);
1242 fdp->fd_ofiles = ntable;
1243 fdp->fd_ofileflags = nfileflags;
1244 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1245 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1246 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1247 free(fdp->fd_map, M_FILEDESC);
1248 fdp->fd_map = nmap;
1249 }
1250 fdp->fd_nfiles = nnfiles;
1251 }
1252
1253 /*
1254 * Allocate a file descriptor for the process.
1255 */
1256 int
1257 fdalloc(struct thread *td, int minfd, int *result)
1258 {
1259 struct proc *p = td->td_proc;
1260 struct filedesc *fdp = p->p_fd;
1261 int fd = -1, maxfd;
1262
1263 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1264
1265 if (fdp->fd_freefile > minfd)
1266 minfd = fdp->fd_freefile;
1267
1268 PROC_LOCK(p);
1269 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1270 PROC_UNLOCK(p);
1271
1272 /*
1273 * Search the bitmap for a free descriptor. If none is found, try
1274 * to grow the file table. Keep at it until we either get a file
1275 * descriptor or run into process or system limits; fdgrowtable()
1276 * may drop the filedesc lock, so we're in a race.
1277 */
1278 for (;;) {
1279 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1280 if (fd >= maxfd)
1281 return (EMFILE);
1282 if (fd < fdp->fd_nfiles)
1283 break;
1284 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1285 }
1286
1287 /*
1288 * Perform some sanity checks, then mark the file descriptor as
1289 * used and return it to the caller.
1290 */
1291 KASSERT(!fdisused(fdp, fd),
1292 ("fd_first_free() returned non-free descriptor"));
1293 KASSERT(fdp->fd_ofiles[fd] == NULL,
1294 ("free descriptor isn't"));
1295 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1296 fdused(fdp, fd);
1297 *result = fd;
1298 return (0);
1299 }
1300
1301 /*
1302 * Check to see whether n user file descriptors
1303 * are available to the process p.
1304 */
1305 int
1306 fdavail(struct thread *td, int n)
1307 {
1308 struct proc *p = td->td_proc;
1309 struct filedesc *fdp = td->td_proc->p_fd;
1310 struct file **fpp;
1311 int i, lim, last;
1312
1313 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1314
1315 PROC_LOCK(p);
1316 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1317 PROC_UNLOCK(p);
1318 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1319 return (1);
1320 last = min(fdp->fd_nfiles, lim);
1321 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1322 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1323 if (*fpp == NULL && --n <= 0)
1324 return (1);
1325 }
1326 return (0);
1327 }
1328
1329 /*
1330 * Create a new open file structure and allocate
1331 * a file decriptor for the process that refers to it.
1332 * We add one reference to the file for the descriptor table
1333 * and one reference for resultfp. This is to prevent us being
1334 * preempted and the entry in the descriptor table closed after
1335 * we release the FILEDESC lock.
1336 */
1337 int
1338 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1339 {
1340 struct proc *p = td->td_proc;
1341 struct file *fp, *fq;
1342 int error, i;
1343 int maxuserfiles = maxfiles - (maxfiles / 20);
1344 static struct timeval lastfail;
1345 static int curfail;
1346
1347 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1348 sx_xlock(&filelist_lock);
1349
1350 if ((openfiles >= maxuserfiles &&
1351 suser_cred(td->td_ucred, SUSER_RUID) != 0) ||
1352 openfiles >= maxfiles) {
1353 if (ppsratecheck(&lastfail, &curfail, 1)) {
1354 printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1355 td->td_ucred->cr_ruid);
1356 }
1357 sx_xunlock(&filelist_lock);
1358 uma_zfree(file_zone, fp);
1359 return (ENFILE);
1360 }
1361 openfiles++;
1362
1363 /*
1364 * If the process has file descriptor zero open, add the new file
1365 * descriptor to the list of open files at that point, otherwise
1366 * put it at the front of the list of open files.
1367 */
1368 fp->f_mtxp = mtx_pool_alloc(mtxpool_sleep);
1369 fp->f_count = 1;
1370 if (resultfp)
1371 fp->f_count++;
1372 fp->f_cred = crhold(td->td_ucred);
1373 fp->f_ops = &badfileops;
1374 fp->f_data = NULL;
1375 fp->f_vnode = NULL;
1376 FILEDESC_LOCK(p->p_fd);
1377 if ((fq = p->p_fd->fd_ofiles[0])) {
1378 LIST_INSERT_AFTER(fq, fp, f_list);
1379 } else {
1380 LIST_INSERT_HEAD(&filehead, fp, f_list);
1381 }
1382 sx_xunlock(&filelist_lock);
1383 if ((error = fdalloc(td, 0, &i))) {
1384 FILEDESC_UNLOCK(p->p_fd);
1385 fdrop(fp, td);
1386 if (resultfp)
1387 fdrop(fp, td);
1388 return (error);
1389 }
1390 p->p_fd->fd_ofiles[i] = fp;
1391 FILEDESC_UNLOCK(p->p_fd);
1392 if (resultfp)
1393 *resultfp = fp;
1394 if (resultfd)
1395 *resultfd = i;
1396 return (0);
1397 }
1398
1399 /*
1400 * Build a new filedesc structure from another.
1401 * Copy the current, root, and jail root vnode references.
1402 */
1403 struct filedesc *
1404 fdinit(struct filedesc *fdp)
1405 {
1406 struct filedesc0 *newfdp;
1407
1408 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1409 mtx_init(&newfdp->fd_fd.fd_mtx, FILEDESC_LOCK_DESC, NULL, MTX_DEF);
1410 if (fdp != NULL) {
1411 FILEDESC_LOCK(fdp);
1412 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1413 if (newfdp->fd_fd.fd_cdir)
1414 VREF(newfdp->fd_fd.fd_cdir);
1415 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1416 if (newfdp->fd_fd.fd_rdir)
1417 VREF(newfdp->fd_fd.fd_rdir);
1418 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1419 if (newfdp->fd_fd.fd_jdir)
1420 VREF(newfdp->fd_fd.fd_jdir);
1421 FILEDESC_UNLOCK(fdp);
1422 }
1423
1424 /* Create the file descriptor table. */
1425 newfdp->fd_fd.fd_refcnt = 1;
1426 newfdp->fd_fd.fd_holdcnt = 1;
1427 newfdp->fd_fd.fd_cmask = CMASK;
1428 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1429 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1430 newfdp->fd_fd.fd_nfiles = NDFILE;
1431 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1432 newfdp->fd_fd.fd_lastfile = -1;
1433 return (&newfdp->fd_fd);
1434 }
1435
1436 static struct filedesc *
1437 fdhold(struct proc *p)
1438 {
1439 struct filedesc *fdp;
1440
1441 mtx_lock(&fdesc_mtx);
1442 fdp = p->p_fd;
1443 if (fdp != NULL)
1444 fdp->fd_holdcnt++;
1445 mtx_unlock(&fdesc_mtx);
1446 return (fdp);
1447 }
1448
1449 static void
1450 fddrop(struct filedesc *fdp)
1451 {
1452 int i;
1453
1454 mtx_lock(&fdesc_mtx);
1455 i = --fdp->fd_holdcnt;
1456 mtx_unlock(&fdesc_mtx);
1457 if (i > 0)
1458 return;
1459
1460 mtx_destroy(&fdp->fd_mtx);
1461 FREE(fdp, M_FILEDESC);
1462 }
1463
1464 /*
1465 * Share a filedesc structure.
1466 */
1467 struct filedesc *
1468 fdshare(struct filedesc *fdp)
1469 {
1470 FILEDESC_LOCK_FAST(fdp);
1471 fdp->fd_refcnt++;
1472 FILEDESC_UNLOCK_FAST(fdp);
1473 return (fdp);
1474 }
1475
1476 /*
1477 * Unshare a filedesc structure, if necessary by making a copy
1478 */
1479 void
1480 fdunshare(struct proc *p, struct thread *td)
1481 {
1482
1483 FILEDESC_LOCK_FAST(p->p_fd);
1484 if (p->p_fd->fd_refcnt > 1) {
1485 struct filedesc *tmp;
1486
1487 FILEDESC_UNLOCK_FAST(p->p_fd);
1488 tmp = fdcopy(p->p_fd);
1489 fdfree(td);
1490 p->p_fd = tmp;
1491 } else
1492 FILEDESC_UNLOCK_FAST(p->p_fd);
1493 }
1494
1495 /*
1496 * Copy a filedesc structure.
1497 * A NULL pointer in returns a NULL reference, this is to ease callers,
1498 * not catch errors.
1499 */
1500 struct filedesc *
1501 fdcopy(struct filedesc *fdp)
1502 {
1503 struct filedesc *newfdp;
1504 int i;
1505
1506 /* Certain daemons might not have file descriptors. */
1507 if (fdp == NULL)
1508 return (NULL);
1509
1510 newfdp = fdinit(fdp);
1511 FILEDESC_LOCK_FAST(fdp);
1512 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1513 FILEDESC_UNLOCK_FAST(fdp);
1514 FILEDESC_LOCK(newfdp);
1515 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1516 FILEDESC_UNLOCK(newfdp);
1517 FILEDESC_LOCK_FAST(fdp);
1518 }
1519 /* copy everything except kqueue descriptors */
1520 newfdp->fd_freefile = -1;
1521 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1522 if (fdisused(fdp, i) &&
1523 fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE &&
1524 (fdp->fd_ofileflags[i] & UF_OPENING) == 0) {
1525 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1526 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1527 fhold(newfdp->fd_ofiles[i]);
1528 newfdp->fd_lastfile = i;
1529 } else {
1530 if (newfdp->fd_freefile == -1)
1531 newfdp->fd_freefile = i;
1532 }
1533 }
1534 FILEDESC_UNLOCK_FAST(fdp);
1535 FILEDESC_LOCK(newfdp);
1536 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1537 if (newfdp->fd_ofiles[i] != NULL)
1538 fdused(newfdp, i);
1539 FILEDESC_UNLOCK(newfdp);
1540 FILEDESC_LOCK_FAST(fdp);
1541 if (newfdp->fd_freefile == -1)
1542 newfdp->fd_freefile = i;
1543 newfdp->fd_cmask = fdp->fd_cmask;
1544 FILEDESC_UNLOCK_FAST(fdp);
1545 return (newfdp);
1546 }
1547
1548 /*
1549 * Release a filedesc structure.
1550 */
1551 void
1552 fdfree(struct thread *td)
1553 {
1554 struct filedesc *fdp;
1555 struct file **fpp;
1556 int i, locked;
1557 struct filedesc_to_leader *fdtol;
1558 struct file *fp;
1559 struct vnode *cdir, *jdir, *rdir, *vp;
1560 struct flock lf;
1561
1562 /* Certain daemons might not have file descriptors. */
1563 fdp = td->td_proc->p_fd;
1564 if (fdp == NULL)
1565 return;
1566
1567 /* Check for special need to clear POSIX style locks */
1568 fdtol = td->td_proc->p_fdtol;
1569 if (fdtol != NULL) {
1570 FILEDESC_LOCK(fdp);
1571 KASSERT(fdtol->fdl_refcount > 0,
1572 ("filedesc_to_refcount botch: fdl_refcount=%d",
1573 fdtol->fdl_refcount));
1574 if (fdtol->fdl_refcount == 1 &&
1575 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1576 for (i = 0, fpp = fdp->fd_ofiles;
1577 i <= fdp->fd_lastfile;
1578 i++, fpp++) {
1579 if (*fpp == NULL ||
1580 (*fpp)->f_type != DTYPE_VNODE)
1581 continue;
1582 fp = *fpp;
1583 fhold(fp);
1584 FILEDESC_UNLOCK(fdp);
1585 lf.l_whence = SEEK_SET;
1586 lf.l_start = 0;
1587 lf.l_len = 0;
1588 lf.l_type = F_UNLCK;
1589 vp = fp->f_vnode;
1590 locked = VFS_LOCK_GIANT(vp->v_mount);
1591 (void) VOP_ADVLOCK(vp,
1592 (caddr_t)td->td_proc->
1593 p_leader,
1594 F_UNLCK,
1595 &lf,
1596 F_POSIX);
1597 VFS_UNLOCK_GIANT(locked);
1598 FILEDESC_LOCK(fdp);
1599 fdrop(fp, td);
1600 fpp = fdp->fd_ofiles + i;
1601 }
1602 }
1603 retry:
1604 if (fdtol->fdl_refcount == 1) {
1605 if (fdp->fd_holdleaderscount > 0 &&
1606 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1607 /*
1608 * close() or do_dup() has cleared a reference
1609 * in a shared file descriptor table.
1610 */
1611 fdp->fd_holdleaderswakeup = 1;
1612 msleep(&fdp->fd_holdleaderscount, &fdp->fd_mtx,
1613 PLOCK, "fdlhold", 0);
1614 goto retry;
1615 }
1616 if (fdtol->fdl_holdcount > 0) {
1617 /*
1618 * Ensure that fdtol->fdl_leader
1619 * remains valid in closef().
1620 */
1621 fdtol->fdl_wakeup = 1;
1622 msleep(fdtol, &fdp->fd_mtx,
1623 PLOCK, "fdlhold", 0);
1624 goto retry;
1625 }
1626 }
1627 fdtol->fdl_refcount--;
1628 if (fdtol->fdl_refcount == 0 &&
1629 fdtol->fdl_holdcount == 0) {
1630 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1631 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1632 } else
1633 fdtol = NULL;
1634 td->td_proc->p_fdtol = NULL;
1635 FILEDESC_UNLOCK(fdp);
1636 if (fdtol != NULL)
1637 FREE(fdtol, M_FILEDESC_TO_LEADER);
1638 }
1639 FILEDESC_LOCK_FAST(fdp);
1640 i = --fdp->fd_refcnt;
1641 FILEDESC_UNLOCK_FAST(fdp);
1642 if (i > 0)
1643 return;
1644 /*
1645 * We are the last reference to the structure, so we can
1646 * safely assume it will not change out from under us.
1647 */
1648 fpp = fdp->fd_ofiles;
1649 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1650 if (*fpp)
1651 (void) closef(*fpp, td);
1652 }
1653 FILEDESC_LOCK(fdp);
1654
1655 /* XXX This should happen earlier. */
1656 mtx_lock(&fdesc_mtx);
1657 td->td_proc->p_fd = NULL;
1658 mtx_unlock(&fdesc_mtx);
1659
1660 if (fdp->fd_nfiles > NDFILE)
1661 FREE(fdp->fd_ofiles, M_FILEDESC);
1662 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1663 FREE(fdp->fd_map, M_FILEDESC);
1664
1665 fdp->fd_nfiles = 0;
1666
1667 cdir = fdp->fd_cdir;
1668 fdp->fd_cdir = NULL;
1669 rdir = fdp->fd_rdir;
1670 fdp->fd_rdir = NULL;
1671 jdir = fdp->fd_jdir;
1672 fdp->fd_jdir = NULL;
1673 FILEDESC_UNLOCK(fdp);
1674
1675 if (cdir) {
1676 locked = VFS_LOCK_GIANT(cdir->v_mount);
1677 vrele(cdir);
1678 VFS_UNLOCK_GIANT(locked);
1679 }
1680 if (rdir) {
1681 locked = VFS_LOCK_GIANT(rdir->v_mount);
1682 vrele(rdir);
1683 VFS_UNLOCK_GIANT(locked);
1684 }
1685 if (jdir) {
1686 locked = VFS_LOCK_GIANT(jdir->v_mount);
1687 vrele(jdir);
1688 VFS_UNLOCK_GIANT(locked);
1689 }
1690
1691 fddrop(fdp);
1692 }
1693
1694 /*
1695 * For setugid programs, we don't want to people to use that setugidness
1696 * to generate error messages which write to a file which otherwise would
1697 * otherwise be off-limits to the process. We check for filesystems where
1698 * the vnode can change out from under us after execve (like [lin]procfs).
1699 *
1700 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1701 * sufficient. We also don't check for setugidness since we know we are.
1702 */
1703 static int
1704 is_unsafe(struct file *fp)
1705 {
1706 if (fp->f_type == DTYPE_VNODE) {
1707 struct vnode *vp = fp->f_vnode;
1708
1709 if ((vp->v_vflag & VV_PROCDEP) != 0)
1710 return (1);
1711 }
1712 return (0);
1713 }
1714
1715 /*
1716 * Make this setguid thing safe, if at all possible.
1717 */
1718 void
1719 setugidsafety(struct thread *td)
1720 {
1721 struct filedesc *fdp;
1722 int i;
1723
1724 /* Certain daemons might not have file descriptors. */
1725 fdp = td->td_proc->p_fd;
1726 if (fdp == NULL)
1727 return;
1728
1729 /*
1730 * Note: fdp->fd_ofiles may be reallocated out from under us while
1731 * we are blocked in a close. Be careful!
1732 */
1733 FILEDESC_LOCK(fdp);
1734 for (i = 0; i <= fdp->fd_lastfile; i++) {
1735 if (i > 2)
1736 break;
1737 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1738 struct file *fp;
1739
1740 knote_fdclose(td, i);
1741 /*
1742 * NULL-out descriptor prior to close to avoid
1743 * a race while close blocks.
1744 */
1745 fp = fdp->fd_ofiles[i];
1746 fdp->fd_ofiles[i] = NULL;
1747 fdp->fd_ofileflags[i] = 0;
1748 fdunused(fdp, i);
1749 FILEDESC_UNLOCK(fdp);
1750 (void) closef(fp, td);
1751 FILEDESC_LOCK(fdp);
1752 }
1753 }
1754 FILEDESC_UNLOCK(fdp);
1755 }
1756
1757 void
1758 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1759 {
1760
1761 FILEDESC_LOCK(fdp);
1762 if (fdp->fd_ofiles[idx] == fp) {
1763 fdp->fd_ofiles[idx] = NULL;
1764 fdunused(fdp, idx);
1765 FILEDESC_UNLOCK(fdp);
1766 fdrop(fp, td);
1767 } else {
1768 FILEDESC_UNLOCK(fdp);
1769 }
1770 }
1771
1772 /*
1773 * Close any files on exec?
1774 */
1775 void
1776 fdcloseexec(struct thread *td)
1777 {
1778 struct filedesc *fdp;
1779 int i;
1780
1781 /* Certain daemons might not have file descriptors. */
1782 fdp = td->td_proc->p_fd;
1783 if (fdp == NULL)
1784 return;
1785
1786 FILEDESC_LOCK(fdp);
1787
1788 /*
1789 * We cannot cache fd_ofiles or fd_ofileflags since operations
1790 * may block and rip them out from under us.
1791 */
1792 for (i = 0; i <= fdp->fd_lastfile; i++) {
1793 if (fdp->fd_ofiles[i] != NULL &&
1794 (fdp->fd_ofileflags[i] & UF_EXCLOSE)) {
1795 struct file *fp;
1796
1797 knote_fdclose(td, i);
1798 /*
1799 * NULL-out descriptor prior to close to avoid
1800 * a race while close blocks.
1801 */
1802 fp = fdp->fd_ofiles[i];
1803 fdp->fd_ofiles[i] = NULL;
1804 fdp->fd_ofileflags[i] = 0;
1805 fdunused(fdp, i);
1806 FILEDESC_UNLOCK(fdp);
1807 (void) closef(fp, td);
1808 FILEDESC_LOCK(fdp);
1809 }
1810 }
1811 FILEDESC_UNLOCK(fdp);
1812 }
1813
1814 /*
1815 * It is unsafe for set[ug]id processes to be started with file
1816 * descriptors 0..2 closed, as these descriptors are given implicit
1817 * significance in the Standard C library. fdcheckstd() will create a
1818 * descriptor referencing /dev/null for each of stdin, stdout, and
1819 * stderr that is not already open.
1820 */
1821 int
1822 fdcheckstd(struct thread *td)
1823 {
1824 struct filedesc *fdp;
1825 register_t retval, save;
1826 int i, error, devnull;
1827
1828 fdp = td->td_proc->p_fd;
1829 if (fdp == NULL)
1830 return (0);
1831 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
1832 devnull = -1;
1833 error = 0;
1834 for (i = 0; i < 3; i++) {
1835 if (fdp->fd_ofiles[i] != NULL)
1836 continue;
1837 if (devnull < 0) {
1838 save = td->td_retval[0];
1839 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
1840 O_RDWR, 0);
1841 devnull = td->td_retval[0];
1842 KASSERT(devnull == i, ("oof, we didn't get our fd"));
1843 td->td_retval[0] = save;
1844 if (error)
1845 break;
1846 } else {
1847 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
1848 if (error != 0)
1849 break;
1850 }
1851 }
1852 return (error);
1853 }
1854
1855 /*
1856 * Internal form of close.
1857 * Decrement reference count on file structure.
1858 * Note: td may be NULL when closing a file that was being passed in a
1859 * message.
1860 *
1861 * XXXRW: Giant is not required for the caller, but often will be held; this
1862 * makes it moderately likely the Giant will be recursed in the VFS case.
1863 */
1864 int
1865 closef(struct file *fp, struct thread *td)
1866 {
1867 struct vnode *vp;
1868 struct flock lf;
1869 struct filedesc_to_leader *fdtol;
1870 struct filedesc *fdp;
1871
1872 /*
1873 * POSIX record locking dictates that any close releases ALL
1874 * locks owned by this process. This is handled by setting
1875 * a flag in the unlock to free ONLY locks obeying POSIX
1876 * semantics, and not to free BSD-style file locks.
1877 * If the descriptor was in a message, POSIX-style locks
1878 * aren't passed with the descriptor, and the thread pointer
1879 * will be NULL. Callers should be careful only to pass a
1880 * NULL thread pointer when there really is no owning
1881 * context that might have locks, or the locks will be
1882 * leaked.
1883 */
1884 if (fp->f_type == DTYPE_VNODE && td != NULL) {
1885 int vfslocked;
1886
1887 vp = fp->f_vnode;
1888 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1889 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1890 lf.l_whence = SEEK_SET;
1891 lf.l_start = 0;
1892 lf.l_len = 0;
1893 lf.l_type = F_UNLCK;
1894 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
1895 F_UNLCK, &lf, F_POSIX);
1896 }
1897 fdtol = td->td_proc->p_fdtol;
1898 if (fdtol != NULL) {
1899 /*
1900 * Handle special case where file descriptor table
1901 * is shared between multiple process leaders.
1902 */
1903 fdp = td->td_proc->p_fd;
1904 FILEDESC_LOCK(fdp);
1905 for (fdtol = fdtol->fdl_next;
1906 fdtol != td->td_proc->p_fdtol;
1907 fdtol = fdtol->fdl_next) {
1908 if ((fdtol->fdl_leader->p_flag &
1909 P_ADVLOCK) == 0)
1910 continue;
1911 fdtol->fdl_holdcount++;
1912 FILEDESC_UNLOCK(fdp);
1913 lf.l_whence = SEEK_SET;
1914 lf.l_start = 0;
1915 lf.l_len = 0;
1916 lf.l_type = F_UNLCK;
1917 vp = fp->f_vnode;
1918 (void) VOP_ADVLOCK(vp,
1919 (caddr_t)fdtol->fdl_leader,
1920 F_UNLCK, &lf, F_POSIX);
1921 FILEDESC_LOCK(fdp);
1922 fdtol->fdl_holdcount--;
1923 if (fdtol->fdl_holdcount == 0 &&
1924 fdtol->fdl_wakeup != 0) {
1925 fdtol->fdl_wakeup = 0;
1926 wakeup(fdtol);
1927 }
1928 }
1929 FILEDESC_UNLOCK(fdp);
1930 }
1931 VFS_UNLOCK_GIANT(vfslocked);
1932 }
1933 return (fdrop(fp, td));
1934 }
1935
1936 /*
1937 * Extract the file pointer associated with the specified descriptor for
1938 * the current user process.
1939 *
1940 * If the descriptor doesn't exist, EBADF is returned.
1941 *
1942 * If the descriptor exists but doesn't match 'flags' then
1943 * return EBADF for read attempts and EINVAL for write attempts.
1944 *
1945 * If 'hold' is set (non-zero) the file's refcount will be bumped on return.
1946 * It should be dropped with fdrop().
1947 * If it is not set, then the refcount will not be bumped however the
1948 * thread's filedesc struct will be returned locked (for fgetsock).
1949 *
1950 * If an error occured the non-zero error is returned and *fpp is set to NULL.
1951 * Otherwise *fpp is set and zero is returned.
1952 */
1953 static __inline int
1954 _fget(struct thread *td, int fd, struct file **fpp, int flags, int hold)
1955 {
1956 struct filedesc *fdp;
1957 struct file *fp;
1958
1959 *fpp = NULL;
1960 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
1961 return (EBADF);
1962 FILEDESC_LOCK(fdp);
1963 if ((fp = fget_locked(fdp, fd)) == NULL || fp->f_ops == &badfileops) {
1964 FILEDESC_UNLOCK(fdp);
1965 return (EBADF);
1966 }
1967
1968 /*
1969 * Note: FREAD failure returns EBADF to maintain backwards
1970 * compatibility with what routines returned before.
1971 *
1972 * Only one flag, or 0, may be specified.
1973 */
1974 if (flags == FREAD && (fp->f_flag & FREAD) == 0) {
1975 FILEDESC_UNLOCK(fdp);
1976 return (EBADF);
1977 }
1978 if (flags == FWRITE && (fp->f_flag & FWRITE) == 0) {
1979 FILEDESC_UNLOCK(fdp);
1980 return (EINVAL);
1981 }
1982 if (hold) {
1983 fhold(fp);
1984 FILEDESC_UNLOCK(fdp);
1985 }
1986 *fpp = fp;
1987 return (0);
1988 }
1989
1990 int
1991 fget(struct thread *td, int fd, struct file **fpp)
1992 {
1993
1994 return(_fget(td, fd, fpp, 0, 1));
1995 }
1996
1997 int
1998 fget_read(struct thread *td, int fd, struct file **fpp)
1999 {
2000
2001 return(_fget(td, fd, fpp, FREAD, 1));
2002 }
2003
2004 int
2005 fget_write(struct thread *td, int fd, struct file **fpp)
2006 {
2007
2008 return(_fget(td, fd, fpp, FWRITE, 1));
2009 }
2010
2011 /*
2012 * Like fget() but loads the underlying vnode, or returns an error if
2013 * the descriptor does not represent a vnode. Note that pipes use vnodes
2014 * but never have VM objects. The returned vnode will be vref()d.
2015 *
2016 * XXX: what about the unused flags ?
2017 */
2018 static __inline int
2019 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2020 {
2021 struct file *fp;
2022 int error;
2023
2024 *vpp = NULL;
2025 if ((error = _fget(td, fd, &fp, flags, 0)) != 0)
2026 return (error);
2027 if (fp->f_vnode == NULL) {
2028 error = EINVAL;
2029 } else {
2030 *vpp = fp->f_vnode;
2031 vref(*vpp);
2032 }
2033 FILEDESC_UNLOCK(td->td_proc->p_fd);
2034 return (error);
2035 }
2036
2037 int
2038 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2039 {
2040
2041 return (_fgetvp(td, fd, vpp, 0));
2042 }
2043
2044 int
2045 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2046 {
2047
2048 return (_fgetvp(td, fd, vpp, FREAD));
2049 }
2050
2051 #ifdef notyet
2052 int
2053 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2054 {
2055
2056 return (_fgetvp(td, fd, vpp, FWRITE));
2057 }
2058 #endif
2059
2060 /*
2061 * Like fget() but loads the underlying socket, or returns an error if
2062 * the descriptor does not represent a socket.
2063 *
2064 * We bump the ref count on the returned socket. XXX Also obtain the SX
2065 * lock in the future.
2066 */
2067 int
2068 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2069 {
2070 struct file *fp;
2071 int error;
2072
2073 NET_ASSERT_GIANT();
2074
2075 *spp = NULL;
2076 if (fflagp != NULL)
2077 *fflagp = 0;
2078 if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
2079 return (error);
2080 if (fp->f_type != DTYPE_SOCKET) {
2081 error = ENOTSOCK;
2082 } else {
2083 *spp = fp->f_data;
2084 if (fflagp)
2085 *fflagp = fp->f_flag;
2086 SOCK_LOCK(*spp);
2087 soref(*spp);
2088 SOCK_UNLOCK(*spp);
2089 }
2090 FILEDESC_UNLOCK(td->td_proc->p_fd);
2091 return (error);
2092 }
2093
2094 /*
2095 * Drop the reference count on the socket and XXX release the SX lock in
2096 * the future. The last reference closes the socket.
2097 */
2098 void
2099 fputsock(struct socket *so)
2100 {
2101
2102 NET_ASSERT_GIANT();
2103 ACCEPT_LOCK();
2104 SOCK_LOCK(so);
2105 sorele(so);
2106 }
2107
2108 int
2109 fdrop(struct file *fp, struct thread *td)
2110 {
2111
2112 FILE_LOCK(fp);
2113 return (fdrop_locked(fp, td));
2114 }
2115
2116 /*
2117 * Drop reference on struct file passed in, may call closef if the
2118 * reference hits zero.
2119 * Expects struct file locked, and will unlock it.
2120 */
2121 static int
2122 fdrop_locked(struct file *fp, struct thread *td)
2123 {
2124 int error;
2125
2126 FILE_LOCK_ASSERT(fp, MA_OWNED);
2127
2128 if (--fp->f_count > 0) {
2129 FILE_UNLOCK(fp);
2130 return (0);
2131 }
2132
2133 /*
2134 * We might have just dropped the last reference to a file
2135 * object that is for a UNIX domain socket whose message
2136 * buffers are being examined in unp_gc(). If that is the
2137 * case, FWAIT will be set in f_gcflag and we need to wait for
2138 * unp_gc() to finish its scan.
2139 */
2140 while (fp->f_gcflag & FWAIT)
2141 msleep(&fp->f_gcflag, fp->f_mtxp, 0, "fpdrop", 0);
2142
2143 /* We have the last ref so we can proceed without the file lock. */
2144 FILE_UNLOCK(fp);
2145 if (fp->f_count < 0)
2146 panic("fdrop: count < 0");
2147 if (fp->f_ops != &badfileops)
2148 error = fo_close(fp, td);
2149 else
2150 error = 0;
2151
2152 sx_xlock(&filelist_lock);
2153 LIST_REMOVE(fp, f_list);
2154 openfiles--;
2155 sx_xunlock(&filelist_lock);
2156 crfree(fp->f_cred);
2157 uma_zfree(file_zone, fp);
2158
2159 return (error);
2160 }
2161
2162 /*
2163 * Apply an advisory lock on a file descriptor.
2164 *
2165 * Just attempt to get a record lock of the requested type on
2166 * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2167 */
2168 #ifndef _SYS_SYSPROTO_H_
2169 struct flock_args {
2170 int fd;
2171 int how;
2172 };
2173 #endif
2174 /*
2175 * MPSAFE
2176 */
2177 /* ARGSUSED */
2178 int
2179 flock(struct thread *td, struct flock_args *uap)
2180 {
2181 struct file *fp;
2182 struct vnode *vp;
2183 struct flock lf;
2184 int error;
2185
2186 if ((error = fget(td, uap->fd, &fp)) != 0)
2187 return (error);
2188 if (fp->f_type != DTYPE_VNODE) {
2189 fdrop(fp, td);
2190 return (EOPNOTSUPP);
2191 }
2192
2193 mtx_lock(&Giant);
2194 vp = fp->f_vnode;
2195 lf.l_whence = SEEK_SET;
2196 lf.l_start = 0;
2197 lf.l_len = 0;
2198 if (uap->how & LOCK_UN) {
2199 lf.l_type = F_UNLCK;
2200 FILE_LOCK(fp);
2201 fp->f_flag &= ~FHASLOCK;
2202 FILE_UNLOCK(fp);
2203 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2204 goto done2;
2205 }
2206 if (uap->how & LOCK_EX)
2207 lf.l_type = F_WRLCK;
2208 else if (uap->how & LOCK_SH)
2209 lf.l_type = F_RDLCK;
2210 else {
2211 error = EBADF;
2212 goto done2;
2213 }
2214 FILE_LOCK(fp);
2215 fp->f_flag |= FHASLOCK;
2216 FILE_UNLOCK(fp);
2217 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2218 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2219 done2:
2220 fdrop(fp, td);
2221 mtx_unlock(&Giant);
2222 return (error);
2223 }
2224 /*
2225 * Duplicate the specified descriptor to a free descriptor.
2226 */
2227 int
2228 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2229 {
2230 struct file *wfp;
2231 struct file *fp;
2232
2233 /*
2234 * If the to-be-dup'd fd number is greater than the allowed number
2235 * of file descriptors, or the fd to be dup'd has already been
2236 * closed, then reject.
2237 */
2238 FILEDESC_LOCK(fdp);
2239 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2240 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2241 FILEDESC_UNLOCK(fdp);
2242 return (EBADF);
2243 }
2244
2245 /*
2246 * There are two cases of interest here.
2247 *
2248 * For ENODEV simply dup (dfd) to file descriptor
2249 * (indx) and return.
2250 *
2251 * For ENXIO steal away the file structure from (dfd) and
2252 * store it in (indx). (dfd) is effectively closed by
2253 * this operation.
2254 *
2255 * Any other error code is just returned.
2256 */
2257 switch (error) {
2258 case ENODEV:
2259 /*
2260 * Check that the mode the file is being opened for is a
2261 * subset of the mode of the existing descriptor.
2262 */
2263 FILE_LOCK(wfp);
2264 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2265 FILE_UNLOCK(wfp);
2266 FILEDESC_UNLOCK(fdp);
2267 return (EACCES);
2268 }
2269 fp = fdp->fd_ofiles[indx];
2270 fdp->fd_ofiles[indx] = wfp;
2271 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2272 if (fp == NULL)
2273 fdused(fdp, indx);
2274 fhold_locked(wfp);
2275 FILE_UNLOCK(wfp);
2276 FILEDESC_UNLOCK(fdp);
2277 if (fp != NULL) {
2278 /*
2279 * We now own the reference to fp that the ofiles[]
2280 * array used to own. Release it.
2281 */
2282 FILE_LOCK(fp);
2283 fdrop_locked(fp, td);
2284 }
2285 return (0);
2286
2287 case ENXIO:
2288 /*
2289 * Steal away the file pointer from dfd and stuff it into indx.
2290 */
2291 fp = fdp->fd_ofiles[indx];
2292 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2293 fdp->fd_ofiles[dfd] = NULL;
2294 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2295 fdp->fd_ofileflags[dfd] = 0;
2296 fdunused(fdp, dfd);
2297 if (fp == NULL)
2298 fdused(fdp, indx);
2299 if (fp != NULL)
2300 FILE_LOCK(fp);
2301
2302 /*
2303 * We now own the reference to fp that the ofiles[] array
2304 * used to own. Release it.
2305 */
2306 if (fp != NULL)
2307 fdrop_locked(fp, td);
2308
2309 FILEDESC_UNLOCK(fdp);
2310
2311 return (0);
2312
2313 default:
2314 FILEDESC_UNLOCK(fdp);
2315 return (error);
2316 }
2317 /* NOTREACHED */
2318 }
2319
2320 /*
2321 * Scan all active processes to see if any of them have a current
2322 * or root directory of `olddp'. If so, replace them with the new
2323 * mount point.
2324 */
2325 void
2326 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2327 {
2328 struct filedesc *fdp;
2329 struct proc *p;
2330 int nrele;
2331
2332 if (vrefcnt(olddp) == 1)
2333 return;
2334 sx_slock(&allproc_lock);
2335 LIST_FOREACH(p, &allproc, p_list) {
2336 fdp = fdhold(p);
2337 if (fdp == NULL)
2338 continue;
2339 nrele = 0;
2340 FILEDESC_LOCK_FAST(fdp);
2341 if (fdp->fd_cdir == olddp) {
2342 vref(newdp);
2343 fdp->fd_cdir = newdp;
2344 nrele++;
2345 }
2346 if (fdp->fd_rdir == olddp) {
2347 vref(newdp);
2348 fdp->fd_rdir = newdp;
2349 nrele++;
2350 }
2351 FILEDESC_UNLOCK_FAST(fdp);
2352 fddrop(fdp);
2353 while (nrele--)
2354 vrele(olddp);
2355 }
2356 sx_sunlock(&allproc_lock);
2357 if (rootvnode == olddp) {
2358 vrele(rootvnode);
2359 vref(newdp);
2360 rootvnode = newdp;
2361 }
2362 }
2363
2364 struct filedesc_to_leader *
2365 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2366 {
2367 struct filedesc_to_leader *fdtol;
2368
2369 MALLOC(fdtol, struct filedesc_to_leader *,
2370 sizeof(struct filedesc_to_leader),
2371 M_FILEDESC_TO_LEADER,
2372 M_WAITOK);
2373 fdtol->fdl_refcount = 1;
2374 fdtol->fdl_holdcount = 0;
2375 fdtol->fdl_wakeup = 0;
2376 fdtol->fdl_leader = leader;
2377 if (old != NULL) {
2378 FILEDESC_LOCK(fdp);
2379 fdtol->fdl_next = old->fdl_next;
2380 fdtol->fdl_prev = old;
2381 old->fdl_next = fdtol;
2382 fdtol->fdl_next->fdl_prev = fdtol;
2383 FILEDESC_UNLOCK(fdp);
2384 } else {
2385 fdtol->fdl_next = fdtol;
2386 fdtol->fdl_prev = fdtol;
2387 }
2388 return (fdtol);
2389 }
2390
2391 /*
2392 * Get file structures.
2393 */
2394 static int
2395 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2396 {
2397 struct xfile xf;
2398 struct filedesc *fdp;
2399 struct file *fp;
2400 struct proc *p;
2401 int error, n;
2402
2403 /*
2404 * Note: because the number of file descriptors is calculated
2405 * in different ways for sizing vs returning the data,
2406 * there is information leakage from the first loop. However,
2407 * it is of a similar order of magnitude to the leakage from
2408 * global system statistics such as kern.openfiles.
2409 */
2410 error = sysctl_wire_old_buffer(req, 0);
2411 if (error != 0)
2412 return (error);
2413 if (req->oldptr == NULL) {
2414 n = 16; /* A slight overestimate. */
2415 sx_slock(&filelist_lock);
2416 LIST_FOREACH(fp, &filehead, f_list) {
2417 /*
2418 * We should grab the lock, but this is an
2419 * estimate, so does it really matter?
2420 */
2421 /* mtx_lock(fp->f_mtxp); */
2422 n += fp->f_count;
2423 /* mtx_unlock(f->f_mtxp); */
2424 }
2425 sx_sunlock(&filelist_lock);
2426 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2427 }
2428 error = 0;
2429 bzero(&xf, sizeof(xf));
2430 xf.xf_size = sizeof(xf);
2431 sx_slock(&allproc_lock);
2432 LIST_FOREACH(p, &allproc, p_list) {
2433 if (p->p_state == PRS_NEW)
2434 continue;
2435 PROC_LOCK(p);
2436 if (p_cansee(req->td, p) != 0) {
2437 PROC_UNLOCK(p);
2438 continue;
2439 }
2440 xf.xf_pid = p->p_pid;
2441 xf.xf_uid = p->p_ucred->cr_uid;
2442 PROC_UNLOCK(p);
2443 fdp = fdhold(p);
2444 if (fdp == NULL)
2445 continue;
2446 FILEDESC_LOCK_FAST(fdp);
2447 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2448 if ((fp = fdp->fd_ofiles[n]) == NULL)
2449 continue;
2450 xf.xf_fd = n;
2451 xf.xf_file = fp;
2452 xf.xf_data = fp->f_data;
2453 xf.xf_vnode = fp->f_vnode;
2454 xf.xf_type = fp->f_type;
2455 xf.xf_count = fp->f_count;
2456 xf.xf_msgcount = fp->f_msgcount;
2457 xf.xf_offset = fp->f_offset;
2458 xf.xf_flag = fp->f_flag;
2459 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2460 if (error)
2461 break;
2462 }
2463 FILEDESC_UNLOCK_FAST(fdp);
2464 fddrop(fdp);
2465 if (error)
2466 break;
2467 }
2468 sx_sunlock(&allproc_lock);
2469 return (error);
2470 }
2471
2472 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2473 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2474
2475 #ifdef DDB
2476 /*
2477 * For the purposes of debugging, generate a human-readable string for the
2478 * file type.
2479 */
2480 static const char *
2481 file_type_to_name(short type)
2482 {
2483
2484 switch (type) {
2485 case 0:
2486 return ("zero");
2487 case DTYPE_VNODE:
2488 return ("vnod");
2489 case DTYPE_SOCKET:
2490 return ("sock");
2491 case DTYPE_PIPE:
2492 return ("pipe");
2493 case DTYPE_FIFO:
2494 return ("fifo");
2495 case DTYPE_CRYPTO:
2496 return ("crpt");
2497 default:
2498 return ("unkn");
2499 }
2500 }
2501
2502 /*
2503 * For the purposes of debugging, identify a process (if any, perhaps one of
2504 * many) that references the passed file in its file descriptor array. Return
2505 * NULL if none.
2506 */
2507 static struct proc *
2508 file_to_first_proc(struct file *fp)
2509 {
2510 struct filedesc *fdp;
2511 struct proc *p;
2512 int n;
2513
2514 LIST_FOREACH(p, &allproc, p_list) {
2515 if (p->p_state == PRS_NEW)
2516 continue;
2517 fdp = p->p_fd;
2518 if (fdp == NULL)
2519 continue;
2520 for (n = 0; n < fdp->fd_nfiles; n++) {
2521 if (fp == fdp->fd_ofiles[n])
2522 return (p);
2523 }
2524 }
2525 return (NULL);
2526 }
2527
2528 DB_SHOW_COMMAND(files, db_show_files)
2529 {
2530 struct file *fp;
2531 struct proc *p;
2532
2533 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n", "File",
2534 "Type", "Data", "Flag", "GCFl", "Count", "MCount", "Vnode",
2535 "FPID", "FCmd");
2536 LIST_FOREACH(fp, &filehead, f_list) {
2537 p = file_to_first_proc(fp);
2538 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
2539 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
2540 fp->f_gcflag, fp->f_count, fp->f_msgcount, fp->f_vnode,
2541 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
2542 }
2543 }
2544 #endif
2545
2546 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
2547 &maxfilesperproc, 0, "Maximum files allowed open per process");
2548
2549 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
2550 &maxfiles, 0, "Maximum number of files");
2551
2552 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
2553 &openfiles, 0, "System-wide number of open files");
2554
2555 /* ARGSUSED*/
2556 static void
2557 filelistinit(void *dummy)
2558 {
2559
2560 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
2561 NULL, NULL, UMA_ALIGN_PTR, 0);
2562 sx_init(&filelist_lock, "filelist lock");
2563 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
2564 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
2565 }
2566 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL)
2567
2568 /*-------------------------------------------------------------------*/
2569
2570 static int
2571 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
2572 {
2573
2574 return (EBADF);
2575 }
2576
2577 static int
2578 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
2579 {
2580
2581 return (EBADF);
2582 }
2583
2584 static int
2585 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
2586 {
2587
2588 return (0);
2589 }
2590
2591 static int
2592 badfo_kqfilter(struct file *fp, struct knote *kn)
2593 {
2594
2595 return (EBADF);
2596 }
2597
2598 static int
2599 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
2600 {
2601
2602 return (EBADF);
2603 }
2604
2605 static int
2606 badfo_close(struct file *fp, struct thread *td)
2607 {
2608
2609 return (EBADF);
2610 }
2611
2612 struct fileops badfileops = {
2613 .fo_read = badfo_readwrite,
2614 .fo_write = badfo_readwrite,
2615 .fo_ioctl = badfo_ioctl,
2616 .fo_poll = badfo_poll,
2617 .fo_kqfilter = badfo_kqfilter,
2618 .fo_stat = badfo_stat,
2619 .fo_close = badfo_close,
2620 };
2621
2622
2623 /*-------------------------------------------------------------------*/
2624
2625 /*
2626 * File Descriptor pseudo-device driver (/dev/fd/).
2627 *
2628 * Opening minor device N dup()s the file (if any) connected to file
2629 * descriptor N belonging to the calling process. Note that this driver
2630 * consists of only the ``open()'' routine, because all subsequent
2631 * references to this file will be direct to the other driver.
2632 *
2633 * XXX: we could give this one a cloning event handler if necessary.
2634 */
2635
2636 /* ARGSUSED */
2637 static int
2638 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
2639 {
2640
2641 /*
2642 * XXX Kludge: set curthread->td_dupfd to contain the value of the
2643 * the file descriptor being sought for duplication. The error
2644 * return ensures that the vnode for this device will be released
2645 * by vn_open. Open will detect this special error and take the
2646 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
2647 * will simply report the error.
2648 */
2649 td->td_dupfd = dev2unit(dev);
2650 return (ENODEV);
2651 }
2652
2653 static struct cdevsw fildesc_cdevsw = {
2654 .d_version = D_VERSION,
2655 .d_flags = D_NEEDGIANT,
2656 .d_open = fdopen,
2657 .d_name = "FD",
2658 };
2659
2660 static void
2661 fildesc_drvinit(void *unused)
2662 {
2663 struct cdev *dev;
2664
2665 dev = make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "fd/0");
2666 make_dev_alias(dev, "stdin");
2667 dev = make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "fd/1");
2668 make_dev_alias(dev, "stdout");
2669 dev = make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "fd/2");
2670 make_dev_alias(dev, "stderr");
2671 }
2672
2673 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL)
Cache object: 2e9606e602b3121508f5564229981d76
|