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