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