]> git.saurik.com Git - apple/xnu.git/blob - bsd/kern/kern_descrip.c
48904239ef98e32928cf7e512b69e072a3681f86
[apple/xnu.git] / bsd / kern / kern_descrip.c
1 /*
2 * Copyright (c) 2000-2016 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /* Copyright (c) 1995, 1997 Apple Computer, Inc. All Rights Reserved */
29 /*
30 * Copyright (c) 1982, 1986, 1989, 1991, 1993
31 * The Regents of the University of California. All rights reserved.
32 * (c) UNIX System Laboratories, Inc.
33 * All or some portions of this file are derived from material licensed
34 * to the University of California by American Telephone and Telegraph
35 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
36 * the permission of UNIX System Laboratories, Inc.
37 *
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
40 * are met:
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. All advertising materials mentioning features or use of this software
47 * must display the following acknowledgement:
48 * This product includes software developed by the University of
49 * California, Berkeley and its contributors.
50 * 4. Neither the name of the University nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
53 *
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64 * SUCH DAMAGE.
65 *
66 * @(#)kern_descrip.c 8.8 (Berkeley) 2/14/95
67 */
68 /*
69 * NOTICE: This file was modified by SPARTA, Inc. in 2006 to introduce
70 * support for mandatory and extensible security protections. This notice
71 * is included in support of clause 2.2 (b) of the Apple Public License,
72 * Version 2.0.
73 */
74
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/filedesc.h>
78 #include <sys/kernel.h>
79 #include <sys/vnode_internal.h>
80 #include <sys/proc_internal.h>
81 #include <sys/kauth.h>
82 #include <sys/file_internal.h>
83 #include <sys/guarded.h>
84 #include <sys/priv.h>
85 #include <sys/socket.h>
86 #include <sys/socketvar.h>
87 #include <sys/stat.h>
88 #include <sys/ioctl.h>
89 #include <sys/fcntl.h>
90 #include <sys/fsctl.h>
91 #include <sys/malloc.h>
92 #include <sys/mman.h>
93 #include <sys/syslog.h>
94 #include <sys/unistd.h>
95 #include <sys/resourcevar.h>
96 #include <sys/aio_kern.h>
97 #include <sys/ev.h>
98 #include <kern/locks.h>
99 #include <sys/uio_internal.h>
100 #include <sys/codesign.h>
101 #include <sys/codedir_internal.h>
102
103 #include <security/audit/audit.h>
104
105 #include <sys/mount_internal.h>
106 #include <sys/kdebug.h>
107 #include <sys/sysproto.h>
108 #include <sys/pipe.h>
109 #include <sys/spawn.h>
110 #include <sys/cprotect.h>
111 #include <kern/kern_types.h>
112 #include <kern/kalloc.h>
113 #include <kern/waitq.h>
114 #include <libkern/OSAtomic.h>
115
116 #include <sys/ubc_internal.h>
117
118 #include <kern/ipc_misc.h>
119 #include <vm/vm_protos.h>
120
121 #include <mach/mach_port.h>
122 #include <stdbool.h>
123
124 #if CONFIG_MACF
125 #include <security/mac_framework.h>
126 #endif
127
128 kern_return_t ipc_object_copyin(ipc_space_t, mach_port_name_t,
129 mach_msg_type_name_t, ipc_port_t *);
130 void ipc_port_release_send(ipc_port_t);
131
132 struct psemnode;
133 struct pshmnode;
134
135 static int finishdup(proc_t p,
136 struct filedesc *fdp, int old, int new, int flags, int32_t *retval);
137
138 int falloc_locked(proc_t p, struct fileproc **resultfp, int *resultfd, vfs_context_t ctx, int locked);
139 void fg_drop(struct fileproc * fp);
140 void fg_free(struct fileglob *fg);
141 void fg_ref(struct fileproc * fp);
142 void fileport_releasefg(struct fileglob *fg);
143
144 /* flags for close_internal_locked */
145 #define FD_DUP2RESV 1
146
147 /* We don't want these exported */
148
149 __private_extern__
150 int unlink1(vfs_context_t, vnode_t, user_addr_t, enum uio_seg, int);
151
152 static void _fdrelse(struct proc * p, int fd);
153
154
155 extern void file_lock_init(void);
156
157 extern kauth_scope_t kauth_scope_fileop;
158
159 /* Conflict wait queue for when selects collide (opaque type) */
160 extern struct waitq select_conflict_queue;
161
162 #ifndef HFS_GET_BOOT_INFO
163 #define HFS_GET_BOOT_INFO (FCNTL_FS_SPECIFIC_BASE + 0x00004)
164 #endif
165
166 #ifndef HFS_SET_BOOT_INFO
167 #define HFS_SET_BOOT_INFO (FCNTL_FS_SPECIFIC_BASE + 0x00005)
168 #endif
169
170 #ifndef APFSIOC_REVERT_TO_SNAPSHOT
171 #define APFSIOC_REVERT_TO_SNAPSHOT _IOW('J', 1, u_int64_t)
172 #endif
173
174 #define f_flag f_fglob->fg_flag
175 #define f_type f_fglob->fg_ops->fo_type
176 #define f_msgcount f_fglob->fg_msgcount
177 #define f_cred f_fglob->fg_cred
178 #define f_ops f_fglob->fg_ops
179 #define f_offset f_fglob->fg_offset
180 #define f_data f_fglob->fg_data
181 #define CHECK_ADD_OVERFLOW_INT64L(x, y) \
182 (((((x) > 0) && ((y) > 0) && ((x) > LLONG_MAX - (y))) || \
183 (((x) < 0) && ((y) < 0) && ((x) < LLONG_MIN - (y)))) \
184 ? 1 : 0)
185 /*
186 * Descriptor management.
187 */
188 struct fmsglist fmsghead; /* head of list of open files */
189 struct fmsglist fmsg_ithead; /* head of list of open files */
190 int nfiles; /* actual number of open files */
191
192
193 lck_grp_attr_t * file_lck_grp_attr;
194 lck_grp_t * file_lck_grp;
195 lck_attr_t * file_lck_attr;
196
197 lck_mtx_t * uipc_lock;
198
199
200 /*
201 * check_file_seek_range
202 *
203 * Description: Checks if seek offsets are in the range of 0 to LLONG_MAX.
204 *
205 * Parameters: fl Flock structure.
206 * cur_file_offset Current offset in the file.
207 *
208 * Returns: 0 on Success.
209 * EOVERFLOW on overflow.
210 * EINVAL on offset less than zero.
211 */
212
213 static int
214 check_file_seek_range(struct flock *fl, off_t cur_file_offset)
215 {
216 if (fl->l_whence == SEEK_CUR) {
217 /* Check if the start marker is beyond LLONG_MAX. */
218 if (CHECK_ADD_OVERFLOW_INT64L(fl->l_start, cur_file_offset)) {
219 /* Check if start marker is negative */
220 if (fl->l_start < 0) {
221 return EINVAL;
222 }
223 return EOVERFLOW;
224 }
225 /* Check if the start marker is negative. */
226 if (fl->l_start + cur_file_offset < 0) {
227 return EINVAL;
228 }
229 /* Check if end marker is beyond LLONG_MAX. */
230 if ((fl->l_len > 0) && (CHECK_ADD_OVERFLOW_INT64L(fl->l_start +
231 cur_file_offset, fl->l_len - 1))) {
232 return EOVERFLOW;
233 }
234 /* Check if the end marker is negative. */
235 if ((fl->l_len <= 0) && (fl->l_start + cur_file_offset +
236 fl->l_len < 0)) {
237 return EINVAL;
238 }
239 } else if (fl->l_whence == SEEK_SET) {
240 /* Check if the start marker is negative. */
241 if (fl->l_start < 0) {
242 return EINVAL;
243 }
244 /* Check if the end marker is beyond LLONG_MAX. */
245 if ((fl->l_len > 0) &&
246 CHECK_ADD_OVERFLOW_INT64L(fl->l_start, fl->l_len - 1)) {
247 return EOVERFLOW;
248 }
249 /* Check if the end marker is negative. */
250 if ((fl->l_len < 0) && fl->l_start + fl->l_len < 0) {
251 return EINVAL;
252 }
253 }
254 return 0;
255 }
256
257
258 /*
259 * file_lock_init
260 *
261 * Description: Initialize the file lock group and the uipc and flist locks
262 *
263 * Parameters: (void)
264 *
265 * Returns: void
266 *
267 * Notes: Called at system startup from bsd_init().
268 */
269 void
270 file_lock_init(void)
271 {
272 /* allocate file lock group attribute and group */
273 file_lck_grp_attr= lck_grp_attr_alloc_init();
274
275 file_lck_grp = lck_grp_alloc_init("file", file_lck_grp_attr);
276
277 /* Allocate file lock attribute */
278 file_lck_attr = lck_attr_alloc_init();
279
280 uipc_lock = lck_mtx_alloc_init(file_lck_grp, file_lck_attr);
281 }
282
283
284 /*
285 * proc_fdlock, proc_fdlock_spin
286 *
287 * Description: Lock to control access to the per process struct fileproc
288 * and struct filedesc
289 *
290 * Parameters: p Process to take the lock on
291 *
292 * Returns: void
293 *
294 * Notes: The lock is initialized in forkproc() and destroyed in
295 * reap_child_process().
296 */
297 void
298 proc_fdlock(proc_t p)
299 {
300 lck_mtx_lock(&p->p_fdmlock);
301 }
302
303 void
304 proc_fdlock_spin(proc_t p)
305 {
306 lck_mtx_lock_spin(&p->p_fdmlock);
307 }
308
309 void
310 proc_fdlock_assert(proc_t p, int assertflags)
311 {
312 lck_mtx_assert(&p->p_fdmlock, assertflags);
313 }
314
315
316 /*
317 * proc_fdunlock
318 *
319 * Description: Unlock the lock previously locked by a call to proc_fdlock()
320 *
321 * Parameters: p Process to drop the lock on
322 *
323 * Returns: void
324 */
325 void
326 proc_fdunlock(proc_t p)
327 {
328 lck_mtx_unlock(&p->p_fdmlock);
329 }
330
331
332 /*
333 * System calls on descriptors.
334 */
335
336
337 /*
338 * getdtablesize
339 *
340 * Description: Returns the per process maximum size of the descriptor table
341 *
342 * Parameters: p Process being queried
343 * retval Pointer to the call return area
344 *
345 * Returns: 0 Success
346 *
347 * Implicit returns:
348 * *retval (modified) Size of dtable
349 */
350 int
351 getdtablesize(proc_t p, __unused struct getdtablesize_args *uap, int32_t *retval)
352 {
353 proc_fdlock_spin(p);
354 *retval = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
355 proc_fdunlock(p);
356
357 return (0);
358 }
359
360
361 void
362 procfdtbl_reservefd(struct proc * p, int fd)
363 {
364 p->p_fd->fd_ofiles[fd] = NULL;
365 p->p_fd->fd_ofileflags[fd] |= UF_RESERVED;
366 }
367
368 void
369 procfdtbl_markclosefd(struct proc * p, int fd)
370 {
371 p->p_fd->fd_ofileflags[fd] |= (UF_RESERVED | UF_CLOSING);
372 }
373
374 void
375 procfdtbl_releasefd(struct proc * p, int fd, struct fileproc * fp)
376 {
377 if (fp != NULL)
378 p->p_fd->fd_ofiles[fd] = fp;
379 p->p_fd->fd_ofileflags[fd] &= ~UF_RESERVED;
380 if ((p->p_fd->fd_ofileflags[fd] & UF_RESVWAIT) == UF_RESVWAIT) {
381 p->p_fd->fd_ofileflags[fd] &= ~UF_RESVWAIT;
382 wakeup(&p->p_fd);
383 }
384 }
385
386 void
387 procfdtbl_waitfd(struct proc * p, int fd)
388 {
389 p->p_fd->fd_ofileflags[fd] |= UF_RESVWAIT;
390 msleep(&p->p_fd, &p->p_fdmlock, PRIBIO, "ftbl_waitfd", NULL);
391 }
392
393
394 void
395 procfdtbl_clearfd(struct proc * p, int fd)
396 {
397 int waiting;
398
399 waiting = (p->p_fd->fd_ofileflags[fd] & UF_RESVWAIT);
400 p->p_fd->fd_ofiles[fd] = NULL;
401 p->p_fd->fd_ofileflags[fd] = 0;
402 if ( waiting == UF_RESVWAIT) {
403 wakeup(&p->p_fd);
404 }
405 }
406
407 /*
408 * _fdrelse
409 *
410 * Description: Inline utility function to free an fd in a filedesc
411 *
412 * Parameters: fdp Pointer to filedesc fd lies in
413 * fd fd to free
414 * reserv fd should be reserved
415 *
416 * Returns: void
417 *
418 * Locks: Assumes proc_fdlock for process pointing to fdp is held by
419 * the caller
420 */
421 static void
422 _fdrelse(struct proc * p, int fd)
423 {
424 struct filedesc *fdp = p->p_fd;
425 int nfd = 0;
426
427 if (fd < fdp->fd_freefile)
428 fdp->fd_freefile = fd;
429 #if DIAGNOSTIC
430 if (fd > fdp->fd_lastfile)
431 panic("fdrelse: fd_lastfile inconsistent");
432 #endif
433 procfdtbl_clearfd(p, fd);
434
435 while ((nfd = fdp->fd_lastfile) > 0 &&
436 fdp->fd_ofiles[nfd] == NULL &&
437 !(fdp->fd_ofileflags[nfd] & UF_RESERVED))
438 /* JMM - What about files with lingering EV_VANISHED knotes? */
439 fdp->fd_lastfile--;
440 }
441
442
443 int
444 fd_rdwr(
445 int fd,
446 enum uio_rw rw,
447 uint64_t base,
448 int64_t len,
449 enum uio_seg segflg,
450 off_t offset,
451 int io_flg,
452 int64_t *aresid)
453 {
454 struct fileproc *fp;
455 proc_t p;
456 int error = 0;
457 int flags = 0;
458 int spacetype;
459 uio_t auio = NULL;
460 char uio_buf[ UIO_SIZEOF(1) ];
461 struct vfs_context context = *(vfs_context_current());
462 bool wrote_some = false;
463
464 p = current_proc();
465
466 error = fp_lookup(p, fd, &fp, 0);
467 if (error)
468 return(error);
469
470 if (fp->f_type != DTYPE_VNODE && fp->f_type != DTYPE_PIPE && fp->f_type != DTYPE_SOCKET) {
471 error = EINVAL;
472 goto out;
473 }
474 if (rw == UIO_WRITE && !(fp->f_flag & FWRITE)) {
475 error = EBADF;
476 goto out;
477 }
478
479 if (rw == UIO_READ && !(fp->f_flag & FREAD)) {
480 error = EBADF;
481 goto out;
482 }
483
484 context.vc_ucred = fp->f_fglob->fg_cred;
485
486 if (UIO_SEG_IS_USER_SPACE(segflg))
487 spacetype = proc_is64bit(p) ? UIO_USERSPACE64 : UIO_USERSPACE32;
488 else
489 spacetype = UIO_SYSSPACE;
490
491 auio = uio_createwithbuffer(1, offset, spacetype, rw, &uio_buf[0], sizeof(uio_buf));
492
493 uio_addiov(auio, base, len);
494
495 if ( !(io_flg & IO_APPEND))
496 flags = FOF_OFFSET;
497
498 if (rw == UIO_WRITE) {
499 user_ssize_t orig_resid = uio_resid(auio);
500 error = fo_write(fp, auio, flags, &context);
501 wrote_some = uio_resid(auio) < orig_resid;
502 } else
503 error = fo_read(fp, auio, flags, &context);
504
505 if (aresid)
506 *aresid = uio_resid(auio);
507 else {
508 if (uio_resid(auio) && error == 0)
509 error = EIO;
510 }
511 out:
512 if (wrote_some)
513 fp_drop_written(p, fd, fp);
514 else
515 fp_drop(p, fd, fp, 0);
516
517 return error;
518 }
519
520
521
522 /*
523 * dup
524 *
525 * Description: Duplicate a file descriptor.
526 *
527 * Parameters: p Process performing the dup
528 * uap->fd The fd to dup
529 * retval Pointer to the call return area
530 *
531 * Returns: 0 Success
532 * !0 Errno
533 *
534 * Implicit returns:
535 * *retval (modified) The new descriptor
536 */
537 int
538 dup(proc_t p, struct dup_args *uap, int32_t *retval)
539 {
540 struct filedesc *fdp = p->p_fd;
541 int old = uap->fd;
542 int new, error;
543 struct fileproc *fp;
544
545 proc_fdlock(p);
546 if ( (error = fp_lookup(p, old, &fp, 1)) ) {
547 proc_fdunlock(p);
548 return(error);
549 }
550 if (FP_ISGUARDED(fp, GUARD_DUP)) {
551 error = fp_guard_exception(p, old, fp, kGUARD_EXC_DUP);
552 (void) fp_drop(p, old, fp, 1);
553 proc_fdunlock(p);
554 return (error);
555 }
556 if ( (error = fdalloc(p, 0, &new)) ) {
557 fp_drop(p, old, fp, 1);
558 proc_fdunlock(p);
559 return (error);
560 }
561 error = finishdup(p, fdp, old, new, 0, retval);
562 fp_drop(p, old, fp, 1);
563 proc_fdunlock(p);
564
565 if (ENTR_SHOULDTRACE && fp->f_type == DTYPE_SOCKET) {
566 KERNEL_ENERGYTRACE(kEnTrActKernSocket, DBG_FUNC_START,
567 new, 0, (int64_t)VM_KERNEL_ADDRPERM(fp->f_data));
568 }
569
570 return (error);
571 }
572
573 /*
574 * dup2
575 *
576 * Description: Duplicate a file descriptor to a particular value.
577 *
578 * Parameters: p Process performing the dup
579 * uap->from The fd to dup
580 * uap->to The fd to dup it to
581 * retval Pointer to the call return area
582 *
583 * Returns: 0 Success
584 * !0 Errno
585 *
586 * Implicit returns:
587 * *retval (modified) The new descriptor
588 */
589 int
590 dup2(proc_t p, struct dup2_args *uap, int32_t *retval)
591 {
592 struct filedesc *fdp = p->p_fd;
593 int old = uap->from, new = uap->to;
594 int i, error;
595 struct fileproc *fp, *nfp;
596
597 proc_fdlock(p);
598
599 startover:
600 if ( (error = fp_lookup(p, old, &fp, 1)) ) {
601 proc_fdunlock(p);
602 return(error);
603 }
604 if (FP_ISGUARDED(fp, GUARD_DUP)) {
605 error = fp_guard_exception(p, old, fp, kGUARD_EXC_DUP);
606 (void) fp_drop(p, old, fp, 1);
607 proc_fdunlock(p);
608 return (error);
609 }
610 if (new < 0 ||
611 (rlim_t)new >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
612 new >= maxfiles) {
613 fp_drop(p, old, fp, 1);
614 proc_fdunlock(p);
615 return (EBADF);
616 }
617 if (old == new) {
618 fp_drop(p, old, fp, 1);
619 *retval = new;
620 proc_fdunlock(p);
621 return (0);
622 }
623 if (new < 0 || new >= fdp->fd_nfiles) {
624 if ( (error = fdalloc(p, new, &i)) ) {
625 fp_drop(p, old, fp, 1);
626 proc_fdunlock(p);
627 return (error);
628 }
629 if (new != i) {
630 fdrelse(p, i);
631 goto closeit;
632 }
633 } else {
634 closeit:
635 while ((fdp->fd_ofileflags[new] & UF_RESERVED) == UF_RESERVED) {
636 fp_drop(p, old, fp, 1);
637 procfdtbl_waitfd(p, new);
638 #if DIAGNOSTIC
639 proc_fdlock_assert(p, LCK_MTX_ASSERT_OWNED);
640 #endif
641 goto startover;
642 }
643
644 if ((fdp->fd_ofiles[new] != NULL) &&
645 ((error = fp_lookup(p, new, &nfp, 1)) == 0)) {
646 fp_drop(p, old, fp, 1);
647 if (FP_ISGUARDED(nfp, GUARD_CLOSE)) {
648 error = fp_guard_exception(p,
649 new, nfp, kGUARD_EXC_CLOSE);
650 (void) fp_drop(p, new, nfp, 1);
651 proc_fdunlock(p);
652 return (error);
653 }
654 (void)close_internal_locked(p, new, nfp, FD_DUP2RESV);
655 #if DIAGNOSTIC
656 proc_fdlock_assert(p, LCK_MTX_ASSERT_OWNED);
657 #endif
658 procfdtbl_clearfd(p, new);
659 goto startover;
660 } else {
661 #if DIAGNOSTIC
662 if (fdp->fd_ofiles[new] != NULL)
663 panic("dup2: no ref on fileproc %d", new);
664 #endif
665 procfdtbl_reservefd(p, new);
666 }
667
668 #if DIAGNOSTIC
669 proc_fdlock_assert(p, LCK_MTX_ASSERT_OWNED);
670 #endif
671
672 }
673 #if DIAGNOSTIC
674 if (fdp->fd_ofiles[new] != 0)
675 panic("dup2: overwriting fd_ofiles with new %d", new);
676 if ((fdp->fd_ofileflags[new] & UF_RESERVED) == 0)
677 panic("dup2: unreserved fileflags with new %d", new);
678 #endif
679 error = finishdup(p, fdp, old, new, 0, retval);
680 fp_drop(p, old, fp, 1);
681 proc_fdunlock(p);
682
683 return(error);
684 }
685
686
687 /*
688 * fcntl
689 *
690 * Description: The file control system call.
691 *
692 * Parameters: p Process performing the fcntl
693 * uap->fd The fd to operate against
694 * uap->cmd The command to perform
695 * uap->arg Pointer to the command argument
696 * retval Pointer to the call return area
697 *
698 * Returns: 0 Success
699 * !0 Errno (see fcntl_nocancel)
700 *
701 * Implicit returns:
702 * *retval (modified) fcntl return value (if any)
703 *
704 * Notes: This system call differs from fcntl_nocancel() in that it
705 * tests for cancellation prior to performing a potentially
706 * blocking operation.
707 */
708 int
709 fcntl(proc_t p, struct fcntl_args *uap, int32_t *retval)
710 {
711 __pthread_testcancel(1);
712 return(fcntl_nocancel(p, (struct fcntl_nocancel_args *)uap, retval));
713 }
714
715
716 /*
717 * fcntl_nocancel
718 *
719 * Description: A non-cancel-testing file control system call.
720 *
721 * Parameters: p Process performing the fcntl
722 * uap->fd The fd to operate against
723 * uap->cmd The command to perform
724 * uap->arg Pointer to the command argument
725 * retval Pointer to the call return area
726 *
727 * Returns: 0 Success
728 * EINVAL
729 * fp_lookup:EBADF Bad file descriptor
730 * [F_DUPFD]
731 * fdalloc:EMFILE
732 * fdalloc:ENOMEM
733 * finishdup:EBADF
734 * finishdup:ENOMEM
735 * [F_SETOWN]
736 * ESRCH
737 * [F_SETLK]
738 * EBADF
739 * EOVERFLOW
740 * copyin:EFAULT
741 * vnode_getwithref:???
742 * VNOP_ADVLOCK:???
743 * msleep:ETIMEDOUT
744 * [F_GETLK]
745 * EBADF
746 * EOVERFLOW
747 * copyin:EFAULT
748 * copyout:EFAULT
749 * vnode_getwithref:???
750 * VNOP_ADVLOCK:???
751 * [F_PREALLOCATE]
752 * EBADF
753 * EINVAL
754 * copyin:EFAULT
755 * copyout:EFAULT
756 * vnode_getwithref:???
757 * VNOP_ALLOCATE:???
758 * [F_SETSIZE,F_RDADVISE]
759 * EBADF
760 * copyin:EFAULT
761 * vnode_getwithref:???
762 * [F_RDAHEAD,F_NOCACHE]
763 * EBADF
764 * vnode_getwithref:???
765 * [???]
766 *
767 * Implicit returns:
768 * *retval (modified) fcntl return value (if any)
769 */
770 int
771 fcntl_nocancel(proc_t p, struct fcntl_nocancel_args *uap, int32_t *retval)
772 {
773 int fd = uap->fd;
774 struct filedesc *fdp = p->p_fd;
775 struct fileproc *fp;
776 char *pop;
777 struct vnode *vp = NULLVP; /* for AUDIT_ARG() at end */
778 int i, tmp, error, error2, flg = 0;
779 struct flock fl;
780 struct flocktimeout fltimeout;
781 struct timespec *timeout = NULL;
782 struct vfs_context context;
783 off_t offset;
784 int newmin;
785 daddr64_t lbn, bn;
786 unsigned int fflag;
787 user_addr_t argp;
788 boolean_t is64bit;
789
790 AUDIT_ARG(fd, uap->fd);
791 AUDIT_ARG(cmd, uap->cmd);
792
793 proc_fdlock(p);
794 if ( (error = fp_lookup(p, fd, &fp, 1)) ) {
795 proc_fdunlock(p);
796 return(error);
797 }
798 context.vc_thread = current_thread();
799 context.vc_ucred = fp->f_cred;
800
801 is64bit = proc_is64bit(p);
802 if (is64bit) {
803 argp = uap->arg;
804 }
805 else {
806 /*
807 * Since the arg parameter is defined as a long but may be
808 * either a long or a pointer we must take care to handle
809 * sign extension issues. Our sys call munger will sign
810 * extend a long when we are called from a 32-bit process.
811 * Since we can never have an address greater than 32-bits
812 * from a 32-bit process we lop off the top 32-bits to avoid
813 * getting the wrong address
814 */
815 argp = CAST_USER_ADDR_T((uint32_t)uap->arg);
816 }
817
818 pop = &fdp->fd_ofileflags[fd];
819
820 #if CONFIG_MACF
821 error = mac_file_check_fcntl(proc_ucred(p), fp->f_fglob, uap->cmd,
822 uap->arg);
823 if (error)
824 goto out;
825 #endif
826
827 switch (uap->cmd) {
828
829 case F_DUPFD:
830 case F_DUPFD_CLOEXEC:
831 if (FP_ISGUARDED(fp, GUARD_DUP)) {
832 error = fp_guard_exception(p, fd, fp, kGUARD_EXC_DUP);
833 goto out;
834 }
835 newmin = CAST_DOWN_EXPLICIT(int, uap->arg); /* arg is an int, so we won't lose bits */
836 AUDIT_ARG(value32, newmin);
837 if ((u_int)newmin >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
838 newmin >= maxfiles) {
839 error = EINVAL;
840 goto out;
841 }
842 if ( (error = fdalloc(p, newmin, &i)) )
843 goto out;
844 error = finishdup(p, fdp, fd, i,
845 uap->cmd == F_DUPFD_CLOEXEC ? UF_EXCLOSE : 0, retval);
846 goto out;
847
848 case F_GETFD:
849 *retval = (*pop & UF_EXCLOSE)? FD_CLOEXEC : 0;
850 error = 0;
851 goto out;
852
853 case F_SETFD:
854 AUDIT_ARG(value32, uap->arg);
855 if (uap->arg & FD_CLOEXEC)
856 *pop |= UF_EXCLOSE;
857 else {
858 if (FILEPROC_TYPE(fp) == FTYPE_GUARDED) {
859 error = fp_guard_exception(p,
860 fd, fp, kGUARD_EXC_NOCLOEXEC);
861 goto out;
862 }
863 *pop &= ~UF_EXCLOSE;
864 }
865 error = 0;
866 goto out;
867
868 case F_GETFL:
869 *retval = OFLAGS(fp->f_flag);
870 error = 0;
871 goto out;
872
873 case F_SETFL:
874 fp->f_flag &= ~FCNTLFLAGS;
875 tmp = CAST_DOWN_EXPLICIT(int, uap->arg); /* arg is an int, so we won't lose bits */
876 AUDIT_ARG(value32, tmp);
877 fp->f_flag |= FFLAGS(tmp) & FCNTLFLAGS;
878 tmp = fp->f_flag & FNONBLOCK;
879 error = fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, &context);
880 if (error)
881 goto out;
882 tmp = fp->f_flag & FASYNC;
883 error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp, &context);
884 if (!error)
885 goto out;
886 fp->f_flag &= ~FNONBLOCK;
887 tmp = 0;
888 (void)fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, &context);
889 goto out;
890
891 case F_GETOWN:
892 if (fp->f_type == DTYPE_SOCKET) {
893 *retval = ((struct socket *)fp->f_data)->so_pgid;
894 error = 0;
895 goto out;
896 }
897 error = fo_ioctl(fp, (int)TIOCGPGRP, (caddr_t)retval, &context);
898 *retval = -*retval;
899 goto out;
900
901 case F_SETOWN:
902 tmp = CAST_DOWN_EXPLICIT(pid_t, uap->arg); /* arg is an int, so we won't lose bits */
903 AUDIT_ARG(value32, tmp);
904 if (fp->f_type == DTYPE_SOCKET) {
905 ((struct socket *)fp->f_data)->so_pgid = tmp;
906 error =0;
907 goto out;
908 }
909 if (fp->f_type == DTYPE_PIPE) {
910 error = fo_ioctl(fp, TIOCSPGRP, (caddr_t)&tmp, &context);
911 goto out;
912 }
913
914 if (tmp <= 0) {
915 tmp = -tmp;
916 } else {
917 proc_t p1 = proc_find(tmp);
918 if (p1 == 0) {
919 error = ESRCH;
920 goto out;
921 }
922 tmp = (int)p1->p_pgrpid;
923 proc_rele(p1);
924 }
925 error = fo_ioctl(fp, (int)TIOCSPGRP, (caddr_t)&tmp, &context);
926 goto out;
927
928 case F_SETNOSIGPIPE:
929 tmp = CAST_DOWN_EXPLICIT(int, uap->arg);
930 if (fp->f_type == DTYPE_SOCKET) {
931 #if SOCKETS
932 error = sock_setsockopt((struct socket *)fp->f_data,
933 SOL_SOCKET, SO_NOSIGPIPE, &tmp, sizeof (tmp));
934 #else
935 error = EINVAL;
936 #endif
937 } else {
938 struct fileglob *fg = fp->f_fglob;
939
940 lck_mtx_lock_spin(&fg->fg_lock);
941 if (tmp)
942 fg->fg_lflags |= FG_NOSIGPIPE;
943 else
944 fg->fg_lflags &= FG_NOSIGPIPE;
945 lck_mtx_unlock(&fg->fg_lock);
946 error = 0;
947 }
948 goto out;
949
950 case F_GETNOSIGPIPE:
951 if (fp->f_type == DTYPE_SOCKET) {
952 #if SOCKETS
953 int retsize = sizeof (*retval);
954 error = sock_getsockopt((struct socket *)fp->f_data,
955 SOL_SOCKET, SO_NOSIGPIPE, retval, &retsize);
956 #else
957 error = EINVAL;
958 #endif
959 } else {
960 *retval = (fp->f_fglob->fg_lflags & FG_NOSIGPIPE) ?
961 1 : 0;
962 error = 0;
963 }
964 goto out;
965
966 case F_SETCONFINED:
967 /*
968 * If this is the only reference to this fglob in the process
969 * and it's already marked as close-on-fork then mark it as
970 * (immutably) "confined" i.e. any fd that points to it will
971 * forever be close-on-fork, and attempts to use an IPC
972 * mechanism to move the descriptor elsewhere will fail.
973 */
974 if (CAST_DOWN_EXPLICIT(int, uap->arg)) {
975 struct fileglob *fg = fp->f_fglob;
976
977 lck_mtx_lock_spin(&fg->fg_lock);
978 if (fg->fg_lflags & FG_CONFINED)
979 error = 0;
980 else if (1 != fg->fg_count)
981 error = EAGAIN; /* go close the dup .. */
982 else if (UF_FORKCLOSE == (*pop & UF_FORKCLOSE)) {
983 fg->fg_lflags |= FG_CONFINED;
984 error = 0;
985 } else
986 error = EBADF; /* open without O_CLOFORK? */
987 lck_mtx_unlock(&fg->fg_lock);
988 } else {
989 /*
990 * Other subsystems may have built on the immutability
991 * of FG_CONFINED; clearing it may be tricky.
992 */
993 error = EPERM; /* immutable */
994 }
995 goto out;
996
997 case F_GETCONFINED:
998 *retval = (fp->f_fglob->fg_lflags & FG_CONFINED) ? 1 : 0;
999 error = 0;
1000 goto out;
1001
1002 case F_SETLKWTIMEOUT:
1003 case F_SETLKW:
1004 case F_OFD_SETLKWTIMEOUT:
1005 case F_OFD_SETLKW:
1006 flg |= F_WAIT;
1007 /* Fall into F_SETLK */
1008
1009 case F_SETLK:
1010 case F_OFD_SETLK:
1011 if (fp->f_type != DTYPE_VNODE) {
1012 error = EBADF;
1013 goto out;
1014 }
1015 vp = (struct vnode *)fp->f_data;
1016
1017 fflag = fp->f_flag;
1018 offset = fp->f_offset;
1019 proc_fdunlock(p);
1020
1021 /* Copy in the lock structure */
1022 if (F_SETLKWTIMEOUT == uap->cmd ||
1023 F_OFD_SETLKWTIMEOUT == uap->cmd) {
1024 error = copyin(argp, (caddr_t) &fltimeout, sizeof(fltimeout));
1025 if (error) {
1026 goto outdrop;
1027 }
1028 fl = fltimeout.fl;
1029 timeout = &fltimeout.timeout;
1030 } else {
1031 error = copyin(argp, (caddr_t)&fl, sizeof(fl));
1032 if (error) {
1033 goto outdrop;
1034 }
1035 }
1036
1037 /* Check starting byte and ending byte for EOVERFLOW in SEEK_CUR */
1038 /* and ending byte for EOVERFLOW in SEEK_SET */
1039 error = check_file_seek_range(&fl, offset);
1040 if (error) {
1041 goto outdrop;
1042 }
1043
1044 if ( (error = vnode_getwithref(vp)) ) {
1045 goto outdrop;
1046 }
1047 if (fl.l_whence == SEEK_CUR)
1048 fl.l_start += offset;
1049
1050 #if CONFIG_MACF
1051 error = mac_file_check_lock(proc_ucred(p), fp->f_fglob,
1052 F_SETLK, &fl);
1053 if (error) {
1054 (void)vnode_put(vp);
1055 goto outdrop;
1056 }
1057 #endif
1058 switch (uap->cmd) {
1059 case F_OFD_SETLK:
1060 case F_OFD_SETLKW:
1061 case F_OFD_SETLKWTIMEOUT:
1062 flg |= F_OFD_LOCK;
1063 switch (fl.l_type) {
1064 case F_RDLCK:
1065 if ((fflag & FREAD) == 0) {
1066 error = EBADF;
1067 break;
1068 }
1069 error = VNOP_ADVLOCK(vp, (caddr_t)fp->f_fglob,
1070 F_SETLK, &fl, flg, &context, timeout);
1071 break;
1072 case F_WRLCK:
1073 if ((fflag & FWRITE) == 0) {
1074 error = EBADF;
1075 break;
1076 }
1077 error = VNOP_ADVLOCK(vp, (caddr_t)fp->f_fglob,
1078 F_SETLK, &fl, flg, &context, timeout);
1079 break;
1080 case F_UNLCK:
1081 error = VNOP_ADVLOCK(vp, (caddr_t)fp->f_fglob,
1082 F_UNLCK, &fl, F_OFD_LOCK, &context,
1083 timeout);
1084 break;
1085 default:
1086 error = EINVAL;
1087 break;
1088 }
1089 if (0 == error &&
1090 (F_RDLCK == fl.l_type || F_WRLCK == fl.l_type)) {
1091 struct fileglob *fg = fp->f_fglob;
1092
1093 /*
1094 * arrange F_UNLCK on last close (once
1095 * set, FG_HAS_OFDLOCK is immutable)
1096 */
1097 if ((fg->fg_lflags & FG_HAS_OFDLOCK) == 0) {
1098 lck_mtx_lock_spin(&fg->fg_lock);
1099 fg->fg_lflags |= FG_HAS_OFDLOCK;
1100 lck_mtx_unlock(&fg->fg_lock);
1101 }
1102 }
1103 break;
1104 default:
1105 flg |= F_POSIX;
1106 switch (fl.l_type) {
1107 case F_RDLCK:
1108 if ((fflag & FREAD) == 0) {
1109 error = EBADF;
1110 break;
1111 }
1112 // XXX UInt32 unsafe for LP64 kernel
1113 OSBitOrAtomic(P_LADVLOCK, &p->p_ladvflag);
1114 error = VNOP_ADVLOCK(vp, (caddr_t)p,
1115 F_SETLK, &fl, flg, &context, timeout);
1116 break;
1117 case F_WRLCK:
1118 if ((fflag & FWRITE) == 0) {
1119 error = EBADF;
1120 break;
1121 }
1122 // XXX UInt32 unsafe for LP64 kernel
1123 OSBitOrAtomic(P_LADVLOCK, &p->p_ladvflag);
1124 error = VNOP_ADVLOCK(vp, (caddr_t)p,
1125 F_SETLK, &fl, flg, &context, timeout);
1126 break;
1127 case F_UNLCK:
1128 error = VNOP_ADVLOCK(vp, (caddr_t)p,
1129 F_UNLCK, &fl, F_POSIX, &context, timeout);
1130 break;
1131 default:
1132 error = EINVAL;
1133 break;
1134 }
1135 break;
1136 }
1137 (void) vnode_put(vp);
1138 goto outdrop;
1139
1140 case F_GETLK:
1141 case F_OFD_GETLK:
1142 #if CONFIG_EMBEDDED
1143 case F_GETLKPID:
1144 case F_OFD_GETLKPID:
1145 #endif
1146 if (fp->f_type != DTYPE_VNODE) {
1147 error = EBADF;
1148 goto out;
1149 }
1150 vp = (struct vnode *)fp->f_data;
1151
1152 offset = fp->f_offset;
1153 proc_fdunlock(p);
1154
1155 /* Copy in the lock structure */
1156 error = copyin(argp, (caddr_t)&fl, sizeof(fl));
1157 if (error)
1158 goto outdrop;
1159
1160 /* Check starting byte and ending byte for EOVERFLOW in SEEK_CUR */
1161 /* and ending byte for EOVERFLOW in SEEK_SET */
1162 error = check_file_seek_range(&fl, offset);
1163 if (error) {
1164 goto outdrop;
1165 }
1166
1167 if ((fl.l_whence == SEEK_SET) && (fl.l_start < 0)) {
1168 error = EINVAL;
1169 goto outdrop;
1170 }
1171
1172 switch (fl.l_type) {
1173 case F_RDLCK:
1174 case F_UNLCK:
1175 case F_WRLCK:
1176 break;
1177 default:
1178 error = EINVAL;
1179 goto outdrop;
1180 }
1181
1182 switch (fl.l_whence) {
1183 case SEEK_CUR:
1184 case SEEK_SET:
1185 case SEEK_END:
1186 break;
1187 default:
1188 error = EINVAL;
1189 goto outdrop;
1190 }
1191
1192 if ( (error = vnode_getwithref(vp)) == 0 ) {
1193 if (fl.l_whence == SEEK_CUR)
1194 fl.l_start += offset;
1195
1196 #if CONFIG_MACF
1197 error = mac_file_check_lock(proc_ucred(p), fp->f_fglob,
1198 uap->cmd, &fl);
1199 if (error == 0)
1200 #endif
1201 switch (uap->cmd) {
1202 case F_OFD_GETLK:
1203 error = VNOP_ADVLOCK(vp, (caddr_t)fp->f_fglob,
1204 F_GETLK, &fl, F_OFD_LOCK, &context, NULL);
1205 break;
1206 case F_OFD_GETLKPID:
1207 error = VNOP_ADVLOCK(vp, (caddr_t)fp->f_fglob,
1208 F_GETLKPID, &fl, F_OFD_LOCK, &context, NULL);
1209 break;
1210 default:
1211 error = VNOP_ADVLOCK(vp, (caddr_t)p,
1212 uap->cmd, &fl, F_POSIX, &context, NULL);
1213 break;
1214 }
1215
1216 (void)vnode_put(vp);
1217
1218 if (error == 0)
1219 error = copyout((caddr_t)&fl, argp, sizeof(fl));
1220 }
1221 goto outdrop;
1222
1223 case F_PREALLOCATE: {
1224 fstore_t alloc_struct; /* structure for allocate command */
1225 u_int32_t alloc_flags = 0;
1226
1227 if (fp->f_type != DTYPE_VNODE) {
1228 error = EBADF;
1229 goto out;
1230 }
1231
1232 vp = (struct vnode *)fp->f_data;
1233 proc_fdunlock(p);
1234
1235 /* make sure that we have write permission */
1236 if ((fp->f_flag & FWRITE) == 0) {
1237 error = EBADF;
1238 goto outdrop;
1239 }
1240
1241 error = copyin(argp, (caddr_t)&alloc_struct, sizeof(alloc_struct));
1242 if (error)
1243 goto outdrop;
1244
1245 /* now set the space allocated to 0 */
1246 alloc_struct.fst_bytesalloc = 0;
1247
1248 /*
1249 * Do some simple parameter checking
1250 */
1251
1252 /* set up the flags */
1253
1254 alloc_flags |= PREALLOCATE;
1255
1256 if (alloc_struct.fst_flags & F_ALLOCATECONTIG)
1257 alloc_flags |= ALLOCATECONTIG;
1258
1259 if (alloc_struct.fst_flags & F_ALLOCATEALL)
1260 alloc_flags |= ALLOCATEALL;
1261
1262 /*
1263 * Do any position mode specific stuff. The only
1264 * position mode supported now is PEOFPOSMODE
1265 */
1266
1267 switch (alloc_struct.fst_posmode) {
1268
1269 case F_PEOFPOSMODE:
1270 if (alloc_struct.fst_offset != 0) {
1271 error = EINVAL;
1272 goto outdrop;
1273 }
1274
1275 alloc_flags |= ALLOCATEFROMPEOF;
1276 break;
1277
1278 case F_VOLPOSMODE:
1279 if (alloc_struct.fst_offset <= 0) {
1280 error = EINVAL;
1281 goto outdrop;
1282 }
1283
1284 alloc_flags |= ALLOCATEFROMVOL;
1285 break;
1286
1287 default: {
1288 error = EINVAL;
1289 goto outdrop;
1290 }
1291 }
1292 if ( (error = vnode_getwithref(vp)) == 0 ) {
1293 /*
1294 * call allocate to get the space
1295 */
1296 error = VNOP_ALLOCATE(vp,alloc_struct.fst_length,alloc_flags,
1297 &alloc_struct.fst_bytesalloc, alloc_struct.fst_offset,
1298 &context);
1299 (void)vnode_put(vp);
1300
1301 error2 = copyout((caddr_t)&alloc_struct, argp, sizeof(alloc_struct));
1302
1303 if (error == 0)
1304 error = error2;
1305 }
1306 goto outdrop;
1307 }
1308 case F_PUNCHHOLE: {
1309 fpunchhole_t args;
1310
1311 if (fp->f_type != DTYPE_VNODE) {
1312 error = EBADF;
1313 goto out;
1314 }
1315
1316 vp = (struct vnode *)fp->f_data;
1317 proc_fdunlock(p);
1318
1319 /* need write permissions */
1320 if ((fp->f_flag & FWRITE) == 0) {
1321 error = EPERM;
1322 goto outdrop;
1323 }
1324
1325 if ((error = copyin(argp, (caddr_t)&args, sizeof(args)))) {
1326 goto outdrop;
1327 }
1328
1329 if ((error = vnode_getwithref(vp))) {
1330 goto outdrop;
1331 }
1332
1333 #if CONFIG_MACF
1334 if ((error = mac_vnode_check_write(&context, fp->f_fglob->fg_cred, vp))) {
1335 (void)vnode_put(vp);
1336 goto outdrop;
1337 }
1338 #endif
1339
1340 error = VNOP_IOCTL(vp, F_PUNCHHOLE, (caddr_t)&args, 0, &context);
1341 (void)vnode_put(vp);
1342
1343 goto outdrop;
1344 }
1345 case F_TRIM_ACTIVE_FILE: {
1346 ftrimactivefile_t args;
1347
1348 if (priv_check_cred(kauth_cred_get(), PRIV_TRIM_ACTIVE_FILE, 0)) {
1349 error = EACCES;
1350 goto out;
1351 }
1352
1353 if (fp->f_type != DTYPE_VNODE) {
1354 error = EBADF;
1355 goto out;
1356 }
1357
1358 vp = (struct vnode *)fp->f_data;
1359 proc_fdunlock(p);
1360
1361 /* need write permissions */
1362 if ((fp->f_flag & FWRITE) == 0) {
1363 error = EPERM;
1364 goto outdrop;
1365 }
1366
1367 if ((error = copyin(argp, (caddr_t)&args, sizeof(args)))) {
1368 goto outdrop;
1369 }
1370
1371 if ((error = vnode_getwithref(vp))) {
1372 goto outdrop;
1373 }
1374
1375 error = VNOP_IOCTL(vp, F_TRIM_ACTIVE_FILE, (caddr_t)&args, 0, &context);
1376 (void)vnode_put(vp);
1377
1378 goto outdrop;
1379 }
1380 case F_SETSIZE:
1381 if (fp->f_type != DTYPE_VNODE) {
1382 error = EBADF;
1383 goto out;
1384 }
1385 vp = (struct vnode *)fp->f_data;
1386 proc_fdunlock(p);
1387
1388 error = copyin(argp, (caddr_t)&offset, sizeof (off_t));
1389 if (error)
1390 goto outdrop;
1391 AUDIT_ARG(value64, offset);
1392
1393 error = vnode_getwithref(vp);
1394 if (error)
1395 goto outdrop;
1396
1397 #if CONFIG_MACF
1398 error = mac_vnode_check_truncate(&context,
1399 fp->f_fglob->fg_cred, vp);
1400 if (error) {
1401 (void)vnode_put(vp);
1402 goto outdrop;
1403 }
1404 #endif
1405 /*
1406 * Make sure that we are root. Growing a file
1407 * without zero filling the data is a security hole
1408 * root would have access anyway so we'll allow it
1409 */
1410 if (!kauth_cred_issuser(kauth_cred_get())) {
1411 error = EACCES;
1412 } else {
1413 /*
1414 * set the file size
1415 */
1416 error = vnode_setsize(vp, offset, IO_NOZEROFILL,
1417 &context);
1418
1419 #if CONFIG_MACF
1420 if (error == 0)
1421 mac_vnode_notify_truncate(&context, fp->f_fglob->fg_cred, vp);
1422 #endif
1423 }
1424
1425 (void)vnode_put(vp);
1426 goto outdrop;
1427
1428 case F_RDAHEAD:
1429 if (fp->f_type != DTYPE_VNODE) {
1430 error = EBADF;
1431 goto out;
1432 }
1433 if (uap->arg)
1434 fp->f_fglob->fg_flag &= ~FNORDAHEAD;
1435 else
1436 fp->f_fglob->fg_flag |= FNORDAHEAD;
1437
1438 goto out;
1439
1440 case F_NOCACHE:
1441 if (fp->f_type != DTYPE_VNODE) {
1442 error = EBADF;
1443 goto out;
1444 }
1445 if (uap->arg)
1446 fp->f_fglob->fg_flag |= FNOCACHE;
1447 else
1448 fp->f_fglob->fg_flag &= ~FNOCACHE;
1449
1450 goto out;
1451
1452 case F_NODIRECT:
1453 if (fp->f_type != DTYPE_VNODE) {
1454 error = EBADF;
1455 goto out;
1456 }
1457 if (uap->arg)
1458 fp->f_fglob->fg_flag |= FNODIRECT;
1459 else
1460 fp->f_fglob->fg_flag &= ~FNODIRECT;
1461
1462 goto out;
1463
1464 case F_SINGLE_WRITER:
1465 if (fp->f_type != DTYPE_VNODE) {
1466 error = EBADF;
1467 goto out;
1468 }
1469 if (uap->arg)
1470 fp->f_fglob->fg_flag |= FSINGLE_WRITER;
1471 else
1472 fp->f_fglob->fg_flag &= ~FSINGLE_WRITER;
1473
1474 goto out;
1475
1476 case F_GLOBAL_NOCACHE:
1477 if (fp->f_type != DTYPE_VNODE) {
1478 error = EBADF;
1479 goto out;
1480 }
1481 vp = (struct vnode *)fp->f_data;
1482 proc_fdunlock(p);
1483
1484 if ( (error = vnode_getwithref(vp)) == 0 ) {
1485
1486 *retval = vnode_isnocache(vp);
1487
1488 if (uap->arg)
1489 vnode_setnocache(vp);
1490 else
1491 vnode_clearnocache(vp);
1492
1493 (void)vnode_put(vp);
1494 }
1495 goto outdrop;
1496
1497 case F_CHECK_OPENEVT:
1498 if (fp->f_type != DTYPE_VNODE) {
1499 error = EBADF;
1500 goto out;
1501 }
1502 vp = (struct vnode *)fp->f_data;
1503 proc_fdunlock(p);
1504
1505 if ( (error = vnode_getwithref(vp)) == 0 ) {
1506
1507 *retval = vnode_is_openevt(vp);
1508
1509 if (uap->arg)
1510 vnode_set_openevt(vp);
1511 else
1512 vnode_clear_openevt(vp);
1513
1514 (void)vnode_put(vp);
1515 }
1516 goto outdrop;
1517
1518 case F_RDADVISE: {
1519 struct radvisory ra_struct;
1520
1521 if (fp->f_type != DTYPE_VNODE) {
1522 error = EBADF;
1523 goto out;
1524 }
1525 vp = (struct vnode *)fp->f_data;
1526 proc_fdunlock(p);
1527
1528 if ( (error = copyin(argp, (caddr_t)&ra_struct, sizeof(ra_struct))) )
1529 goto outdrop;
1530 if ( (error = vnode_getwithref(vp)) == 0 ) {
1531 error = VNOP_IOCTL(vp, F_RDADVISE, (caddr_t)&ra_struct, 0, &context);
1532
1533 (void)vnode_put(vp);
1534 }
1535 goto outdrop;
1536 }
1537
1538 case F_FLUSH_DATA:
1539
1540 if (fp->f_type != DTYPE_VNODE) {
1541 error = EBADF;
1542 goto out;
1543 }
1544 vp = (struct vnode *)fp->f_data;
1545 proc_fdunlock(p);
1546
1547 if ( (error = vnode_getwithref(vp)) == 0 ) {
1548 error = VNOP_FSYNC(vp, MNT_NOWAIT, &context);
1549
1550 (void)vnode_put(vp);
1551 }
1552 goto outdrop;
1553
1554 case F_LOG2PHYS:
1555 case F_LOG2PHYS_EXT: {
1556 struct log2phys l2p_struct; /* structure for allocate command */
1557 int devBlockSize;
1558
1559 off_t file_offset = 0;
1560 size_t a_size = 0;
1561 size_t run = 0;
1562
1563 if (uap->cmd == F_LOG2PHYS_EXT) {
1564 error = copyin(argp, (caddr_t)&l2p_struct, sizeof(l2p_struct));
1565 if (error)
1566 goto out;
1567 file_offset = l2p_struct.l2p_devoffset;
1568 } else {
1569 file_offset = fp->f_offset;
1570 }
1571 if (fp->f_type != DTYPE_VNODE) {
1572 error = EBADF;
1573 goto out;
1574 }
1575 vp = (struct vnode *)fp->f_data;
1576 proc_fdunlock(p);
1577 if ( (error = vnode_getwithref(vp)) ) {
1578 goto outdrop;
1579 }
1580 error = VNOP_OFFTOBLK(vp, file_offset, &lbn);
1581 if (error) {
1582 (void)vnode_put(vp);
1583 goto outdrop;
1584 }
1585 error = VNOP_BLKTOOFF(vp, lbn, &offset);
1586 if (error) {
1587 (void)vnode_put(vp);
1588 goto outdrop;
1589 }
1590 devBlockSize = vfs_devblocksize(vnode_mount(vp));
1591 if (uap->cmd == F_LOG2PHYS_EXT) {
1592 if (l2p_struct.l2p_contigbytes < 0) {
1593 vnode_put(vp);
1594 error = EINVAL;
1595 goto outdrop;
1596 }
1597
1598 a_size = MIN((uint64_t)l2p_struct.l2p_contigbytes, SIZE_MAX);
1599 } else {
1600 a_size = devBlockSize;
1601 }
1602
1603 error = VNOP_BLOCKMAP(vp, offset, a_size, &bn, &run, NULL, 0, &context);
1604
1605 (void)vnode_put(vp);
1606
1607 if (!error) {
1608 l2p_struct.l2p_flags = 0; /* for now */
1609 if (uap->cmd == F_LOG2PHYS_EXT) {
1610 l2p_struct.l2p_contigbytes = run - (file_offset - offset);
1611 } else {
1612 l2p_struct.l2p_contigbytes = 0; /* for now */
1613 }
1614
1615 /*
1616 * The block number being -1 suggests that the file offset is not backed
1617 * by any real blocks on-disk. As a result, just let it be passed back up wholesale.
1618 */
1619 if (bn == -1) {
1620 /* Don't multiply it by the block size */
1621 l2p_struct.l2p_devoffset = bn;
1622 }
1623 else {
1624 l2p_struct.l2p_devoffset = bn * devBlockSize;
1625 l2p_struct.l2p_devoffset += file_offset - offset;
1626 }
1627 error = copyout((caddr_t)&l2p_struct, argp, sizeof(l2p_struct));
1628 }
1629 goto outdrop;
1630 }
1631 case F_GETPATH: {
1632 char *pathbufp;
1633 int pathlen;
1634
1635 if (fp->f_type != DTYPE_VNODE) {
1636 error = EBADF;
1637 goto out;
1638 }
1639 vp = (struct vnode *)fp->f_data;
1640 proc_fdunlock(p);
1641
1642 pathlen = MAXPATHLEN;
1643 MALLOC(pathbufp, char *, pathlen, M_TEMP, M_WAITOK);
1644 if (pathbufp == NULL) {
1645 error = ENOMEM;
1646 goto outdrop;
1647 }
1648 if ( (error = vnode_getwithref(vp)) == 0 ) {
1649 error = vn_getpath(vp, pathbufp, &pathlen);
1650 (void)vnode_put(vp);
1651
1652 if (error == 0)
1653 error = copyout((caddr_t)pathbufp, argp, pathlen);
1654 }
1655 FREE(pathbufp, M_TEMP);
1656 goto outdrop;
1657 }
1658
1659 case F_PATHPKG_CHECK: {
1660 char *pathbufp;
1661 size_t pathlen;
1662
1663 if (fp->f_type != DTYPE_VNODE) {
1664 error = EBADF;
1665 goto out;
1666 }
1667 vp = (struct vnode *)fp->f_data;
1668 proc_fdunlock(p);
1669
1670 pathlen = MAXPATHLEN;
1671 pathbufp = kalloc(MAXPATHLEN);
1672
1673 if ( (error = copyinstr(argp, pathbufp, MAXPATHLEN, &pathlen)) == 0 ) {
1674 if ( (error = vnode_getwithref(vp)) == 0 ) {
1675 AUDIT_ARG(text, pathbufp);
1676 error = vn_path_package_check(vp, pathbufp, pathlen, retval);
1677
1678 (void)vnode_put(vp);
1679 }
1680 }
1681 kfree(pathbufp, MAXPATHLEN);
1682 goto outdrop;
1683 }
1684
1685 case F_CHKCLEAN: // used by regression tests to see if all dirty pages got cleaned by fsync()
1686 case F_FULLFSYNC: // fsync + flush the journal + DKIOCSYNCHRONIZE
1687 case F_BARRIERFSYNC: // fsync + barrier
1688 case F_FREEZE_FS: // freeze all other fs operations for the fs of this fd
1689 case F_THAW_FS: { // thaw all frozen fs operations for the fs of this fd
1690 if (fp->f_type != DTYPE_VNODE) {
1691 error = EBADF;
1692 goto out;
1693 }
1694 vp = (struct vnode *)fp->f_data;
1695 proc_fdunlock(p);
1696
1697 if ( (error = vnode_getwithref(vp)) == 0 ) {
1698 error = VNOP_IOCTL(vp, uap->cmd, (caddr_t)NULL, 0, &context);
1699
1700 (void)vnode_put(vp);
1701 }
1702 break;
1703 }
1704
1705 /*
1706 * SPI (private) for opening a file starting from a dir fd
1707 */
1708 case F_OPENFROM: {
1709 struct user_fopenfrom fopen;
1710 struct vnode_attr va;
1711 struct nameidata nd;
1712 int cmode;
1713
1714 /* Check if this isn't a valid file descriptor */
1715 if ((fp->f_type != DTYPE_VNODE) ||
1716 (fp->f_flag & FREAD) == 0) {
1717 error = EBADF;
1718 goto out;
1719 }
1720 vp = (struct vnode *)fp->f_data;
1721 proc_fdunlock(p);
1722
1723 if (vnode_getwithref(vp)) {
1724 error = ENOENT;
1725 goto outdrop;
1726 }
1727
1728 /* Only valid for directories */
1729 if (vp->v_type != VDIR) {
1730 vnode_put(vp);
1731 error = ENOTDIR;
1732 goto outdrop;
1733 }
1734
1735 /* Get flags, mode and pathname arguments. */
1736 if (IS_64BIT_PROCESS(p)) {
1737 error = copyin(argp, &fopen, sizeof(fopen));
1738 } else {
1739 struct user32_fopenfrom fopen32;
1740
1741 error = copyin(argp, &fopen32, sizeof(fopen32));
1742 fopen.o_flags = fopen32.o_flags;
1743 fopen.o_mode = fopen32.o_mode;
1744 fopen.o_pathname = CAST_USER_ADDR_T(fopen32.o_pathname);
1745 }
1746 if (error) {
1747 vnode_put(vp);
1748 goto outdrop;
1749 }
1750 AUDIT_ARG(fflags, fopen.o_flags);
1751 AUDIT_ARG(mode, fopen.o_mode);
1752 VATTR_INIT(&va);
1753 /* Mask off all but regular access permissions */
1754 cmode = ((fopen.o_mode &~ fdp->fd_cmask) & ALLPERMS) & ~S_ISTXT;
1755 VATTR_SET(&va, va_mode, cmode & ACCESSPERMS);
1756
1757 /* Start the lookup relative to the file descriptor's vnode. */
1758 NDINIT(&nd, LOOKUP, OP_OPEN, USEDVP | FOLLOW | AUDITVNPATH1, UIO_USERSPACE,
1759 fopen.o_pathname, &context);
1760 nd.ni_dvp = vp;
1761
1762 error = open1(&context, &nd, fopen.o_flags, &va,
1763 fileproc_alloc_init, NULL, retval);
1764
1765 vnode_put(vp);
1766 break;
1767 }
1768 /*
1769 * SPI (private) for unlinking a file starting from a dir fd
1770 */
1771 case F_UNLINKFROM: {
1772 user_addr_t pathname;
1773
1774 /* Check if this isn't a valid file descriptor */
1775 if ((fp->f_type != DTYPE_VNODE) ||
1776 (fp->f_flag & FREAD) == 0) {
1777 error = EBADF;
1778 goto out;
1779 }
1780 vp = (struct vnode *)fp->f_data;
1781 proc_fdunlock(p);
1782
1783 if (vnode_getwithref(vp)) {
1784 error = ENOENT;
1785 goto outdrop;
1786 }
1787
1788 /* Only valid for directories */
1789 if (vp->v_type != VDIR) {
1790 vnode_put(vp);
1791 error = ENOTDIR;
1792 goto outdrop;
1793 }
1794
1795 /* Get flags, mode and pathname arguments. */
1796 if (IS_64BIT_PROCESS(p)) {
1797 pathname = (user_addr_t)argp;
1798 } else {
1799 pathname = CAST_USER_ADDR_T(argp);
1800 }
1801
1802 /* Start the lookup relative to the file descriptor's vnode. */
1803 error = unlink1(&context, vp, pathname, UIO_USERSPACE, 0);
1804
1805 vnode_put(vp);
1806 break;
1807
1808 }
1809
1810 case F_ADDSIGS:
1811 case F_ADDFILESIGS:
1812 case F_ADDFILESIGS_FOR_DYLD_SIM:
1813 case F_ADDFILESIGS_RETURN:
1814 {
1815 struct cs_blob *blob = NULL;
1816 struct user_fsignatures fs;
1817 kern_return_t kr;
1818 vm_offset_t kernel_blob_addr;
1819 vm_size_t kernel_blob_size;
1820 int blob_add_flags = 0;
1821
1822 if (fp->f_type != DTYPE_VNODE) {
1823 error = EBADF;
1824 goto out;
1825 }
1826 vp = (struct vnode *)fp->f_data;
1827 proc_fdunlock(p);
1828
1829 if (uap->cmd == F_ADDFILESIGS_FOR_DYLD_SIM) {
1830 blob_add_flags |= MAC_VNODE_CHECK_DYLD_SIM;
1831 if ((p->p_csflags & CS_KILL) == 0) {
1832 proc_lock(p);
1833 p->p_csflags |= CS_KILL;
1834 proc_unlock(p);
1835 }
1836 }
1837
1838 error = vnode_getwithref(vp);
1839 if (error)
1840 goto outdrop;
1841
1842 if (IS_64BIT_PROCESS(p)) {
1843 error = copyin(argp, &fs, sizeof (fs));
1844 } else {
1845 struct user32_fsignatures fs32;
1846
1847 error = copyin(argp, &fs32, sizeof (fs32));
1848 fs.fs_file_start = fs32.fs_file_start;
1849 fs.fs_blob_start = CAST_USER_ADDR_T(fs32.fs_blob_start);
1850 fs.fs_blob_size = fs32.fs_blob_size;
1851 }
1852
1853 if (error) {
1854 vnode_put(vp);
1855 goto outdrop;
1856 }
1857
1858 /*
1859 * First check if we have something loaded a this offset
1860 */
1861 blob = ubc_cs_blob_get(vp, CPU_TYPE_ANY, fs.fs_file_start);
1862 if (blob != NULL)
1863 {
1864 /* If this is for dyld_sim revalidate the blob */
1865 if (uap->cmd == F_ADDFILESIGS_FOR_DYLD_SIM) {
1866 error = ubc_cs_blob_revalidate(vp, blob, NULL, blob_add_flags);
1867 if (error) {
1868 vnode_put(vp);
1869 goto outdrop;
1870 }
1871 }
1872
1873 } else {
1874 /*
1875 * An arbitrary limit, to prevent someone from mapping in a 20GB blob. This should cover
1876 * our use cases for the immediate future, but note that at the time of this commit, some
1877 * platforms are nearing 2MB blob sizes (with a prior soft limit of 2.5MB).
1878 *
1879 * We should consider how we can manage this more effectively; the above means that some
1880 * platforms are using megabytes of memory for signing data; it merely hasn't crossed the
1881 * threshold considered ridiculous at the time of this change.
1882 */
1883 #define CS_MAX_BLOB_SIZE (40ULL * 1024ULL * 1024ULL)
1884 if (fs.fs_blob_size > CS_MAX_BLOB_SIZE) {
1885 error = E2BIG;
1886 vnode_put(vp);
1887 goto outdrop;
1888 }
1889
1890 kernel_blob_size = CAST_DOWN(vm_size_t, fs.fs_blob_size);
1891 kr = ubc_cs_blob_allocate(&kernel_blob_addr, &kernel_blob_size);
1892 if (kr != KERN_SUCCESS) {
1893 error = ENOMEM;
1894 vnode_put(vp);
1895 goto outdrop;
1896 }
1897
1898 if(uap->cmd == F_ADDSIGS) {
1899 error = copyin(fs.fs_blob_start,
1900 (void *) kernel_blob_addr,
1901 kernel_blob_size);
1902 } else /* F_ADDFILESIGS || F_ADDFILESIGS_RETURN || F_ADDFILESIGS_FOR_DYLD_SIM */ {
1903 int resid;
1904
1905 error = vn_rdwr(UIO_READ,
1906 vp,
1907 (caddr_t) kernel_blob_addr,
1908 kernel_blob_size,
1909 fs.fs_file_start + fs.fs_blob_start,
1910 UIO_SYSSPACE,
1911 0,
1912 kauth_cred_get(),
1913 &resid,
1914 p);
1915 if ((error == 0) && resid) {
1916 /* kernel_blob_size rounded to a page size, but signature may be at end of file */
1917 memset((void *)(kernel_blob_addr + (kernel_blob_size - resid)), 0x0, resid);
1918 }
1919 }
1920
1921 if (error) {
1922 ubc_cs_blob_deallocate(kernel_blob_addr,
1923 kernel_blob_size);
1924 vnode_put(vp);
1925 goto outdrop;
1926 }
1927
1928 blob = NULL;
1929 error = ubc_cs_blob_add(vp,
1930 CPU_TYPE_ANY, /* not for a specific architecture */
1931 fs.fs_file_start,
1932 &kernel_blob_addr,
1933 kernel_blob_size,
1934 NULL,
1935 blob_add_flags,
1936 &blob);
1937
1938 /* ubc_blob_add() has consumed "kernel_blob_addr" if it is zeroed */
1939 if (error) {
1940 if (kernel_blob_addr) {
1941 ubc_cs_blob_deallocate(kernel_blob_addr,
1942 kernel_blob_size);
1943 }
1944 vnode_put(vp);
1945 goto outdrop;
1946 } else {
1947 #if CHECK_CS_VALIDATION_BITMAP
1948 ubc_cs_validation_bitmap_allocate( vp );
1949 #endif
1950 }
1951 }
1952
1953 if (uap->cmd == F_ADDFILESIGS_RETURN || uap->cmd == F_ADDFILESIGS_FOR_DYLD_SIM) {
1954 /*
1955 * The first element of the structure is a
1956 * off_t that happen to have the same size for
1957 * all archs. Lets overwrite that.
1958 */
1959 off_t end_offset = 0;
1960 if (blob)
1961 end_offset = blob->csb_end_offset;
1962 error = copyout(&end_offset, argp, sizeof (end_offset));
1963 }
1964
1965 (void) vnode_put(vp);
1966 break;
1967 }
1968 case F_GETCODEDIR:
1969 case F_FINDSIGS: {
1970 error = ENOTSUP;
1971 goto out;
1972 }
1973 case F_CHECK_LV: {
1974 struct fileglob *fg;
1975 fchecklv_t lv;
1976
1977 if (fp->f_type != DTYPE_VNODE) {
1978 error = EBADF;
1979 goto out;
1980 }
1981 fg = fp->f_fglob;
1982 proc_fdunlock(p);
1983
1984 if (IS_64BIT_PROCESS(p)) {
1985 error = copyin(argp, &lv, sizeof (lv));
1986 } else {
1987 struct user32_fchecklv lv32;
1988
1989 error = copyin(argp, &lv32, sizeof (lv32));
1990 lv.lv_file_start = lv32.lv_file_start;
1991 lv.lv_error_message = (void *)(uintptr_t)lv32.lv_error_message;
1992 lv.lv_error_message_size = lv32.lv_error_message;
1993 }
1994 if (error)
1995 goto outdrop;
1996
1997 #if CONFIG_MACF
1998 error = mac_file_check_library_validation(p, fg, lv.lv_file_start,
1999 (user_long_t)lv.lv_error_message, lv.lv_error_message_size);
2000 #endif
2001
2002 break;
2003 }
2004 #if CONFIG_PROTECT
2005 case F_GETPROTECTIONCLASS: {
2006 if (fp->f_type != DTYPE_VNODE) {
2007 error = EBADF;
2008 goto out;
2009 }
2010 vp = (struct vnode *)fp->f_data;
2011
2012 proc_fdunlock(p);
2013
2014 if (vnode_getwithref(vp)) {
2015 error = ENOENT;
2016 goto outdrop;
2017 }
2018
2019 struct vnode_attr va;
2020
2021 VATTR_INIT(&va);
2022 VATTR_WANTED(&va, va_dataprotect_class);
2023 error = VNOP_GETATTR(vp, &va, &context);
2024 if (!error) {
2025 if (VATTR_IS_SUPPORTED(&va, va_dataprotect_class))
2026 *retval = va.va_dataprotect_class;
2027 else
2028 error = ENOTSUP;
2029 }
2030
2031 vnode_put(vp);
2032 break;
2033 }
2034
2035 case F_SETPROTECTIONCLASS: {
2036 /* tmp must be a valid PROTECTION_CLASS_* */
2037 tmp = CAST_DOWN_EXPLICIT(uint32_t, uap->arg);
2038
2039 if (fp->f_type != DTYPE_VNODE) {
2040 error = EBADF;
2041 goto out;
2042 }
2043 vp = (struct vnode *)fp->f_data;
2044
2045 proc_fdunlock(p);
2046
2047 if (vnode_getwithref(vp)) {
2048 error = ENOENT;
2049 goto outdrop;
2050 }
2051
2052 /* Only go forward if you have write access */
2053 vfs_context_t ctx = vfs_context_current();
2054 if(vnode_authorize(vp, NULLVP, (KAUTH_VNODE_ACCESS | KAUTH_VNODE_WRITE_DATA), ctx) != 0) {
2055 vnode_put(vp);
2056 error = EBADF;
2057 goto outdrop;
2058 }
2059
2060 struct vnode_attr va;
2061
2062 VATTR_INIT(&va);
2063 VATTR_SET(&va, va_dataprotect_class, tmp);
2064
2065 error = VNOP_SETATTR(vp, &va, ctx);
2066
2067 vnode_put(vp);
2068 break;
2069 }
2070
2071 case F_TRANSCODEKEY: {
2072 if (fp->f_type != DTYPE_VNODE) {
2073 error = EBADF;
2074 goto out;
2075 }
2076
2077 vp = (struct vnode *)fp->f_data;
2078 proc_fdunlock(p);
2079
2080 if (vnode_getwithref(vp)) {
2081 error = ENOENT;
2082 goto outdrop;
2083 }
2084
2085 cp_key_t k = {
2086 .len = CP_MAX_WRAPPEDKEYSIZE,
2087 };
2088
2089 MALLOC(k.key, char *, k.len, M_TEMP, M_WAITOK);
2090
2091 error = VNOP_IOCTL(vp, F_TRANSCODEKEY, (caddr_t)&k, 1, &context);
2092
2093 vnode_put(vp);
2094
2095 if (error == 0) {
2096 error = copyout(k.key, argp, k.len);
2097 *retval = k.len;
2098 }
2099
2100 FREE(k.key, M_TEMP);
2101
2102 break;
2103 }
2104
2105 case F_GETPROTECTIONLEVEL: {
2106 if (fp->f_type != DTYPE_VNODE) {
2107 error = EBADF;
2108 goto out;
2109 }
2110
2111 vp = (struct vnode*) fp->f_data;
2112 proc_fdunlock (p);
2113
2114 if (vnode_getwithref(vp)) {
2115 error = ENOENT;
2116 goto outdrop;
2117 }
2118
2119 error = VNOP_IOCTL(vp, F_GETPROTECTIONLEVEL, (caddr_t)retval, 0, &context);
2120
2121 vnode_put (vp);
2122 break;
2123 }
2124
2125 case F_GETDEFAULTPROTLEVEL: {
2126 if (fp->f_type != DTYPE_VNODE) {
2127 error = EBADF;
2128 goto out;
2129 }
2130
2131 vp = (struct vnode*) fp->f_data;
2132 proc_fdunlock (p);
2133
2134 if (vnode_getwithref(vp)) {
2135 error = ENOENT;
2136 goto outdrop;
2137 }
2138
2139 /*
2140 * if cp_get_major_vers fails, error will be set to proper errno
2141 * and cp_version will still be 0.
2142 */
2143
2144 error = VNOP_IOCTL(vp, F_GETDEFAULTPROTLEVEL, (caddr_t)retval, 0, &context);
2145
2146 vnode_put (vp);
2147 break;
2148 }
2149
2150 #endif /* CONFIG_PROTECT */
2151
2152 case F_MOVEDATAEXTENTS: {
2153 struct fileproc *fp2 = NULL;
2154 struct vnode *src_vp = NULLVP;
2155 struct vnode *dst_vp = NULLVP;
2156 /* We need to grab the 2nd FD out of the argments before moving on. */
2157 int fd2 = CAST_DOWN_EXPLICIT(int32_t, uap->arg);
2158
2159 error = priv_check_cred(kauth_cred_get(), PRIV_VFS_MOVE_DATA_EXTENTS, 0);
2160 if (error)
2161 goto out;
2162
2163 if (fp->f_type != DTYPE_VNODE) {
2164 error = EBADF;
2165 goto out;
2166 }
2167
2168 /* For now, special case HFS+ only, since this is SPI. */
2169 src_vp = (struct vnode *)fp->f_data;
2170 if (src_vp->v_tag != VT_HFS) {
2171 error = EINVAL;
2172 goto out;
2173 }
2174
2175 /*
2176 * Get the references before we start acquiring iocounts on the vnodes,
2177 * while we still hold the proc fd lock
2178 */
2179 if ( (error = fp_lookup(p, fd2, &fp2, 1)) ) {
2180 error = EBADF;
2181 goto out;
2182 }
2183 if (fp2->f_type != DTYPE_VNODE) {
2184 fp_drop(p, fd2, fp2, 1);
2185 error = EBADF;
2186 goto out;
2187 }
2188 dst_vp = (struct vnode *)fp2->f_data;
2189 if (dst_vp->v_tag != VT_HFS) {
2190 fp_drop(p, fd2, fp2, 1);
2191 error = EINVAL;
2192 goto out;
2193 }
2194
2195 #if CONFIG_MACF
2196 /* Re-do MAC checks against the new FD, pass in a fake argument */
2197 error = mac_file_check_fcntl(proc_ucred(p), fp2->f_fglob, uap->cmd, 0);
2198 if (error) {
2199 fp_drop(p, fd2, fp2, 1);
2200 goto out;
2201 }
2202 #endif
2203 /* Audit the 2nd FD */
2204 AUDIT_ARG(fd, fd2);
2205
2206 proc_fdunlock(p);
2207
2208 if (vnode_getwithref(src_vp)) {
2209 fp_drop(p, fd2, fp2, 0);
2210 error = ENOENT;
2211 goto outdrop;
2212 }
2213 if (vnode_getwithref(dst_vp)) {
2214 vnode_put (src_vp);
2215 fp_drop(p, fd2, fp2, 0);
2216 error = ENOENT;
2217 goto outdrop;
2218 }
2219
2220 /*
2221 * Basic asserts; validate they are not the same and that
2222 * both live on the same filesystem.
2223 */
2224 if (dst_vp == src_vp) {
2225 vnode_put (src_vp);
2226 vnode_put (dst_vp);
2227 fp_drop (p, fd2, fp2, 0);
2228 error = EINVAL;
2229 goto outdrop;
2230 }
2231
2232 if (dst_vp->v_mount != src_vp->v_mount) {
2233 vnode_put (src_vp);
2234 vnode_put (dst_vp);
2235 fp_drop (p, fd2, fp2, 0);
2236 error = EXDEV;
2237 goto outdrop;
2238 }
2239
2240 /* Now we have a legit pair of FDs. Go to work */
2241
2242 /* Now check for write access to the target files */
2243 if(vnode_authorize(src_vp, NULLVP,
2244 (KAUTH_VNODE_ACCESS | KAUTH_VNODE_WRITE_DATA), &context) != 0) {
2245 vnode_put(src_vp);
2246 vnode_put(dst_vp);
2247 fp_drop(p, fd2, fp2, 0);
2248 error = EBADF;
2249 goto outdrop;
2250 }
2251
2252 if(vnode_authorize(dst_vp, NULLVP,
2253 (KAUTH_VNODE_ACCESS | KAUTH_VNODE_WRITE_DATA), &context) != 0) {
2254 vnode_put(src_vp);
2255 vnode_put(dst_vp);
2256 fp_drop(p, fd2, fp2, 0);
2257 error = EBADF;
2258 goto outdrop;
2259 }
2260
2261 /* Verify that both vps point to files and not directories */
2262 if ( !vnode_isreg(src_vp) || !vnode_isreg(dst_vp)) {
2263 error = EINVAL;
2264 vnode_put (src_vp);
2265 vnode_put (dst_vp);
2266 fp_drop (p, fd2, fp2, 0);
2267 goto outdrop;
2268 }
2269
2270 /*
2271 * The exchangedata syscall handler passes in 0 for the flags to VNOP_EXCHANGE.
2272 * We'll pass in our special bit indicating that the new behavior is expected
2273 */
2274
2275 error = VNOP_EXCHANGE(src_vp, dst_vp, FSOPT_EXCHANGE_DATA_ONLY, &context);
2276
2277 vnode_put (src_vp);
2278 vnode_put (dst_vp);
2279 fp_drop(p, fd2, fp2, 0);
2280 break;
2281 }
2282
2283 /*
2284 * SPI for making a file compressed.
2285 */
2286 case F_MAKECOMPRESSED: {
2287 uint32_t gcounter = CAST_DOWN_EXPLICIT(uint32_t, uap->arg);
2288
2289 if (fp->f_type != DTYPE_VNODE) {
2290 error = EBADF;
2291 goto out;
2292 }
2293
2294 vp = (struct vnode*) fp->f_data;
2295 proc_fdunlock (p);
2296
2297 /* get the vnode */
2298 if (vnode_getwithref(vp)) {
2299 error = ENOENT;
2300 goto outdrop;
2301 }
2302
2303 /* Is it a file? */
2304 if ((vnode_isreg(vp) == 0) && (vnode_islnk(vp) == 0)) {
2305 vnode_put(vp);
2306 error = EBADF;
2307 goto outdrop;
2308 }
2309
2310 /* invoke ioctl to pass off to FS */
2311 /* Only go forward if you have write access */
2312 vfs_context_t ctx = vfs_context_current();
2313 if(vnode_authorize(vp, NULLVP, (KAUTH_VNODE_ACCESS | KAUTH_VNODE_WRITE_DATA), ctx) != 0) {
2314 vnode_put(vp);
2315 error = EBADF;
2316 goto outdrop;
2317 }
2318
2319 error = VNOP_IOCTL(vp, uap->cmd, (caddr_t)&gcounter, 0, &context);
2320
2321 vnode_put (vp);
2322 break;
2323 }
2324
2325 /*
2326 * SPI (private) for indicating to a filesystem that subsequent writes to
2327 * the open FD will written to the Fastflow.
2328 */
2329 case F_SET_GREEDY_MODE:
2330 /* intentionally drop through to the same handler as F_SETSTATIC.
2331 * both fcntls should pass the argument and their selector into VNOP_IOCTL.
2332 */
2333
2334 /*
2335 * SPI (private) for indicating to a filesystem that subsequent writes to
2336 * the open FD will represent static content.
2337 */
2338 case F_SETSTATICCONTENT: {
2339 caddr_t ioctl_arg = NULL;
2340
2341 if (uap->arg) {
2342 ioctl_arg = (caddr_t) 1;
2343 }
2344
2345 if (fp->f_type != DTYPE_VNODE) {
2346 error = EBADF;
2347 goto out;
2348 }
2349 vp = (struct vnode *)fp->f_data;
2350 proc_fdunlock(p);
2351
2352 error = vnode_getwithref(vp);
2353 if (error) {
2354 error = ENOENT;
2355 goto outdrop;
2356 }
2357
2358 /* Only go forward if you have write access */
2359 vfs_context_t ctx = vfs_context_current();
2360 if(vnode_authorize(vp, NULLVP, (KAUTH_VNODE_ACCESS | KAUTH_VNODE_WRITE_DATA), ctx) != 0) {
2361 vnode_put(vp);
2362 error = EBADF;
2363 goto outdrop;
2364 }
2365
2366 error = VNOP_IOCTL(vp, uap->cmd, ioctl_arg, 0, &context);
2367 (void)vnode_put(vp);
2368
2369 break;
2370 }
2371
2372 /*
2373 * SPI (private) for indicating to the lower level storage driver that the
2374 * subsequent writes should be of a particular IO type (burst, greedy, static),
2375 * or other flavors that may be necessary.
2376 */
2377 case F_SETIOTYPE: {
2378 caddr_t param_ptr;
2379 uint32_t param;
2380
2381 if (uap->arg) {
2382 /* extract 32 bits of flags from userland */
2383 param_ptr = (caddr_t) uap->arg;
2384 param = (uint32_t) param_ptr;
2385 }
2386 else {
2387 /* If no argument is specified, error out */
2388 error = EINVAL;
2389 goto out;
2390 }
2391
2392 /*
2393 * Validate the different types of flags that can be specified:
2394 * all of them are mutually exclusive for now.
2395 */
2396 switch (param) {
2397 case F_IOTYPE_ISOCHRONOUS:
2398 break;
2399
2400 default:
2401 error = EINVAL;
2402 goto out;
2403 }
2404
2405
2406 if (fp->f_type != DTYPE_VNODE) {
2407 error = EBADF;
2408 goto out;
2409 }
2410 vp = (struct vnode *)fp->f_data;
2411 proc_fdunlock(p);
2412
2413 error = vnode_getwithref(vp);
2414 if (error) {
2415 error = ENOENT;
2416 goto outdrop;
2417 }
2418
2419 /* Only go forward if you have write access */
2420 vfs_context_t ctx = vfs_context_current();
2421 if(vnode_authorize(vp, NULLVP, (KAUTH_VNODE_ACCESS | KAUTH_VNODE_WRITE_DATA), ctx) != 0) {
2422 vnode_put(vp);
2423 error = EBADF;
2424 goto outdrop;
2425 }
2426
2427 error = VNOP_IOCTL(vp, uap->cmd, param_ptr, 0, &context);
2428 (void)vnode_put(vp);
2429
2430 break;
2431 }
2432
2433 /*
2434 * Set the vnode pointed to by 'fd'
2435 * and tag it as the (potentially future) backing store
2436 * for another filesystem
2437 */
2438 case F_SETBACKINGSTORE: {
2439 if (fp->f_type != DTYPE_VNODE) {
2440 error = EBADF;
2441 goto out;
2442 }
2443
2444 vp = (struct vnode *)fp->f_data;
2445
2446 if (vp->v_tag != VT_HFS) {
2447 error = EINVAL;
2448 goto out;
2449 }
2450 proc_fdunlock(p);
2451
2452 if (vnode_getwithref(vp)) {
2453 error = ENOENT;
2454 goto outdrop;
2455 }
2456
2457 /* only proceed if you have write access */
2458 vfs_context_t ctx = vfs_context_current();
2459 if(vnode_authorize(vp, NULLVP, (KAUTH_VNODE_ACCESS | KAUTH_VNODE_WRITE_DATA), ctx) != 0) {
2460 vnode_put(vp);
2461 error = EBADF;
2462 goto outdrop;
2463 }
2464
2465
2466 /* If arg != 0, set, otherwise unset */
2467 if (uap->arg) {
2468 error = VNOP_IOCTL (vp, uap->cmd, (caddr_t)1, 0, &context);
2469 }
2470 else {
2471 error = VNOP_IOCTL (vp, uap->cmd, (caddr_t)NULL, 0, &context);
2472 }
2473
2474 vnode_put(vp);
2475 break;
2476 }
2477
2478 /*
2479 * like F_GETPATH, but special semantics for
2480 * the mobile time machine handler.
2481 */
2482 case F_GETPATH_MTMINFO: {
2483 char *pathbufp;
2484 int pathlen;
2485
2486 if (fp->f_type != DTYPE_VNODE) {
2487 error = EBADF;
2488 goto out;
2489 }
2490 vp = (struct vnode *)fp->f_data;
2491 proc_fdunlock(p);
2492
2493 pathlen = MAXPATHLEN;
2494 MALLOC(pathbufp, char *, pathlen, M_TEMP, M_WAITOK);
2495 if (pathbufp == NULL) {
2496 error = ENOMEM;
2497 goto outdrop;
2498 }
2499 if ( (error = vnode_getwithref(vp)) == 0 ) {
2500 int backingstore = 0;
2501
2502 /* Check for error from vn_getpath before moving on */
2503 if ((error = vn_getpath(vp, pathbufp, &pathlen)) == 0) {
2504 if (vp->v_tag == VT_HFS) {
2505 error = VNOP_IOCTL (vp, uap->cmd, (caddr_t) &backingstore, 0, &context);
2506 }
2507 (void)vnode_put(vp);
2508
2509 if (error == 0) {
2510 error = copyout((caddr_t)pathbufp, argp, pathlen);
2511 }
2512 if (error == 0) {
2513 /*
2514 * If the copyout was successful, now check to ensure
2515 * that this vnode is not a BACKINGSTORE vnode. mtmd
2516 * wants the path regardless.
2517 */
2518 if (backingstore) {
2519 error = EBUSY;
2520 }
2521 }
2522 } else
2523 (void)vnode_put(vp);
2524 }
2525 FREE(pathbufp, M_TEMP);
2526 goto outdrop;
2527 }
2528
2529 #if DEBUG || DEVELOPMENT
2530 case F_RECYCLE:
2531 if (fp->f_type != DTYPE_VNODE) {
2532 error = EBADF;
2533 goto out;
2534 }
2535 vp = (struct vnode *)fp->f_data;
2536 proc_fdunlock(p);
2537
2538 vnode_recycle(vp);
2539 break;
2540 #endif
2541
2542 default:
2543 /*
2544 * This is an fcntl() that we d not recognize at this level;
2545 * if this is a vnode, we send it down into the VNOP_IOCTL
2546 * for this vnode; this can include special devices, and will
2547 * effectively overload fcntl() to send ioctl()'s.
2548 */
2549 if((uap->cmd & IOC_VOID) && (uap->cmd & IOC_INOUT)){
2550 error = EINVAL;
2551 goto out;
2552 }
2553
2554 /* Catch any now-invalid fcntl() selectors */
2555 switch (uap->cmd) {
2556 case (int)APFSIOC_REVERT_TO_SNAPSHOT:
2557 case (int)FSIOC_FIOSEEKHOLE:
2558 case (int)FSIOC_FIOSEEKDATA:
2559 case HFS_GET_BOOT_INFO:
2560 case HFS_SET_BOOT_INFO:
2561 case FIOPINSWAP:
2562 case F_MARKDEPENDENCY:
2563 error = EINVAL;
2564 goto out;
2565 default:
2566 break;
2567 }
2568
2569 if (fp->f_type != DTYPE_VNODE) {
2570 error = EBADF;
2571 goto out;
2572 }
2573 vp = (struct vnode *)fp->f_data;
2574 proc_fdunlock(p);
2575
2576 if ( (error = vnode_getwithref(vp)) == 0 ) {
2577 #define STK_PARAMS 128
2578 char stkbuf[STK_PARAMS] = {0};
2579 unsigned int size;
2580 caddr_t data, memp;
2581 /*
2582 * For this to work properly, we have to copy in the
2583 * ioctl() cmd argument if there is one; we must also
2584 * check that a command parameter, if present, does
2585 * not exceed the maximum command length dictated by
2586 * the number of bits we have available in the command
2587 * to represent a structure length. Finally, we have
2588 * to copy the results back out, if it is that type of
2589 * ioctl().
2590 */
2591 size = IOCPARM_LEN(uap->cmd);
2592 if (size > IOCPARM_MAX) {
2593 (void)vnode_put(vp);
2594 error = EINVAL;
2595 break;
2596 }
2597
2598 memp = NULL;
2599 if (size > sizeof (stkbuf)) {
2600 if ((memp = (caddr_t)kalloc(size)) == 0) {
2601 (void)vnode_put(vp);
2602 error = ENOMEM;
2603 goto outdrop;
2604 }
2605 data = memp;
2606 } else {
2607 data = &stkbuf[0];
2608 }
2609
2610 if (uap->cmd & IOC_IN) {
2611 if (size) {
2612 /* structure */
2613 error = copyin(argp, data, size);
2614 if (error) {
2615 (void)vnode_put(vp);
2616 if (memp)
2617 kfree(memp, size);
2618 goto outdrop;
2619 }
2620
2621 /* Bzero the section beyond that which was needed */
2622 if (size <= sizeof(stkbuf)) {
2623 bzero ( (((uint8_t*)data) + size), (sizeof(stkbuf) - size));
2624 }
2625 } else {
2626 /* int */
2627 if (is64bit) {
2628 *(user_addr_t *)data = argp;
2629 } else {
2630 *(uint32_t *)data = (uint32_t)argp;
2631 }
2632 };
2633 } else if ((uap->cmd & IOC_OUT) && size) {
2634 /*
2635 * Zero the buffer so the user always
2636 * gets back something deterministic.
2637 */
2638 bzero(data, size);
2639 } else if (uap->cmd & IOC_VOID) {
2640 if (is64bit) {
2641 *(user_addr_t *)data = argp;
2642 } else {
2643 *(uint32_t *)data = (uint32_t)argp;
2644 }
2645 }
2646
2647 error = VNOP_IOCTL(vp, uap->cmd, CAST_DOWN(caddr_t, data), 0, &context);
2648
2649 (void)vnode_put(vp);
2650
2651 /* Copy any output data to user */
2652 if (error == 0 && (uap->cmd & IOC_OUT) && size)
2653 error = copyout(data, argp, size);
2654 if (memp)
2655 kfree(memp, size);
2656 }
2657 break;
2658 }
2659
2660 outdrop:
2661 AUDIT_ARG(vnpath_withref, vp, ARG_VNODE1);
2662 fp_drop(p, fd, fp, 0);
2663 return(error);
2664 out:
2665 fp_drop(p, fd, fp, 1);
2666 proc_fdunlock(p);
2667 return(error);
2668 }
2669
2670
2671 /*
2672 * finishdup
2673 *
2674 * Description: Common code for dup, dup2, and fcntl(F_DUPFD).
2675 *
2676 * Parameters: p Process performing the dup
2677 * old The fd to dup
2678 * new The fd to dup it to
2679 * fd_flags Flags to augment the new fd
2680 * retval Pointer to the call return area
2681 *
2682 * Returns: 0 Success
2683 * EBADF
2684 * ENOMEM
2685 *
2686 * Implicit returns:
2687 * *retval (modified) The new descriptor
2688 *
2689 * Locks: Assumes proc_fdlock for process pointing to fdp is held by
2690 * the caller
2691 *
2692 * Notes: This function may drop and reacquire this lock; it is unsafe
2693 * for a caller to assume that other state protected by the lock
2694 * has not been subsequently changed out from under it.
2695 */
2696 int
2697 finishdup(proc_t p,
2698 struct filedesc *fdp, int old, int new, int fd_flags, int32_t *retval)
2699 {
2700 struct fileproc *nfp;
2701 struct fileproc *ofp;
2702 #if CONFIG_MACF
2703 int error;
2704 #endif
2705
2706 #if DIAGNOSTIC
2707 proc_fdlock_assert(p, LCK_MTX_ASSERT_OWNED);
2708 #endif
2709 if ((ofp = fdp->fd_ofiles[old]) == NULL ||
2710 (fdp->fd_ofileflags[old] & UF_RESERVED)) {
2711 fdrelse(p, new);
2712 return (EBADF);
2713 }
2714 fg_ref(ofp);
2715
2716 #if CONFIG_MACF
2717 error = mac_file_check_dup(proc_ucred(p), ofp->f_fglob, new);
2718 if (error) {
2719 fg_drop(ofp);
2720 fdrelse(p, new);
2721 return (error);
2722 }
2723 #endif
2724
2725 proc_fdunlock(p);
2726
2727 nfp = fileproc_alloc_init(NULL);
2728
2729 proc_fdlock(p);
2730
2731 if (nfp == NULL) {
2732 fg_drop(ofp);
2733 fdrelse(p, new);
2734 return (ENOMEM);
2735 }
2736
2737 nfp->f_fglob = ofp->f_fglob;
2738
2739 #if DIAGNOSTIC
2740 if (fdp->fd_ofiles[new] != 0)
2741 panic("finishdup: overwriting fd_ofiles with new %d", new);
2742 if ((fdp->fd_ofileflags[new] & UF_RESERVED) == 0)
2743 panic("finishdup: unreserved fileflags with new %d", new);
2744 #endif
2745
2746 if (new > fdp->fd_lastfile)
2747 fdp->fd_lastfile = new;
2748 *fdflags(p, new) |= fd_flags;
2749 procfdtbl_releasefd(p, new, nfp);
2750 *retval = new;
2751 return (0);
2752 }
2753
2754
2755 /*
2756 * close
2757 *
2758 * Description: The implementation of the close(2) system call
2759 *
2760 * Parameters: p Process in whose per process file table
2761 * the close is to occur
2762 * uap->fd fd to be closed
2763 * retval <unused>
2764 *
2765 * Returns: 0 Success
2766 * fp_lookup:EBADF Bad file descriptor
2767 * fp_guard_exception:??? Guarded file descriptor
2768 * close_internal:EBADF
2769 * close_internal:??? Anything returnable by a per-fileops
2770 * close function
2771 */
2772 int
2773 close(proc_t p, struct close_args *uap, int32_t *retval)
2774 {
2775 __pthread_testcancel(1);
2776 return(close_nocancel(p, (struct close_nocancel_args *)uap, retval));
2777 }
2778
2779
2780 int
2781 close_nocancel(proc_t p, struct close_nocancel_args *uap, __unused int32_t *retval)
2782 {
2783 struct fileproc *fp;
2784 int fd = uap->fd;
2785 int error;
2786
2787 AUDIT_SYSCLOSE(p, fd);
2788
2789 proc_fdlock(p);
2790
2791 if ( (error = fp_lookup(p,fd,&fp, 1)) ) {
2792 proc_fdunlock(p);
2793 return(error);
2794 }
2795
2796 if (FP_ISGUARDED(fp, GUARD_CLOSE)) {
2797 error = fp_guard_exception(p, fd, fp, kGUARD_EXC_CLOSE);
2798 (void) fp_drop(p, fd, fp, 1);
2799 proc_fdunlock(p);
2800 return (error);
2801 }
2802
2803 error = close_internal_locked(p, fd, fp, 0);
2804
2805 proc_fdunlock(p);
2806
2807 return (error);
2808 }
2809
2810
2811 /*
2812 * close_internal_locked
2813 *
2814 * Close a file descriptor.
2815 *
2816 * Parameters: p Process in whose per process file table
2817 * the close is to occur
2818 * fd fd to be closed
2819 * fp fileproc associated with the fd
2820 *
2821 * Returns: 0 Success
2822 * EBADF fd already in close wait state
2823 * closef_locked:??? Anything returnable by a per-fileops
2824 * close function
2825 *
2826 * Locks: Assumes proc_fdlock for process is held by the caller and returns
2827 * with lock held
2828 *
2829 * Notes: This function may drop and reacquire this lock; it is unsafe
2830 * for a caller to assume that other state protected by the lock
2831 * has not been subsequently changed out from under it.
2832 */
2833 int
2834 close_internal_locked(proc_t p, int fd, struct fileproc *fp, int flags)
2835 {
2836 struct filedesc *fdp = p->p_fd;
2837 int error =0;
2838 int resvfd = flags & FD_DUP2RESV;
2839
2840
2841 #if DIAGNOSTIC
2842 proc_fdlock_assert(p, LCK_MTX_ASSERT_OWNED);
2843 #endif
2844
2845 /* Keep people from using the filedesc while we are closing it */
2846 procfdtbl_markclosefd(p, fd);
2847
2848
2849 if ((fp->f_flags & FP_CLOSING) == FP_CLOSING) {
2850 panic("close_internal_locked: being called on already closing fd");
2851 }
2852
2853
2854 #if DIAGNOSTIC
2855 if ((fdp->fd_ofileflags[fd] & UF_RESERVED) == 0)
2856 panic("close_internal: unreserved fileflags with fd %d", fd);
2857 #endif
2858
2859 fp->f_flags |= FP_CLOSING;
2860
2861 if ( (fp->f_flags & FP_AIOISSUED) || kauth_authorize_fileop_has_listeners() ) {
2862
2863 proc_fdunlock(p);
2864
2865 if ( (fp->f_type == DTYPE_VNODE) && kauth_authorize_fileop_has_listeners() ) {
2866 /*
2867 * call out to allow 3rd party notification of close.
2868 * Ignore result of kauth_authorize_fileop call.
2869 */
2870 if (vnode_getwithref((vnode_t)fp->f_data) == 0) {
2871 u_int fileop_flags = 0;
2872 if ((fp->f_flags & FP_WRITTEN) != 0)
2873 fileop_flags |= KAUTH_FILEOP_CLOSE_MODIFIED;
2874 kauth_authorize_fileop(fp->f_fglob->fg_cred, KAUTH_FILEOP_CLOSE,
2875 (uintptr_t)fp->f_data, (uintptr_t)fileop_flags);
2876 vnode_put((vnode_t)fp->f_data);
2877 }
2878 }
2879 if (fp->f_flags & FP_AIOISSUED)
2880 /*
2881 * cancel all async IO requests that can be cancelled.
2882 */
2883 _aio_close( p, fd );
2884
2885 proc_fdlock(p);
2886 }
2887
2888 if (fd < fdp->fd_knlistsize)
2889 knote_fdclose(p, fd, FALSE);
2890
2891 if (fp->f_flags & FP_WAITEVENT)
2892 (void)waitevent_close(p, fp);
2893
2894 fileproc_drain(p, fp);
2895
2896 if (resvfd == 0) {
2897 _fdrelse(p, fd);
2898 } else {
2899 procfdtbl_reservefd(p, fd);
2900 }
2901
2902 if (ENTR_SHOULDTRACE && fp->f_type == DTYPE_SOCKET)
2903 KERNEL_ENERGYTRACE(kEnTrActKernSocket, DBG_FUNC_END,
2904 fd, 0, (int64_t)VM_KERNEL_ADDRPERM(fp->f_data));
2905
2906 error = closef_locked(fp, fp->f_fglob, p);
2907 if ((fp->f_flags & FP_WAITCLOSE) == FP_WAITCLOSE)
2908 wakeup(&fp->f_flags);
2909 fp->f_flags &= ~(FP_WAITCLOSE | FP_CLOSING);
2910
2911 proc_fdunlock(p);
2912
2913 fileproc_free(fp);
2914
2915 proc_fdlock(p);
2916
2917 #if DIAGNOSTIC
2918 if (resvfd != 0) {
2919 if ((fdp->fd_ofileflags[fd] & UF_RESERVED) == 0)
2920 panic("close with reserved fd returns with freed fd:%d: proc: %p", fd, p);
2921 }
2922 #endif
2923
2924 return(error);
2925 }
2926
2927
2928 /*
2929 * fstat1
2930 *
2931 * Description: Return status information about a file descriptor.
2932 *
2933 * Parameters: p The process doing the fstat
2934 * fd The fd to stat
2935 * ub The user stat buffer
2936 * xsecurity The user extended security
2937 * buffer, or 0 if none
2938 * xsecurity_size The size of xsecurity, or 0
2939 * if no xsecurity
2940 * isstat64 Flag to indicate 64 bit version
2941 * for inode size, etc.
2942 *
2943 * Returns: 0 Success
2944 * EBADF
2945 * EFAULT
2946 * fp_lookup:EBADF Bad file descriptor
2947 * vnode_getwithref:???
2948 * copyout:EFAULT
2949 * vnode_getwithref:???
2950 * vn_stat:???
2951 * soo_stat:???
2952 * pipe_stat:???
2953 * pshm_stat:???
2954 * kqueue_stat:???
2955 *
2956 * Notes: Internal implementation for all other fstat() related
2957 * functions
2958 *
2959 * XXX switch on node type is bogus; need a stat in struct
2960 * XXX fileops instead.
2961 */
2962 static int
2963 fstat1(proc_t p, int fd, user_addr_t ub, user_addr_t xsecurity, user_addr_t xsecurity_size, int isstat64)
2964 {
2965 struct fileproc *fp;
2966 union {
2967 struct stat sb;
2968 struct stat64 sb64;
2969 } source;
2970 union {
2971 struct user64_stat user64_sb;
2972 struct user32_stat user32_sb;
2973 struct user64_stat64 user64_sb64;
2974 struct user32_stat64 user32_sb64;
2975 } dest;
2976 int error, my_size;
2977 file_type_t type;
2978 caddr_t data;
2979 kauth_filesec_t fsec;
2980 user_size_t xsecurity_bufsize;
2981 vfs_context_t ctx = vfs_context_current();
2982 void * sbptr;
2983
2984
2985 AUDIT_ARG(fd, fd);
2986
2987 if ((error = fp_lookup(p, fd, &fp, 0)) != 0) {
2988 return(error);
2989 }
2990 type = fp->f_type;
2991 data = fp->f_data;
2992 fsec = KAUTH_FILESEC_NONE;
2993
2994 sbptr = (void *)&source;
2995
2996 switch (type) {
2997
2998 case DTYPE_VNODE:
2999 if ((error = vnode_getwithref((vnode_t)data)) == 0) {
3000 /*
3001 * If the caller has the file open, and is not
3002 * requesting extended security information, we are
3003 * going to let them get the basic stat information.
3004 */
3005 if (xsecurity == USER_ADDR_NULL) {
3006 error = vn_stat_noauth((vnode_t)data, sbptr, NULL, isstat64, ctx,
3007 fp->f_fglob->fg_cred);
3008 } else {
3009 error = vn_stat((vnode_t)data, sbptr, &fsec, isstat64, ctx);
3010 }
3011
3012 AUDIT_ARG(vnpath, (struct vnode *)data, ARG_VNODE1);
3013 (void)vnode_put((vnode_t)data);
3014 }
3015 break;
3016
3017 #if SOCKETS
3018 case DTYPE_SOCKET:
3019 error = soo_stat((struct socket *)data, sbptr, isstat64);
3020 break;
3021 #endif /* SOCKETS */
3022
3023 case DTYPE_PIPE:
3024 error = pipe_stat((void *)data, sbptr, isstat64);
3025 break;
3026
3027 case DTYPE_PSXSHM:
3028 error = pshm_stat((void *)data, sbptr, isstat64);
3029 break;
3030
3031 case DTYPE_KQUEUE:
3032 error = kqueue_stat((void *)data, sbptr, isstat64, p);
3033 break;
3034
3035 default:
3036 error = EBADF;
3037 goto out;
3038 }
3039 if (error == 0) {
3040 caddr_t sbp;
3041
3042 if (isstat64 != 0) {
3043 source.sb64.st_lspare = 0;
3044 source.sb64.st_qspare[0] = 0LL;
3045 source.sb64.st_qspare[1] = 0LL;
3046
3047 if (IS_64BIT_PROCESS(current_proc())) {
3048 munge_user64_stat64(&source.sb64, &dest.user64_sb64);
3049 my_size = sizeof(dest.user64_sb64);
3050 sbp = (caddr_t)&dest.user64_sb64;
3051 } else {
3052 munge_user32_stat64(&source.sb64, &dest.user32_sb64);
3053 my_size = sizeof(dest.user32_sb64);
3054 sbp = (caddr_t)&dest.user32_sb64;
3055 }
3056 } else {
3057 source.sb.st_lspare = 0;
3058 source.sb.st_qspare[0] = 0LL;
3059 source.sb.st_qspare[1] = 0LL;
3060 if (IS_64BIT_PROCESS(current_proc())) {
3061 munge_user64_stat(&source.sb, &dest.user64_sb);
3062 my_size = sizeof(dest.user64_sb);
3063 sbp = (caddr_t)&dest.user64_sb;
3064 } else {
3065 munge_user32_stat(&source.sb, &dest.user32_sb);
3066 my_size = sizeof(dest.user32_sb);
3067 sbp = (caddr_t)&dest.user32_sb;
3068 }
3069 }
3070
3071 error = copyout(sbp, ub, my_size);
3072 }
3073
3074 /* caller wants extended security information? */
3075 if (xsecurity != USER_ADDR_NULL) {
3076
3077 /* did we get any? */
3078 if (fsec == KAUTH_FILESEC_NONE) {
3079 if (susize(xsecurity_size, 0) != 0) {
3080 error = EFAULT;
3081 goto out;
3082 }
3083 } else {
3084 /* find the user buffer size */
3085 xsecurity_bufsize = fusize(xsecurity_size);
3086
3087 /* copy out the actual data size */
3088 if (susize(xsecurity_size, KAUTH_FILESEC_COPYSIZE(fsec)) != 0) {
3089 error = EFAULT;
3090 goto out;
3091 }
3092
3093 /* if the caller supplied enough room, copy out to it */
3094 if (xsecurity_bufsize >= KAUTH_FILESEC_COPYSIZE(fsec))
3095 error = copyout(fsec, xsecurity, KAUTH_FILESEC_COPYSIZE(fsec));
3096 }
3097 }
3098 out:
3099 fp_drop(p, fd, fp, 0);
3100 if (fsec != NULL)
3101 kauth_filesec_free(fsec);
3102 return (error);
3103 }
3104
3105
3106 /*
3107 * fstat_extended
3108 *
3109 * Description: Extended version of fstat supporting returning extended
3110 * security information
3111 *
3112 * Parameters: p The process doing the fstat
3113 * uap->fd The fd to stat
3114 * uap->ub The user stat buffer
3115 * uap->xsecurity The user extended security
3116 * buffer, or 0 if none
3117 * uap->xsecurity_size The size of xsecurity, or 0
3118 *
3119 * Returns: 0 Success
3120 * !0 Errno (see fstat1)
3121 */
3122 int
3123 fstat_extended(proc_t p, struct fstat_extended_args *uap, __unused int32_t *retval)
3124 {
3125 return(fstat1(p, uap->fd, uap->ub, uap->xsecurity, uap->xsecurity_size, 0));
3126 }
3127
3128
3129 /*
3130 * fstat
3131 *
3132 * Description: Get file status for the file associated with fd
3133 *
3134 * Parameters: p The process doing the fstat
3135 * uap->fd The fd to stat
3136 * uap->ub The user stat buffer
3137 *
3138 * Returns: 0 Success
3139 * !0 Errno (see fstat1)
3140 */
3141 int
3142 fstat(proc_t p, struct fstat_args *uap, __unused int32_t *retval)
3143 {
3144 return(fstat1(p, uap->fd, uap->ub, 0, 0, 0));
3145 }
3146
3147
3148 /*
3149 * fstat64_extended
3150 *
3151 * Description: Extended version of fstat64 supporting returning extended
3152 * security information
3153 *
3154 * Parameters: p The process doing the fstat
3155 * uap->fd The fd to stat
3156 * uap->ub The user stat buffer
3157 * uap->xsecurity The user extended security
3158 * buffer, or 0 if none
3159 * uap->xsecurity_size The size of xsecurity, or 0
3160 *
3161 * Returns: 0 Success
3162 * !0 Errno (see fstat1)
3163 */
3164 int
3165 fstat64_extended(proc_t p, struct fstat64_extended_args *uap, __unused int32_t *retval)
3166 {
3167 return(fstat1(p, uap->fd, uap->ub, uap->xsecurity, uap->xsecurity_size, 1));
3168 }
3169
3170
3171 /*
3172 * fstat64
3173 *
3174 * Description: Get 64 bit version of the file status for the file associated
3175 * with fd
3176 *
3177 * Parameters: p The process doing the fstat
3178 * uap->fd The fd to stat
3179 * uap->ub The user stat buffer
3180 *
3181 * Returns: 0 Success
3182 * !0 Errno (see fstat1)
3183 */
3184 int
3185 fstat64(proc_t p, struct fstat64_args *uap, __unused int32_t *retval)
3186 {
3187 return(fstat1(p, uap->fd, uap->ub, 0, 0, 1));
3188 }
3189
3190
3191 /*
3192 * fpathconf
3193 *
3194 * Description: Return pathconf information about a file descriptor.
3195 *
3196 * Parameters: p Process making the request
3197 * uap->fd fd to get information about
3198 * uap->name Name of information desired
3199 * retval Pointer to the call return area
3200 *
3201 * Returns: 0 Success
3202 * EINVAL
3203 * fp_lookup:EBADF Bad file descriptor
3204 * vnode_getwithref:???
3205 * vn_pathconf:???
3206 *
3207 * Implicit returns:
3208 * *retval (modified) Returned information (numeric)
3209 */
3210 int
3211 fpathconf(proc_t p, struct fpathconf_args *uap, int32_t *retval)
3212 {
3213 int fd = uap->fd;
3214 struct fileproc *fp;
3215 struct vnode *vp;
3216 int error = 0;
3217 file_type_t type;
3218 caddr_t data;
3219
3220
3221 AUDIT_ARG(fd, uap->fd);
3222 if ( (error = fp_lookup(p, fd, &fp, 0)) )
3223 return(error);
3224 type = fp->f_type;
3225 data = fp->f_data;
3226
3227 switch (type) {
3228
3229 case DTYPE_SOCKET:
3230 if (uap->name != _PC_PIPE_BUF) {
3231 error = EINVAL;
3232 goto out;
3233 }
3234 *retval = PIPE_BUF;
3235 error = 0;
3236 goto out;
3237
3238 case DTYPE_PIPE:
3239 if (uap->name != _PC_PIPE_BUF) {
3240 error = EINVAL;
3241 goto out;
3242 }
3243 *retval = PIPE_BUF;
3244 error = 0;
3245 goto out;
3246
3247 case DTYPE_VNODE:
3248 vp = (struct vnode *)data;
3249
3250 if ( (error = vnode_getwithref(vp)) == 0) {
3251 AUDIT_ARG(vnpath, vp, ARG_VNODE1);
3252
3253 error = vn_pathconf(vp, uap->name, retval, vfs_context_current());
3254
3255 (void)vnode_put(vp);
3256 }
3257 goto out;
3258
3259 default:
3260 error = EINVAL;
3261 goto out;
3262
3263 }
3264 /*NOTREACHED*/
3265 out:
3266 fp_drop(p, fd, fp, 0);
3267 return(error);
3268 }
3269
3270 /*
3271 * Statistics counter for the number of times a process calling fdalloc()
3272 * has resulted in an expansion of the per process open file table.
3273 *
3274 * XXX This would likely be of more use if it were per process
3275 */
3276 int fdexpand;
3277
3278
3279 /*
3280 * fdalloc
3281 *
3282 * Description: Allocate a file descriptor for the process.
3283 *
3284 * Parameters: p Process to allocate the fd in
3285 * want The fd we would prefer to get
3286 * result Pointer to fd we got
3287 *
3288 * Returns: 0 Success
3289 * EMFILE
3290 * ENOMEM
3291 *
3292 * Implicit returns:
3293 * *result (modified) The fd which was allocated
3294 */
3295 int
3296 fdalloc(proc_t p, int want, int *result)
3297 {
3298 struct filedesc *fdp = p->p_fd;
3299 int i;
3300 int lim, last, numfiles, oldnfiles;
3301 struct fileproc **newofiles, **ofiles;
3302 char *newofileflags;
3303
3304 /*
3305 * Search for a free descriptor starting at the higher
3306 * of want or fd_freefile. If that fails, consider
3307 * expanding the ofile array.
3308 */
3309 #if DIAGNOSTIC
3310 proc_fdlock_assert(p, LCK_MTX_ASSERT_OWNED);
3311 #endif
3312
3313 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
3314 for (;;) {
3315 last = min(fdp->fd_nfiles, lim);
3316 if ((i = want) < fdp->fd_freefile)
3317 i = fdp->fd_freefile;
3318 for (; i < last; i++) {
3319 if (fdp->fd_ofiles[i] == NULL && !(fdp->fd_ofileflags[i] & UF_RESERVED)) {
3320 procfdtbl_reservefd(p, i);
3321 if (i > fdp->fd_lastfile)
3322 fdp->fd_lastfile = i;
3323 if (want <= fdp->fd_freefile)
3324 fdp->fd_freefile = i;
3325 *result = i;
3326 return (0);
3327 }
3328 }
3329
3330 /*
3331 * No space in current array. Expand?
3332 */
3333 if (fdp->fd_nfiles >= lim)
3334 return (EMFILE);
3335 if (fdp->fd_nfiles < NDEXTENT)
3336 numfiles = NDEXTENT;
3337 else
3338 numfiles = 2 * fdp->fd_nfiles;
3339 /* Enforce lim */
3340 if (numfiles > lim)
3341 numfiles = lim;
3342 proc_fdunlock(p);
3343 MALLOC_ZONE(newofiles, struct fileproc **,
3344 numfiles * OFILESIZE, M_OFILETABL, M_WAITOK);
3345 proc_fdlock(p);
3346 if (newofiles == NULL) {
3347 return (ENOMEM);
3348 }
3349 if (fdp->fd_nfiles >= numfiles) {
3350 FREE_ZONE(newofiles, numfiles * OFILESIZE, M_OFILETABL);
3351 continue;
3352 }
3353 newofileflags = (char *) &newofiles[numfiles];
3354 /*
3355 * Copy the existing ofile and ofileflags arrays
3356 * and zero the new portion of each array.
3357 */
3358 oldnfiles = fdp->fd_nfiles;
3359 (void) memcpy(newofiles, fdp->fd_ofiles,
3360 oldnfiles * sizeof(*fdp->fd_ofiles));
3361 (void) memset(&newofiles[oldnfiles], 0,
3362 (numfiles - oldnfiles) * sizeof(*fdp->fd_ofiles));
3363
3364 (void) memcpy(newofileflags, fdp->fd_ofileflags,
3365 oldnfiles * sizeof(*fdp->fd_ofileflags));
3366 (void) memset(&newofileflags[oldnfiles], 0,
3367 (numfiles - oldnfiles) *
3368 sizeof(*fdp->fd_ofileflags));
3369 ofiles = fdp->fd_ofiles;
3370 fdp->fd_ofiles = newofiles;
3371 fdp->fd_ofileflags = newofileflags;
3372 fdp->fd_nfiles = numfiles;
3373 FREE_ZONE(ofiles, oldnfiles * OFILESIZE, M_OFILETABL);
3374 fdexpand++;
3375 }
3376 }
3377
3378
3379 /*
3380 * fdavail
3381 *
3382 * Description: Check to see whether n user file descriptors are available
3383 * to the process p.
3384 *
3385 * Parameters: p Process to check in
3386 * n The number of fd's desired
3387 *
3388 * Returns: 0 No
3389 * 1 Yes
3390 *
3391 * Locks: Assumes proc_fdlock for process is held by the caller
3392 *
3393 * Notes: The answer only remains valid so long as the proc_fdlock is
3394 * held by the caller.
3395 */
3396 int
3397 fdavail(proc_t p, int n)
3398 {
3399 struct filedesc *fdp = p->p_fd;
3400 struct fileproc **fpp;
3401 char *flags;
3402 int i, lim;
3403
3404 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
3405 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
3406 return (1);
3407 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
3408 flags = &fdp->fd_ofileflags[fdp->fd_freefile];
3409 for (i = fdp->fd_nfiles - fdp->fd_freefile; --i >= 0; fpp++, flags++)
3410 if (*fpp == NULL && !(*flags & UF_RESERVED) && --n <= 0)
3411 return (1);
3412 return (0);
3413 }
3414
3415
3416 /*
3417 * fdrelse
3418 *
3419 * Description: Legacy KPI wrapper function for _fdrelse
3420 *
3421 * Parameters: p Process in which fd lives
3422 * fd fd to free
3423 *
3424 * Returns: void
3425 *
3426 * Locks: Assumes proc_fdlock for process is held by the caller
3427 */
3428 void
3429 fdrelse(proc_t p, int fd)
3430 {
3431 _fdrelse(p, fd);
3432 }
3433
3434
3435 /*
3436 * fdgetf_noref
3437 *
3438 * Description: Get the fileproc pointer for the given fd from the per process
3439 * open file table without taking an explicit reference on it.
3440 *
3441 * Parameters: p Process containing fd
3442 * fd fd to obtain fileproc for
3443 * resultfp Pointer to pointer return area
3444 *
3445 * Returns: 0 Success
3446 * EBADF
3447 *
3448 * Implicit returns:
3449 * *resultfp (modified) Pointer to fileproc pointer
3450 *
3451 * Locks: Assumes proc_fdlock for process is held by the caller
3452 *
3453 * Notes: Because there is no reference explicitly taken, the returned
3454 * fileproc pointer is only valid so long as the proc_fdlock
3455 * remains held by the caller.
3456 */
3457 int
3458 fdgetf_noref(proc_t p, int fd, struct fileproc **resultfp)
3459 {
3460 struct filedesc *fdp = p->p_fd;
3461 struct fileproc *fp;
3462
3463 if (fd < 0 || fd >= fdp->fd_nfiles ||
3464 (fp = fdp->fd_ofiles[fd]) == NULL ||
3465 (fdp->fd_ofileflags[fd] & UF_RESERVED)) {
3466 return (EBADF);
3467 }
3468 if (resultfp)
3469 *resultfp = fp;
3470 return (0);
3471 }
3472
3473
3474 /*
3475 * fp_getfvp
3476 *
3477 * Description: Get fileproc and vnode pointer for a given fd from the per
3478 * process open file table of the specified process, and if
3479 * successful, increment the f_iocount
3480 *
3481 * Parameters: p Process in which fd lives
3482 * fd fd to get information for
3483 * resultfp Pointer to result fileproc
3484 * pointer area, or 0 if none
3485 * resultvp Pointer to result vnode pointer
3486 * area, or 0 if none
3487 *
3488 * Returns: 0 Success
3489 * EBADF Bad file descriptor
3490 * ENOTSUP fd does not refer to a vnode
3491 *
3492 * Implicit returns:
3493 * *resultfp (modified) Fileproc pointer
3494 * *resultvp (modified) vnode pointer
3495 *
3496 * Notes: The resultfp and resultvp fields are optional, and may be
3497 * independently specified as NULL to skip returning information
3498 *
3499 * Locks: Internally takes and releases proc_fdlock
3500 */
3501 int
3502 fp_getfvp(proc_t p, int fd, struct fileproc **resultfp, struct vnode **resultvp)
3503 {
3504 struct filedesc *fdp = p->p_fd;
3505 struct fileproc *fp;
3506
3507 proc_fdlock_spin(p);
3508 if (fd < 0 || fd >= fdp->fd_nfiles ||
3509 (fp = fdp->fd_ofiles[fd]) == NULL ||
3510 (fdp->fd_ofileflags[fd] & UF_RESERVED)) {
3511 proc_fdunlock(p);
3512 return (EBADF);
3513 }
3514 if (fp->f_type != DTYPE_VNODE) {
3515 proc_fdunlock(p);
3516 return(ENOTSUP);
3517 }
3518 fp->f_iocount++;
3519
3520 if (resultfp)
3521 *resultfp = fp;
3522 if (resultvp)
3523 *resultvp = (struct vnode *)fp->f_data;
3524 proc_fdunlock(p);
3525
3526 return (0);
3527 }
3528
3529
3530 /*
3531 * fp_getfvpandvid
3532 *
3533 * Description: Get fileproc, vnode pointer, and vid for a given fd from the
3534 * per process open file table of the specified process, and if
3535 * successful, increment the f_iocount
3536 *
3537 * Parameters: p Process in which fd lives
3538 * fd fd to get information for
3539 * resultfp Pointer to result fileproc
3540 * pointer area, or 0 if none
3541 * resultvp Pointer to result vnode pointer
3542 * area, or 0 if none
3543 * vidp Pointer to resuld vid area
3544 *
3545 * Returns: 0 Success
3546 * EBADF Bad file descriptor
3547 * ENOTSUP fd does not refer to a vnode
3548 *
3549 * Implicit returns:
3550 * *resultfp (modified) Fileproc pointer
3551 * *resultvp (modified) vnode pointer
3552 * *vidp vid value
3553 *
3554 * Notes: The resultfp and resultvp fields are optional, and may be
3555 * independently specified as NULL to skip returning information
3556 *
3557 * Locks: Internally takes and releases proc_fdlock
3558 */
3559 int
3560 fp_getfvpandvid(proc_t p, int fd, struct fileproc **resultfp,
3561 struct vnode **resultvp, uint32_t *vidp)
3562 {
3563 struct filedesc *fdp = p->p_fd;
3564 struct fileproc *fp;
3565
3566 proc_fdlock_spin(p);
3567 if (fd < 0 || fd >= fdp->fd_nfiles ||
3568 (fp = fdp->fd_ofiles[fd]) == NULL ||
3569 (fdp->fd_ofileflags[fd] & UF_RESERVED)) {
3570 proc_fdunlock(p);
3571 return (EBADF);
3572 }
3573 if (fp->f_type != DTYPE_VNODE) {
3574 proc_fdunlock(p);
3575 return(ENOTSUP);
3576 }
3577 fp->f_iocount++;
3578
3579 if (resultfp)
3580 *resultfp = fp;
3581 if (resultvp)
3582 *resultvp = (struct vnode *)fp->f_data;
3583 if (vidp)
3584 *vidp = (uint32_t)vnode_vid((struct vnode *)fp->f_data);
3585 proc_fdunlock(p);
3586
3587 return (0);
3588 }
3589
3590
3591 /*
3592 * fp_getfsock
3593 *
3594 * Description: Get fileproc and socket pointer for a given fd from the
3595 * per process open file table of the specified process, and if
3596 * successful, increment the f_iocount
3597 *
3598 * Parameters: p Process in which fd lives
3599 * fd fd to get information for
3600 * resultfp Pointer to result fileproc
3601 * pointer area, or 0 if none
3602 * results Pointer to result socket
3603 * pointer area, or 0 if none
3604 *
3605 * Returns: EBADF The file descriptor is invalid
3606 * EOPNOTSUPP The file descriptor is not a socket
3607 * 0 Success
3608 *
3609 * Implicit returns:
3610 * *resultfp (modified) Fileproc pointer
3611 * *results (modified) socket pointer
3612 *
3613 * Notes: EOPNOTSUPP should probably be ENOTSOCK; this function is only
3614 * ever called from accept1().
3615 */
3616 int
3617 fp_getfsock(proc_t p, int fd, struct fileproc **resultfp,
3618 struct socket **results)
3619 {
3620 struct filedesc *fdp = p->p_fd;
3621 struct fileproc *fp;
3622
3623 proc_fdlock_spin(p);
3624 if (fd < 0 || fd >= fdp->fd_nfiles ||
3625 (fp = fdp->fd_ofiles[fd]) == NULL ||
3626 (fdp->fd_ofileflags[fd] & UF_RESERVED)) {
3627 proc_fdunlock(p);
3628 return (EBADF);
3629 }
3630 if (fp->f_type != DTYPE_SOCKET) {
3631 proc_fdunlock(p);
3632 return(EOPNOTSUPP);
3633 }
3634 fp->f_iocount++;
3635
3636 if (resultfp)
3637 *resultfp = fp;
3638 if (results)
3639 *results = (struct socket *)fp->f_data;
3640 proc_fdunlock(p);
3641
3642 return (0);
3643 }
3644
3645
3646 /*
3647 * fp_getfkq
3648 *
3649 * Description: Get fileproc and kqueue pointer for a given fd from the
3650 * per process open file table of the specified process, and if
3651 * successful, increment the f_iocount
3652 *
3653 * Parameters: p Process in which fd lives
3654 * fd fd to get information for
3655 * resultfp Pointer to result fileproc
3656 * pointer area, or 0 if none
3657 * resultkq Pointer to result kqueue
3658 * pointer area, or 0 if none
3659 *
3660 * Returns: EBADF The file descriptor is invalid
3661 * EBADF The file descriptor is not a socket
3662 * 0 Success
3663 *
3664 * Implicit returns:
3665 * *resultfp (modified) Fileproc pointer
3666 * *resultkq (modified) kqueue pointer
3667 *
3668 * Notes: The second EBADF should probably be something else to make
3669 * the error condition distinct.
3670 */
3671 int
3672 fp_getfkq(proc_t p, int fd, struct fileproc **resultfp,
3673 struct kqueue **resultkq)
3674 {
3675 struct filedesc *fdp = p->p_fd;
3676 struct fileproc *fp;
3677
3678 proc_fdlock_spin(p);
3679 if ( fd < 0 || fd >= fdp->fd_nfiles ||
3680 (fp = fdp->fd_ofiles[fd]) == NULL ||
3681 (fdp->fd_ofileflags[fd] & UF_RESERVED)) {
3682 proc_fdunlock(p);
3683 return (EBADF);
3684 }
3685 if (fp->f_type != DTYPE_KQUEUE) {
3686 proc_fdunlock(p);
3687 return(EBADF);
3688 }
3689 fp->f_iocount++;
3690
3691 if (resultfp)
3692 *resultfp = fp;
3693 if (resultkq)
3694 *resultkq = (struct kqueue *)fp->f_data;
3695 proc_fdunlock(p);
3696
3697 return (0);
3698 }
3699
3700
3701 /*
3702 * fp_getfpshm
3703 *
3704 * Description: Get fileproc and POSIX shared memory pointer for a given fd
3705 * from the per process open file table of the specified process
3706 * and if successful, increment the f_iocount
3707 *
3708 * Parameters: p Process in which fd lives
3709 * fd fd to get information for
3710 * resultfp Pointer to result fileproc
3711 * pointer area, or 0 if none
3712 * resultpshm Pointer to result POSIX
3713 * shared memory pointer
3714 * pointer area, or 0 if none
3715 *
3716 * Returns: EBADF The file descriptor is invalid
3717 * EBADF The file descriptor is not a POSIX
3718 * shared memory area
3719 * 0 Success
3720 *
3721 * Implicit returns:
3722 * *resultfp (modified) Fileproc pointer
3723 * *resultpshm (modified) POSIX shared memory pointer
3724 *
3725 * Notes: The second EBADF should probably be something else to make
3726 * the error condition distinct.
3727 */
3728 int
3729 fp_getfpshm(proc_t p, int fd, struct fileproc **resultfp,
3730 struct pshmnode **resultpshm)
3731 {
3732 struct filedesc *fdp = p->p_fd;
3733 struct fileproc *fp;
3734
3735 proc_fdlock_spin(p);
3736 if (fd < 0 || fd >= fdp->fd_nfiles ||
3737 (fp = fdp->fd_ofiles[fd]) == NULL ||
3738 (fdp->fd_ofileflags[fd] & UF_RESERVED)) {
3739 proc_fdunlock(p);
3740 return (EBADF);
3741 }
3742 if (fp->f_type != DTYPE_PSXSHM) {
3743
3744 proc_fdunlock(p);
3745 return(EBADF);
3746 }
3747 fp->f_iocount++;
3748
3749 if (resultfp)
3750 *resultfp = fp;
3751 if (resultpshm)
3752 *resultpshm = (struct pshmnode *)fp->f_data;
3753 proc_fdunlock(p);
3754
3755 return (0);
3756 }
3757
3758
3759 /*
3760 * fp_getfsem
3761 *
3762 * Description: Get fileproc and POSIX semaphore pointer for a given fd from
3763 * the per process open file table of the specified process
3764 * and if successful, increment the f_iocount
3765 *
3766 * Parameters: p Process in which fd lives
3767 * fd fd to get information for
3768 * resultfp Pointer to result fileproc
3769 * pointer area, or 0 if none
3770 * resultpsem Pointer to result POSIX
3771 * semaphore pointer area, or
3772 * 0 if none
3773 *
3774 * Returns: EBADF The file descriptor is invalid
3775 * EBADF The file descriptor is not a POSIX
3776 * semaphore
3777 * 0 Success
3778 *
3779 * Implicit returns:
3780 * *resultfp (modified) Fileproc pointer
3781 * *resultpsem (modified) POSIX semaphore pointer
3782 *
3783 * Notes: The second EBADF should probably be something else to make
3784 * the error condition distinct.
3785 *
3786 * In order to support unnamed POSIX semaphores, the named
3787 * POSIX semaphores will have to move out of the per-process
3788 * open filetable, and into a global table that is shared with
3789 * unnamed POSIX semaphores, since unnamed POSIX semaphores
3790 * are typically used by declaring instances in shared memory,
3791 * and there's no other way to do this without changing the
3792 * underlying type, which would introduce binary compatibility
3793 * issues.
3794 */
3795 int
3796 fp_getfpsem(proc_t p, int fd, struct fileproc **resultfp,
3797 struct psemnode **resultpsem)
3798 {
3799 struct filedesc *fdp = p->p_fd;
3800 struct fileproc *fp;
3801
3802 proc_fdlock_spin(p);
3803 if (fd < 0 || fd >= fdp->fd_nfiles ||
3804 (fp = fdp->fd_ofiles[fd]) == NULL ||
3805 (fdp->fd_ofileflags[fd] & UF_RESERVED)) {
3806 proc_fdunlock(p);
3807 return (EBADF);
3808 }
3809 if (fp->f_type != DTYPE_PSXSEM) {
3810 proc_fdunlock(p);
3811 return(EBADF);
3812 }
3813 fp->f_iocount++;
3814
3815 if (resultfp)
3816 *resultfp = fp;
3817 if (resultpsem)
3818 *resultpsem = (struct psemnode *)fp->f_data;
3819 proc_fdunlock(p);
3820
3821 return (0);
3822 }
3823
3824
3825 /*
3826 * fp_getfpipe
3827 *
3828 * Description: Get fileproc and pipe pointer for a given fd from the
3829 * per process open file table of the specified process
3830 * and if successful, increment the f_iocount
3831 *
3832 * Parameters: p Process in which fd lives
3833 * fd fd to get information for
3834 * resultfp Pointer to result fileproc
3835 * pointer area, or 0 if none
3836 * resultpipe Pointer to result pipe
3837 * pointer area, or 0 if none
3838 *
3839 * Returns: EBADF The file descriptor is invalid
3840 * EBADF The file descriptor is not a socket
3841 * 0 Success
3842 *
3843 * Implicit returns:
3844 * *resultfp (modified) Fileproc pointer
3845 * *resultpipe (modified) pipe pointer
3846 *
3847 * Notes: The second EBADF should probably be something else to make
3848 * the error condition distinct.
3849 */
3850 int
3851 fp_getfpipe(proc_t p, int fd, struct fileproc **resultfp,
3852 struct pipe **resultpipe)
3853 {
3854 struct filedesc *fdp = p->p_fd;
3855 struct fileproc *fp;
3856
3857 proc_fdlock_spin(p);
3858 if (fd < 0 || fd >= fdp->fd_nfiles ||
3859 (fp = fdp->fd_ofiles[fd]) == NULL ||
3860 (fdp->fd_ofileflags[fd] & UF_RESERVED)) {
3861 proc_fdunlock(p);
3862 return (EBADF);
3863 }
3864 if (fp->f_type != DTYPE_PIPE) {
3865 proc_fdunlock(p);
3866 return(EBADF);
3867 }
3868 fp->f_iocount++;
3869
3870 if (resultfp)
3871 *resultfp = fp;
3872 if (resultpipe)
3873 *resultpipe = (struct pipe *)fp->f_data;
3874 proc_fdunlock(p);
3875
3876 return (0);
3877 }
3878
3879
3880 /*
3881 * fp_lookup
3882 *
3883 * Description: Get fileproc pointer for a given fd from the per process
3884 * open file table of the specified process and if successful,
3885 * increment the f_iocount
3886 *
3887 * Parameters: p Process in which fd lives
3888 * fd fd to get information for
3889 * resultfp Pointer to result fileproc
3890 * pointer area, or 0 if none
3891 * locked !0 if the caller holds the
3892 * proc_fdlock, 0 otherwise
3893 *
3894 * Returns: 0 Success
3895 * EBADF Bad file descriptor
3896 *
3897 * Implicit returns:
3898 * *resultfp (modified) Fileproc pointer
3899 *
3900 * Locks: If the argument 'locked' is non-zero, then the caller is
3901 * expected to have taken and held the proc_fdlock; if it is
3902 * zero, than this routine internally takes and drops this lock.
3903 */
3904 int
3905 fp_lookup(proc_t p, int fd, struct fileproc **resultfp, int locked)
3906 {
3907 struct filedesc *fdp = p->p_fd;
3908 struct fileproc *fp;
3909
3910 if (!locked)
3911 proc_fdlock_spin(p);
3912 if (fd < 0 || fdp == NULL || fd >= fdp->fd_nfiles ||
3913 (fp = fdp->fd_ofiles[fd]) == NULL ||
3914 (fdp->fd_ofileflags[fd] & UF_RESERVED)) {
3915 if (!locked)
3916 proc_fdunlock(p);
3917 return (EBADF);
3918 }
3919 fp->f_iocount++;
3920
3921 if (resultfp)
3922 *resultfp = fp;
3923 if (!locked)
3924 proc_fdunlock(p);
3925
3926 return (0);
3927 }
3928
3929
3930 /*
3931 * fp_tryswap
3932 *
3933 * Description: Swap the fileproc pointer for a given fd with a new
3934 * fileproc pointer in the per-process open file table of
3935 * the specified process. The fdlock must be held at entry.
3936 *
3937 * Parameters: p Process containing the fd
3938 * fd The fd of interest
3939 * nfp Pointer to the newfp
3940 *
3941 * Returns: 0 Success
3942 * EBADF Bad file descriptor
3943 * EINTR Interrupted
3944 * EKEEPLOOKING f_iocount changed while lock was dropped.
3945 */
3946 int
3947 fp_tryswap(proc_t p, int fd, struct fileproc *nfp)
3948 {
3949 struct fileproc *fp;
3950 int error;
3951
3952 proc_fdlock_assert(p, LCK_MTX_ASSERT_OWNED);
3953
3954 if (0 != (error = fp_lookup(p, fd, &fp, 1)))
3955 return (error);
3956 /*
3957 * At this point, our caller (change_guardedfd_np) has
3958 * one f_iocount reference, and we just took another
3959 * one to begin the replacement.
3960 */
3961 if (fp->f_iocount < 2) {
3962 panic("f_iocount too small %d", fp->f_iocount);
3963 } else if (2 == fp->f_iocount) {
3964
3965 /* Copy the contents of *fp, preserving the "type" of *nfp */
3966
3967 nfp->f_flags = (nfp->f_flags & FP_TYPEMASK) |
3968 (fp->f_flags & ~FP_TYPEMASK);
3969 nfp->f_iocount = fp->f_iocount;
3970 nfp->f_fglob = fp->f_fglob;
3971 nfp->f_wset = fp->f_wset;
3972
3973 p->p_fd->fd_ofiles[fd] = nfp;
3974 (void) fp_drop(p, fd, nfp, 1);
3975 } else {
3976 /*
3977 * Wait for all other active references to evaporate.
3978 */
3979 p->p_fpdrainwait = 1;
3980 error = msleep(&p->p_fpdrainwait, &p->p_fdmlock,
3981 PRIBIO | PCATCH, "tryswap fpdrain", NULL);
3982 if (0 == error) {
3983 /*
3984 * Return an "internal" errno to trigger a full
3985 * reevaluation of the change-guard attempt.
3986 */
3987 error = EKEEPLOOKING;
3988 printf("%s: lookup collision fd %d\n", __func__, fd);
3989 }
3990 (void) fp_drop(p, fd, fp, 1);
3991 }
3992 return (error);
3993 }
3994
3995
3996 /*
3997 * fp_drop_written
3998 *
3999 * Description: Set the FP_WRITTEN flag on the fileproc and drop the I/O
4000 * reference previously taken by calling fp_lookup et. al.
4001 *
4002 * Parameters: p Process in which the fd lives
4003 * fd fd associated with the fileproc
4004 * fp fileproc on which to set the
4005 * flag and drop the reference
4006 *
4007 * Returns: 0 Success
4008 * fp_drop:EBADF Bad file descriptor
4009 *
4010 * Locks: This function internally takes and drops the proc_fdlock for
4011 * the supplied process
4012 *
4013 * Notes: The fileproc must correspond to the fd in the supplied proc
4014 */
4015 int
4016 fp_drop_written(proc_t p, int fd, struct fileproc *fp)
4017 {
4018 int error;
4019
4020 proc_fdlock_spin(p);
4021
4022 fp->f_flags |= FP_WRITTEN;
4023
4024 error = fp_drop(p, fd, fp, 1);
4025
4026 proc_fdunlock(p);
4027
4028 return (error);
4029 }
4030
4031
4032 /*
4033 * fp_drop_event
4034 *
4035 * Description: Set the FP_WAITEVENT flag on the fileproc and drop the I/O
4036 * reference previously taken by calling fp_lookup et. al.
4037 *
4038 * Parameters: p Process in which the fd lives
4039 * fd fd associated with the fileproc
4040 * fp fileproc on which to set the
4041 * flag and drop the reference
4042 *
4043 * Returns: 0 Success
4044 * fp_drop:EBADF Bad file descriptor
4045 *
4046 * Locks: This function internally takes and drops the proc_fdlock for
4047 * the supplied process
4048 *
4049 * Notes: The fileproc must correspond to the fd in the supplied proc
4050 */
4051 int
4052 fp_drop_event(proc_t p, int fd, struct fileproc *fp)
4053 {
4054 int error;
4055
4056 proc_fdlock_spin(p);
4057
4058 fp->f_flags |= FP_WAITEVENT;
4059
4060 error = fp_drop(p, fd, fp, 1);
4061
4062 proc_fdunlock(p);
4063
4064 return (error);
4065 }
4066
4067
4068 /*
4069 * fp_drop
4070 *
4071 * Description: Drop the I/O reference previously taken by calling fp_lookup
4072 * et. al.
4073 *
4074 * Parameters: p Process in which the fd lives
4075 * fd fd associated with the fileproc
4076 * fp fileproc on which to set the
4077 * flag and drop the reference
4078 * locked flag to internally take and
4079 * drop proc_fdlock if it is not
4080 * already held by the caller
4081 *
4082 * Returns: 0 Success
4083 * EBADF Bad file descriptor
4084 *
4085 * Locks: This function internally takes and drops the proc_fdlock for
4086 * the supplied process if 'locked' is non-zero, and assumes that
4087 * the caller already holds this lock if 'locked' is non-zero.
4088 *
4089 * Notes: The fileproc must correspond to the fd in the supplied proc
4090 */
4091 int
4092 fp_drop(proc_t p, int fd, struct fileproc *fp, int locked)
4093 {
4094 struct filedesc *fdp = p->p_fd;
4095 int needwakeup = 0;
4096
4097 if (!locked)
4098 proc_fdlock_spin(p);
4099 if ((fp == FILEPROC_NULL) && (fd < 0 || fd >= fdp->fd_nfiles ||
4100 (fp = fdp->fd_ofiles[fd]) == NULL ||
4101 ((fdp->fd_ofileflags[fd] & UF_RESERVED) &&
4102 !(fdp->fd_ofileflags[fd] & UF_CLOSING)))) {
4103 if (!locked)
4104 proc_fdunlock(p);
4105 return (EBADF);
4106 }
4107 fp->f_iocount--;
4108
4109 if (fp->f_iocount == 0) {
4110 if (fp->f_flags & FP_SELCONFLICT)
4111 fp->f_flags &= ~FP_SELCONFLICT;
4112
4113 if (p->p_fpdrainwait) {
4114 p->p_fpdrainwait = 0;
4115 needwakeup = 1;
4116 }
4117 }
4118 if (!locked)
4119 proc_fdunlock(p);
4120 if (needwakeup)
4121 wakeup(&p->p_fpdrainwait);
4122
4123 return (0);
4124 }
4125
4126
4127 /*
4128 * file_vnode
4129 *
4130 * Description: Given an fd, look it up in the current process's per process
4131 * open file table, and return its internal vnode pointer.
4132 *
4133 * Parameters: fd fd to obtain vnode from
4134 * vpp pointer to vnode return area
4135 *
4136 * Returns: 0 Success
4137 * EINVAL The fd does not refer to a
4138 * vnode fileproc entry
4139 * fp_lookup:EBADF Bad file descriptor
4140 *
4141 * Implicit returns:
4142 * *vpp (modified) Returned vnode pointer
4143 *
4144 * Locks: This function internally takes and drops the proc_fdlock for
4145 * the current process
4146 *
4147 * Notes: If successful, this function increments the f_iocount on the
4148 * fd's corresponding fileproc.
4149 *
4150 * The fileproc referenced is not returned; because of this, care
4151 * must be taken to not drop the last reference (e.g. by closing
4152 * the file). This is inherently unsafe, since the reference may
4153 * not be recoverable from the vnode, if there is a subsequent
4154 * close that destroys the associate fileproc. The caller should
4155 * therefore retain their own reference on the fileproc so that
4156 * the f_iocount can be dropped subsequently. Failure to do this
4157 * can result in the returned pointer immediately becoming invalid
4158 * following the call.
4159 *
4160 * Use of this function is discouraged.
4161 */
4162 int
4163 file_vnode(int fd, struct vnode **vpp)
4164 {
4165 proc_t p = current_proc();
4166 struct fileproc *fp;
4167 int error;
4168
4169 proc_fdlock_spin(p);
4170 if ( (error = fp_lookup(p, fd, &fp, 1)) ) {
4171 proc_fdunlock(p);
4172 return(error);
4173 }
4174 if (fp->f_type != DTYPE_VNODE) {
4175 fp_drop(p, fd, fp,1);
4176 proc_fdunlock(p);
4177 return(EINVAL);
4178 }
4179 if (vpp != NULL)
4180 *vpp = (struct vnode *)fp->f_data;
4181 proc_fdunlock(p);
4182
4183 return(0);
4184 }
4185
4186
4187 /*
4188 * file_vnode_withvid
4189 *
4190 * Description: Given an fd, look it up in the current process's per process
4191 * open file table, and return its internal vnode pointer.
4192 *
4193 * Parameters: fd fd to obtain vnode from
4194 * vpp pointer to vnode return area
4195 * vidp pointer to vid of the returned vnode
4196 *
4197 * Returns: 0 Success
4198 * EINVAL The fd does not refer to a
4199 * vnode fileproc entry
4200 * fp_lookup:EBADF Bad file descriptor
4201 *
4202 * Implicit returns:
4203 * *vpp (modified) Returned vnode pointer
4204 *
4205 * Locks: This function internally takes and drops the proc_fdlock for
4206 * the current process
4207 *
4208 * Notes: If successful, this function increments the f_iocount on the
4209 * fd's corresponding fileproc.
4210 *
4211 * The fileproc referenced is not returned; because of this, care
4212 * must be taken to not drop the last reference (e.g. by closing
4213 * the file). This is inherently unsafe, since the reference may
4214 * not be recoverable from the vnode, if there is a subsequent
4215 * close that destroys the associate fileproc. The caller should
4216 * therefore retain their own reference on the fileproc so that
4217 * the f_iocount can be dropped subsequently. Failure to do this
4218 * can result in the returned pointer immediately becoming invalid
4219 * following the call.
4220 *
4221 * Use of this function is discouraged.
4222 */
4223 int
4224 file_vnode_withvid(int fd, struct vnode **vpp, uint32_t * vidp)
4225 {
4226 proc_t p = current_proc();
4227 struct fileproc *fp;
4228 vnode_t vp;
4229 int error;
4230
4231 proc_fdlock_spin(p);
4232 if ( (error = fp_lookup(p, fd, &fp, 1)) ) {
4233 proc_fdunlock(p);
4234 return(error);
4235 }
4236 if (fp->f_type != DTYPE_VNODE) {
4237 fp_drop(p, fd, fp,1);
4238 proc_fdunlock(p);
4239 return(EINVAL);
4240 }
4241 vp = (struct vnode *)fp->f_data;
4242 if (vpp != NULL)
4243 *vpp = vp;
4244
4245 if ((vidp != NULL) && (vp != NULLVP))
4246 *vidp = (uint32_t)vp->v_id;
4247
4248 proc_fdunlock(p);
4249
4250 return(0);
4251 }
4252
4253
4254 /*
4255 * file_socket
4256 *
4257 * Description: Given an fd, look it up in the current process's per process
4258 * open file table, and return its internal socket pointer.
4259 *
4260 * Parameters: fd fd to obtain vnode from
4261 * sp pointer to socket return area
4262 *
4263 * Returns: 0 Success
4264 * ENOTSOCK Not a socket
4265 * fp_lookup:EBADF Bad file descriptor
4266 *
4267 * Implicit returns:
4268 * *sp (modified) Returned socket pointer
4269 *
4270 * Locks: This function internally takes and drops the proc_fdlock for
4271 * the current process
4272 *
4273 * Notes: If successful, this function increments the f_iocount on the
4274 * fd's corresponding fileproc.
4275 *
4276 * The fileproc referenced is not returned; because of this, care
4277 * must be taken to not drop the last reference (e.g. by closing
4278 * the file). This is inherently unsafe, since the reference may
4279 * not be recoverable from the socket, if there is a subsequent
4280 * close that destroys the associate fileproc. The caller should
4281 * therefore retain their own reference on the fileproc so that
4282 * the f_iocount can be dropped subsequently. Failure to do this
4283 * can result in the returned pointer immediately becoming invalid
4284 * following the call.
4285 *
4286 * Use of this function is discouraged.
4287 */
4288 int
4289 file_socket(int fd, struct socket **sp)
4290 {
4291 proc_t p = current_proc();
4292 struct fileproc *fp;
4293 int error;
4294
4295 proc_fdlock_spin(p);
4296 if ( (error = fp_lookup(p, fd, &fp, 1)) ) {
4297 proc_fdunlock(p);
4298 return(error);
4299 }
4300 if (fp->f_type != DTYPE_SOCKET) {
4301 fp_drop(p, fd, fp,1);
4302 proc_fdunlock(p);
4303 return(ENOTSOCK);
4304 }
4305 *sp = (struct socket *)fp->f_data;
4306 proc_fdunlock(p);
4307
4308 return(0);
4309 }
4310
4311
4312 /*
4313 * file_flags
4314 *
4315 * Description: Given an fd, look it up in the current process's per process
4316 * open file table, and return its fileproc's flags field.
4317 *
4318 * Parameters: fd fd whose flags are to be
4319 * retrieved
4320 * flags pointer to flags data area
4321 *
4322 * Returns: 0 Success
4323 * ENOTSOCK Not a socket
4324 * fp_lookup:EBADF Bad file descriptor
4325 *
4326 * Implicit returns:
4327 * *flags (modified) Returned flags field
4328 *
4329 * Locks: This function internally takes and drops the proc_fdlock for
4330 * the current process
4331 *
4332 * Notes: This function will internally increment and decrement the
4333 * f_iocount of the fileproc as part of its operation.
4334 */
4335 int
4336 file_flags(int fd, int *flags)
4337 {
4338
4339 proc_t p = current_proc();
4340 struct fileproc *fp;
4341 int error;
4342
4343 proc_fdlock_spin(p);
4344 if ( (error = fp_lookup(p, fd, &fp, 1)) ) {
4345 proc_fdunlock(p);
4346 return(error);
4347 }
4348 *flags = (int)fp->f_flag;
4349 fp_drop(p, fd, fp,1);
4350 proc_fdunlock(p);
4351
4352 return(0);
4353 }
4354
4355
4356 /*
4357 * file_drop
4358 *
4359 * Description: Drop an iocount reference on an fd, and wake up any waiters
4360 * for draining (i.e. blocked in fileproc_drain() called during
4361 * the last attempt to close a file).
4362 *
4363 * Parameters: fd fd on which an ioreference is
4364 * to be dropped
4365 *
4366 * Returns: 0 Success
4367 * EBADF Bad file descriptor
4368 *
4369 * Description: Given an fd, look it up in the current process's per process
4370 * open file table, and drop it's fileproc's f_iocount by one
4371 *
4372 * Notes: This is intended as a corresponding operation to the functions
4373 * file_vnode() and file_socket() operations.
4374 *
4375 * Technically, the close reference is supposed to be protected
4376 * by a fileproc_drain(), however, a drain will only block if
4377 * the fd refers to a character device, and that device has had
4378 * preparefileread() called on it. If it refers to something
4379 * other than a character device, then the drain will occur and
4380 * block each close attempt, rather than merely the last close.
4381 *
4382 * Since it's possible for an fd that refers to a character
4383 * device to have an intermediate close followed by an open to
4384 * cause a different file to correspond to that descriptor,
4385 * unless there was a cautionary reference taken on the fileproc,
4386 * this is an inherently unsafe function. This happens in the
4387 * case where multiple fd's in a process refer to the same
4388 * character device (e.g. stdin/out/err pointing to a tty, etc.).
4389 *
4390 * Use of this function is discouraged.
4391 */
4392 int
4393 file_drop(int fd)
4394 {
4395 struct fileproc *fp;
4396 proc_t p = current_proc();
4397 int needwakeup = 0;
4398
4399 proc_fdlock_spin(p);
4400 if (fd < 0 || fd >= p->p_fd->fd_nfiles ||
4401 (fp = p->p_fd->fd_ofiles[fd]) == NULL ||
4402 ((p->p_fd->fd_ofileflags[fd] & UF_RESERVED) &&
4403 !(p->p_fd->fd_ofileflags[fd] & UF_CLOSING))) {
4404 proc_fdunlock(p);
4405 return (EBADF);
4406 }
4407 fp->f_iocount --;
4408
4409 if (fp->f_iocount == 0) {
4410 if (fp->f_flags & FP_SELCONFLICT)
4411 fp->f_flags &= ~FP_SELCONFLICT;
4412
4413 if (p->p_fpdrainwait) {
4414 p->p_fpdrainwait = 0;
4415 needwakeup = 1;
4416 }
4417 }
4418 proc_fdunlock(p);
4419
4420 if (needwakeup)
4421 wakeup(&p->p_fpdrainwait);
4422 return(0);
4423 }
4424
4425
4426 static int falloc_withalloc_locked(proc_t, struct fileproc **, int *,
4427 vfs_context_t, struct fileproc * (*)(void *), void *, int);
4428
4429 /*
4430 * falloc
4431 *
4432 * Description: Allocate an entry in the per process open file table and
4433 * return the corresponding fileproc and fd.
4434 *
4435 * Parameters: p The process in whose open file
4436 * table the fd is to be allocated
4437 * resultfp Pointer to fileproc pointer
4438 * return area
4439 * resultfd Pointer to fd return area
4440 * ctx VFS context
4441 *
4442 * Returns: 0 Success
4443 * falloc:ENFILE Too many open files in system
4444 * falloc:EMFILE Too many open files in process
4445 * falloc:ENOMEM M_FILEPROC or M_FILEGLOB zone
4446 * exhausted
4447 *
4448 * Implicit returns:
4449 * *resultfd (modified) Returned fileproc pointer
4450 * *resultfd (modified) Returned fd
4451 *
4452 * Locks: This function takes and drops the proc_fdlock; if this lock
4453 * is already held, use falloc_locked() instead.
4454 *
4455 * Notes: This function takes separate process and context arguments
4456 * solely to support kern_exec.c; otherwise, it would take
4457 * neither, and expect falloc_locked() to use the
4458 * vfs_context_current() routine internally.
4459 */
4460 int
4461 falloc(proc_t p, struct fileproc **resultfp, int *resultfd, vfs_context_t ctx)
4462 {
4463 return (falloc_withalloc(p, resultfp, resultfd, ctx,
4464 fileproc_alloc_init, NULL));
4465 }
4466
4467 /*
4468 * Like falloc, but including the fileproc allocator and create-args
4469 */
4470 int
4471 falloc_withalloc(proc_t p, struct fileproc **resultfp, int *resultfd,
4472 vfs_context_t ctx, fp_allocfn_t fp_zalloc, void *arg)
4473 {
4474 int error;
4475
4476 proc_fdlock(p);
4477 error = falloc_withalloc_locked(p,
4478 resultfp, resultfd, ctx, fp_zalloc, arg, 1);
4479 proc_fdunlock(p);
4480
4481 return (error);
4482 }
4483
4484 /*
4485 * "uninitialized" ops -- ensure fg->fg_ops->fo_type always exists
4486 */
4487 static const struct fileops uninitops;
4488
4489 /*
4490 * falloc_locked
4491 *
4492 * Create a new open file structure and allocate
4493 * a file descriptor for the process that refers to it.
4494 *
4495 * Returns: 0 Success
4496 *
4497 * Description: Allocate an entry in the per process open file table and
4498 * return the corresponding fileproc and fd.
4499 *
4500 * Parameters: p The process in whose open file
4501 * table the fd is to be allocated
4502 * resultfp Pointer to fileproc pointer
4503 * return area
4504 * resultfd Pointer to fd return area
4505 * ctx VFS context
4506 * locked Flag to indicate whether the
4507 * caller holds proc_fdlock
4508 *
4509 * Returns: 0 Success
4510 * ENFILE Too many open files in system
4511 * fdalloc:EMFILE Too many open files in process
4512 * ENOMEM M_FILEPROC or M_FILEGLOB zone
4513 * exhausted
4514 * fdalloc:ENOMEM
4515 *
4516 * Implicit returns:
4517 * *resultfd (modified) Returned fileproc pointer
4518 * *resultfd (modified) Returned fd
4519 *
4520 * Locks: If the parameter 'locked' is zero, this function takes and
4521 * drops the proc_fdlock; if non-zero, the caller must hold the
4522 * lock.
4523 *
4524 * Notes: If you intend to use a non-zero 'locked' parameter, use the
4525 * utility function falloc() instead.
4526 *
4527 * This function takes separate process and context arguments
4528 * solely to support kern_exec.c; otherwise, it would take
4529 * neither, and use the vfs_context_current() routine internally.
4530 */
4531 int
4532 falloc_locked(proc_t p, struct fileproc **resultfp, int *resultfd,
4533 vfs_context_t ctx, int locked)
4534 {
4535 return (falloc_withalloc_locked(p, resultfp, resultfd, ctx,
4536 fileproc_alloc_init, NULL, locked));
4537 }
4538
4539 static int
4540 falloc_withalloc_locked(proc_t p, struct fileproc **resultfp, int *resultfd,
4541 vfs_context_t ctx, fp_allocfn_t fp_zalloc, void *crarg,
4542 int locked)
4543 {
4544 struct fileproc *fp;
4545 struct fileglob *fg;
4546 int error, nfd;
4547
4548 if (!locked)
4549 proc_fdlock(p);
4550 if ( (error = fdalloc(p, 0, &nfd)) ) {
4551 if (!locked)
4552 proc_fdunlock(p);
4553 return (error);
4554 }
4555 if (nfiles >= maxfiles) {
4556 if (!locked)
4557 proc_fdunlock(p);
4558 tablefull("file");
4559 return (ENFILE);
4560 }
4561 #if CONFIG_MACF
4562 error = mac_file_check_create(proc_ucred(p));
4563 if (error) {
4564 if (!locked)
4565 proc_fdunlock(p);
4566 return (error);
4567 }
4568 #endif
4569
4570 /*
4571 * Allocate a new file descriptor.
4572 * If the process has file descriptor zero open, add to the list
4573 * of open files at that point, otherwise put it at the front of
4574 * the list of open files.
4575 */
4576 proc_fdunlock(p);
4577
4578 fp = (*fp_zalloc)(crarg);
4579 if (fp == NULL) {
4580 if (locked)
4581 proc_fdlock(p);
4582 return (ENOMEM);
4583 }
4584 MALLOC_ZONE(fg, struct fileglob *, sizeof(struct fileglob), M_FILEGLOB, M_WAITOK);
4585 if (fg == NULL) {
4586 fileproc_free(fp);
4587 if (locked)
4588 proc_fdlock(p);
4589 return (ENOMEM);
4590 }
4591 bzero(fg, sizeof(struct fileglob));
4592 lck_mtx_init(&fg->fg_lock, file_lck_grp, file_lck_attr);
4593
4594 fp->f_iocount = 1;
4595 fg->fg_count = 1;
4596 fg->fg_ops = &uninitops;
4597 fp->f_fglob = fg;
4598 #if CONFIG_MACF
4599 mac_file_label_init(fg);
4600 #endif
4601
4602 kauth_cred_ref(ctx->vc_ucred);
4603
4604 proc_fdlock(p);
4605
4606 fp->f_cred = ctx->vc_ucred;
4607
4608 #if CONFIG_MACF
4609 mac_file_label_associate(fp->f_cred, fg);
4610 #endif
4611
4612 OSAddAtomic(1, &nfiles);
4613
4614 p->p_fd->fd_ofiles[nfd] = fp;
4615
4616 if (!locked)
4617 proc_fdunlock(p);
4618
4619 if (resultfp)
4620 *resultfp = fp;
4621 if (resultfd)
4622 *resultfd = nfd;
4623
4624 return (0);
4625 }
4626
4627
4628 /*
4629 * fg_free
4630 *
4631 * Description: Free a file structure; drop the global open file count, and
4632 * drop the credential reference, if the fileglob has one, and
4633 * destroy the instance mutex before freeing
4634 *
4635 * Parameters: fg Pointer to fileglob to be
4636 * freed
4637 *
4638 * Returns: void
4639 */
4640 void
4641 fg_free(struct fileglob *fg)
4642 {
4643 OSAddAtomic(-1, &nfiles);
4644
4645 if (fg->fg_vn_data) {
4646 fg_vn_data_free(fg->fg_vn_data);
4647 fg->fg_vn_data = NULL;
4648 }
4649
4650 if (IS_VALID_CRED(fg->fg_cred)) {
4651 kauth_cred_unref(&fg->fg_cred);
4652 }
4653 lck_mtx_destroy(&fg->fg_lock, file_lck_grp);
4654
4655 #if CONFIG_MACF
4656 mac_file_label_destroy(fg);
4657 #endif
4658 FREE_ZONE(fg, sizeof *fg, M_FILEGLOB);
4659 }
4660
4661
4662
4663 /*
4664 * fdexec
4665 *
4666 * Description: Perform close-on-exec processing for all files in a process
4667 * that are either marked as close-on-exec, or which were in the
4668 * process of being opened at the time of the execve
4669 *
4670 * Also handles the case (via posix_spawn()) where -all-
4671 * files except those marked with "inherit" as treated as
4672 * close-on-exec.
4673 *
4674 * Parameters: p Pointer to process calling
4675 * execve
4676 *
4677 * Returns: void
4678 *
4679 * Locks: This function internally takes and drops proc_fdlock()
4680 * But assumes tables don't grow/change while unlocked.
4681 *
4682 */
4683 void
4684 fdexec(proc_t p, short flags, int self_exec)
4685 {
4686 struct filedesc *fdp = p->p_fd;
4687 int i;
4688 boolean_t cloexec_default = (flags & POSIX_SPAWN_CLOEXEC_DEFAULT) != 0;
4689 thread_t self = current_thread();
4690 struct uthread *ut = get_bsdthread_info(self);
4691 struct kqueue *dealloc_kq = NULL;
4692
4693 /*
4694 * If the current thread is bound as a workq/workloop
4695 * servicing thread, we need to unbind it first.
4696 */
4697 if (ut->uu_kqueue_bound && self_exec) {
4698 kevent_qos_internal_unbind(p, 0, self,
4699 ut->uu_kqueue_flags);
4700 }
4701
4702 proc_fdlock(p);
4703
4704 /*
4705 * Deallocate the knotes for this process
4706 * and mark the tables non-existent so
4707 * subsequent kqueue closes go faster.
4708 */
4709 knotes_dealloc(p);
4710 assert(fdp->fd_knlistsize == -1);
4711 assert(fdp->fd_knhashmask == 0);
4712
4713 for (i = fdp->fd_lastfile; i >= 0; i--) {
4714
4715 struct fileproc *fp = fdp->fd_ofiles[i];
4716 char *flagp = &fdp->fd_ofileflags[i];
4717
4718 if (fp && cloexec_default) {
4719 /*
4720 * Reverse the usual semantics of file descriptor
4721 * inheritance - all of them should be closed
4722 * except files marked explicitly as "inherit" and
4723 * not marked close-on-exec.
4724 */
4725 if ((*flagp & (UF_EXCLOSE|UF_INHERIT)) != UF_INHERIT)
4726 *flagp |= UF_EXCLOSE;
4727 *flagp &= ~UF_INHERIT;
4728 }
4729
4730 if (
4731 ((*flagp & (UF_RESERVED|UF_EXCLOSE)) == UF_EXCLOSE)
4732 #if CONFIG_MACF
4733 || (fp && mac_file_check_inherit(proc_ucred(p), fp->f_fglob))
4734 #endif
4735 ) {
4736 procfdtbl_clearfd(p, i);
4737 if (i == fdp->fd_lastfile && i > 0)
4738 fdp->fd_lastfile--;
4739 if (i < fdp->fd_freefile)
4740 fdp->fd_freefile = i;
4741
4742 /*
4743 * Wait for any third party viewers (e.g., lsof)
4744 * to release their references to this fileproc.
4745 */
4746 while (fp->f_iocount > 0) {
4747 p->p_fpdrainwait = 1;
4748 msleep(&p->p_fpdrainwait, &p->p_fdmlock, PRIBIO,
4749 "fpdrain", NULL);
4750 }
4751
4752 closef_locked(fp, fp->f_fglob, p);
4753
4754 fileproc_free(fp);
4755 }
4756 }
4757
4758 /* release the per-process workq kq */
4759 if (fdp->fd_wqkqueue) {
4760 dealloc_kq = fdp->fd_wqkqueue;
4761 fdp->fd_wqkqueue = NULL;
4762 }
4763
4764 proc_fdunlock(p);
4765
4766 /* Anything to free? */
4767 if (dealloc_kq)
4768 kqueue_dealloc(dealloc_kq);
4769 }
4770
4771
4772 /*
4773 * fdcopy
4774 *
4775 * Description: Copy a filedesc structure. This is normally used as part of
4776 * forkproc() when forking a new process, to copy the per process
4777 * open file table over to the new process.
4778 *
4779 * Parameters: p Process whose open file table
4780 * is to be copied (parent)
4781 * uth_cdir Per thread current working
4782 * cirectory, or NULL
4783 *
4784 * Returns: NULL Copy failed
4785 * !NULL Pointer to new struct filedesc
4786 *
4787 * Locks: This function internally takes and drops proc_fdlock()
4788 *
4789 * Notes: Files are copied directly, ignoring the new resource limits
4790 * for the process that's being copied into. Since the descriptor
4791 * references are just additional references, this does not count
4792 * against the number of open files on the system.
4793 *
4794 * The struct filedesc includes the current working directory,
4795 * and the current root directory, if the process is chroot'ed.
4796 *
4797 * If the exec was called by a thread using a per thread current
4798 * working directory, we inherit the working directory from the
4799 * thread making the call, rather than from the process.
4800 *
4801 * In the case of a failure to obtain a reference, for most cases,
4802 * the file entry will be silently dropped. There's an exception
4803 * for the case of a chroot dir, since a failure to to obtain a
4804 * reference there would constitute an "escape" from the chroot
4805 * environment, which must not be allowed. In that case, we will
4806 * deny the execve() operation, rather than allowing the escape.
4807 */
4808 struct filedesc *
4809 fdcopy(proc_t p, vnode_t uth_cdir)
4810 {
4811 struct filedesc *newfdp, *fdp = p->p_fd;
4812 int i;
4813 struct fileproc *ofp, *fp;
4814 vnode_t v_dir;
4815
4816 MALLOC_ZONE(newfdp, struct filedesc *,
4817 sizeof(*newfdp), M_FILEDESC, M_WAITOK);
4818 if (newfdp == NULL)
4819 return(NULL);
4820
4821 proc_fdlock(p);
4822
4823 /*
4824 * the FD_CHROOT flag will be inherited via this copy
4825 */
4826 (void) memcpy(newfdp, fdp, sizeof(*newfdp));
4827
4828 /*
4829 * If we are running with per-thread current working directories,
4830 * inherit the new current working directory from the current thread
4831 * instead, before we take our references.
4832 */
4833 if (uth_cdir != NULLVP)
4834 newfdp->fd_cdir = uth_cdir;
4835
4836 /*
4837 * For both fd_cdir and fd_rdir make sure we get
4838 * a valid reference... if we can't, than set
4839 * set the pointer(s) to NULL in the child... this
4840 * will keep us from using a non-referenced vp
4841 * and allows us to do the vnode_rele only on
4842 * a properly referenced vp
4843 */
4844 if ( (v_dir = newfdp->fd_cdir) ) {
4845 if (vnode_getwithref(v_dir) == 0) {
4846 if ( (vnode_ref(v_dir)) )
4847 newfdp->fd_cdir = NULL;
4848 vnode_put(v_dir);
4849 } else
4850 newfdp->fd_cdir = NULL;
4851 }
4852 if (newfdp->fd_cdir == NULL && fdp->fd_cdir) {
4853 /*
4854 * we couldn't get a new reference on
4855 * the current working directory being
4856 * inherited... we might as well drop
4857 * our reference from the parent also
4858 * since the vnode has gone DEAD making
4859 * it useless... by dropping it we'll
4860 * be that much closer to recycling it
4861 */
4862 vnode_rele(fdp->fd_cdir);
4863 fdp->fd_cdir = NULL;
4864 }
4865
4866 if ( (v_dir = newfdp->fd_rdir) ) {
4867 if (vnode_getwithref(v_dir) == 0) {
4868 if ( (vnode_ref(v_dir)) )
4869 newfdp->fd_rdir = NULL;
4870 vnode_put(v_dir);
4871 } else {
4872 newfdp->fd_rdir = NULL;
4873 }
4874 }
4875 /* Coming from a chroot environment and unable to get a reference... */
4876 if (newfdp->fd_rdir == NULL && fdp->fd_rdir) {
4877 /*
4878 * We couldn't get a new reference on
4879 * the chroot directory being
4880 * inherited... this is fatal, since
4881 * otherwise it would constitute an
4882 * escape from a chroot environment by
4883 * the new process.
4884 */
4885 if (newfdp->fd_cdir)
4886 vnode_rele(newfdp->fd_cdir);
4887 FREE_ZONE(newfdp, sizeof *newfdp, M_FILEDESC);
4888 return(NULL);
4889 }
4890
4891 /*
4892 * If the number of open files fits in the internal arrays
4893 * of the open file structure, use them, otherwise allocate
4894 * additional memory for the number of descriptors currently
4895 * in use.
4896 */
4897 if (newfdp->fd_lastfile < NDFILE)
4898 i = NDFILE;
4899 else {
4900 /*
4901 * Compute the smallest multiple of NDEXTENT needed
4902 * for the file descriptors currently in use,
4903 * allowing the table to shrink.
4904 */
4905 i = newfdp->fd_nfiles;
4906 while (i > 1 + 2 * NDEXTENT && i > 1 + newfdp->fd_lastfile * 2)
4907 i /= 2;
4908 }
4909 proc_fdunlock(p);
4910
4911 MALLOC_ZONE(newfdp->fd_ofiles, struct fileproc **,
4912 i * OFILESIZE, M_OFILETABL, M_WAITOK);
4913 if (newfdp->fd_ofiles == NULL) {
4914 if (newfdp->fd_cdir)
4915 vnode_rele(newfdp->fd_cdir);
4916 if (newfdp->fd_rdir)
4917 vnode_rele(newfdp->fd_rdir);
4918
4919 FREE_ZONE(newfdp, sizeof(*newfdp), M_FILEDESC);
4920 return(NULL);
4921 }
4922 (void) memset(newfdp->fd_ofiles, 0, i * OFILESIZE);
4923 proc_fdlock(p);
4924
4925 newfdp->fd_ofileflags = (char *) &newfdp->fd_ofiles[i];
4926 newfdp->fd_nfiles = i;
4927
4928 if (fdp->fd_nfiles > 0) {
4929 struct fileproc **fpp;
4930 char *flags;
4931
4932 (void) memcpy(newfdp->fd_ofiles, fdp->fd_ofiles,
4933 (newfdp->fd_lastfile + 1) * sizeof(*fdp->fd_ofiles));
4934 (void) memcpy(newfdp->fd_ofileflags, fdp->fd_ofileflags,
4935 (newfdp->fd_lastfile + 1) * sizeof(*fdp->fd_ofileflags));
4936
4937 /*
4938 * kq descriptors cannot be copied.
4939 */
4940 if (newfdp->fd_knlistsize != -1) {
4941 fpp = &newfdp->fd_ofiles[newfdp->fd_lastfile];
4942 flags = &newfdp->fd_ofileflags[newfdp->fd_lastfile];
4943 for (i = newfdp->fd_lastfile;
4944 i >= 0; i--, fpp--, flags--) {
4945 if (*flags & UF_RESERVED)
4946 continue; /* (removed below) */
4947 if (*fpp != NULL && (*fpp)->f_type == DTYPE_KQUEUE) {
4948 *fpp = NULL;
4949 *flags = 0;
4950 if (i < newfdp->fd_freefile)
4951 newfdp->fd_freefile = i;
4952 }
4953 if (*fpp == NULL && i == newfdp->fd_lastfile && i > 0)
4954 newfdp->fd_lastfile--;
4955 }
4956 }
4957 fpp = newfdp->fd_ofiles;
4958 flags = newfdp->fd_ofileflags;
4959
4960 for (i = newfdp->fd_lastfile + 1; --i >= 0; fpp++, flags++)
4961 if ((ofp = *fpp) != NULL &&
4962 0 == (ofp->f_fglob->fg_lflags & FG_CONFINED) &&
4963 0 == (*flags & (UF_FORKCLOSE|UF_RESERVED))) {
4964 #if DEBUG
4965 if (FILEPROC_TYPE(ofp) != FTYPE_SIMPLE)
4966 panic("complex fileproc");
4967 #endif
4968 fp = fileproc_alloc_init(NULL);
4969 if (fp == NULL) {
4970 /*
4971 * XXX no room to copy, unable to
4972 * XXX safely unwind state at present
4973 */
4974 *fpp = NULL;
4975 } else {
4976 fp->f_flags |=
4977 (ofp->f_flags & ~FP_TYPEMASK);
4978 fp->f_fglob = ofp->f_fglob;
4979 (void)fg_ref(fp);
4980 *fpp = fp;
4981 }
4982 } else {
4983 if (i < newfdp->fd_freefile)
4984 newfdp->fd_freefile = i;
4985 *fpp = NULL;
4986 *flags = 0;
4987 }
4988 }
4989
4990 proc_fdunlock(p);
4991
4992 /*
4993 * Initialize knote and kqueue tracking structs
4994 */
4995 newfdp->fd_knlist = NULL;
4996 newfdp->fd_knlistsize = -1;
4997 newfdp->fd_knhash = NULL;
4998 newfdp->fd_knhashmask = 0;
4999 newfdp->fd_kqhash = NULL;
5000 newfdp->fd_kqhashmask = 0;
5001 newfdp->fd_wqkqueue = NULL;
5002 lck_mtx_init(&newfdp->fd_kqhashlock, proc_kqhashlock_grp, proc_lck_attr);
5003 lck_mtx_init(&newfdp->fd_knhashlock, proc_knhashlock_grp, proc_lck_attr);
5004
5005 return (newfdp);
5006 }
5007
5008
5009 /*
5010 * fdfree
5011 *
5012 * Description: Release a filedesc (per process open file table) structure;
5013 * this is done on process exit(), or from forkproc_free() if
5014 * the fork fails for some reason subsequent to a successful
5015 * call to fdcopy()
5016 *
5017 * Parameters: p Pointer to process going away
5018 *
5019 * Returns: void
5020 *
5021 * Locks: This function internally takes and drops proc_fdlock()
5022 */
5023 void
5024 fdfree(proc_t p)
5025 {
5026 struct filedesc *fdp;
5027 struct fileproc *fp;
5028 struct kqueue *dealloc_kq = NULL;
5029 int i;
5030
5031 proc_fdlock(p);
5032
5033 if (p == kernproc || NULL == (fdp = p->p_fd)) {
5034 proc_fdunlock(p);
5035 return;
5036 }
5037
5038 extern struct filedesc filedesc0;
5039
5040 if (&filedesc0 == fdp)
5041 panic("filedesc0");
5042
5043 /*
5044 * deallocate all the knotes up front and claim empty
5045 * tables to make any subsequent kqueue closes faster.
5046 */
5047 knotes_dealloc(p);
5048 assert(fdp->fd_knlistsize == -1);
5049 assert(fdp->fd_knhashmask == 0);
5050
5051 /* close file descriptors */
5052 if (fdp->fd_nfiles > 0 && fdp->fd_ofiles) {
5053 for (i = fdp->fd_lastfile; i >= 0; i--) {
5054 if ((fp = fdp->fd_ofiles[i]) != NULL) {
5055
5056 if (fdp->fd_ofileflags[i] & UF_RESERVED)
5057 panic("fdfree: found fp with UF_RESERVED");
5058
5059 procfdtbl_reservefd(p, i);
5060
5061 if (fp->f_flags & FP_WAITEVENT)
5062 (void)waitevent_close(p, fp);
5063 (void) closef_locked(fp, fp->f_fglob, p);
5064 fileproc_free(fp);
5065 }
5066 }
5067 FREE_ZONE(fdp->fd_ofiles, fdp->fd_nfiles * OFILESIZE, M_OFILETABL);
5068 fdp->fd_ofiles = NULL;
5069 fdp->fd_nfiles = 0;
5070 }
5071
5072 if (fdp->fd_wqkqueue) {
5073 dealloc_kq = fdp->fd_wqkqueue;
5074 fdp->fd_wqkqueue = NULL;
5075 }
5076
5077 proc_fdunlock(p);
5078
5079 if (dealloc_kq)
5080 kqueue_dealloc(dealloc_kq);
5081
5082 if (fdp->fd_cdir)
5083 vnode_rele(fdp->fd_cdir);
5084 if (fdp->fd_rdir)
5085 vnode_rele(fdp->fd_rdir);
5086
5087 proc_fdlock_spin(p);
5088 p->p_fd = NULL;
5089 proc_fdunlock(p);
5090
5091 if (fdp->fd_kqhash) {
5092 for (uint32_t j = 0; j <= fdp->fd_kqhashmask; j++)
5093 assert(SLIST_EMPTY(&fdp->fd_kqhash[j]));
5094 FREE(fdp->fd_kqhash, M_KQUEUE);
5095 }
5096
5097 lck_mtx_destroy(&fdp->fd_kqhashlock, proc_kqhashlock_grp);
5098 lck_mtx_destroy(&fdp->fd_knhashlock, proc_knhashlock_grp);
5099
5100 FREE_ZONE(fdp, sizeof(*fdp), M_FILEDESC);
5101 }
5102
5103 /*
5104 * closef_locked
5105 *
5106 * Description: Internal form of closef; called with proc_fdlock held
5107 *
5108 * Parameters: fp Pointer to fileproc for fd
5109 * fg Pointer to fileglob for fd
5110 * p Pointer to proc structure
5111 *
5112 * Returns: 0 Success
5113 * closef_finish:??? Anything returnable by a per-fileops
5114 * close function
5115 *
5116 * Note: Decrements reference count on file structure; if this was the
5117 * last reference, then closef_finish() is called
5118 *
5119 * p and fp are allowed to be NULL when closing a file that was
5120 * being passed in a message (but only if we are called when this
5121 * is NOT the last reference).
5122 */
5123 int
5124 closef_locked(struct fileproc *fp, struct fileglob *fg, proc_t p)
5125 {
5126 struct vnode *vp;
5127 struct flock lf;
5128 struct vfs_context context;
5129 int error;
5130
5131 if (fg == NULL) {
5132 return (0);
5133 }
5134
5135 /* Set up context with cred stashed in fg */
5136 if (p == current_proc())
5137 context.vc_thread = current_thread();
5138 else
5139 context.vc_thread = NULL;
5140 context.vc_ucred = fg->fg_cred;
5141
5142 /*
5143 * POSIX record locking dictates that any close releases ALL
5144 * locks owned by this process. This is handled by setting
5145 * a flag in the unlock to free ONLY locks obeying POSIX
5146 * semantics, and not to free BSD-style file locks.
5147 * If the descriptor was in a message, POSIX-style locks
5148 * aren't passed with the descriptor.
5149 */
5150 if (p && (p->p_ladvflag & P_LADVLOCK) &&
5151 DTYPE_VNODE == FILEGLOB_DTYPE(fg)) {
5152 proc_fdunlock(p);
5153
5154 lf.l_whence = SEEK_SET;
5155 lf.l_start = 0;
5156 lf.l_len = 0;
5157 lf.l_type = F_UNLCK;
5158 vp = (struct vnode *)fg->fg_data;
5159
5160 if ( (error = vnode_getwithref(vp)) == 0 ) {
5161 (void) VNOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, F_POSIX, &context, NULL);
5162 (void)vnode_put(vp);
5163 }
5164 proc_fdlock(p);
5165 }
5166 lck_mtx_lock_spin(&fg->fg_lock);
5167 fg->fg_count--;
5168
5169 if (fg->fg_count > 0) {
5170 lck_mtx_unlock(&fg->fg_lock);
5171 return (0);
5172 }
5173 #if DIAGNOSTIC
5174 if (fg->fg_count != 0)
5175 panic("fg %p: being freed with bad fg_count (%d)", fg, fg->fg_count);
5176 #endif
5177
5178 if (fp && (fp->f_flags & FP_WRITTEN))
5179 fg->fg_flag |= FWASWRITTEN;
5180
5181 fg->fg_lflags |= FG_TERM;
5182 lck_mtx_unlock(&fg->fg_lock);
5183
5184 if (p)
5185 proc_fdunlock(p);
5186
5187 /* Since we ensure that fg->fg_ops is always initialized,
5188 * it is safe to invoke fo_close on the fg */
5189 error = fo_close(fg, &context);
5190
5191 fg_free(fg);
5192
5193 if (p)
5194 proc_fdlock(p);
5195
5196 return(error);
5197 }
5198
5199
5200 /*
5201 * fileproc_drain
5202 *
5203 * Description: Drain out pending I/O operations
5204 *
5205 * Parameters: p Process closing this file
5206 * fp fileproc struct for the open
5207 * instance on the file
5208 *
5209 * Returns: void
5210 *
5211 * Locks: Assumes the caller holds the proc_fdlock
5212 *
5213 * Notes: For character devices, this occurs on the last close of the
5214 * device; for all other file descriptors, this occurs on each
5215 * close to prevent fd's from being closed out from under
5216 * operations currently in progress and blocked
5217 *
5218 * See Also: file_vnode(), file_socket(), file_drop(), and the cautions
5219 * regarding their use and interaction with this function.
5220 */
5221 void
5222 fileproc_drain(proc_t p, struct fileproc * fp)
5223 {
5224 struct vfs_context context;
5225
5226 context.vc_thread = proc_thread(p); /* XXX */
5227 context.vc_ucred = fp->f_fglob->fg_cred;
5228
5229 fp->f_iocount-- ; /* (the one the close holds) */
5230
5231 while (fp->f_iocount) {
5232
5233 lck_mtx_convert_spin(&p->p_fdmlock);
5234
5235 if (fp->f_fglob->fg_ops->fo_drain) {
5236 (*fp->f_fglob->fg_ops->fo_drain)(fp, &context);
5237 }
5238 if ((fp->f_flags & FP_INSELECT) == FP_INSELECT) {
5239 if (waitq_wakeup64_all((struct waitq *)fp->f_wset, NO_EVENT64,
5240 THREAD_INTERRUPTED, WAITQ_ALL_PRIORITIES) == KERN_INVALID_ARGUMENT)
5241 panic("bad wait queue for waitq_wakeup64_all %p (fp:%p)", fp->f_wset, fp);
5242 }
5243 if ((fp->f_flags & FP_SELCONFLICT) == FP_SELCONFLICT) {
5244 if (waitq_wakeup64_all(&select_conflict_queue, NO_EVENT64,
5245 THREAD_INTERRUPTED, WAITQ_ALL_PRIORITIES) == KERN_INVALID_ARGUMENT)
5246 panic("bad select_conflict_queue");
5247 }
5248 p->p_fpdrainwait = 1;
5249
5250 msleep(&p->p_fpdrainwait, &p->p_fdmlock, PRIBIO, "fpdrain", NULL);
5251
5252 }
5253 #if DIAGNOSTIC
5254 if ((fp->f_flags & FP_INSELECT) != 0)
5255 panic("FP_INSELECT set on drained fp");
5256 #endif
5257 if ((fp->f_flags & FP_SELCONFLICT) == FP_SELCONFLICT)
5258 fp->f_flags &= ~FP_SELCONFLICT;
5259 }
5260
5261
5262 /*
5263 * fp_free
5264 *
5265 * Description: Release the fd and free the fileproc associated with the fd
5266 * in the per process open file table of the specified process;
5267 * these values must correspond.
5268 *
5269 * Parameters: p Process containing fd
5270 * fd fd to be released
5271 * fp fileproc to be freed
5272 *
5273 * Returns: 0 Success
5274 *
5275 * Notes: XXX function should be void - no one interprets the returns
5276 * XXX code
5277 */
5278 int
5279 fp_free(proc_t p, int fd, struct fileproc * fp)
5280 {
5281 proc_fdlock_spin(p);
5282 fdrelse(p, fd);
5283 proc_fdunlock(p);
5284
5285 fg_free(fp->f_fglob);
5286 fileproc_free(fp);
5287 return(0);
5288 }
5289
5290
5291 /*
5292 * flock
5293 *
5294 * Description: Apply an advisory lock on a file descriptor.
5295 *
5296 * Parameters: p Process making request
5297 * uap->fd fd on which the lock is to be
5298 * attempted
5299 * uap->how (Un)Lock bits, including type
5300 * retval Pointer to the call return area
5301 *
5302 * Returns: 0 Success
5303 * fp_getfvp:EBADF Bad file descriptor
5304 * fp_getfvp:ENOTSUP fd does not refer to a vnode
5305 * vnode_getwithref:???
5306 * VNOP_ADVLOCK:???
5307 *
5308 * Implicit returns:
5309 * *retval (modified) Size of dtable
5310 *
5311 * Notes: Just attempt to get a record lock of the requested type on
5312 * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
5313 */
5314 int
5315 flock(proc_t p, struct flock_args *uap, __unused int32_t *retval)
5316 {
5317 int fd = uap->fd;
5318 int how = uap->how;
5319 struct fileproc *fp;
5320 struct vnode *vp;
5321 struct flock lf;
5322 vfs_context_t ctx = vfs_context_current();
5323 int error=0;
5324
5325 AUDIT_ARG(fd, uap->fd);
5326 if ( (error = fp_getfvp(p, fd, &fp, &vp)) ) {
5327 return(error);
5328 }
5329 if ( (error = vnode_getwithref(vp)) ) {
5330 goto out1;
5331 }
5332 AUDIT_ARG(vnpath, vp, ARG_VNODE1);
5333
5334 lf.l_whence = SEEK_SET;
5335 lf.l_start = 0;
5336 lf.l_len = 0;
5337 if (how & LOCK_UN) {
5338 lf.l_type = F_UNLCK;
5339 fp->f_flag &= ~FHASLOCK;
5340 error = VNOP_ADVLOCK(vp, (caddr_t)fp->f_fglob, F_UNLCK, &lf, F_FLOCK, ctx, NULL);
5341 goto out;
5342 }
5343 if (how & LOCK_EX)
5344 lf.l_type = F_WRLCK;
5345 else if (how & LOCK_SH)
5346 lf.l_type = F_RDLCK;
5347 else {
5348 error = EBADF;
5349 goto out;
5350 }
5351 #if CONFIG_MACF
5352 error = mac_file_check_lock(proc_ucred(p), fp->f_fglob, F_SETLK, &lf);
5353 if (error)
5354 goto out;
5355 #endif
5356 error = VNOP_ADVLOCK(vp, (caddr_t)fp->f_fglob, F_SETLK, &lf,
5357 (how & LOCK_NB ? F_FLOCK : F_FLOCK | F_WAIT),
5358 ctx, NULL);
5359 if (!error)
5360 fp->f_flag |= FHASLOCK;
5361 out:
5362 (void)vnode_put(vp);
5363 out1:
5364 fp_drop(p, fd, fp, 0);
5365 return(error);
5366
5367 }
5368
5369 /*
5370 * fileport_makeport
5371 *
5372 * Description: Obtain a Mach send right for a given file descriptor.
5373 *
5374 * Parameters: p Process calling fileport
5375 * uap->fd The fd to reference
5376 * uap->portnamep User address at which to place port name.
5377 *
5378 * Returns: 0 Success.
5379 * EBADF Bad file descriptor.
5380 * EINVAL File descriptor had type that cannot be sent, misc. other errors.
5381 * EFAULT Address at which to store port name is not valid.
5382 * EAGAIN Resource shortage.
5383 *
5384 * Implicit returns:
5385 * On success, name of send right is stored at user-specified address.
5386 */
5387 int
5388 fileport_makeport(proc_t p, struct fileport_makeport_args *uap,
5389 __unused int *retval)
5390 {
5391 int err;
5392 int fd = uap->fd;
5393 user_addr_t user_portaddr = uap->portnamep;
5394 struct fileproc *fp = FILEPROC_NULL;
5395 struct fileglob *fg = NULL;
5396 ipc_port_t fileport;
5397 mach_port_name_t name = MACH_PORT_NULL;
5398
5399 proc_fdlock(p);
5400 err = fp_lookup(p, fd, &fp, 1);
5401 if (err != 0) {
5402 goto out_unlock;
5403 }
5404
5405 if (!file_issendable(p, fp)) {
5406 err = EINVAL;
5407 goto out_unlock;
5408 }
5409
5410 if (FP_ISGUARDED(fp, GUARD_FILEPORT)) {
5411 err = fp_guard_exception(p, fd, fp, kGUARD_EXC_FILEPORT);
5412 goto out_unlock;
5413 }
5414
5415 /* Dropped when port is deallocated */
5416 fg = fp->f_fglob;
5417 fg_ref(fp);
5418
5419 proc_fdunlock(p);
5420
5421 /* Allocate and initialize a port */
5422 fileport = fileport_alloc(fg);
5423 if (fileport == IPC_PORT_NULL) {
5424 err = EAGAIN;
5425 fg_drop(fp);
5426 goto out;
5427 }
5428
5429 /* Add an entry. Deallocates port on failure. */
5430 name = ipc_port_copyout_send(fileport, get_task_ipcspace(p->task));
5431 if (!MACH_PORT_VALID(name)) {
5432 err = EINVAL;
5433 goto out;
5434 }
5435
5436 err = copyout(&name, user_portaddr, sizeof(mach_port_name_t));
5437 if (err != 0) {
5438 goto out;
5439 }
5440
5441 /* Tag the fileglob for debugging purposes */
5442 lck_mtx_lock_spin(&fg->fg_lock);
5443 fg->fg_lflags |= FG_PORTMADE;
5444 lck_mtx_unlock(&fg->fg_lock);
5445
5446 fp_drop(p, fd, fp, 0);
5447
5448 return 0;
5449
5450 out_unlock:
5451 proc_fdunlock(p);
5452 out:
5453 if (MACH_PORT_VALID(name)) {
5454 /* Don't care if another thread races us to deallocate the entry */
5455 (void) mach_port_deallocate(get_task_ipcspace(p->task), name);
5456 }
5457
5458 if (fp != FILEPROC_NULL) {
5459 fp_drop(p, fd, fp, 0);
5460 }
5461
5462 return err;
5463 }
5464
5465 void
5466 fileport_releasefg(struct fileglob *fg)
5467 {
5468 (void)closef_locked(NULL, fg, PROC_NULL);
5469
5470 return;
5471 }
5472
5473
5474 /*
5475 * fileport_makefd
5476 *
5477 * Description: Obtain the file descriptor for a given Mach send right.
5478 *
5479 * Parameters: p Process calling fileport
5480 * uap->port Name of send right to file port.
5481 *
5482 * Returns: 0 Success
5483 * EINVAL Invalid Mach port name, or port is not for a file.
5484 * fdalloc:EMFILE
5485 * fdalloc:ENOMEM Unable to allocate fileproc or extend file table.
5486 *
5487 * Implicit returns:
5488 * *retval (modified) The new descriptor
5489 */
5490 int
5491 fileport_makefd(proc_t p, struct fileport_makefd_args *uap, int32_t *retval)
5492 {
5493 struct fileglob *fg;
5494 struct fileproc *fp = FILEPROC_NULL;
5495 ipc_port_t port = IPC_PORT_NULL;
5496 mach_port_name_t send = uap->port;
5497 kern_return_t res;
5498 int fd;
5499 int err;
5500
5501 res = ipc_object_copyin(get_task_ipcspace(p->task),
5502 send, MACH_MSG_TYPE_COPY_SEND, &port);
5503
5504 if (res != KERN_SUCCESS) {
5505 err = EINVAL;
5506 goto out;
5507 }
5508
5509 fg = fileport_port_to_fileglob(port);
5510 if (fg == NULL) {
5511 err = EINVAL;
5512 goto out;
5513 }
5514
5515 fp = fileproc_alloc_init(NULL);
5516 if (fp == FILEPROC_NULL) {
5517 err = ENOMEM;
5518 goto out;
5519 }
5520
5521 fp->f_fglob = fg;
5522 fg_ref(fp);
5523
5524 proc_fdlock(p);
5525 err = fdalloc(p, 0, &fd);
5526 if (err != 0) {
5527 proc_fdunlock(p);
5528 fg_drop(fp);
5529 goto out;
5530 }
5531 *fdflags(p, fd) |= UF_EXCLOSE;
5532
5533 procfdtbl_releasefd(p, fd, fp);
5534 proc_fdunlock(p);
5535
5536 *retval = fd;
5537 err = 0;
5538 out:
5539 if ((fp != NULL) && (0 != err)) {
5540 fileproc_free(fp);
5541 }
5542
5543 if (IPC_PORT_NULL != port) {
5544 ipc_port_release_send(port);
5545 }
5546
5547 return err;
5548 }
5549
5550
5551 /*
5552 * dupfdopen
5553 *
5554 * Description: Duplicate the specified descriptor to a free descriptor;
5555 * this is the second half of fdopen(), above.
5556 *
5557 * Parameters: fdp filedesc pointer to fill in
5558 * indx fd to dup to
5559 * dfd fd to dup from
5560 * mode mode to set on new fd
5561 * error command code
5562 *
5563 * Returns: 0 Success
5564 * EBADF Source fd is bad
5565 * EACCES Requested mode not allowed
5566 * !0 'error', if not ENODEV or
5567 * ENXIO
5568 *
5569 * Notes: XXX This is not thread safe; see fdopen() above
5570 */
5571 int
5572 dupfdopen(struct filedesc *fdp, int indx, int dfd, int flags, int error)
5573 {
5574 struct fileproc *wfp;
5575 struct fileproc *fp;
5576 #if CONFIG_MACF
5577 int myerror;
5578 #endif
5579 proc_t p = current_proc();
5580
5581 /*
5582 * If the to-be-dup'd fd number is greater than the allowed number
5583 * of file descriptors, or the fd to be dup'd has already been
5584 * closed, reject. Note, check for new == old is necessary as
5585 * falloc could allocate an already closed to-be-dup'd descriptor
5586 * as the new descriptor.
5587 */
5588 proc_fdlock(p);
5589
5590 fp = fdp->fd_ofiles[indx];
5591 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
5592 (wfp = fdp->fd_ofiles[dfd]) == NULL || wfp == fp ||
5593 (fdp->fd_ofileflags[dfd] & UF_RESERVED)) {
5594
5595 proc_fdunlock(p);
5596 return (EBADF);
5597 }
5598 #if CONFIG_MACF
5599 myerror = mac_file_check_dup(proc_ucred(p), wfp->f_fglob, dfd);
5600 if (myerror) {
5601 proc_fdunlock(p);
5602 return (myerror);
5603 }
5604 #endif
5605 /*
5606 * There are two cases of interest here.
5607 *
5608 * For ENODEV simply dup (dfd) to file descriptor
5609 * (indx) and return.
5610 *
5611 * For ENXIO steal away the file structure from (dfd) and
5612 * store it in (indx). (dfd) is effectively closed by
5613 * this operation.
5614 *
5615 * Any other error code is just returned.
5616 */
5617 switch (error) {
5618 case ENODEV:
5619 if (FP_ISGUARDED(wfp, GUARD_DUP)) {
5620 proc_fdunlock(p);
5621 return (EPERM);
5622 }
5623
5624 /*
5625 * Check that the mode the file is being opened for is a
5626 * subset of the mode of the existing descriptor.
5627 */
5628 if (((flags & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
5629 proc_fdunlock(p);
5630 return (EACCES);
5631 }
5632 if (indx > fdp->fd_lastfile)
5633 fdp->fd_lastfile = indx;
5634 (void)fg_ref(wfp);
5635
5636 if (fp->f_fglob)
5637 fg_free(fp->f_fglob);
5638 fp->f_fglob = wfp->f_fglob;
5639
5640 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd] |
5641 (flags & O_CLOEXEC) ? UF_EXCLOSE : 0;
5642
5643 proc_fdunlock(p);
5644 return (0);
5645
5646 default:
5647 proc_fdunlock(p);
5648 return (error);
5649 }
5650 /* NOTREACHED */
5651 }
5652
5653
5654 /*
5655 * fg_ref
5656 *
5657 * Description: Add a reference to a fileglob by fileproc
5658 *
5659 * Parameters: fp fileproc containing fileglob
5660 * pointer
5661 *
5662 * Returns: void
5663 *
5664 * Notes: XXX Should use OSAddAtomic?
5665 */
5666 void
5667 fg_ref(struct fileproc * fp)
5668 {
5669 struct fileglob *fg;
5670
5671 fg = fp->f_fglob;
5672
5673 lck_mtx_lock_spin(&fg->fg_lock);
5674
5675 #if DIAGNOSTIC
5676 if ((fp->f_flags & ~((unsigned int)FP_VALID_FLAGS)) != 0)
5677 panic("fg_ref: invalid bits on fp %p", fp);
5678
5679 if (fg->fg_count == 0)
5680 panic("fg_ref: adding fgcount to zeroed fg: fp %p fg %p",
5681 fp, fg);
5682 #endif
5683 fg->fg_count++;
5684 lck_mtx_unlock(&fg->fg_lock);
5685 }
5686
5687
5688 /*
5689 * fg_drop
5690 *
5691 * Description: Remove a reference to a fileglob by fileproc
5692 *
5693 * Parameters: fp fileproc containing fileglob
5694 * pointer
5695 *
5696 * Returns: void
5697 *
5698 * Notes: XXX Should use OSAddAtomic?
5699 */
5700 void
5701 fg_drop(struct fileproc * fp)
5702 {
5703 struct fileglob *fg;
5704
5705 fg = fp->f_fglob;
5706 lck_mtx_lock_spin(&fg->fg_lock);
5707 fg->fg_count--;
5708 lck_mtx_unlock(&fg->fg_lock);
5709 }
5710
5711 #if SOCKETS
5712 /*
5713 * fg_insertuipc_mark
5714 *
5715 * Description: Mark fileglob for insertion onto message queue if needed
5716 * Also takes fileglob reference
5717 *
5718 * Parameters: fg Fileglob pointer to insert
5719 *
5720 * Returns: true, if the fileglob needs to be inserted onto msg queue
5721 *
5722 * Locks: Takes and drops fg_lock, potentially many times
5723 */
5724 boolean_t
5725 fg_insertuipc_mark(struct fileglob * fg)
5726 {
5727 boolean_t insert = FALSE;
5728
5729 lck_mtx_lock_spin(&fg->fg_lock);
5730 while (fg->fg_lflags & FG_RMMSGQ) {
5731 lck_mtx_convert_spin(&fg->fg_lock);
5732
5733 fg->fg_lflags |= FG_WRMMSGQ;
5734 msleep(&fg->fg_lflags, &fg->fg_lock, 0, "fg_insertuipc", NULL);
5735 }
5736
5737 fg->fg_count++;
5738 fg->fg_msgcount++;
5739 if (fg->fg_msgcount == 1) {
5740 fg->fg_lflags |= FG_INSMSGQ;
5741 insert = TRUE;
5742 }
5743 lck_mtx_unlock(&fg->fg_lock);
5744 return (insert);
5745 }
5746
5747 /*
5748 * fg_insertuipc
5749 *
5750 * Description: Insert marked fileglob onto message queue
5751 *
5752 * Parameters: fg Fileglob pointer to insert
5753 *
5754 * Returns: void
5755 *
5756 * Locks: Takes and drops fg_lock & uipc_lock
5757 * DO NOT call this function with proc_fdlock held as unp_gc()
5758 * can potentially try to acquire proc_fdlock, which can result
5759 * in a deadlock if this function is in unp_gc_wait().
5760 */
5761 void
5762 fg_insertuipc(struct fileglob * fg)
5763 {
5764 if (fg->fg_lflags & FG_INSMSGQ) {
5765 lck_mtx_lock_spin(uipc_lock);
5766 unp_gc_wait();
5767 LIST_INSERT_HEAD(&fmsghead, fg, f_msglist);
5768 lck_mtx_unlock(uipc_lock);
5769 lck_mtx_lock(&fg->fg_lock);
5770 fg->fg_lflags &= ~FG_INSMSGQ;
5771 if (fg->fg_lflags & FG_WINSMSGQ) {
5772 fg->fg_lflags &= ~FG_WINSMSGQ;
5773 wakeup(&fg->fg_lflags);
5774 }
5775 lck_mtx_unlock(&fg->fg_lock);
5776 }
5777 }
5778
5779 /*
5780 * fg_removeuipc_mark
5781 *
5782 * Description: Mark the fileglob for removal from message queue if needed
5783 * Also releases fileglob message queue reference
5784 *
5785 * Parameters: fg Fileglob pointer to remove
5786 *
5787 * Returns: true, if the fileglob needs to be removed from msg queue
5788 *
5789 * Locks: Takes and drops fg_lock, potentially many times
5790 */
5791 boolean_t
5792 fg_removeuipc_mark(struct fileglob * fg)
5793 {
5794 boolean_t remove = FALSE;
5795
5796 lck_mtx_lock_spin(&fg->fg_lock);
5797 while (fg->fg_lflags & FG_INSMSGQ) {
5798 lck_mtx_convert_spin(&fg->fg_lock);
5799
5800 fg->fg_lflags |= FG_WINSMSGQ;
5801 msleep(&fg->fg_lflags, &fg->fg_lock, 0, "fg_removeuipc", NULL);
5802 }
5803 fg->fg_msgcount--;
5804 if (fg->fg_msgcount == 0) {
5805 fg->fg_lflags |= FG_RMMSGQ;
5806 remove = TRUE;
5807 }
5808 lck_mtx_unlock(&fg->fg_lock);
5809 return (remove);
5810 }
5811
5812 /*
5813 * fg_removeuipc
5814 *
5815 * Description: Remove marked fileglob from message queue
5816 *
5817 * Parameters: fg Fileglob pointer to remove
5818 *
5819 * Returns: void
5820 *
5821 * Locks: Takes and drops fg_lock & uipc_lock
5822 * DO NOT call this function with proc_fdlock held as unp_gc()
5823 * can potentially try to acquire proc_fdlock, which can result
5824 * in a deadlock if this function is in unp_gc_wait().
5825 */
5826 void
5827 fg_removeuipc(struct fileglob * fg)
5828 {
5829 if (fg->fg_lflags & FG_RMMSGQ) {
5830 lck_mtx_lock_spin(uipc_lock);
5831 unp_gc_wait();
5832 LIST_REMOVE(fg, f_msglist);
5833 lck_mtx_unlock(uipc_lock);
5834 lck_mtx_lock(&fg->fg_lock);
5835 fg->fg_lflags &= ~FG_RMMSGQ;
5836 if (fg->fg_lflags & FG_WRMMSGQ) {
5837 fg->fg_lflags &= ~FG_WRMMSGQ;
5838 wakeup(&fg->fg_lflags);
5839 }
5840 lck_mtx_unlock(&fg->fg_lock);
5841 }
5842 }
5843 #endif /* SOCKETS */
5844
5845 /*
5846 * fo_read
5847 *
5848 * Description: Generic fileops read indirected through the fileops pointer
5849 * in the fileproc structure
5850 *
5851 * Parameters: fp fileproc structure pointer
5852 * uio user I/O structure pointer
5853 * flags FOF_ flags
5854 * ctx VFS context for operation
5855 *
5856 * Returns: 0 Success
5857 * !0 Errno from read
5858 */
5859 int
5860 fo_read(struct fileproc *fp, struct uio *uio, int flags, vfs_context_t ctx)
5861 {
5862 return ((*fp->f_ops->fo_read)(fp, uio, flags, ctx));
5863 }
5864
5865
5866 /*
5867 * fo_write
5868 *
5869 * Description: Generic fileops write indirected through the fileops pointer
5870 * in the fileproc structure
5871 *
5872 * Parameters: fp fileproc structure pointer
5873 * uio user I/O structure pointer
5874 * flags FOF_ flags
5875 * ctx VFS context for operation
5876 *
5877 * Returns: 0 Success
5878 * !0 Errno from write
5879 */
5880 int
5881 fo_write(struct fileproc *fp, struct uio *uio, int flags, vfs_context_t ctx)
5882 {
5883 return((*fp->f_ops->fo_write)(fp, uio, flags, ctx));
5884 }
5885
5886
5887 /*
5888 * fo_ioctl
5889 *
5890 * Description: Generic fileops ioctl indirected through the fileops pointer
5891 * in the fileproc structure
5892 *
5893 * Parameters: fp fileproc structure pointer
5894 * com ioctl command
5895 * data pointer to internalized copy
5896 * of user space ioctl command
5897 * parameter data in kernel space
5898 * ctx VFS context for operation
5899 *
5900 * Returns: 0 Success
5901 * !0 Errno from ioctl
5902 *
5903 * Locks: The caller is assumed to have held the proc_fdlock; this
5904 * function releases and reacquires this lock. If the caller
5905 * accesses data protected by this lock prior to calling this
5906 * function, it will need to revalidate/reacquire any cached
5907 * protected data obtained prior to the call.
5908 */
5909 int
5910 fo_ioctl(struct fileproc *fp, u_long com, caddr_t data, vfs_context_t ctx)
5911 {
5912 int error;
5913
5914 proc_fdunlock(vfs_context_proc(ctx));
5915 error = (*fp->f_ops->fo_ioctl)(fp, com, data, ctx);
5916 proc_fdlock(vfs_context_proc(ctx));
5917 return(error);
5918 }
5919
5920
5921 /*
5922 * fo_select
5923 *
5924 * Description: Generic fileops select indirected through the fileops pointer
5925 * in the fileproc structure
5926 *
5927 * Parameters: fp fileproc structure pointer
5928 * which select which
5929 * wql pointer to wait queue list
5930 * ctx VFS context for operation
5931 *
5932 * Returns: 0 Success
5933 * !0 Errno from select
5934 */
5935 int
5936 fo_select(struct fileproc *fp, int which, void *wql, vfs_context_t ctx)
5937 {
5938 return((*fp->f_ops->fo_select)(fp, which, wql, ctx));
5939 }
5940
5941
5942 /*
5943 * fo_close
5944 *
5945 * Description: Generic fileops close indirected through the fileops pointer
5946 * in the fileproc structure
5947 *
5948 * Parameters: fp fileproc structure pointer for
5949 * file to close
5950 * ctx VFS context for operation
5951 *
5952 * Returns: 0 Success
5953 * !0 Errno from close
5954 */
5955 int
5956 fo_close(struct fileglob *fg, vfs_context_t ctx)
5957 {
5958 return((*fg->fg_ops->fo_close)(fg, ctx));
5959 }
5960
5961
5962 /*
5963 * fo_kqfilter
5964 *
5965 * Description: Generic fileops kqueue filter indirected through the fileops
5966 * pointer in the fileproc structure
5967 *
5968 * Parameters: fp fileproc structure pointer
5969 * kn pointer to knote to filter on
5970 * ctx VFS context for operation
5971 *
5972 * Returns: (kn->kn_flags & EV_ERROR) error in kn->kn_data
5973 * 0 Filter is not active
5974 * !0 Filter is active
5975 */
5976 int
5977 fo_kqfilter(struct fileproc *fp, struct knote *kn,
5978 struct kevent_internal_s *kev, vfs_context_t ctx)
5979 {
5980 return ((*fp->f_ops->fo_kqfilter)(fp, kn, kev, ctx));
5981 }
5982
5983 /*
5984 * The ability to send a file descriptor to another
5985 * process is opt-in by file type.
5986 */
5987 boolean_t
5988 file_issendable(proc_t p, struct fileproc *fp)
5989 {
5990 proc_fdlock_assert(p, LCK_MTX_ASSERT_OWNED);
5991
5992 switch (fp->f_type) {
5993 case DTYPE_VNODE:
5994 case DTYPE_SOCKET:
5995 case DTYPE_PIPE:
5996 case DTYPE_PSXSHM:
5997 case DTYPE_NETPOLICY:
5998 return (0 == (fp->f_fglob->fg_lflags & FG_CONFINED));
5999 default:
6000 /* DTYPE_KQUEUE, DTYPE_FSEVENTS, DTYPE_PSXSEM */
6001 return FALSE;
6002 }
6003 }
6004
6005
6006 struct fileproc *
6007 fileproc_alloc_init(__unused void *arg)
6008 {
6009 struct fileproc *fp;
6010
6011 MALLOC_ZONE(fp, struct fileproc *, sizeof (*fp), M_FILEPROC, M_WAITOK);
6012 if (fp)
6013 bzero(fp, sizeof (*fp));
6014
6015 return (fp);
6016 }
6017
6018 void
6019 fileproc_free(struct fileproc *fp)
6020 {
6021 switch (FILEPROC_TYPE(fp)) {
6022 case FTYPE_SIMPLE:
6023 FREE_ZONE(fp, sizeof (*fp), M_FILEPROC);
6024 break;
6025 case FTYPE_GUARDED:
6026 guarded_fileproc_free(fp);
6027 break;
6028 default:
6029 panic("%s: corrupt fp %p flags %x", __func__, fp, fp->f_flags);
6030 }
6031 }