2 * Copyright (c) 2000-2015 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
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.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
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.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
28 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
30 * Copyright (c) 1982, 1986, 1989, 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.
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
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.
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
66 * @(#)sys_generic.c 8.9 (Berkeley) 2/14/95
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,
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/filedesc.h>
78 #include <sys/ioctl.h>
79 #include <sys/file_internal.h>
80 #include <sys/proc_internal.h>
81 #include <sys/socketvar.h>
82 #include <sys/uio_internal.h>
83 #include <sys/kernel.h>
84 #include <sys/guarded.h>
86 #include <sys/malloc.h>
87 #include <sys/sysproto.h>
89 #include <sys/mount_internal.h>
90 #include <sys/protosw.h>
93 #include <sys/kdebug.h>
95 #include <sys/event.h>
96 #include <sys/eventvar.h>
98 #include <sys/kauth.h>
100 #include <machine/smp.h>
101 #include <mach/mach_types.h>
102 #include <kern/kern_types.h>
103 #include <kern/assert.h>
104 #include <kern/kalloc.h>
105 #include <kern/thread.h>
106 #include <kern/clock.h>
107 #include <kern/ledger.h>
108 #include <kern/task.h>
109 #include <kern/telemetry.h>
110 #include <kern/waitq.h>
111 #include <kern/sched_prim.h>
112 #include <kern/mpsc_queue.h>
114 #include <sys/mbuf.h>
115 #include <sys/domain.h>
116 #include <sys/socket.h>
117 #include <sys/socketvar.h>
118 #include <sys/errno.h>
119 #include <sys/syscall.h>
120 #include <sys/pipe.h>
122 #include <security/audit/audit.h>
125 #include <net/route.h>
127 #include <netinet/in.h>
128 #include <netinet/in_systm.h>
129 #include <netinet/ip.h>
130 #include <netinet/in_pcb.h>
131 #include <netinet/ip_var.h>
132 #include <netinet/ip6.h>
133 #include <netinet/tcp.h>
134 #include <netinet/tcp_fsm.h>
135 #include <netinet/tcp_seq.h>
136 #include <netinet/tcp_timer.h>
137 #include <netinet/tcp_var.h>
138 #include <netinet/tcpip.h>
139 #include <netinet/tcp_debug.h>
140 /* for wait queue based select */
141 #include <kern/waitq.h>
142 #include <kern/kalloc.h>
143 #include <sys/vnode_internal.h>
144 /* for remote time api*/
145 #include <kern/remote_time.h>
147 #include <sys/log_data.h>
150 #include <security/mac_framework.h>
153 /* for entitlement check */
154 #include <IOKit/IOBSD.h>
156 /* XXX should be in a header file somewhere */
157 void evsofree(struct socket
*);
158 void evpipefree(struct pipe
*);
159 void postpipeevent(struct pipe
*, int);
160 void postevent(struct socket
*, struct sockbuf
*, int);
161 extern kern_return_t
IOBSDGetPlatformUUID(__darwin_uuid_t uuid
, mach_timespec_t timeoutp
);
163 int rd_uio(struct proc
*p
, int fdes
, uio_t uio
, user_ssize_t
*retval
);
164 int wr_uio(struct proc
*p
, struct fileproc
*fp
, uio_t uio
, user_ssize_t
*retval
);
166 __private_extern__
int dofileread(vfs_context_t ctx
, struct fileproc
*fp
,
167 user_addr_t bufp
, user_size_t nbyte
,
168 off_t offset
, int flags
, user_ssize_t
*retval
);
169 __private_extern__
int dofilewrite(vfs_context_t ctx
, struct fileproc
*fp
,
170 user_addr_t bufp
, user_size_t nbyte
,
171 off_t offset
, int flags
, user_ssize_t
*retval
);
172 __private_extern__
int preparefileread(struct proc
*p
, struct fileproc
**fp_ret
, int fd
, int check_for_vnode
);
173 __private_extern__
void donefileread(struct proc
*p
, struct fileproc
*fp_ret
, int fd
);
175 /* Conflict wait queue for when selects collide (opaque type) */
176 struct waitq select_conflict_queue
;
179 * Init routine called from bsd_init.c
181 void select_waitq_init(void);
183 select_waitq_init(void)
185 waitq_init(&select_conflict_queue
, SYNC_POLICY_FIFO
);
188 #define f_flag f_fglob->fg_flag
189 #define f_type f_fglob->fg_ops->fo_type
190 #define f_msgcount f_fglob->fg_msgcount
191 #define f_cred f_fglob->fg_cred
192 #define f_ops f_fglob->fg_ops
193 #define f_offset f_fglob->fg_offset
194 #define f_data f_fglob->fg_data
200 * preparefileread:EBADF
201 * preparefileread:ESPIPE
202 * preparefileread:ENXIO
203 * preparefileread:EBADF
207 read(struct proc
*p
, struct read_args
*uap
, user_ssize_t
*retval
)
209 __pthread_testcancel(1);
210 return read_nocancel(p
, (struct read_nocancel_args
*)uap
, retval
);
214 read_nocancel(struct proc
*p
, struct read_nocancel_args
*uap
, user_ssize_t
*retval
)
219 struct vfs_context context
;
221 if ((error
= preparefileread(p
, &fp
, fd
, 0))) {
225 context
= *(vfs_context_current());
226 context
.vc_ucred
= fp
->f_fglob
->fg_cred
;
228 error
= dofileread(&context
, fp
, uap
->cbuf
, uap
->nbyte
,
229 (off_t
)-1, 0, retval
);
231 donefileread(p
, fp
, fd
);
240 * preparefileread:EBADF
241 * preparefileread:ESPIPE
242 * preparefileread:ENXIO
243 * preparefileread:EBADF
247 pread(struct proc
*p
, struct pread_args
*uap
, user_ssize_t
*retval
)
249 __pthread_testcancel(1);
250 return pread_nocancel(p
, (struct pread_nocancel_args
*)uap
, retval
);
254 pread_nocancel(struct proc
*p
, struct pread_nocancel_args
*uap
, user_ssize_t
*retval
)
256 struct fileproc
*fp
= NULL
; /* fp set by preparefileread() */
259 struct vfs_context context
;
261 if ((error
= preparefileread(p
, &fp
, fd
, 1))) {
265 context
= *(vfs_context_current());
266 context
.vc_ucred
= fp
->f_fglob
->fg_cred
;
268 error
= dofileread(&context
, fp
, uap
->buf
, uap
->nbyte
,
269 uap
->offset
, FOF_OFFSET
, retval
);
271 donefileread(p
, fp
, fd
);
273 KERNEL_DEBUG_CONSTANT((BSDDBG_CODE(DBG_BSD_SC_EXTENDED_INFO
, SYS_pread
) | DBG_FUNC_NONE
),
274 uap
->fd
, uap
->nbyte
, (unsigned int)((uap
->offset
>> 32)), (unsigned int)(uap
->offset
), 0);
281 * Code common for read and pread
285 donefileread(struct proc
*p
, struct fileproc
*fp
, int fd
)
288 fp_drop(p
, fd
, fp
, 1);
301 preparefileread(struct proc
*p
, struct fileproc
**fp_ret
, int fd
, int check_for_pread
)
311 error
= fp_lookup(p
, fd
, &fp
, 1);
317 if ((fp
->f_flag
& FREAD
) == 0) {
321 if (check_for_pread
&& (fp
->f_type
!= DTYPE_VNODE
)) {
325 if (fp
->f_type
== DTYPE_VNODE
) {
326 vp
= (struct vnode
*)fp
->f_fglob
->fg_data
;
328 if (check_for_pread
&& (vnode_isfifo(vp
))) {
332 if (check_for_pread
&& (vp
->v_flag
& VISTTY
)) {
344 fp_drop(p
, fd
, fp
, 1);
355 __private_extern__
int
356 dofileread(vfs_context_t ctx
, struct fileproc
*fp
,
357 user_addr_t bufp
, user_size_t nbyte
, off_t offset
, int flags
,
358 user_ssize_t
*retval
)
361 user_ssize_t bytecnt
;
363 char uio_buf
[UIO_SIZEOF(1)];
365 if (nbyte
> INT_MAX
) {
369 if (IS_64BIT_PROCESS(vfs_context_proc(ctx
))) {
370 auio
= uio_createwithbuffer(1, offset
, UIO_USERSPACE64
, UIO_READ
,
371 &uio_buf
[0], sizeof(uio_buf
));
373 auio
= uio_createwithbuffer(1, offset
, UIO_USERSPACE32
, UIO_READ
,
374 &uio_buf
[0], sizeof(uio_buf
));
376 if (uio_addiov(auio
, bufp
, nbyte
) != 0) {
383 if ((error
= fo_read(fp
, auio
, flags
, ctx
))) {
384 if (uio_resid(auio
) != bytecnt
&& (error
== ERESTART
||
385 error
== EINTR
|| error
== EWOULDBLOCK
)) {
389 bytecnt
-= uio_resid(auio
);
397 * Scatter read system call.
406 readv(struct proc
*p
, struct readv_args
*uap
, user_ssize_t
*retval
)
408 __pthread_testcancel(1);
409 return readv_nocancel(p
, (struct readv_nocancel_args
*)uap
, retval
);
413 readv_nocancel(struct proc
*p
, struct readv_nocancel_args
*uap
, user_ssize_t
*retval
)
417 struct user_iovec
*iovp
;
419 /* Verify range bedfore calling uio_create() */
420 if (uap
->iovcnt
<= 0 || uap
->iovcnt
> UIO_MAXIOV
) {
424 /* allocate a uio large enough to hold the number of iovecs passed */
425 auio
= uio_create(uap
->iovcnt
, 0,
426 (IS_64BIT_PROCESS(p
) ? UIO_USERSPACE64
: UIO_USERSPACE32
),
429 /* get location of iovecs within the uio. then copyin the iovecs from
432 iovp
= uio_iovsaddr(auio
);
435 goto ExitThisRoutine
;
437 error
= copyin_user_iovec_array(uap
->iovp
,
438 IS_64BIT_PROCESS(p
) ? UIO_USERSPACE64
: UIO_USERSPACE32
,
441 goto ExitThisRoutine
;
444 /* finalize uio_t for use and do the IO
446 error
= uio_calculateresid(auio
);
448 goto ExitThisRoutine
;
450 error
= rd_uio(p
, uap
->fd
, auio
, retval
);
468 write(struct proc
*p
, struct write_args
*uap
, user_ssize_t
*retval
)
470 __pthread_testcancel(1);
471 return write_nocancel(p
, (struct write_nocancel_args
*)uap
, retval
);
475 write_nocancel(struct proc
*p
, struct write_nocancel_args
*uap
, user_ssize_t
*retval
)
480 bool wrote_some
= false;
484 error
= fp_lookup(p
, fd
, &fp
, 0);
488 if ((fp
->f_flag
& FWRITE
) == 0) {
490 } else if (FP_ISGUARDED(fp
, GUARD_WRITE
)) {
492 error
= fp_guard_exception(p
, fd
, fp
, kGUARD_EXC_WRITE
);
495 struct vfs_context context
= *(vfs_context_current());
496 context
.vc_ucred
= fp
->f_fglob
->fg_cred
;
498 error
= dofilewrite(&context
, fp
, uap
->cbuf
, uap
->nbyte
,
499 (off_t
)-1, 0, retval
);
501 wrote_some
= *retval
> 0;
504 fp_drop_written(p
, fd
, fp
);
506 fp_drop(p
, fd
, fp
, 0);
523 pwrite(struct proc
*p
, struct pwrite_args
*uap
, user_ssize_t
*retval
)
525 __pthread_testcancel(1);
526 return pwrite_nocancel(p
, (struct pwrite_nocancel_args
*)uap
, retval
);
530 pwrite_nocancel(struct proc
*p
, struct pwrite_nocancel_args
*uap
, user_ssize_t
*retval
)
535 vnode_t vp
= (vnode_t
)0;
536 bool wrote_some
= false;
540 error
= fp_lookup(p
, fd
, &fp
, 0);
545 if ((fp
->f_flag
& FWRITE
) == 0) {
547 } else if (FP_ISGUARDED(fp
, GUARD_WRITE
)) {
549 error
= fp_guard_exception(p
, fd
, fp
, kGUARD_EXC_WRITE
);
552 struct vfs_context context
= *vfs_context_current();
553 context
.vc_ucred
= fp
->f_fglob
->fg_cred
;
555 if (fp
->f_type
!= DTYPE_VNODE
) {
559 vp
= (vnode_t
)fp
->f_fglob
->fg_data
;
560 if (vnode_isfifo(vp
)) {
564 if ((vp
->v_flag
& VISTTY
)) {
568 if (uap
->offset
== (off_t
)-1) {
573 error
= dofilewrite(&context
, fp
, uap
->buf
, uap
->nbyte
,
574 uap
->offset
, FOF_OFFSET
, retval
);
575 wrote_some
= *retval
> 0;
579 fp_drop_written(p
, fd
, fp
);
581 fp_drop(p
, fd
, fp
, 0);
584 KERNEL_DEBUG_CONSTANT((BSDDBG_CODE(DBG_BSD_SC_EXTENDED_INFO
, SYS_pwrite
) | DBG_FUNC_NONE
),
585 uap
->fd
, uap
->nbyte
, (unsigned int)((uap
->offset
>> 32)), (unsigned int)(uap
->offset
), 0);
594 * <fo_write>:??? [indirect through struct fileops]
596 __private_extern__
int
597 dofilewrite(vfs_context_t ctx
, struct fileproc
*fp
,
598 user_addr_t bufp
, user_size_t nbyte
, off_t offset
, int flags
,
599 user_ssize_t
*retval
)
603 user_ssize_t bytecnt
;
604 char uio_buf
[UIO_SIZEOF(1)];
606 if (nbyte
> INT_MAX
) {
611 if (IS_64BIT_PROCESS(vfs_context_proc(ctx
))) {
612 auio
= uio_createwithbuffer(1, offset
, UIO_USERSPACE64
, UIO_WRITE
,
613 &uio_buf
[0], sizeof(uio_buf
));
615 auio
= uio_createwithbuffer(1, offset
, UIO_USERSPACE32
, UIO_WRITE
,
616 &uio_buf
[0], sizeof(uio_buf
));
618 if (uio_addiov(auio
, bufp
, nbyte
) != 0) {
624 if ((error
= fo_write(fp
, auio
, flags
, ctx
))) {
625 if (uio_resid(auio
) != bytecnt
&& (error
== ERESTART
||
626 error
== EINTR
|| error
== EWOULDBLOCK
)) {
629 /* The socket layer handles SIGPIPE */
630 if (error
== EPIPE
&& fp
->f_type
!= DTYPE_SOCKET
&&
631 (fp
->f_fglob
->fg_lflags
& FG_NOSIGPIPE
) == 0) {
632 /* XXX Raise the signal on the thread? */
633 psignal(vfs_context_proc(ctx
), SIGPIPE
);
636 bytecnt
-= uio_resid(auio
);
643 * Gather write system call
646 writev(struct proc
*p
, struct writev_args
*uap
, user_ssize_t
*retval
)
648 __pthread_testcancel(1);
649 return writev_nocancel(p
, (struct writev_nocancel_args
*)uap
, retval
);
653 writev_nocancel(struct proc
*p
, struct writev_nocancel_args
*uap
, user_ssize_t
*retval
)
658 struct user_iovec
*iovp
;
659 bool wrote_some
= false;
661 AUDIT_ARG(fd
, uap
->fd
);
663 /* Verify range bedfore calling uio_create() */
664 if (uap
->iovcnt
<= 0 || uap
->iovcnt
> UIO_MAXIOV
) {
668 /* allocate a uio large enough to hold the number of iovecs passed */
669 auio
= uio_create(uap
->iovcnt
, 0,
670 (IS_64BIT_PROCESS(p
) ? UIO_USERSPACE64
: UIO_USERSPACE32
),
673 /* get location of iovecs within the uio. then copyin the iovecs from
676 iovp
= uio_iovsaddr(auio
);
679 goto ExitThisRoutine
;
681 error
= copyin_user_iovec_array(uap
->iovp
,
682 IS_64BIT_PROCESS(p
) ? UIO_USERSPACE64
: UIO_USERSPACE32
,
685 goto ExitThisRoutine
;
688 /* finalize uio_t for use and do the IO
690 error
= uio_calculateresid(auio
);
692 goto ExitThisRoutine
;
695 error
= fp_lookup(p
, uap
->fd
, &fp
, 0);
697 goto ExitThisRoutine
;
700 if ((fp
->f_flag
& FWRITE
) == 0) {
702 } else if (FP_ISGUARDED(fp
, GUARD_WRITE
)) {
704 error
= fp_guard_exception(p
, uap
->fd
, fp
, kGUARD_EXC_WRITE
);
707 error
= wr_uio(p
, fp
, auio
, retval
);
708 wrote_some
= *retval
> 0;
712 fp_drop_written(p
, uap
->fd
, fp
);
714 fp_drop(p
, uap
->fd
, fp
, 0);
726 wr_uio(struct proc
*p
, struct fileproc
*fp
, uio_t uio
, user_ssize_t
*retval
)
730 struct vfs_context context
= *vfs_context_current();
732 count
= uio_resid(uio
);
734 context
.vc_ucred
= fp
->f_cred
;
735 error
= fo_write(fp
, uio
, 0, &context
);
737 if (uio_resid(uio
) != count
&& (error
== ERESTART
||
738 error
== EINTR
|| error
== EWOULDBLOCK
)) {
741 /* The socket layer handles SIGPIPE */
742 if (error
== EPIPE
&& fp
->f_type
!= DTYPE_SOCKET
&&
743 (fp
->f_fglob
->fg_lflags
& FG_NOSIGPIPE
) == 0) {
747 *retval
= count
- uio_resid(uio
);
754 rd_uio(struct proc
*p
, int fdes
, uio_t uio
, user_ssize_t
*retval
)
759 struct vfs_context context
= *vfs_context_current();
761 if ((error
= preparefileread(p
, &fp
, fdes
, 0))) {
765 count
= uio_resid(uio
);
767 context
.vc_ucred
= fp
->f_cred
;
769 error
= fo_read(fp
, uio
, 0, &context
);
772 if (uio_resid(uio
) != count
&& (error
== ERESTART
||
773 error
== EINTR
|| error
== EWOULDBLOCK
)) {
777 *retval
= count
- uio_resid(uio
);
779 donefileread(p
, fp
, fdes
);
794 * fp_lookup:EBADF Bad file descriptor
798 ioctl(struct proc
*p
, struct ioctl_args
*uap
, __unused
int32_t *retval
)
800 struct fileproc
*fp
= NULL
;
803 caddr_t datap
= NULL
, memp
= NULL
;
804 boolean_t is64bit
= FALSE
;
806 #define STK_PARAMS 128
807 char stkbuf
[STK_PARAMS
] = {};
809 u_long com
= uap
->com
;
810 struct vfs_context context
= *vfs_context_current();
812 AUDIT_ARG(fd
, uap
->fd
);
813 AUDIT_ARG(addr
, uap
->data
);
815 is64bit
= proc_is64bit(p
);
818 AUDIT_ARG(value64
, com
);
820 AUDIT_ARG(cmd
, CAST_DOWN_EXPLICIT(int, com
));
822 #endif /* CONFIG_AUDIT */
825 * Interpret high order word to find amount of data to be
826 * copied to/from the user's address space.
828 size
= IOCPARM_LEN(com
);
829 if (size
> IOCPARM_MAX
) {
832 if (size
> sizeof(stkbuf
)) {
833 if ((memp
= (caddr_t
)kalloc(size
)) == 0) {
842 error
= copyin(uap
->data
, datap
, size
);
847 /* XXX - IOC_IN and no size? we should proably return an error here!! */
849 *(user_addr_t
*)datap
= uap
->data
;
851 *(uint32_t *)datap
= (uint32_t)uap
->data
;
854 } else if ((com
& IOC_OUT
) && size
) {
856 * Zero the buffer so the user always
857 * gets back something deterministic.
860 } else if (com
& IOC_VOID
) {
861 /* XXX - this is odd since IOC_VOID means no parameters */
863 *(user_addr_t
*)datap
= uap
->data
;
865 *(uint32_t *)datap
= (uint32_t)uap
->data
;
870 error
= fp_lookup(p
, fd
, &fp
, 1);
876 AUDIT_ARG(file
, p
, fp
);
878 if ((fp
->f_flag
& (FREAD
| FWRITE
)) == 0) {
883 context
.vc_ucred
= fp
->f_fglob
->fg_cred
;
886 error
= mac_file_check_ioctl(context
.vc_ucred
, fp
->f_fglob
, com
);
894 *fdflags(p
, fd
) &= ~UF_EXCLOSE
;
898 *fdflags(p
, fd
) |= UF_EXCLOSE
;
902 if ((tmp
= *(int *)datap
)) {
903 fp
->f_flag
|= FNONBLOCK
;
905 fp
->f_flag
&= ~FNONBLOCK
;
907 error
= fo_ioctl(fp
, FIONBIO
, (caddr_t
)&tmp
, &context
);
911 if ((tmp
= *(int *)datap
)) {
912 fp
->f_flag
|= FASYNC
;
914 fp
->f_flag
&= ~FASYNC
;
916 error
= fo_ioctl(fp
, FIOASYNC
, (caddr_t
)&tmp
, &context
);
921 if (fp
->f_type
== DTYPE_SOCKET
) {
922 ((struct socket
*)fp
->f_data
)->so_pgid
= tmp
;
925 if (fp
->f_type
== DTYPE_PIPE
) {
926 error
= fo_ioctl(fp
, TIOCSPGRP
, (caddr_t
)&tmp
, &context
);
932 struct proc
*p1
= proc_find(tmp
);
940 error
= fo_ioctl(fp
, TIOCSPGRP
, (caddr_t
)&tmp
, &context
);
944 if (fp
->f_type
== DTYPE_SOCKET
) {
945 *(int *)datap
= ((struct socket
*)fp
->f_data
)->so_pgid
;
948 error
= fo_ioctl(fp
, TIOCGPGRP
, datap
, &context
);
949 *(int *)datap
= -*(int *)datap
;
953 error
= fo_ioctl(fp
, com
, datap
, &context
);
955 * Copy any data to user, size was
956 * already set and checked above.
958 if (error
== 0 && (com
& IOC_OUT
) && size
) {
959 error
= copyout(datap
, uap
->data
, (u_int
)size
);
964 fp_drop(p
, fd
, fp
, 1);
974 int selwait
, nselcoll
;
975 #define SEL_FIRSTPASS 1
976 #define SEL_SECONDPASS 2
977 extern int selcontinue(int error
);
978 extern int selprocess(int error
, int sel_pass
);
979 static int selscan(struct proc
*p
, struct _select
* sel
, struct _select_data
* seldata
,
980 int nfd
, int32_t *retval
, int sel_pass
, struct waitq_set
*wqset
);
981 static int selcount(struct proc
*p
, u_int32_t
*ibits
, int nfd
, int *count
);
982 static int seldrop_locked(struct proc
*p
, u_int32_t
*ibits
, int nfd
, int lim
, int *need_wakeup
, int fromselcount
);
983 static int seldrop(struct proc
*p
, u_int32_t
*ibits
, int nfd
);
984 static int select_internal(struct proc
*p
, struct select_nocancel_args
*uap
, uint64_t timeout
, int32_t *retval
);
987 * Select system call.
990 * EINVAL Invalid argument
991 * EAGAIN Nonconformant error if allocation fails
994 select(struct proc
*p
, struct select_args
*uap
, int32_t *retval
)
996 __pthread_testcancel(1);
997 return select_nocancel(p
, (struct select_nocancel_args
*)uap
, retval
);
1001 select_nocancel(struct proc
*p
, struct select_nocancel_args
*uap
, int32_t *retval
)
1003 uint64_t timeout
= 0;
1008 if (IS_64BIT_PROCESS(p
)) {
1009 struct user64_timeval atv64
;
1010 err
= copyin(uap
->tv
, (caddr_t
)&atv64
, sizeof(atv64
));
1011 /* Loses resolution - assume timeout < 68 years */
1012 atv
.tv_sec
= atv64
.tv_sec
;
1013 atv
.tv_usec
= atv64
.tv_usec
;
1015 struct user32_timeval atv32
;
1016 err
= copyin(uap
->tv
, (caddr_t
)&atv32
, sizeof(atv32
));
1017 atv
.tv_sec
= atv32
.tv_sec
;
1018 atv
.tv_usec
= atv32
.tv_usec
;
1024 if (itimerfix(&atv
)) {
1029 clock_absolutetime_interval_to_deadline(tvtoabstime(&atv
), &timeout
);
1032 return select_internal(p
, uap
, timeout
, retval
);
1036 pselect(struct proc
*p
, struct pselect_args
*uap
, int32_t *retval
)
1038 __pthread_testcancel(1);
1039 return pselect_nocancel(p
, (struct pselect_nocancel_args
*)uap
, retval
);
1043 pselect_nocancel(struct proc
*p
, struct pselect_nocancel_args
*uap
, int32_t *retval
)
1047 uint64_t timeout
= 0;
1052 if (IS_64BIT_PROCESS(p
)) {
1053 struct user64_timespec ts64
;
1054 err
= copyin(uap
->ts
, (caddr_t
)&ts64
, sizeof(ts64
));
1055 ts
.tv_sec
= ts64
.tv_sec
;
1056 ts
.tv_nsec
= ts64
.tv_nsec
;
1058 struct user32_timespec ts32
;
1059 err
= copyin(uap
->ts
, (caddr_t
)&ts32
, sizeof(ts32
));
1060 ts
.tv_sec
= ts32
.tv_sec
;
1061 ts
.tv_nsec
= ts32
.tv_nsec
;
1067 if (!timespec_is_valid(&ts
)) {
1070 clock_absolutetime_interval_to_deadline(tstoabstime(&ts
), &timeout
);
1073 ut
= get_bsdthread_info(current_thread());
1075 if (uap
->mask
!= USER_ADDR_NULL
) {
1076 /* save current mask, then copyin and set new mask */
1078 err
= copyin(uap
->mask
, &newset
, sizeof(sigset_t
));
1082 ut
->uu_oldmask
= ut
->uu_sigmask
;
1083 ut
->uu_flag
|= UT_SAS_OLDMASK
;
1084 ut
->uu_sigmask
= (newset
& ~sigcantmask
);
1087 err
= select_internal(p
, (struct select_nocancel_args
*)uap
, timeout
, retval
);
1089 if (err
!= EINTR
&& ut
->uu_flag
& UT_SAS_OLDMASK
) {
1091 * Restore old mask (direct return case). NOTE: EINTR can also be returned
1092 * if the thread is cancelled. In that case, we don't reset the signal
1093 * mask to its original value (which usually happens in the signal
1094 * delivery path). This behavior is permitted by POSIX.
1096 ut
->uu_sigmask
= ut
->uu_oldmask
;
1098 ut
->uu_flag
&= ~UT_SAS_OLDMASK
;
1105 * Generic implementation of {,p}select. Care: we type-pun uap across the two
1106 * syscalls, which differ slightly. The first 4 arguments (nfds and the fd sets)
1107 * are identical. The 5th (timeout) argument points to different types, so we
1108 * unpack in the syscall-specific code, but the generic code still does a null
1109 * check on this argument to determine if a timeout was specified.
1112 select_internal(struct proc
*p
, struct select_nocancel_args
*uap
, uint64_t timeout
, int32_t *retval
)
1117 struct uthread
*uth
;
1118 struct _select
*sel
;
1119 struct _select_data
*seldata
;
1120 int needzerofill
= 1;
1124 th_act
= current_thread();
1125 uth
= get_bsdthread_info(th_act
);
1126 sel
= &uth
->uu_select
;
1127 seldata
= &uth
->uu_save
.uus_select_data
;
1130 seldata
->args
= uap
;
1131 seldata
->retval
= retval
;
1132 seldata
->wqp
= NULL
;
1139 /* select on thread of process that already called proc_exit() */
1140 if (p
->p_fd
== NULL
) {
1144 if (uap
->nd
> p
->p_fd
->fd_nfiles
) {
1145 uap
->nd
= p
->p_fd
->fd_nfiles
; /* forgiving; slightly wrong */
1147 nw
= howmany(uap
->nd
, NFDBITS
);
1148 ni
= nw
* sizeof(fd_mask
);
1151 * if the previously allocated space for the bits is smaller than
1152 * what is requested or no space has yet been allocated for this
1153 * thread, allocate enough space now.
1155 * Note: If this process fails, select() will return EAGAIN; this
1156 * is the same thing pool() returns in a no-memory situation, but
1157 * it is not a POSIX compliant error code for select().
1159 if (sel
->nbytes
< (3 * ni
)) {
1160 int nbytes
= 3 * ni
;
1162 /* Free previous allocation, if any */
1163 if (sel
->ibits
!= NULL
) {
1164 FREE(sel
->ibits
, M_TEMP
);
1166 if (sel
->obits
!= NULL
) {
1167 FREE(sel
->obits
, M_TEMP
);
1168 /* NULL out; subsequent ibits allocation may fail */
1172 MALLOC(sel
->ibits
, u_int32_t
*, nbytes
, M_TEMP
, M_WAITOK
| M_ZERO
);
1173 if (sel
->ibits
== NULL
) {
1176 MALLOC(sel
->obits
, u_int32_t
*, nbytes
, M_TEMP
, M_WAITOK
| M_ZERO
);
1177 if (sel
->obits
== NULL
) {
1178 FREE(sel
->ibits
, M_TEMP
);
1182 sel
->nbytes
= nbytes
;
1187 bzero((caddr_t
)sel
->ibits
, sel
->nbytes
);
1188 bzero((caddr_t
)sel
->obits
, sel
->nbytes
);
1192 * get the bits from the user address space
1194 #define getbits(name, x) \
1196 if (uap->name && (error = copyin(uap->name, \
1197 (caddr_t)&sel->ibits[(x) * nw], ni))) \
1198 goto continuation; \
1206 seldata
->abstime
= timeout
;
1208 if ((error
= selcount(p
, sel
->ibits
, uap
->nd
, &count
))) {
1213 * We need an array of waitq pointers. This is due to the new way
1214 * in which waitqs are linked to sets. When a thread selects on a
1215 * file descriptor, a waitq (embedded in a selinfo structure) is
1216 * added to the thread's local waitq set. There is no longer any
1217 * way to directly iterate over all members of a given waitq set.
1218 * The process of linking a waitq into a set may allocate a link
1219 * table object. Because we can't iterate over all the waitqs to
1220 * which our thread waitq set belongs, we need a way of removing
1223 * Thus we need a buffer which will hold one waitq pointer
1224 * per FD being selected. During the tear-down phase we can use
1225 * these pointers to dis-associate the underlying selinfo's waitq
1226 * from our thread's waitq set.
1228 * Because we also need to allocate a waitq set for this thread,
1229 * we use a bare buffer pointer to hold all the memory. Note that
1230 * this memory is cached in the thread pointer and not reaped until
1231 * the thread exists. This is generally OK because threads that
1232 * call select tend to keep calling select repeatedly.
1234 sz
= ALIGN(sizeof(struct waitq_set
)) + (count
* sizeof(uint64_t));
1235 if (sz
> uth
->uu_wqstate_sz
) {
1236 /* (re)allocate a buffer to hold waitq pointers */
1237 if (uth
->uu_wqset
) {
1238 if (waitq_set_is_valid(uth
->uu_wqset
)) {
1239 waitq_set_deinit(uth
->uu_wqset
);
1241 FREE(uth
->uu_wqset
, M_SELECT
);
1242 } else if (uth
->uu_wqstate_sz
&& !uth
->uu_wqset
) {
1243 panic("select: thread structure corrupt! "
1244 "uu_wqstate_sz:%ld, wqstate_buf == NULL",
1245 uth
->uu_wqstate_sz
);
1247 uth
->uu_wqstate_sz
= sz
;
1248 MALLOC(uth
->uu_wqset
, struct waitq_set
*, sz
, M_SELECT
, M_WAITOK
);
1249 if (!uth
->uu_wqset
) {
1250 panic("can't allocate %ld bytes for wqstate buffer",
1251 uth
->uu_wqstate_sz
);
1253 waitq_set_init(uth
->uu_wqset
,
1254 SYNC_POLICY_FIFO
| SYNC_POLICY_PREPOST
, NULL
, NULL
);
1257 if (!waitq_set_is_valid(uth
->uu_wqset
)) {
1258 waitq_set_init(uth
->uu_wqset
,
1259 SYNC_POLICY_FIFO
| SYNC_POLICY_PREPOST
, NULL
, NULL
);
1262 /* the last chunk of our buffer is an array of waitq pointers */
1263 seldata
->wqp
= (uint64_t *)((char *)(uth
->uu_wqset
) + ALIGN(sizeof(struct waitq_set
)));
1264 bzero(seldata
->wqp
, sz
- ALIGN(sizeof(struct waitq_set
)));
1266 seldata
->count
= count
;
1272 * We have already cleaned up any state we established,
1273 * either locally or as a result of selcount(). We don't
1274 * need to wait_subqueue_unlink_all(), since we haven't set
1275 * anything at this point.
1280 return selprocess(0, SEL_FIRSTPASS
);
1284 selcontinue(int error
)
1286 return selprocess(error
, SEL_SECONDPASS
);
1293 * Parameters: error The error code from our caller
1294 * sel_pass The pass we are on
1297 selprocess(int error
, int sel_pass
)
1302 struct uthread
*uth
;
1304 struct select_nocancel_args
*uap
;
1306 struct _select
*sel
;
1307 struct _select_data
*seldata
;
1312 wait_result_t wait_result
;
1315 th_act
= current_thread();
1316 uth
= get_bsdthread_info(th_act
);
1317 sel
= &uth
->uu_select
;
1318 seldata
= &uth
->uu_save
.uus_select_data
;
1319 uap
= seldata
->args
;
1320 retval
= seldata
->retval
;
1322 if ((error
!= 0) && (sel_pass
== SEL_FIRSTPASS
)) {
1325 if (seldata
->count
== 0) {
1334 OSBitOrAtomic(P_SELECT
, &p
->p_flag
);
1336 /* skip scans if the select is just for timeouts */
1337 if (seldata
->count
) {
1338 error
= selscan(p
, sel
, seldata
, uap
->nd
, retval
, sel_pass
, uth
->uu_wqset
);
1339 if (error
|| *retval
) {
1342 if (prepost
|| somewakeup
) {
1344 * if the select of log, then we can wakeup and
1345 * discover some one else already read the data;
1346 * go to select again if time permits
1357 clock_get_uptime(&now
);
1358 if (now
>= seldata
->abstime
) {
1364 /* cleanup obits and try again */
1366 sel_pass
= SEL_FIRSTPASS
;
1371 * To effect a poll, the timeout argument should be
1372 * non-nil, pointing to a zero-valued timeval structure.
1374 if (uap
->tv
&& seldata
->abstime
== 0) {
1378 /* No spurious wakeups due to colls,no need to check for them */
1379 if ((sel_pass
== SEL_SECONDPASS
) || ((p
->p_flag
& P_SELECT
) == 0)) {
1380 sel_pass
= SEL_FIRSTPASS
;
1384 OSBitAndAtomic(~((uint32_t)P_SELECT
), &p
->p_flag
);
1386 /* if the select is just for timeout skip check */
1387 if (seldata
->count
&& (sel_pass
== SEL_SECONDPASS
)) {
1388 panic("selprocess: 2nd pass assertwaiting");
1391 /* waitq_set has waitqueue as first element */
1392 wait_result
= waitq_assert_wait64_leeway((struct waitq
*)uth
->uu_wqset
,
1393 NO_EVENT64
, THREAD_ABORTSAFE
,
1394 TIMEOUT_URGENCY_USER_NORMAL
,
1397 if (wait_result
!= THREAD_AWAKENED
) {
1398 /* there are no preposted events */
1399 error
= tsleep1(NULL
, PSOCK
| PCATCH
,
1400 "select", 0, selcontinue
);
1407 sel_pass
= SEL_SECONDPASS
;
1415 seldrop(p
, sel
->ibits
, uap
->nd
);
1416 waitq_set_deinit(uth
->uu_wqset
);
1418 * zero out the waitq pointer array to avoid use-after free
1419 * errors in the selcount error path (seldrop_locked) if/when
1420 * the thread re-calls select().
1422 bzero((void *)uth
->uu_wqset
, uth
->uu_wqstate_sz
);
1424 OSBitAndAtomic(~((uint32_t)P_SELECT
), &p
->p_flag
);
1425 /* select is not restarted after signals... */
1426 if (error
== ERESTART
) {
1429 if (error
== EWOULDBLOCK
) {
1432 nw
= howmany(uap
->nd
, NFDBITS
);
1433 ni
= nw
* sizeof(fd_mask
);
1435 #define putbits(name, x) \
1437 if (uap->name && (error2 = \
1438 copyout((caddr_t)&sel->obits[(x) * nw], uap->name, ni))) \
1451 if (error
!= EINTR
&& sel_pass
== SEL_SECONDPASS
&& uth
->uu_flag
& UT_SAS_OLDMASK
) {
1452 /* restore signal mask - continuation case */
1453 uth
->uu_sigmask
= uth
->uu_oldmask
;
1454 uth
->uu_oldmask
= 0;
1455 uth
->uu_flag
&= ~UT_SAS_OLDMASK
;
1463 * remove the fileproc's underlying waitq from the supplied waitq set;
1464 * clear FP_INSELECT when appropriate
1467 * fp File proc that is potentially currently in select
1468 * wqset Waitq set to which the fileproc may belong
1469 * (usually this is the thread's private waitq set)
1471 * proc_fdlock is held
1474 selunlinkfp(struct fileproc
*fp
, uint64_t wqp_id
, struct waitq_set
*wqset
)
1476 int valid_set
= waitq_set_is_valid(wqset
);
1477 int valid_q
= !!wqp_id
;
1480 * This could be called (from selcount error path) before we setup
1481 * the thread's wqset. Check the wqset passed in, and only unlink if
1485 /* unlink the underlying waitq from the input set (thread waitq set) */
1486 if (valid_q
&& valid_set
) {
1487 waitq_unlink_by_prepost_id(wqp_id
, wqset
);
1490 /* allow passing a NULL/invalid fp for seldrop unwind */
1491 if (!fp
|| !(fp
->f_flags
& (FP_INSELECT
| FP_SELCONFLICT
))) {
1496 * We can always remove the conflict queue from our thread's set: this
1497 * will not affect other threads that potentially need to be awoken on
1498 * the conflict queue during a fileproc_drain - those sets will still
1499 * be linked with the global conflict queue, and the last waiter
1500 * on the fp clears the CONFLICT marker.
1502 if (valid_set
&& (fp
->f_flags
& FP_SELCONFLICT
)) {
1503 waitq_unlink(&select_conflict_queue
, wqset
);
1507 * This isn't quite right - we don't actually know if this
1508 * fileproc is in another select or not! Here we just assume
1509 * that if we were the first thread to select on the FD, then
1510 * we'll be the one to clear this flag...
1512 if (valid_set
&& fp
->f_wset
== (void *)wqset
) {
1513 fp
->f_flags
&= ~FP_INSELECT
;
1519 * connect a fileproc to the given wqset, potentially bridging to a waitq
1520 * pointed to indirectly by wq_data
1523 * fp File proc potentially currently in select
1524 * wq_data Pointer to a pointer to a waitq (could be NULL)
1525 * wqset Waitq set to which the fileproc should now belong
1526 * (usually this is the thread's private waitq set)
1529 * proc_fdlock is held
1532 sellinkfp(struct fileproc
*fp
, void **wq_data
, struct waitq_set
*wqset
)
1534 struct waitq
*f_wq
= NULL
;
1536 if ((fp
->f_flags
& FP_INSELECT
) != FP_INSELECT
) {
1538 panic("non-null data:%p on fp:%p not in select?!"
1539 "(wqset:%p)", wq_data
, fp
, wqset
);
1544 if ((fp
->f_flags
& FP_SELCONFLICT
) == FP_SELCONFLICT
) {
1545 waitq_link(&select_conflict_queue
, wqset
, WAITQ_SHOULD_LOCK
, NULL
);
1549 * The wq_data parameter has potentially been set by selrecord called
1550 * from a subsystems fo_select() function. If the subsystem does not
1551 * call selrecord, then wq_data will be NULL
1553 * Use memcpy to get the value into a proper pointer because
1554 * wq_data most likely points to a stack variable that could be
1555 * unaligned on 32-bit systems.
1558 memcpy(&f_wq
, wq_data
, sizeof(f_wq
));
1559 if (!waitq_is_valid(f_wq
)) {
1564 /* record the first thread's wqset in the fileproc structure */
1566 fp
->f_wset
= (void *)wqset
;
1569 /* handles NULL f_wq */
1570 return waitq_get_prepost_id(f_wq
);
1577 * Parameters: p Process performing the select
1578 * sel The per-thread select context structure
1579 * nfd The number of file descriptors to scan
1580 * retval The per thread system call return area
1581 * sel_pass Which pass this is; allowed values are
1582 * SEL_FIRSTPASS and SEL_SECONDPASS
1583 * wqset The per thread wait queue set
1585 * Returns: 0 Success
1586 * EIO Invalid p->p_fd field XXX Obsolete?
1587 * EBADF One of the files in the bit vector is
1591 selscan(struct proc
*p
, struct _select
*sel
, struct _select_data
* seldata
,
1592 int nfd
, int32_t *retval
, int sel_pass
, struct waitq_set
*wqset
)
1594 struct filedesc
*fdp
= p
->p_fd
;
1597 struct fileproc
*fp
;
1598 int n
= 0; /* count of bits */
1599 int nc
= 0; /* bit vector offset (nc'th bit) */
1600 static int flag
[3] = { FREAD
, FWRITE
, 0 };
1601 u_int32_t
*iptr
, *optr
;
1603 u_int32_t
*ibits
, *obits
;
1604 uint64_t reserved_link
, *rl_ptr
= NULL
;
1606 struct vfs_context context
= *vfs_context_current();
1609 * Problems when reboot; due to MacOSX signal probs
1610 * in Beaker1C ; verify that the p->p_fd is valid
1619 nw
= howmany(nfd
, NFDBITS
);
1621 count
= seldata
->count
;
1630 for (msk
= 0; msk
< 3; msk
++) {
1631 iptr
= (u_int32_t
*)&ibits
[msk
* nw
];
1632 optr
= (u_int32_t
*)&obits
[msk
* nw
];
1634 for (i
= 0; i
< nfd
; i
+= NFDBITS
) {
1635 bits
= iptr
[i
/ NFDBITS
];
1637 while ((j
= ffs(bits
)) && (fd
= i
+ --j
) < nfd
) {
1640 if (fd
< fdp
->fd_nfiles
) {
1641 fp
= fdp
->fd_ofiles
[fd
];
1646 if (fp
== NULL
|| (fdp
->fd_ofileflags
[fd
] & UF_RESERVED
)) {
1648 * If we abort because of a bad
1649 * fd, let the caller unwind...
1654 if (sel_pass
== SEL_SECONDPASS
) {
1657 selunlinkfp(fp
, seldata
->wqp
[nc
], wqset
);
1659 reserved_link
= waitq_link_reserve((struct waitq
*)wqset
);
1660 rl_ptr
= &reserved_link
;
1661 if (fp
->f_flags
& FP_INSELECT
) {
1662 /* someone is already in select on this fp */
1663 fp
->f_flags
|= FP_SELCONFLICT
;
1665 fp
->f_flags
|= FP_INSELECT
;
1668 waitq_set_lazy_init_link(wqset
);
1671 context
.vc_ucred
= fp
->f_cred
;
1674 * stash this value b/c fo_select may replace
1675 * reserved_link with a pointer to a waitq object
1677 uint64_t rsvd
= reserved_link
;
1679 /* The select; set the bit, if true */
1680 if (fp
->f_ops
&& fp
->f_type
1681 && fo_select(fp
, flag
[msk
], rl_ptr
, &context
)) {
1682 optr
[fd
/ NFDBITS
] |= (1U << (fd
% NFDBITS
));
1685 if (sel_pass
== SEL_FIRSTPASS
) {
1686 waitq_link_release(rsvd
);
1688 * If the fp's supporting selinfo structure was linked
1689 * to this thread's waitq set, then 'reserved_link'
1690 * will have been updated by selrecord to be a pointer
1691 * to the selinfo's waitq.
1693 if (reserved_link
== rsvd
) {
1694 rl_ptr
= NULL
; /* fo_select never called selrecord() */
1697 * Hook up the thread's waitq set either to
1698 * the fileproc structure, or to the global
1699 * conflict queue: but only on the first
1702 seldata
->wqp
[nc
] = sellinkfp(fp
, (void **)rl_ptr
, wqset
);
1714 static int poll_callback(struct kevent_qos_s
*, kevent_ctx_t
);
1717 poll(struct proc
*p
, struct poll_args
*uap
, int32_t *retval
)
1719 __pthread_testcancel(1);
1720 return poll_nocancel(p
, (struct poll_nocancel_args
*)uap
, retval
);
1725 poll_nocancel(struct proc
*p
, struct poll_nocancel_args
*uap
, int32_t *retval
)
1727 struct pollfd
*fds
= NULL
;
1728 struct kqueue
*kq
= NULL
;
1729 int ncoll
, error
= 0;
1730 u_int nfds
= uap
->nfds
;
1734 * This is kinda bogus. We have fd limits, but that is not
1735 * really related to the size of the pollfd array. Make sure
1736 * we let the process use at least FD_SETSIZE entries and at
1737 * least enough for the current limits. We want to be reasonably
1738 * safe, but not overly restrictive.
1740 if (nfds
> OPEN_MAX
||
1741 (nfds
> p
->p_rlimit
[RLIMIT_NOFILE
].rlim_cur
&& (proc_suser(p
) || nfds
> FD_SETSIZE
))) {
1745 kq
= kqueue_alloc(p
);
1751 size_t ni
= nfds
* sizeof(struct pollfd
);
1752 MALLOC(fds
, struct pollfd
*, ni
, M_TEMP
, M_WAITOK
);
1758 error
= copyin(uap
->fds
, fds
, nfds
* sizeof(struct pollfd
));
1764 /* JMM - all this P_SELECT stuff is bogus */
1766 OSBitOrAtomic(P_SELECT
, &p
->p_flag
);
1767 for (u_int i
= 0; i
< nfds
; i
++) {
1768 short events
= fds
[i
].events
;
1769 __assert_only
int rc
;
1771 /* per spec, ignore fd values below zero */
1772 if (fds
[i
].fd
< 0) {
1777 /* convert the poll event into a kqueue kevent */
1778 struct kevent_qos_s kev
= {
1780 .flags
= EV_ADD
| EV_ONESHOT
| EV_POLL
,
1781 .udata
= CAST_USER_ADDR_T(&fds
[i
])
1784 /* Handle input events */
1785 if (events
& (POLLIN
| POLLRDNORM
| POLLPRI
| POLLRDBAND
| POLLHUP
)) {
1786 kev
.filter
= EVFILT_READ
;
1787 if (events
& (POLLPRI
| POLLRDBAND
)) {
1788 kev
.flags
|= EV_OOBAND
;
1790 rc
= kevent_register(kq
, &kev
, NULL
);
1791 assert((rc
& FILTER_REGISTER_WAIT
) == 0);
1794 /* Handle output events */
1795 if ((kev
.flags
& EV_ERROR
) == 0 &&
1796 (events
& (POLLOUT
| POLLWRNORM
| POLLWRBAND
))) {
1797 kev
.filter
= EVFILT_WRITE
;
1798 rc
= kevent_register(kq
, &kev
, NULL
);
1799 assert((rc
& FILTER_REGISTER_WAIT
) == 0);
1802 /* Handle BSD extension vnode events */
1803 if ((kev
.flags
& EV_ERROR
) == 0 &&
1804 (events
& (POLLEXTEND
| POLLATTRIB
| POLLNLINK
| POLLWRITE
))) {
1805 kev
.filter
= EVFILT_VNODE
;
1807 if (events
& POLLEXTEND
) {
1808 kev
.fflags
|= NOTE_EXTEND
;
1810 if (events
& POLLATTRIB
) {
1811 kev
.fflags
|= NOTE_ATTRIB
;
1813 if (events
& POLLNLINK
) {
1814 kev
.fflags
|= NOTE_LINK
;
1816 if (events
& POLLWRITE
) {
1817 kev
.fflags
|= NOTE_WRITE
;
1819 rc
= kevent_register(kq
, &kev
, NULL
);
1820 assert((rc
& FILTER_REGISTER_WAIT
) == 0);
1823 if (kev
.flags
& EV_ERROR
) {
1824 fds
[i
].revents
= POLLNVAL
;
1832 * Did we have any trouble registering?
1833 * If user space passed 0 FDs, then respect any timeout value passed.
1834 * This is an extremely inefficient sleep. If user space passed one or
1835 * more FDs, and we had trouble registering _all_ of them, then bail
1836 * out. If a subset of the provided FDs failed to register, then we
1837 * will still call the kqueue_scan function.
1839 if (nfds
&& (rfds
== nfds
)) {
1843 /* scan for, and possibly wait for, the kevents to trigger */
1844 kevent_ctx_t kectx
= kevent_get_context(current_thread());
1845 *kectx
= (struct kevent_ctx_s
){
1846 .kec_process_noutputs
= rfds
,
1847 .kec_process_flags
= KEVENT_FLAG_POLL
,
1848 .kec_deadline
= 0, /* wait forever */
1852 * If any events have trouble registering, an event has fired and we
1853 * shouldn't wait for events in kqueue_scan.
1856 kectx
->kec_process_flags
|= KEVENT_FLAG_IMMEDIATE
;
1857 } else if (uap
->timeout
!= -1) {
1858 clock_interval_to_deadline(uap
->timeout
, NSEC_PER_MSEC
,
1859 &kectx
->kec_deadline
);
1862 error
= kqueue_scan(kq
, kectx
->kec_process_flags
, kectx
, poll_callback
);
1863 rfds
= kectx
->kec_process_noutputs
;
1866 OSBitAndAtomic(~((uint32_t)P_SELECT
), &p
->p_flag
);
1867 /* poll is not restarted after signals... */
1868 if (error
== ERESTART
) {
1872 error
= copyout(fds
, uap
->fds
, nfds
* sizeof(struct pollfd
));
1886 poll_callback(struct kevent_qos_s
*kevp
, kevent_ctx_t kectx
)
1888 struct pollfd
*fds
= CAST_DOWN(struct pollfd
*, kevp
->udata
);
1889 short prev_revents
= fds
->revents
;
1892 /* convert the results back into revents */
1893 if (kevp
->flags
& EV_EOF
) {
1894 fds
->revents
|= POLLHUP
;
1896 if (kevp
->flags
& EV_ERROR
) {
1897 fds
->revents
|= POLLERR
;
1900 switch (kevp
->filter
) {
1902 if (fds
->revents
& POLLHUP
) {
1903 mask
= (POLLIN
| POLLRDNORM
| POLLPRI
| POLLRDBAND
);
1905 mask
= (POLLIN
| POLLRDNORM
);
1906 if (kevp
->flags
& EV_OOBAND
) {
1907 mask
|= (POLLPRI
| POLLRDBAND
);
1910 fds
->revents
|= (fds
->events
& mask
);
1914 if (!(fds
->revents
& POLLHUP
)) {
1915 fds
->revents
|= (fds
->events
& (POLLOUT
| POLLWRNORM
| POLLWRBAND
));
1920 if (kevp
->fflags
& NOTE_EXTEND
) {
1921 fds
->revents
|= (fds
->events
& POLLEXTEND
);
1923 if (kevp
->fflags
& NOTE_ATTRIB
) {
1924 fds
->revents
|= (fds
->events
& POLLATTRIB
);
1926 if (kevp
->fflags
& NOTE_LINK
) {
1927 fds
->revents
|= (fds
->events
& POLLNLINK
);
1929 if (kevp
->fflags
& NOTE_WRITE
) {
1930 fds
->revents
|= (fds
->events
& POLLWRITE
);
1935 if (fds
->revents
!= 0 && prev_revents
== 0) {
1936 kectx
->kec_process_noutputs
++;
1943 seltrue(__unused dev_t dev
, __unused
int flag
, __unused
struct proc
*p
)
1951 * Count the number of bits set in the input bit vector, and establish an
1952 * outstanding fp->f_iocount for each of the descriptors which will be in
1953 * use in the select operation.
1955 * Parameters: p The process doing the select
1956 * ibits The input bit vector
1957 * nfd The number of fd's in the vector
1958 * countp Pointer to where to store the bit count
1960 * Returns: 0 Success
1961 * EIO Bad per process open file table
1962 * EBADF One of the bits in the input bit vector
1963 * references an invalid fd
1965 * Implicit: *countp (modified) Count of fd's
1967 * Notes: This function is the first pass under the proc_fdlock() that
1968 * permits us to recognize invalid descriptors in the bit vector;
1969 * the may, however, not remain valid through the drop and
1970 * later reacquisition of the proc_fdlock().
1973 selcount(struct proc
*p
, u_int32_t
*ibits
, int nfd
, int *countp
)
1975 struct filedesc
*fdp
= p
->p_fd
;
1978 struct fileproc
*fp
;
1984 int need_wakeup
= 0;
1987 * Problems when reboot; due to MacOSX signal probs
1988 * in Beaker1C ; verify that the p->p_fd is valid
1994 nw
= howmany(nfd
, NFDBITS
);
1997 for (msk
= 0; msk
< 3; msk
++) {
1998 iptr
= (u_int32_t
*)&ibits
[msk
* nw
];
1999 for (i
= 0; i
< nfd
; i
+= NFDBITS
) {
2000 bits
= iptr
[i
/ NFDBITS
];
2001 while ((j
= ffs(bits
)) && (fd
= i
+ --j
) < nfd
) {
2004 if (fd
< fdp
->fd_nfiles
) {
2005 fp
= fdp
->fd_ofiles
[fd
];
2011 (fdp
->fd_ofileflags
[fd
] & UF_RESERVED
)) {
2016 os_ref_retain_locked(&fp
->f_iocount
);
2032 /* Ignore error return; it's already EBADF */
2033 (void)seldrop_locked(p
, ibits
, nfd
, n
, &need_wakeup
, 1);
2038 wakeup(&p
->p_fpdrainwait
);
2047 * Drop outstanding wait queue references set up during selscan(); drop the
2048 * outstanding per fileproc f_iocount() picked up during the selcount().
2050 * Parameters: p Process performing the select
2051 * ibits Input bit bector of fd's
2052 * nfd Number of fd's
2053 * lim Limit to number of vector entries to
2054 * consider, or -1 for "all"
2056 * need_wakeup Pointer to flag to set to do a wakeup
2057 * if f_iocont on any descriptor goes to 0
2059 * Returns: 0 Success
2060 * EBADF One or more fds in the bit vector
2061 * were invalid, but the rest
2062 * were successfully dropped
2064 * Notes: An fd make become bad while the proc_fdlock() is not held,
2065 * if a multithreaded application closes the fd out from under
2066 * the in progress select. In this case, we still have to
2067 * clean up after the set up on the remaining fds.
2070 seldrop_locked(struct proc
*p
, u_int32_t
*ibits
, int nfd
, int lim
, int *need_wakeup
, int fromselcount
)
2072 struct filedesc
*fdp
= p
->p_fd
;
2073 int msk
, i
, j
, nc
, fd
;
2075 struct fileproc
*fp
;
2080 uthread_t uth
= get_bsdthread_info(current_thread());
2081 struct _select_data
*seldata
;
2086 * Problems when reboot; due to MacOSX signal probs
2087 * in Beaker1C ; verify that the p->p_fd is valid
2093 nw
= howmany(nfd
, NFDBITS
);
2094 seldata
= &uth
->uu_save
.uus_select_data
;
2097 for (msk
= 0; msk
< 3; msk
++) {
2098 iptr
= (u_int32_t
*)&ibits
[msk
* nw
];
2099 for (i
= 0; i
< nfd
; i
+= NFDBITS
) {
2100 bits
= iptr
[i
/ NFDBITS
];
2101 while ((j
= ffs(bits
)) && (fd
= i
+ --j
) < nfd
) {
2103 fp
= fdp
->fd_ofiles
[fd
];
2105 * If we've already dropped as many as were
2106 * counted/scanned, then we are done.
2108 if ((fromselcount
!= 0) && (++dropcount
> lim
)) {
2113 * unlink even potentially NULL fileprocs.
2114 * If the FD was closed from under us, we
2115 * still need to cleanup the waitq links!
2118 seldata
->wqp
? seldata
->wqp
[nc
] : 0,
2124 /* skip (now) bad fds */
2129 const os_ref_count_t refc
= os_ref_release_locked(&fp
->f_iocount
);
2131 panic("f_iocount overdecrement!");
2136 * The last iocount is responsible for clearing
2137 * selconfict flag - even if we didn't set it -
2138 * and is also responsible for waking up anyone
2139 * waiting on iocounts to drain.
2141 if (fp
->f_flags
& FP_SELCONFLICT
) {
2142 fp
->f_flags
&= ~FP_SELCONFLICT
;
2144 if (p
->p_fpdrainwait
) {
2145 p
->p_fpdrainwait
= 0;
2158 seldrop(struct proc
*p
, u_int32_t
*ibits
, int nfd
)
2161 int need_wakeup
= 0;
2164 error
= seldrop_locked(p
, ibits
, nfd
, nfd
, &need_wakeup
, 0);
2167 wakeup(&p
->p_fpdrainwait
);
2173 * Record a select request.
2176 selrecord(__unused
struct proc
*selector
, struct selinfo
*sip
, void *s_data
)
2178 thread_t cur_act
= current_thread();
2179 struct uthread
* ut
= get_bsdthread_info(cur_act
);
2180 /* on input, s_data points to the 64-bit ID of a reserved link object */
2181 uint64_t *reserved_link
= (uint64_t *)s_data
;
2183 /* need to look at collisions */
2185 /*do not record if this is second pass of select */
2190 if ((sip
->si_flags
& SI_INITED
) == 0) {
2191 waitq_init(&sip
->si_waitq
, SYNC_POLICY_FIFO
);
2192 sip
->si_flags
|= SI_INITED
;
2193 sip
->si_flags
&= ~SI_CLEAR
;
2196 if (sip
->si_flags
& SI_RECORDED
) {
2197 sip
->si_flags
|= SI_COLL
;
2199 sip
->si_flags
&= ~SI_COLL
;
2202 sip
->si_flags
|= SI_RECORDED
;
2203 /* note: this checks for pre-existing linkage */
2204 waitq_link(&sip
->si_waitq
, ut
->uu_wqset
,
2205 WAITQ_SHOULD_LOCK
, reserved_link
);
2208 * Always consume the reserved link.
2209 * We can always call waitq_link_release() safely because if
2210 * waitq_link is successful, it consumes the link and resets the
2211 * value to 0, in which case our call to release becomes a no-op.
2212 * If waitq_link fails, then the following release call will actually
2213 * release the reserved link object.
2215 waitq_link_release(*reserved_link
);
2219 * Use the s_data pointer as an output parameter as well
2220 * This avoids changing the prototype for this function which is
2221 * used by many kexts. We need to surface the waitq object
2222 * associated with the selinfo we just added to the thread's select
2223 * set. New waitq sets do not have back-pointers to set members, so
2224 * the only way to clear out set linkage objects is to go from the
2225 * waitq to the set. We use a memcpy because s_data could be
2226 * pointing to an unaligned value on the stack
2227 * (especially on 32-bit systems)
2229 void *wqptr
= (void *)&sip
->si_waitq
;
2230 memcpy((void *)s_data
, (void *)&wqptr
, sizeof(void *));
2236 selwakeup(struct selinfo
*sip
)
2238 if ((sip
->si_flags
& SI_INITED
) == 0) {
2242 if (sip
->si_flags
& SI_COLL
) {
2244 sip
->si_flags
&= ~SI_COLL
;
2246 /* will not support */
2247 //wakeup((caddr_t)&selwait);
2251 if (sip
->si_flags
& SI_RECORDED
) {
2252 waitq_wakeup64_all(&sip
->si_waitq
, NO_EVENT64
,
2253 THREAD_AWAKENED
, WAITQ_ALL_PRIORITIES
);
2254 sip
->si_flags
&= ~SI_RECORDED
;
2259 selthreadclear(struct selinfo
*sip
)
2263 if ((sip
->si_flags
& SI_INITED
) == 0) {
2266 if (sip
->si_flags
& SI_RECORDED
) {
2268 sip
->si_flags
&= ~(SI_RECORDED
| SI_COLL
);
2270 sip
->si_flags
|= SI_CLEAR
;
2271 sip
->si_flags
&= ~SI_INITED
;
2273 wq
= &sip
->si_waitq
;
2276 * Higher level logic may have a handle on this waitq's prepost ID,
2277 * but that's OK because the waitq_deinit will remove/invalidate the
2278 * prepost object (as well as mark the waitq invalid). This de-couples
2279 * us from any callers that may have a handle to this waitq via the
2288 #define DBG_POST 0x10
2289 #define DBG_WATCH 0x11
2290 #define DBG_WAIT 0x12
2291 #define DBG_MOD 0x13
2292 #define DBG_EWAKEUP 0x14
2293 #define DBG_ENQUEUE 0x15
2294 #define DBG_DEQUEUE 0x16
2296 #define DBG_MISC_POST MISCDBG_CODE(DBG_EVENT,DBG_POST)
2297 #define DBG_MISC_WATCH MISCDBG_CODE(DBG_EVENT,DBG_WATCH)
2298 #define DBG_MISC_WAIT MISCDBG_CODE(DBG_EVENT,DBG_WAIT)
2299 #define DBG_MISC_MOD MISCDBG_CODE(DBG_EVENT,DBG_MOD)
2300 #define DBG_MISC_EWAKEUP MISCDBG_CODE(DBG_EVENT,DBG_EWAKEUP)
2301 #define DBG_MISC_ENQUEUE MISCDBG_CODE(DBG_EVENT,DBG_ENQUEUE)
2302 #define DBG_MISC_DEQUEUE MISCDBG_CODE(DBG_EVENT,DBG_DEQUEUE)
2305 #define EVPROCDEQUE(p, evq) do { \
2307 if (evq->ee_flags & EV_QUEUED) { \
2308 TAILQ_REMOVE(&p->p_evlist, evq, ee_plist); \
2309 evq->ee_flags &= ~EV_QUEUED; \
2316 * called upon socket close. deque and free all events for
2317 * the socket... socket must be locked by caller.
2320 evsofree(struct socket
*sp
)
2322 struct eventqelt
*evq
, *next
;
2329 for (evq
= sp
->so_evlist
.tqh_first
; evq
!= NULL
; evq
= next
) {
2330 next
= evq
->ee_slist
.tqe_next
;
2333 if (evq
->ee_flags
& EV_QUEUED
) {
2334 EVPROCDEQUE(p
, evq
);
2336 TAILQ_REMOVE(&sp
->so_evlist
, evq
, ee_slist
); // remove from socket q
2343 * called upon pipe close. deque and free all events for
2344 * the pipe... pipe must be locked by caller
2347 evpipefree(struct pipe
*cpipe
)
2349 struct eventqelt
*evq
, *next
;
2352 for (evq
= cpipe
->pipe_evlist
.tqh_first
; evq
!= NULL
; evq
= next
) {
2353 next
= evq
->ee_slist
.tqe_next
;
2356 EVPROCDEQUE(p
, evq
);
2358 TAILQ_REMOVE(&cpipe
->pipe_evlist
, evq
, ee_slist
); // remove from pipe q
2365 * enqueue this event if it's not already queued. wakeup
2366 * the proc if we do queue this event to it...
2367 * entered with proc lock held... we drop it before
2368 * doing the wakeup and return in that state
2371 evprocenque(struct eventqelt
*evq
)
2378 KERNEL_DEBUG(DBG_MISC_ENQUEUE
| DBG_FUNC_START
, (uint32_t)evq
, evq
->ee_flags
, evq
->ee_eventmask
, 0, 0);
2382 if (evq
->ee_flags
& EV_QUEUED
) {
2385 KERNEL_DEBUG(DBG_MISC_ENQUEUE
| DBG_FUNC_END
, 0, 0, 0, 0, 0);
2388 evq
->ee_flags
|= EV_QUEUED
;
2390 TAILQ_INSERT_TAIL(&p
->p_evlist
, evq
, ee_plist
);
2394 wakeup(&p
->p_evlist
);
2396 KERNEL_DEBUG(DBG_MISC_ENQUEUE
| DBG_FUNC_END
, 0, 0, 0, 0, 0);
2401 * pipe lock must be taken by the caller
2404 postpipeevent(struct pipe
*pipep
, int event
)
2407 struct eventqelt
*evq
;
2409 if (pipep
== NULL
) {
2412 KERNEL_DEBUG(DBG_MISC_POST
| DBG_FUNC_START
, event
, 0, 0, 1, 0);
2414 for (evq
= pipep
->pipe_evlist
.tqh_first
;
2415 evq
!= NULL
; evq
= evq
->ee_slist
.tqe_next
) {
2416 if (evq
->ee_eventmask
== 0) {
2421 switch (event
& (EV_RWBYTES
| EV_RCLOSED
| EV_WCLOSED
)) {
2423 if ((evq
->ee_eventmask
& EV_RE
) && pipep
->pipe_buffer
.cnt
) {
2425 evq
->ee_req
.er_rcnt
= pipep
->pipe_buffer
.cnt
;
2427 if ((evq
->ee_eventmask
& EV_WR
) &&
2428 (MAX(pipep
->pipe_buffer
.size
, PIPE_SIZE
) - pipep
->pipe_buffer
.cnt
) >= PIPE_BUF
) {
2429 if (pipep
->pipe_state
& PIPE_EOF
) {
2430 mask
|= EV_WR
| EV_RESET
;
2434 evq
->ee_req
.er_wcnt
= MAX(pipep
->pipe_buffer
.size
, PIPE_SIZE
) - pipep
->pipe_buffer
.cnt
;
2440 if ((evq
->ee_eventmask
& EV_RE
)) {
2441 mask
|= EV_RE
| EV_RCLOSED
;
2443 if ((evq
->ee_eventmask
& EV_WR
)) {
2444 mask
|= EV_WR
| EV_WCLOSED
;
2453 * disarm... postevents are nops until this event is 'read' via
2454 * waitevent and then re-armed via modwatch
2456 evq
->ee_eventmask
= 0;
2459 * since events are disarmed until after the waitevent
2460 * the ee_req.er_xxxx fields can't change once we've
2461 * inserted this event into the proc queue...
2462 * therefore, the waitevent will see a 'consistent'
2463 * snapshot of the event, even though it won't hold
2464 * the pipe lock, and we're updating the event outside
2465 * of the proc lock, which it will hold
2467 evq
->ee_req
.er_eventbits
|= mask
;
2469 KERNEL_DEBUG(DBG_MISC_POST
, (uint32_t)evq
, evq
->ee_req
.er_eventbits
, mask
, 1, 0);
2474 KERNEL_DEBUG(DBG_MISC_POST
| DBG_FUNC_END
, 0, 0, 0, 1, 0);
2479 * given either a sockbuf or a socket run down the
2480 * event list and queue ready events found...
2481 * the socket must be locked by the caller
2484 postevent(struct socket
*sp
, struct sockbuf
*sb
, int event
)
2487 struct eventqelt
*evq
;
2497 KERNEL_DEBUG(DBG_MISC_POST
| DBG_FUNC_START
, (int)sp
, event
, 0, 0, 0);
2499 for (evq
= sp
->so_evlist
.tqh_first
;
2500 evq
!= NULL
; evq
= evq
->ee_slist
.tqe_next
) {
2501 if (evq
->ee_eventmask
== 0) {
2506 /* ready for reading:
2507 * - byte cnt >= receive low water mark
2508 * - read-half of conn closed
2509 * - conn pending for listening sock
2510 * - socket error pending
2513 * - byte cnt avail >= send low water mark
2514 * - write half of conn closed
2515 * - socket error pending
2516 * - non-blocking conn completed successfully
2519 * - out of band data
2520 * - sock at out of band mark
2523 switch (event
& EV_DMASK
) {
2525 if ((evq
->ee_eventmask
& EV_EX
)) {
2526 if (sp
->so_oobmark
|| ((sp
->so_state
& SS_RCVATMARK
))) {
2527 mask
|= EV_EX
| EV_OOB
;
2532 case EV_RWBYTES
| EV_OOB
:
2533 if ((evq
->ee_eventmask
& EV_EX
)) {
2534 if (sp
->so_oobmark
|| ((sp
->so_state
& SS_RCVATMARK
))) {
2535 mask
|= EV_EX
| EV_OOB
;
2539 * fall into the next case
2542 if ((evq
->ee_eventmask
& EV_RE
) && soreadable(sp
)) {
2543 /* for AFP/OT purposes; may go away in future */
2544 if ((SOCK_DOM(sp
) == PF_INET
||
2545 SOCK_DOM(sp
) == PF_INET6
) &&
2546 SOCK_PROTO(sp
) == IPPROTO_TCP
&&
2547 (sp
->so_error
== ECONNREFUSED
||
2548 sp
->so_error
== ECONNRESET
)) {
2549 if (sp
->so_pcb
== NULL
||
2550 sotoinpcb(sp
)->inp_state
==
2552 (tp
= sototcpcb(sp
)) == NULL
||
2553 tp
->t_state
== TCPS_CLOSED
) {
2554 mask
|= EV_RE
| EV_RESET
;
2559 evq
->ee_req
.er_rcnt
= sp
->so_rcv
.sb_cc
;
2561 if (sp
->so_state
& SS_CANTRCVMORE
) {
2566 if ((evq
->ee_eventmask
& EV_WR
) && sowriteable(sp
)) {
2567 /* for AFP/OT purposes; may go away in future */
2568 if ((SOCK_DOM(sp
) == PF_INET
||
2569 SOCK_DOM(sp
) == PF_INET6
) &&
2570 SOCK_PROTO(sp
) == IPPROTO_TCP
&&
2571 (sp
->so_error
== ECONNREFUSED
||
2572 sp
->so_error
== ECONNRESET
)) {
2573 if (sp
->so_pcb
== NULL
||
2574 sotoinpcb(sp
)->inp_state
==
2576 (tp
= sototcpcb(sp
)) == NULL
||
2577 tp
->t_state
== TCPS_CLOSED
) {
2578 mask
|= EV_WR
| EV_RESET
;
2583 evq
->ee_req
.er_wcnt
= sbspace(&sp
->so_snd
);
2588 if ((evq
->ee_eventmask
& EV_RE
)) {
2589 mask
|= EV_RE
| EV_RCONN
;
2590 evq
->ee_req
.er_rcnt
= sp
->so_qlen
+ 1; // incl this one
2595 if ((evq
->ee_eventmask
& EV_WR
)) {
2596 mask
|= EV_WR
| EV_WCONN
;
2601 if ((evq
->ee_eventmask
& EV_RE
)) {
2602 mask
|= EV_RE
| EV_RCLOSED
;
2607 if ((evq
->ee_eventmask
& EV_WR
)) {
2608 mask
|= EV_WR
| EV_WCLOSED
;
2613 if (evq
->ee_eventmask
& EV_RE
) {
2614 mask
|= EV_RE
| EV_FIN
;
2620 if (evq
->ee_eventmask
& EV_RE
) {
2621 mask
|= EV_RE
| event
;
2623 if (evq
->ee_eventmask
& EV_WR
) {
2624 mask
|= EV_WR
| event
;
2629 KERNEL_DEBUG(DBG_MISC_POST
| DBG_FUNC_END
, (int)sp
, -1, 0, 0, 0);
2633 KERNEL_DEBUG(DBG_MISC_POST
, (int)evq
, evq
->ee_eventmask
, evq
->ee_req
.er_eventbits
, mask
, 0);
2637 * disarm... postevents are nops until this event is 'read' via
2638 * waitevent and then re-armed via modwatch
2640 evq
->ee_eventmask
= 0;
2643 * since events are disarmed until after the waitevent
2644 * the ee_req.er_xxxx fields can't change once we've
2645 * inserted this event into the proc queue...
2646 * since waitevent can't see this event until we
2647 * enqueue it, waitevent will see a 'consistent'
2648 * snapshot of the event, even though it won't hold
2649 * the socket lock, and we're updating the event outside
2650 * of the proc lock, which it will hold
2652 evq
->ee_req
.er_eventbits
|= mask
;
2657 KERNEL_DEBUG(DBG_MISC_POST
| DBG_FUNC_END
, (int)sp
, 0, 0, 0, 0);
2659 #endif /* SOCKETS */
2663 * watchevent system call. user passes us an event to watch
2664 * for. we malloc an event object, initialize it, and queue
2665 * it to the open socket. when the event occurs, postevent()
2666 * will enque it back to our proc where we can retrieve it
2669 * should this prevent duplicate events on same socket?
2672 * ENOMEM No memory for operation
2676 watchevent(proc_t p
, struct watchevent_args
*uap
, __unused
int *retval
)
2678 struct eventqelt
*evq
= (struct eventqelt
*)0;
2679 struct eventqelt
*np
= NULL
;
2680 struct eventreq64
*erp
;
2681 struct fileproc
*fp
= NULL
;
2684 KERNEL_DEBUG(DBG_MISC_WATCH
| DBG_FUNC_START
, 0, 0, 0, 0, 0);
2686 // get a qelt and fill with users req
2687 MALLOC(evq
, struct eventqelt
*, sizeof(struct eventqelt
), M_TEMP
, M_WAITOK
);
2694 // get users request pkt
2696 if (IS_64BIT_PROCESS(p
)) {
2697 error
= copyin(uap
->u_req
, (caddr_t
)erp
, sizeof(struct eventreq64
));
2699 struct eventreq32 er32
;
2701 error
= copyin(uap
->u_req
, (caddr_t
)&er32
, sizeof(struct eventreq32
));
2704 * the user only passes in the
2705 * er_type, er_handle and er_data...
2706 * the other fields are initialized
2707 * below, so don't bother to copy
2709 erp
->er_type
= er32
.er_type
;
2710 erp
->er_handle
= er32
.er_handle
;
2711 erp
->er_data
= (user_addr_t
)er32
.er_data
;
2716 KERNEL_DEBUG(DBG_MISC_WATCH
| DBG_FUNC_END
, error
, 0, 0, 0, 0);
2720 KERNEL_DEBUG(DBG_MISC_WATCH
, erp
->er_handle
, uap
->u_eventmask
, (uint32_t)evq
, 0, 0);
2722 // validate, freeing qelt if errors
2726 if (erp
->er_type
!= EV_FD
) {
2728 } else if ((error
= fp_lookup(p
, erp
->er_handle
, &fp
, 1)) != 0) {
2731 } else if (fp
->f_type
== DTYPE_SOCKET
) {
2732 socket_lock((struct socket
*)fp
->f_data
, 1);
2733 np
= ((struct socket
*)fp
->f_data
)->so_evlist
.tqh_first
;
2734 #endif /* SOCKETS */
2735 } else if (fp
->f_type
== DTYPE_PIPE
) {
2736 PIPE_LOCK((struct pipe
*)fp
->f_data
);
2737 np
= ((struct pipe
*)fp
->f_data
)->pipe_evlist
.tqh_first
;
2739 fp_drop(p
, erp
->er_handle
, fp
, 1);
2747 KERNEL_DEBUG(DBG_MISC_WATCH
| DBG_FUNC_END
, error
, 0, 0, 0, 0);
2752 * only allow one watch per file per proc
2754 for (; np
!= NULL
; np
= np
->ee_slist
.tqe_next
) {
2755 if (np
->ee_proc
== p
) {
2757 if (fp
->f_type
== DTYPE_SOCKET
) {
2758 socket_unlock((struct socket
*)fp
->f_data
, 1);
2760 #endif /* SOCKETS */
2761 PIPE_UNLOCK((struct pipe
*)fp
->f_data
);
2762 fp_drop(p
, erp
->er_handle
, fp
, 0);
2765 KERNEL_DEBUG(DBG_MISC_WATCH
| DBG_FUNC_END
, EINVAL
, 0, 0, 0, 0);
2769 erp
->er_ecnt
= erp
->er_rcnt
= erp
->er_wcnt
= erp
->er_eventbits
= 0;
2771 evq
->ee_eventmask
= uap
->u_eventmask
& EV_MASK
;
2775 if (fp
->f_type
== DTYPE_SOCKET
) {
2776 TAILQ_INSERT_TAIL(&((struct socket
*)fp
->f_data
)->so_evlist
, evq
, ee_slist
);
2777 postevent((struct socket
*)fp
->f_data
, 0, EV_RWBYTES
); // catch existing events
2779 socket_unlock((struct socket
*)fp
->f_data
, 1);
2781 #endif /* SOCKETS */
2783 TAILQ_INSERT_TAIL(&((struct pipe
*)fp
->f_data
)->pipe_evlist
, evq
, ee_slist
);
2784 postpipeevent((struct pipe
*)fp
->f_data
, EV_RWBYTES
);
2786 PIPE_UNLOCK((struct pipe
*)fp
->f_data
);
2788 fp_drop_event(p
, erp
->er_handle
, fp
);
2790 KERNEL_DEBUG(DBG_MISC_WATCH
| DBG_FUNC_END
, 0, 0, 0, 0, 0);
2797 * waitevent system call.
2798 * grabs the next waiting event for this proc and returns
2799 * it. if no events, user can request to sleep with timeout
2800 * or without or poll mode
2801 * ((tv != NULL && interval == 0) || tv == -1)
2804 waitevent(proc_t p
, struct waitevent_args
*uap
, int *retval
)
2807 struct eventqelt
*evq
;
2808 struct eventreq64
*erp
;
2809 uint64_t abstime
, interval
;
2810 boolean_t fast_poll
= FALSE
;
2812 struct eventreq64 er64
;
2813 struct eventreq32 er32
;
2821 * check for fast poll method
2823 if (IS_64BIT_PROCESS(p
)) {
2824 if (uap
->tv
== (user_addr_t
)-1) {
2827 } else if (uap
->tv
== (user_addr_t
)((uint32_t)-1)) {
2831 if (fast_poll
== TRUE
) {
2832 if (p
->p_evlist
.tqh_first
== NULL
) {
2833 KERNEL_DEBUG(DBG_MISC_WAIT
| DBG_FUNC_NONE
, -1, 0, 0, 0, 0);
2843 if (IS_64BIT_PROCESS(p
)) {
2844 struct user64_timeval atv64
;
2845 error
= copyin(uap
->tv
, (caddr_t
)&atv64
, sizeof(atv64
));
2846 /* Loses resolution - assume timeout < 68 years */
2847 atv
.tv_sec
= atv64
.tv_sec
;
2848 atv
.tv_usec
= atv64
.tv_usec
;
2850 struct user32_timeval atv32
;
2851 error
= copyin(uap
->tv
, (caddr_t
)&atv32
, sizeof(atv32
));
2852 atv
.tv_sec
= atv32
.tv_sec
;
2853 atv
.tv_usec
= atv32
.tv_usec
;
2859 if (itimerfix(&atv
)) {
2863 interval
= tvtoabstime(&atv
);
2865 KERNEL_DEBUG(DBG_MISC_WAIT
| DBG_FUNC_START
, 0, 0, 0, 0, 0);
2869 if ((evq
= p
->p_evlist
.tqh_first
) != NULL
) {
2871 * found one... make a local copy while it's still on the queue
2872 * to prevent it from changing while in the midst of copying
2873 * don't want to hold the proc lock across a copyout because
2874 * it might block on a page fault at the target in user space
2878 if (IS_64BIT_PROCESS(p
)) {
2879 bcopy((caddr_t
)erp
, (caddr_t
)&uer
.er64
, sizeof(struct eventreq64
));
2881 uer
.er32
.er_type
= erp
->er_type
;
2882 uer
.er32
.er_handle
= erp
->er_handle
;
2883 uer
.er32
.er_data
= (uint32_t)erp
->er_data
;
2884 uer
.er32
.er_ecnt
= erp
->er_ecnt
;
2885 uer
.er32
.er_rcnt
= erp
->er_rcnt
;
2886 uer
.er32
.er_wcnt
= erp
->er_wcnt
;
2887 uer
.er32
.er_eventbits
= erp
->er_eventbits
;
2889 TAILQ_REMOVE(&p
->p_evlist
, evq
, ee_plist
);
2891 evq
->ee_flags
&= ~EV_QUEUED
;
2895 if (IS_64BIT_PROCESS(p
)) {
2896 error
= copyout((caddr_t
)&uer
.er64
, uap
->u_req
, sizeof(struct eventreq64
));
2898 error
= copyout((caddr_t
)&uer
.er32
, uap
->u_req
, sizeof(struct eventreq32
));
2901 KERNEL_DEBUG(DBG_MISC_WAIT
| DBG_FUNC_END
, error
,
2902 evq
->ee_req
.er_handle
, evq
->ee_req
.er_eventbits
, (uint32_t)evq
, 0);
2905 if (uap
->tv
&& interval
== 0) {
2907 *retval
= 1; // poll failed
2909 KERNEL_DEBUG(DBG_MISC_WAIT
| DBG_FUNC_END
, error
, 0, 0, 0, 0);
2912 if (interval
!= 0) {
2913 clock_absolutetime_interval_to_deadline(interval
, &abstime
);
2918 KERNEL_DEBUG(DBG_MISC_WAIT
, 1, (uint32_t)&p
->p_evlist
, 0, 0, 0);
2920 error
= msleep1(&p
->p_evlist
, &p
->p_mlock
, (PSOCK
| PCATCH
), "waitevent", abstime
);
2922 KERNEL_DEBUG(DBG_MISC_WAIT
, 2, (uint32_t)&p
->p_evlist
, 0, 0, 0);
2927 if (error
== ERESTART
) {
2930 if (error
== EWOULDBLOCK
) {
2937 KERNEL_DEBUG(DBG_MISC_WAIT
| DBG_FUNC_END
, 0, 0, 0, 0, 0);
2943 * modwatch system call. user passes in event to modify.
2944 * if we find it we reset the event bits and que/deque event
2948 modwatch(proc_t p
, struct modwatch_args
*uap
, __unused
int *retval
)
2950 struct eventreq64 er
;
2951 struct eventreq64
*erp
= &er
;
2952 struct eventqelt
*evq
= NULL
; /* protected by error return */
2954 struct fileproc
*fp
;
2957 KERNEL_DEBUG(DBG_MISC_MOD
| DBG_FUNC_START
, 0, 0, 0, 0, 0);
2960 * get user's request pkt
2961 * just need the er_type and er_handle which sit above the
2962 * problematic er_data (32/64 issue)... so only copy in
2965 if ((error
= copyin(uap
->u_req
, (caddr_t
)erp
, sizeof(er
.er_type
) + sizeof(er
.er_handle
)))) {
2966 KERNEL_DEBUG(DBG_MISC_MOD
| DBG_FUNC_END
, error
, 0, 0, 0, 0);
2971 if (erp
->er_type
!= EV_FD
) {
2973 } else if ((error
= fp_lookup(p
, erp
->er_handle
, &fp
, 1)) != 0) {
2976 } else if (fp
->f_type
== DTYPE_SOCKET
) {
2977 socket_lock((struct socket
*)fp
->f_data
, 1);
2978 evq
= ((struct socket
*)fp
->f_data
)->so_evlist
.tqh_first
;
2979 #endif /* SOCKETS */
2980 } else if (fp
->f_type
== DTYPE_PIPE
) {
2981 PIPE_LOCK((struct pipe
*)fp
->f_data
);
2982 evq
= ((struct pipe
*)fp
->f_data
)->pipe_evlist
.tqh_first
;
2984 fp_drop(p
, erp
->er_handle
, fp
, 1);
2990 KERNEL_DEBUG(DBG_MISC_MOD
| DBG_FUNC_END
, error
, 0, 0, 0, 0);
2994 if ((uap
->u_eventmask
== EV_RM
) && (fp
->f_flags
& FP_WAITEVENT
)) {
2995 fp
->f_flags
&= ~FP_WAITEVENT
;
2999 // locate event if possible
3000 for (; evq
!= NULL
; evq
= evq
->ee_slist
.tqe_next
) {
3001 if (evq
->ee_proc
== p
) {
3007 if (fp
->f_type
== DTYPE_SOCKET
) {
3008 socket_unlock((struct socket
*)fp
->f_data
, 1);
3010 #endif /* SOCKETS */
3011 PIPE_UNLOCK((struct pipe
*)fp
->f_data
);
3012 fp_drop(p
, erp
->er_handle
, fp
, 0);
3013 KERNEL_DEBUG(DBG_MISC_MOD
| DBG_FUNC_END
, EINVAL
, 0, 0, 0, 0);
3016 KERNEL_DEBUG(DBG_MISC_MOD
, erp
->er_handle
, uap
->u_eventmask
, (uint32_t)evq
, 0, 0);
3018 if (uap
->u_eventmask
== EV_RM
) {
3019 EVPROCDEQUE(p
, evq
);
3022 if (fp
->f_type
== DTYPE_SOCKET
) {
3023 TAILQ_REMOVE(&((struct socket
*)fp
->f_data
)->so_evlist
, evq
, ee_slist
);
3024 socket_unlock((struct socket
*)fp
->f_data
, 1);
3026 #endif /* SOCKETS */
3028 TAILQ_REMOVE(&((struct pipe
*)fp
->f_data
)->pipe_evlist
, evq
, ee_slist
);
3029 PIPE_UNLOCK((struct pipe
*)fp
->f_data
);
3031 fp_drop(p
, erp
->er_handle
, fp
, 0);
3033 KERNEL_DEBUG(DBG_MISC_MOD
| DBG_FUNC_END
, 0, 0, 0, 0, 0);
3036 switch (uap
->u_eventmask
& EV_MASK
) {
3053 case EV_EX
| EV_RE
| EV_WR
:
3054 flag
= EV_OOB
| EV_RWBYTES
;
3059 if (fp
->f_type
== DTYPE_SOCKET
) {
3060 socket_unlock((struct socket
*)fp
->f_data
, 1);
3062 #endif /* SOCKETS */
3063 PIPE_UNLOCK((struct pipe
*)fp
->f_data
);
3064 fp_drop(p
, erp
->er_handle
, fp
, 0);
3065 KERNEL_DEBUG(DBG_MISC_WATCH
| DBG_FUNC_END
, EINVAL
, 0, 0, 0, 0);
3069 * since we're holding the socket/pipe lock, the event
3070 * cannot go from the unqueued state to the queued state
3071 * however, it can go from the queued state to the unqueued state
3072 * since that direction is protected by the proc_lock...
3073 * so do a quick check for EV_QUEUED w/o holding the proc lock
3074 * since by far the common case will be NOT EV_QUEUED, this saves
3075 * us taking the proc_lock the majority of the time
3077 if (evq
->ee_flags
& EV_QUEUED
) {
3079 * EVPROCDEQUE will recheck the state after it grabs the proc_lock
3081 EVPROCDEQUE(p
, evq
);
3084 * while the event is off the proc queue and
3085 * we're holding the socket/pipe lock
3086 * it's safe to update these fields...
3088 evq
->ee_req
.er_eventbits
= 0;
3089 evq
->ee_eventmask
= uap
->u_eventmask
& EV_MASK
;
3092 if (fp
->f_type
== DTYPE_SOCKET
) {
3093 postevent((struct socket
*)fp
->f_data
, 0, flag
);
3094 socket_unlock((struct socket
*)fp
->f_data
, 1);
3096 #endif /* SOCKETS */
3098 postpipeevent((struct pipe
*)fp
->f_data
, flag
);
3099 PIPE_UNLOCK((struct pipe
*)fp
->f_data
);
3101 fp_drop(p
, erp
->er_handle
, fp
, 0);
3102 KERNEL_DEBUG(DBG_MISC_MOD
| DBG_FUNC_END
, evq
->ee_req
.er_handle
, evq
->ee_eventmask
, (uint32_t)fp
->f_data
, flag
, 0);
3106 /* this routine is called from the close of fd with proc_fdlock held */
3108 waitevent_close(struct proc
*p
, struct fileproc
*fp
)
3110 struct eventqelt
*evq
;
3113 fp
->f_flags
&= ~FP_WAITEVENT
;
3116 if (fp
->f_type
== DTYPE_SOCKET
) {
3117 socket_lock((struct socket
*)fp
->f_data
, 1);
3118 evq
= ((struct socket
*)fp
->f_data
)->so_evlist
.tqh_first
;
3120 #endif /* SOCKETS */
3121 if (fp
->f_type
== DTYPE_PIPE
) {
3122 PIPE_LOCK((struct pipe
*)fp
->f_data
);
3123 evq
= ((struct pipe
*)fp
->f_data
)->pipe_evlist
.tqh_first
;
3130 // locate event if possible
3131 for (; evq
!= NULL
; evq
= evq
->ee_slist
.tqe_next
) {
3132 if (evq
->ee_proc
== p
) {
3138 if (fp
->f_type
== DTYPE_SOCKET
) {
3139 socket_unlock((struct socket
*)fp
->f_data
, 1);
3141 #endif /* SOCKETS */
3142 PIPE_UNLOCK((struct pipe
*)fp
->f_data
);
3148 EVPROCDEQUE(p
, evq
);
3151 if (fp
->f_type
== DTYPE_SOCKET
) {
3152 TAILQ_REMOVE(&((struct socket
*)fp
->f_data
)->so_evlist
, evq
, ee_slist
);
3153 socket_unlock((struct socket
*)fp
->f_data
, 1);
3155 #endif /* SOCKETS */
3157 TAILQ_REMOVE(&((struct pipe
*)fp
->f_data
)->pipe_evlist
, evq
, ee_slist
);
3158 PIPE_UNLOCK((struct pipe
*)fp
->f_data
);
3171 * Description: Get the host UUID from IOKit and return it to user space.
3173 * Parameters: uuid_buf Pointer to buffer to receive UUID
3174 * timeout Timespec for timout
3176 * Returns: 0 Success
3177 * EWOULDBLOCK Timeout is too short
3178 * copyout:EFAULT Bad user buffer
3179 * mac_system_check_info:EPERM Client not allowed to perform this operation
3181 * Notes: A timeout seems redundant, since if it's tolerable to not
3182 * have a system UUID in hand, then why ask for one?
3185 gethostuuid(struct proc
*p
, struct gethostuuid_args
*uap
, __unused
int32_t *retval
)
3189 mach_timespec_t mach_ts
; /* for IOKit call */
3190 __darwin_uuid_t uuid_kern
= {}; /* for IOKit call */
3192 /* Check entitlement */
3193 if (!IOTaskHasEntitlement(current_task(), "com.apple.private.getprivatesysid")) {
3196 if ((error
= mac_system_check_info(kauth_cred_get(), "hw.uuid")) != 0) {
3197 /* EPERM invokes userspace upcall if present */
3204 /* Convert the 32/64 bit timespec into a mach_timespec_t */
3205 if (proc_is64bit(p
)) {
3206 struct user64_timespec ts
;
3207 error
= copyin(uap
->timeoutp
, &ts
, sizeof(ts
));
3211 mach_ts
.tv_sec
= ts
.tv_sec
;
3212 mach_ts
.tv_nsec
= ts
.tv_nsec
;
3214 struct user32_timespec ts
;
3215 error
= copyin(uap
->timeoutp
, &ts
, sizeof(ts
));
3219 mach_ts
.tv_sec
= ts
.tv_sec
;
3220 mach_ts
.tv_nsec
= ts
.tv_nsec
;
3223 /* Call IOKit with the stack buffer to get the UUID */
3224 kret
= IOBSDGetPlatformUUID(uuid_kern
, mach_ts
);
3227 * If we get it, copy out the data to the user buffer; note that a
3228 * uuid_t is an array of characters, so this is size invariant for
3231 if (kret
== KERN_SUCCESS
) {
3232 error
= copyout(uuid_kern
, uap
->uuid_buf
, sizeof(uuid_kern
));
3234 error
= EWOULDBLOCK
;
3243 * Description: Omnibus system call for ledger operations
3246 ledger(struct proc
*p
, struct ledger_args
*args
, __unused
int32_t *retval
)
3251 int rval
, pid
, len
, error
;
3253 struct ledger_limit_args lla
;
3258 /* Finish copying in the necessary args before taking the proc lock */
3261 if (args
->cmd
== LEDGER_ENTRY_INFO
) {
3262 error
= copyin(args
->arg3
, (char *)&len
, sizeof(len
));
3263 } else if (args
->cmd
== LEDGER_TEMPLATE_INFO
) {
3264 error
= copyin(args
->arg2
, (char *)&len
, sizeof(len
));
3265 } else if (args
->cmd
== LEDGER_LIMIT
)
3267 { error
= copyin(args
->arg2
, (char *)&lla
, sizeof(lla
));}
3271 else if ((args
->cmd
< 0) || (args
->cmd
> LEDGER_MAX_CMD
)) {
3283 if (args
->cmd
!= LEDGER_TEMPLATE_INFO
) {
3285 proc
= proc_find(pid
);
3291 error
= mac_proc_check_ledger(p
, proc
, args
->cmd
);
3301 switch (args
->cmd
) {
3303 case LEDGER_LIMIT
: {
3304 if (!kauth_cred_issuser(kauth_cred_get())) {
3307 rval
= ledger_limit(task
, &lla
);
3313 struct ledger_info info
= {};
3315 rval
= ledger_info(task
, &info
);
3318 rval
= copyout(&info
, args
->arg2
,
3324 case LEDGER_ENTRY_INFO
: {
3328 rval
= ledger_get_task_entry_info_multiple(task
, &buf
, &len
);
3330 if ((rval
== 0) && (len
>= 0)) {
3331 sz
= len
* sizeof(struct ledger_entry_info
);
3332 rval
= copyout(buf
, args
->arg2
, sz
);
3336 rval
= copyout(&len
, args
->arg3
, sizeof(len
));
3341 case LEDGER_TEMPLATE_INFO
: {
3345 rval
= ledger_template_info(&buf
, &len
);
3346 if ((rval
== 0) && (len
>= 0)) {
3347 sz
= len
* sizeof(struct ledger_template_info
);
3348 rval
= copyout(buf
, args
->arg1
, sz
);
3352 rval
= copyout(&len
, args
->arg2
, sizeof(len
));
3358 panic("ledger syscall logic error -- command type %d", args
->cmd
);
3367 telemetry(__unused
struct proc
*p
, struct telemetry_args
*args
, __unused
int32_t *retval
)
3371 switch (args
->cmd
) {
3372 #if CONFIG_TELEMETRY
3373 case TELEMETRY_CMD_TIMER_EVENT
:
3374 error
= telemetry_timer_event(args
->deadline
, args
->interval
, args
->leeway
);
3376 case TELEMETRY_CMD_PMI_SETUP
:
3377 error
= telemetry_pmi_setup((enum telemetry_pmi
)args
->deadline
, args
->interval
);
3379 #endif /* CONFIG_TELEMETRY */
3380 case TELEMETRY_CMD_VOUCHER_NAME
:
3381 if (thread_set_voucher_name((mach_port_name_t
)args
->deadline
)) {
3397 * Description: syscall to access kernel logging from userspace
3400 * tag - used for syncing with userspace on the version.
3401 * flags - flags used by the syscall.
3402 * buffer - userspace address of string to copy.
3403 * size - size of buffer.
3406 log_data(__unused
struct proc
*p
, struct log_data_args
*args
, int *retval
)
3408 unsigned int tag
= args
->tag
;
3409 unsigned int flags
= args
->flags
;
3410 user_addr_t buffer
= args
->buffer
;
3411 unsigned int size
= args
->size
;
3413 char *log_msg
= NULL
;
3418 * Tag synchronize the syscall version with userspace.
3419 * Tag == 0 => flags == OS_LOG_TYPE
3426 * OS_LOG_TYPE are defined in libkern/os/log.h
3427 * In userspace they are defined in libtrace/os/log.h
3429 if (flags
!= OS_LOG_TYPE_DEFAULT
&&
3430 flags
!= OS_LOG_TYPE_INFO
&&
3431 flags
!= OS_LOG_TYPE_DEBUG
&&
3432 flags
!= OS_LOG_TYPE_ERROR
&&
3433 flags
!= OS_LOG_TYPE_FAULT
) {
3441 /* truncate to OS_LOG_DATA_MAX_SIZE */
3442 if (size
> OS_LOG_DATA_MAX_SIZE
) {
3443 printf("%s: WARNING msg is going to be truncated from %u to %u\n", __func__
, size
, OS_LOG_DATA_MAX_SIZE
);
3444 size
= OS_LOG_DATA_MAX_SIZE
;
3447 log_msg
= kalloc(size
);
3452 error
= copyin(buffer
, log_msg
, size
);
3457 log_msg
[size
- 1] = '\0';
3460 * This will log to dmesg and logd.
3461 * The call will fail if the current
3462 * process is not a driverKit process.
3464 os_log_driverKit(&ret
, OS_LOG_DEFAULT
, flags
, "%s", log_msg
);
3467 if (log_msg
!= NULL
) {
3468 kfree(log_msg
, size
);
3474 #if DEVELOPMENT || DEBUG
3475 #if CONFIG_WAITQ_DEBUG
3476 static uint64_t g_wqset_num
= 0;
3479 struct waitq_set
*wqset
;
3482 static queue_head_t g_wqset_list
;
3483 static struct waitq_set
*g_waitq_set
= NULL
;
3485 static inline struct waitq_set
*
3486 sysctl_get_wqset(int idx
)
3488 struct g_wqset
*gwqs
;
3491 queue_init(&g_wqset_list
);
3494 /* don't bother with locks: this is test-only code! */
3495 qe_foreach_element(gwqs
, &g_wqset_list
, link
) {
3496 if ((int)(wqset_id(gwqs
->wqset
) & 0xffffffff) == idx
) {
3501 /* allocate a new one */
3503 gwqs
= (struct g_wqset
*)kalloc(sizeof(*gwqs
));
3504 assert(gwqs
!= NULL
);
3506 gwqs
->wqset
= waitq_set_alloc(SYNC_POLICY_FIFO
| SYNC_POLICY_PREPOST
, NULL
);
3507 enqueue_tail(&g_wqset_list
, &gwqs
->link
);
3508 printf("[WQ]: created new waitq set 0x%llx\n", wqset_id(gwqs
->wqset
));
3513 #define MAX_GLOBAL_TEST_QUEUES 64
3514 static int g_wq_init
= 0;
3515 static struct waitq g_wq
[MAX_GLOBAL_TEST_QUEUES
];
3517 static inline struct waitq
*
3518 global_test_waitq(int idx
)
3526 for (int i
= 0; i
< MAX_GLOBAL_TEST_QUEUES
; i
++) {
3527 waitq_init(&g_wq
[i
], SYNC_POLICY_FIFO
);
3531 return &g_wq
[idx
% MAX_GLOBAL_TEST_QUEUES
];
3534 static int sysctl_waitq_wakeup_one SYSCTL_HANDLER_ARGS
3536 #pragma unused(oidp, arg1, arg2)
3539 struct waitq
*waitq
;
3541 int64_t event64
= 0;
3543 error
= SYSCTL_IN(req
, &event64
, sizeof(event64
));
3549 return SYSCTL_OUT(req
, &event64
, sizeof(event64
));
3553 index
= (int)((-event64
) & 0xffffffff);
3554 waitq
= wqset_waitq(sysctl_get_wqset(index
));
3557 index
= (int)event64
;
3558 waitq
= global_test_waitq(index
);
3563 printf("[WQ]: Waking one thread on waitq [%d] event:0x%llx\n",
3565 kr
= waitq_wakeup64_one(waitq
, (event64_t
)event64
, THREAD_AWAKENED
,
3566 WAITQ_ALL_PRIORITIES
);
3567 printf("[WQ]: \tkr=%d\n", kr
);
3569 return SYSCTL_OUT(req
, &kr
, sizeof(kr
));
3571 SYSCTL_PROC(_kern
, OID_AUTO
, waitq_wakeup_one
, CTLTYPE_QUAD
| CTLFLAG_RW
| CTLFLAG_LOCKED
,
3572 0, 0, sysctl_waitq_wakeup_one
, "Q", "wakeup one thread waiting on given event");
3575 static int sysctl_waitq_wakeup_all SYSCTL_HANDLER_ARGS
3577 #pragma unused(oidp, arg1, arg2)
3580 struct waitq
*waitq
;
3582 int64_t event64
= 0;
3584 error
= SYSCTL_IN(req
, &event64
, sizeof(event64
));
3590 return SYSCTL_OUT(req
, &event64
, sizeof(event64
));
3594 index
= (int)((-event64
) & 0xffffffff);
3595 waitq
= wqset_waitq(sysctl_get_wqset(index
));
3598 index
= (int)event64
;
3599 waitq
= global_test_waitq(index
);
3604 printf("[WQ]: Waking all threads on waitq [%d] event:0x%llx\n",
3606 kr
= waitq_wakeup64_all(waitq
, (event64_t
)event64
,
3607 THREAD_AWAKENED
, WAITQ_ALL_PRIORITIES
);
3608 printf("[WQ]: \tkr=%d\n", kr
);
3610 return SYSCTL_OUT(req
, &kr
, sizeof(kr
));
3612 SYSCTL_PROC(_kern
, OID_AUTO
, waitq_wakeup_all
, CTLTYPE_QUAD
| CTLFLAG_RW
| CTLFLAG_LOCKED
,
3613 0, 0, sysctl_waitq_wakeup_all
, "Q", "wakeup all threads waiting on given event");
3616 static int sysctl_waitq_wait SYSCTL_HANDLER_ARGS
3618 #pragma unused(oidp, arg1, arg2)
3621 struct waitq
*waitq
;
3623 int64_t event64
= 0;
3625 error
= SYSCTL_IN(req
, &event64
, sizeof(event64
));
3631 return SYSCTL_OUT(req
, &event64
, sizeof(event64
));
3635 index
= (int)((-event64
) & 0xffffffff);
3636 waitq
= wqset_waitq(sysctl_get_wqset(index
));
3639 index
= (int)event64
;
3640 waitq
= global_test_waitq(index
);
3645 printf("[WQ]: Current thread waiting on waitq [%d] event:0x%llx\n",
3647 kr
= waitq_assert_wait64(waitq
, (event64_t
)event64
, THREAD_INTERRUPTIBLE
, 0);
3648 if (kr
== THREAD_WAITING
) {
3649 thread_block(THREAD_CONTINUE_NULL
);
3651 printf("[WQ]: \tWoke Up: kr=%d\n", kr
);
3653 return SYSCTL_OUT(req
, &kr
, sizeof(kr
));
3655 SYSCTL_PROC(_kern
, OID_AUTO
, waitq_wait
, CTLTYPE_QUAD
| CTLFLAG_RW
| CTLFLAG_LOCKED
,
3656 0, 0, sysctl_waitq_wait
, "Q", "start waiting on given event");
3659 static int sysctl_wqset_select SYSCTL_HANDLER_ARGS
3661 #pragma unused(oidp, arg1, arg2)
3663 struct waitq_set
*wqset
;
3664 uint64_t event64
= 0;
3666 error
= SYSCTL_IN(req
, &event64
, sizeof(event64
));
3675 wqset
= sysctl_get_wqset((int)(event64
& 0xffffffff));
3676 g_waitq_set
= wqset
;
3678 event64
= wqset_id(wqset
);
3679 printf("[WQ]: selected wqset 0x%llx\n", event64
);
3683 event64
= wqset_id(g_waitq_set
);
3685 event64
= (uint64_t)(-1);
3688 return SYSCTL_OUT(req
, &event64
, sizeof(event64
));
3690 SYSCTL_PROC(_kern
, OID_AUTO
, wqset_select
, CTLTYPE_QUAD
| CTLFLAG_RW
| CTLFLAG_LOCKED
,
3691 0, 0, sysctl_wqset_select
, "Q", "select/create a global waitq set");
3694 static int sysctl_waitq_link SYSCTL_HANDLER_ARGS
3696 #pragma unused(oidp, arg1, arg2)
3699 struct waitq
*waitq
;
3700 struct waitq_set
*wqset
;
3702 uint64_t reserved_link
= 0;
3703 int64_t event64
= 0;
3705 error
= SYSCTL_IN(req
, &event64
, sizeof(event64
));
3711 return SYSCTL_OUT(req
, &event64
, sizeof(event64
));
3715 g_waitq_set
= sysctl_get_wqset(1);
3717 wqset
= g_waitq_set
;
3720 struct waitq_set
*tmp
;
3721 index
= (int)((-event64
) & 0xffffffff);
3722 tmp
= sysctl_get_wqset(index
);
3726 waitq
= wqset_waitq(tmp
);
3729 index
= (int)event64
;
3730 waitq
= global_test_waitq(index
);
3733 printf("[WQ]: linking waitq [%d] to global wqset (0x%llx)\n",
3734 index
, wqset_id(wqset
));
3735 reserved_link
= waitq_link_reserve(waitq
);
3736 kr
= waitq_link(waitq
, wqset
, WAITQ_SHOULD_LOCK
, &reserved_link
);
3737 waitq_link_release(reserved_link
);
3739 printf("[WQ]: \tkr=%d\n", kr
);
3742 return SYSCTL_OUT(req
, &kr
, sizeof(kr
));
3744 SYSCTL_PROC(_kern
, OID_AUTO
, waitq_link
, CTLTYPE_QUAD
| CTLFLAG_RW
| CTLFLAG_LOCKED
,
3745 0, 0, sysctl_waitq_link
, "Q", "link global waitq to test waitq set");
3748 static int sysctl_waitq_unlink SYSCTL_HANDLER_ARGS
3750 #pragma unused(oidp, arg1, arg2)
3753 struct waitq
*waitq
;
3754 struct waitq_set
*wqset
;
3756 uint64_t event64
= 0;
3758 error
= SYSCTL_IN(req
, &event64
, sizeof(event64
));
3764 return SYSCTL_OUT(req
, &event64
, sizeof(event64
));
3768 g_waitq_set
= sysctl_get_wqset(1);
3770 wqset
= g_waitq_set
;
3772 index
= (int)event64
;
3773 waitq
= global_test_waitq(index
);
3775 printf("[WQ]: unlinking waitq [%d] from global wqset (0x%llx)\n",
3776 index
, wqset_id(wqset
));
3778 kr
= waitq_unlink(waitq
, wqset
);
3779 printf("[WQ]: \tkr=%d\n", kr
);
3781 return SYSCTL_OUT(req
, &kr
, sizeof(kr
));
3783 SYSCTL_PROC(_kern
, OID_AUTO
, waitq_unlink
, CTLTYPE_QUAD
| CTLFLAG_RW
| CTLFLAG_LOCKED
,
3784 0, 0, sysctl_waitq_unlink
, "Q", "unlink global waitq from test waitq set");
3787 static int sysctl_waitq_clear_prepost SYSCTL_HANDLER_ARGS
3789 #pragma unused(oidp, arg1, arg2)
3790 struct waitq
*waitq
;
3791 uint64_t event64
= 0;
3794 error
= SYSCTL_IN(req
, &event64
, sizeof(event64
));
3800 return SYSCTL_OUT(req
, &event64
, sizeof(event64
));
3803 index
= (int)event64
;
3804 waitq
= global_test_waitq(index
);
3806 printf("[WQ]: clearing prepost on waitq [%d]\n", index
);
3807 waitq_clear_prepost(waitq
);
3809 return SYSCTL_OUT(req
, &event64
, sizeof(event64
));
3811 SYSCTL_PROC(_kern
, OID_AUTO
, waitq_clear_prepost
, CTLTYPE_QUAD
| CTLFLAG_RW
| CTLFLAG_LOCKED
,
3812 0, 0, sysctl_waitq_clear_prepost
, "Q", "clear prepost on given waitq");
3815 static int sysctl_wqset_unlink_all SYSCTL_HANDLER_ARGS
3817 #pragma unused(oidp, arg1, arg2)
3819 struct waitq_set
*wqset
;
3821 uint64_t event64
= 0;
3823 error
= SYSCTL_IN(req
, &event64
, sizeof(event64
));
3829 return SYSCTL_OUT(req
, &event64
, sizeof(event64
));
3833 g_waitq_set
= sysctl_get_wqset(1);
3835 wqset
= g_waitq_set
;
3837 printf("[WQ]: unlinking all queues from global wqset (0x%llx)\n",
3840 kr
= waitq_set_unlink_all(wqset
);
3841 printf("[WQ]: \tkr=%d\n", kr
);
3843 return SYSCTL_OUT(req
, &kr
, sizeof(kr
));
3845 SYSCTL_PROC(_kern
, OID_AUTO
, wqset_unlink_all
, CTLTYPE_QUAD
| CTLFLAG_RW
| CTLFLAG_LOCKED
,
3846 0, 0, sysctl_wqset_unlink_all
, "Q", "unlink all queues from test waitq set");
3849 static int sysctl_wqset_clear_preposts SYSCTL_HANDLER_ARGS
3851 #pragma unused(oidp, arg1, arg2)
3852 struct waitq_set
*wqset
= NULL
;
3853 uint64_t event64
= 0;
3856 error
= SYSCTL_IN(req
, &event64
, sizeof(event64
));
3865 index
= (int)((event64
) & 0xffffffff);
3866 wqset
= sysctl_get_wqset(index
);
3867 assert(wqset
!= NULL
);
3869 printf("[WQ]: clearing preposts on wqset 0x%llx\n", wqset_id(wqset
));
3870 waitq_set_clear_preposts(wqset
);
3874 event64
= wqset_id(wqset
);
3876 event64
= (uint64_t)(-1);
3879 return SYSCTL_OUT(req
, &event64
, sizeof(event64
));
3881 SYSCTL_PROC(_kern
, OID_AUTO
, wqset_clear_preposts
, CTLTYPE_QUAD
| CTLFLAG_RW
| CTLFLAG_LOCKED
,
3882 0, 0, sysctl_wqset_clear_preposts
, "Q", "clear preposts on given waitq set");
3884 #endif /* CONFIG_WAITQ_DEBUG */
3887 sysctl_waitq_set_nelem SYSCTL_HANDLER_ARGS
3889 #pragma unused(oidp, arg1, arg2)
3893 if (req
->newptr
!= USER_ADDR_NULL
) {
3897 nelem
= sysctl_helper_waitq_set_nelem();
3899 return SYSCTL_OUT(req
, &nelem
, sizeof(nelem
));
3902 SYSCTL_PROC(_kern
, OID_AUTO
, n_ltable_entries
, CTLFLAG_RD
| CTLFLAG_LOCKED
,
3903 0, 0, sysctl_waitq_set_nelem
, "I", "ltable elementis currently used");
3907 sysctl_mpsc_test_pingpong SYSCTL_HANDLER_ARGS
3909 #pragma unused(oidp, arg1, arg2)
3913 error
= SYSCTL_IN(req
, &value
, sizeof(value
));
3918 if (error
== 0 && req
->newptr
) {
3919 error
= mpsc_test_pingpong(value
, &value
);
3921 error
= SYSCTL_OUT(req
, &value
, sizeof(value
));
3927 SYSCTL_PROC(_kern
, OID_AUTO
, mpsc_test_pingpong
, CTLTYPE_QUAD
| CTLFLAG_RW
| CTLFLAG_LOCKED
,
3928 0, 0, sysctl_mpsc_test_pingpong
, "Q", "MPSC tests: pingpong");
3930 #endif /* DEVELOPMENT || DEBUG */
3933 SYSCTL_NODE(_machdep
, OID_AUTO
, remotetime
, CTLFLAG_RD
| CTLFLAG_LOCKED
, 0, "Remote time api");
3935 #if DEVELOPMENT || DEBUG
3936 #if CONFIG_MACH_BRIDGE_SEND_TIME
3937 extern _Atomic
uint32_t bt_init_flag
;
3938 extern uint32_t mach_bridge_timer_enable(uint32_t, int);
3940 SYSCTL_INT(_machdep_remotetime
, OID_AUTO
, bridge_timer_init_flag
,
3941 CTLFLAG_RD
| CTLFLAG_LOCKED
, &bt_init_flag
, 0, "");
3943 static int sysctl_mach_bridge_timer_enable SYSCTL_HANDLER_ARGS
3945 #pragma unused(oidp, arg1, arg2)
3948 /* User is querying buffer size */
3949 if (req
->oldptr
== USER_ADDR_NULL
&& req
->newptr
== USER_ADDR_NULL
) {
3950 req
->oldidx
= sizeof(value
);
3953 if (os_atomic_load(&bt_init_flag
, acquire
)) {
3956 error
= SYSCTL_IN(req
, &new_value
, sizeof(new_value
));
3960 if (new_value
== 0 || new_value
== 1) {
3961 value
= mach_bridge_timer_enable(new_value
, 1);
3966 value
= mach_bridge_timer_enable(0, 0);
3969 error
= SYSCTL_OUT(req
, &value
, sizeof(value
));
3973 SYSCTL_PROC(_machdep_remotetime
, OID_AUTO
, bridge_timer_enable
,
3974 CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
,
3975 0, 0, sysctl_mach_bridge_timer_enable
, "I", "");
3977 #endif /* CONFIG_MACH_BRIDGE_SEND_TIME */
3979 static int sysctl_mach_bridge_remote_time SYSCTL_HANDLER_ARGS
3981 #pragma unused(oidp, arg1, arg2)
3982 uint64_t ltime
= 0, rtime
= 0;
3983 if (req
->oldptr
== USER_ADDR_NULL
) {
3984 req
->oldidx
= sizeof(rtime
);
3988 int error
= SYSCTL_IN(req
, <ime
, sizeof(ltime
));
3993 rtime
= mach_bridge_remote_time(ltime
);
3994 return SYSCTL_OUT(req
, &rtime
, sizeof(rtime
));
3996 SYSCTL_PROC(_machdep_remotetime
, OID_AUTO
, mach_bridge_remote_time
,
3997 CTLTYPE_QUAD
| CTLFLAG_RW
| CTLFLAG_LOCKED
,
3998 0, 0, sysctl_mach_bridge_remote_time
, "Q", "");
4000 #endif /* DEVELOPMENT || DEBUG */
4002 #if CONFIG_MACH_BRIDGE_RECV_TIME
4003 extern struct bt_params
bt_params_get_latest(void);
4005 static int sysctl_mach_bridge_conversion_params SYSCTL_HANDLER_ARGS
4007 #pragma unused(oidp, arg1, arg2)
4008 struct bt_params params
= {};
4009 if (req
->oldptr
== USER_ADDR_NULL
) {
4010 req
->oldidx
= sizeof(struct bt_params
);
4016 params
= bt_params_get_latest();
4017 return SYSCTL_OUT(req
, ¶ms
, MIN(sizeof(params
), req
->oldlen
));
4020 SYSCTL_PROC(_machdep_remotetime
, OID_AUTO
, conversion_params
,
4021 CTLTYPE_STRUCT
| CTLFLAG_RD
| CTLFLAG_LOCKED
, 0,
4022 0, sysctl_mach_bridge_conversion_params
, "S,bt_params", "");
4024 #endif /* CONFIG_MACH_BRIDGE_RECV_TIME */
4026 #if DEVELOPMENT || DEBUG
4027 #endif /* DEVELOPMENT || DEBUG */
4029 extern uint32_t task_exc_guard_default
;
4031 SYSCTL_INT(_kern
, OID_AUTO
, task_exc_guard_default
,
4032 CTLFLAG_RD
| CTLFLAG_LOCKED
, &task_exc_guard_default
, 0, "");
4036 sysctl_kern_tcsm_available SYSCTL_HANDLER_ARGS
4038 #pragma unused(oidp, arg1, arg2)
4039 uint32_t value
= machine_csv(CPUVN_CI
) ? 1 : 0;
4045 return SYSCTL_OUT(req
, &value
, sizeof(value
));
4047 SYSCTL_PROC(_kern
, OID_AUTO
, tcsm_available
,
4048 CTLTYPE_INT
| CTLFLAG_RD
| CTLFLAG_LOCKED
| CTLFLAG_MASKED
| CTLFLAG_ANYBODY
,
4049 0, 0, sysctl_kern_tcsm_available
, "I", "");
4053 sysctl_kern_tcsm_enable SYSCTL_HANDLER_ARGS
4055 #pragma unused(oidp, arg1, arg2)
4056 uint32_t soflags
= 0;
4057 uint32_t old_value
= thread_get_no_smt() ? 1 : 0;
4059 int error
= SYSCTL_IN(req
, &soflags
, sizeof(soflags
));
4064 if (soflags
&& machine_csv(CPUVN_CI
)) {
4065 thread_set_no_smt(true);
4066 machine_tecs(current_thread());
4069 return SYSCTL_OUT(req
, &old_value
, sizeof(old_value
));
4071 SYSCTL_PROC(_kern
, OID_AUTO
, tcsm_enable
,
4072 CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
| CTLFLAG_MASKED
| CTLFLAG_ANYBODY
,
4073 0, 0, sysctl_kern_tcsm_enable
, "I", "");
4076 #if DEVELOPMENT || DEBUG
4077 extern void sysctl_task_set_no_smt(char no_smt
);
4078 extern char sysctl_task_get_no_smt(void);
4081 sysctl_kern_sched_task_set_no_smt SYSCTL_HANDLER_ARGS
4083 #pragma unused(oidp, arg1, arg2)
4086 int error
= SYSCTL_IN(req
, buff
, 1);
4090 char no_smt
= buff
[0];
4096 sysctl_task_set_no_smt(no_smt
);
4098 no_smt
= sysctl_task_get_no_smt();
4101 return SYSCTL_OUT(req
, buff
, 1);
4104 SYSCTL_PROC(_kern
, OID_AUTO
, sched_task_set_no_smt
, CTLTYPE_STRING
| CTLFLAG_RW
| CTLFLAG_LOCKED
| CTLFLAG_ANYBODY
,
4105 0, 0, sysctl_kern_sched_task_set_no_smt
, "A", "");
4108 sysctl_kern_sched_thread_set_no_smt(__unused
struct sysctl_oid
*oidp
, __unused
void *arg1
, __unused
int arg2
, struct sysctl_req
*req
)
4110 int new_value
, changed
;
4111 int old_value
= thread_get_no_smt() ? 1 : 0;
4112 int error
= sysctl_io_number(req
, old_value
, sizeof(int), &new_value
, &changed
);
4115 thread_set_no_smt(!!new_value
);
4121 SYSCTL_PROC(_kern
, OID_AUTO
, sched_thread_set_no_smt
,
4122 CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
| CTLFLAG_ANYBODY
,
4123 0, 0, sysctl_kern_sched_thread_set_no_smt
, "I", "");
4124 #endif /* DEVELOPMENT || DEBUG */