]> git.saurik.com Git - apple/xnu.git/blame - bsd/kern/kern_event.c
xnu-2050.22.13.tar.gz
[apple/xnu.git] / bsd / kern / kern_event.c
CommitLineData
1c79356b 1/*
316670eb 2 * Copyright (c) 2000-2011 Apple Inc. All rights reserved.
1c79356b 3 *
2d21ac55 4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
1c79356b 5 *
2d21ac55
A
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.
8f6c56a5 14 *
2d21ac55
A
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
8f6c56a5
A
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
2d21ac55
A
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.
8f6c56a5 25 *
2d21ac55 26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
1c79356b
A
27 *
28 */
55e303ae
A
29/*-
30 * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
31 * All rights reserved.
32 *
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
35 * are met:
36 * 1. Redistributions of source code must retain the above copyright
37 * notice, this list of conditions and the following disclaimer.
38 * 2. Redistributions in binary form must reproduce the above copyright
39 * notice, this list of conditions and the following disclaimer in the
40 * documentation and/or other materials provided with the distribution.
41 *
42 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
43 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
44 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
45 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
46 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
47 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
48 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
49 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
50 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
51 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * SUCH DAMAGE.
53 */
1c79356b
A
54/*
55 * @(#)kern_event.c 1.0 (3/31/2000)
56 */
91447636 57#include <stdint.h>
1c79356b 58
55e303ae
A
59#include <sys/param.h>
60#include <sys/systm.h>
61#include <sys/filedesc.h>
62#include <sys/kernel.h>
91447636
A
63#include <sys/proc_internal.h>
64#include <sys/kauth.h>
55e303ae
A
65#include <sys/malloc.h>
66#include <sys/unistd.h>
91447636 67#include <sys/file_internal.h>
55e303ae
A
68#include <sys/fcntl.h>
69#include <sys/select.h>
70#include <sys/queue.h>
71#include <sys/event.h>
72#include <sys/eventvar.h>
73#include <sys/protosw.h>
74#include <sys/socket.h>
75#include <sys/socketvar.h>
76#include <sys/stat.h>
77#include <sys/sysctl.h>
78#include <sys/uio.h>
91447636
A
79#include <sys/sysproto.h>
80#include <sys/user.h>
b0d623f7 81#include <sys/vnode_internal.h>
91447636 82#include <string.h>
0c530ab8 83#include <sys/proc_info.h>
91447636
A
84
85#include <kern/lock.h>
86#include <kern/clock.h>
87#include <kern/thread_call.h>
88#include <kern/sched_prim.h>
55e303ae 89#include <kern/zalloc.h>
91447636
A
90#include <kern/assert.h>
91
92#include <libkern/libkern.h>
b0d623f7 93#include "net/net_str_id.h"
55e303ae 94
6d2010ae 95#include <mach/task.h>
316670eb
A
96
97#if VM_PRESSURE_EVENTS
6d2010ae 98#include <kern/vm_pressure.h>
316670eb 99#endif
6d2010ae 100
55e303ae
A
101MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
102
b0d623f7
A
103#define KQ_EVENT NULL
104
91447636
A
105static inline void kqlock(struct kqueue *kq);
106static inline void kqunlock(struct kqueue *kq);
107
108static int kqlock2knoteuse(struct kqueue *kq, struct knote *kn);
109static int kqlock2knoteusewait(struct kqueue *kq, struct knote *kn);
110static int kqlock2knotedrop(struct kqueue *kq, struct knote *kn);
111static int knoteuse2kqlock(struct kqueue *kq, struct knote *kn);
55e303ae 112
b0d623f7 113static void kqueue_wakeup(struct kqueue *kq, int closed);
91447636 114static int kqueue_read(struct fileproc *fp, struct uio *uio,
2d21ac55 115 int flags, vfs_context_t ctx);
91447636 116static int kqueue_write(struct fileproc *fp, struct uio *uio,
2d21ac55 117 int flags, vfs_context_t ctx);
91447636 118static int kqueue_ioctl(struct fileproc *fp, u_long com, caddr_t data,
2d21ac55 119 vfs_context_t ctx);
91447636 120static int kqueue_select(struct fileproc *fp, int which, void *wql,
2d21ac55 121 vfs_context_t ctx);
b0d623f7 122static int kqueue_close(struct fileglob *fg, vfs_context_t ctx);
2d21ac55 123static int kqueue_kqfilter(struct fileproc *fp, struct knote *kn, vfs_context_t ctx);
b0d623f7 124static int kqueue_drain(struct fileproc *fp, vfs_context_t ctx);
2d21ac55 125extern int kqueue_stat(struct fileproc *fp, void *ub, int isstat64, vfs_context_t ctx);
55e303ae
A
126
127static struct fileops kqueueops = {
b0d623f7
A
128 .fo_read = kqueue_read,
129 .fo_write = kqueue_write,
130 .fo_ioctl = kqueue_ioctl,
131 .fo_select = kqueue_select,
132 .fo_close = kqueue_close,
133 .fo_kqfilter = kqueue_kqfilter,
134 .fo_drain = kqueue_drain,
55e303ae
A
135};
136
b0d623f7
A
137static int kevent_internal(struct proc *p, int iskev64, user_addr_t changelist,
138 int nchanges, user_addr_t eventlist, int nevents, int fd,
139 user_addr_t utimeout, unsigned int flags, int32_t *retval);
140static int kevent_copyin(user_addr_t *addrp, struct kevent64_s *kevp, struct proc *p, int iskev64);
141static int kevent_copyout(struct kevent64_s *kevp, user_addr_t *addrp, struct proc *p, int iskev64);
142char * kevent_description(struct kevent64_s *kevp, char *s, size_t n);
91447636 143
b0d623f7 144static int kevent_callback(struct kqueue *kq, struct kevent64_s *kevp, void *data);
91447636 145static void kevent_continue(struct kqueue *kq, void *data, int error);
b0d623f7
A
146static void kqueue_scan_continue(void *contp, wait_result_t wait_result);
147static int kqueue_process(struct kqueue *kq, kevent_callback_t callback,
91447636 148 void *data, int *countp, struct proc *p);
6d2010ae
A
149static int kqueue_begin_processing(struct kqueue *kq);
150static void kqueue_end_processing(struct kqueue *kq);
b0d623f7
A
151static int knote_process(struct knote *kn, kevent_callback_t callback,
152 void *data, struct kqtailq *inprocessp, struct proc *p);
91447636
A
153static void knote_put(struct knote *kn);
154static int knote_fdpattach(struct knote *kn, struct filedesc *fdp, struct proc *p);
55e303ae 155static void knote_drop(struct knote *kn, struct proc *p);
b0d623f7 156static void knote_activate(struct knote *kn, int);
91447636 157static void knote_deactivate(struct knote *kn);
55e303ae
A
158static void knote_enqueue(struct knote *kn);
159static void knote_dequeue(struct knote *kn);
160static struct knote *knote_alloc(void);
161static void knote_free(struct knote *kn);
162
163static int filt_fileattach(struct knote *kn);
b0d623f7
A
164static struct filterops file_filtops = {
165 .f_isfd = 1,
166 .f_attach = filt_fileattach,
167};
55e303ae
A
168
169static void filt_kqdetach(struct knote *kn);
170static int filt_kqueue(struct knote *kn, long hint);
b0d623f7
A
171static struct filterops kqread_filtops = {
172 .f_isfd = 1,
173 .f_detach = filt_kqdetach,
174 .f_event = filt_kqueue,
175};
55e303ae
A
176
177/*
91447636 178 * placeholder for not-yet-implemented filters
55e303ae
A
179 */
180static int filt_badattach(struct knote *kn);
b0d623f7
A
181static struct filterops bad_filtops = {
182 .f_attach = filt_badattach,
183};
55e303ae
A
184
185static int filt_procattach(struct knote *kn);
186static void filt_procdetach(struct knote *kn);
187static int filt_proc(struct knote *kn, long hint);
b0d623f7
A
188static struct filterops proc_filtops = {
189 .f_attach = filt_procattach,
190 .f_detach = filt_procdetach,
191 .f_event = filt_proc,
192};
55e303ae 193
316670eb 194#if VM_PRESSURE_EVENTS
6d2010ae
A
195static int filt_vmattach(struct knote *kn);
196static void filt_vmdetach(struct knote *kn);
197static int filt_vm(struct knote *kn, long hint);
198static struct filterops vm_filtops = {
199 .f_attach = filt_vmattach,
200 .f_detach = filt_vmdetach,
201 .f_event = filt_vm,
202};
316670eb 203#endif /* VM_PRESSURE_EVENTS */
6d2010ae 204
55e303ae
A
205extern struct filterops fs_filtops;
206
207extern struct filterops sig_filtops;
208
91447636 209/* Timer filter */
55e303ae
A
210static int filt_timerattach(struct knote *kn);
211static void filt_timerdetach(struct knote *kn);
212static int filt_timer(struct knote *kn, long hint);
b0d623f7
A
213static void filt_timertouch(struct knote *kn, struct kevent64_s *kev,
214 long type);
215static struct filterops timer_filtops = {
216 .f_attach = filt_timerattach,
217 .f_detach = filt_timerdetach,
218 .f_event = filt_timer,
219 .f_touch = filt_timertouch,
220};
55e303ae 221
b0d623f7
A
222/* Helpers */
223
224static void filt_timerexpire(void *knx, void *param1);
225static int filt_timervalidate(struct knote *kn);
226static void filt_timerupdate(struct knote *kn);
227static void filt_timercancel(struct knote *kn);
55e303ae 228
b0d623f7
A
229#define TIMER_RUNNING 0x1
230#define TIMER_CANCELWAIT 0x2
55e303ae 231
91447636
A
232static lck_mtx_t _filt_timerlock;
233static void filt_timerlock(void);
234static void filt_timerunlock(void);
55e303ae 235
91447636 236static zone_t knote_zone;
55e303ae 237
55e303ae
A
238#define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
239
240#if 0
241extern struct filterops aio_filtops;
242#endif
243
b0d623f7
A
244/* Mach portset filter */
245extern struct filterops machport_filtops;
246
247/* User filter */
248static int filt_userattach(struct knote *kn);
249static void filt_userdetach(struct knote *kn);
250static int filt_user(struct knote *kn, long hint);
251static void filt_usertouch(struct knote *kn, struct kevent64_s *kev,
252 long type);
253static struct filterops user_filtops = {
254 .f_attach = filt_userattach,
255 .f_detach = filt_userdetach,
256 .f_event = filt_user,
257 .f_touch = filt_usertouch,
258};
259
55e303ae
A
260/*
261 * Table for for all system-defined filters.
262 */
263static struct filterops *sysfilt_ops[] = {
264 &file_filtops, /* EVFILT_READ */
265 &file_filtops, /* EVFILT_WRITE */
266#if 0
267 &aio_filtops, /* EVFILT_AIO */
268#else
269 &bad_filtops, /* EVFILT_AIO */
270#endif
271 &file_filtops, /* EVFILT_VNODE */
272 &proc_filtops, /* EVFILT_PROC */
273 &sig_filtops, /* EVFILT_SIGNAL */
55e303ae 274 &timer_filtops, /* EVFILT_TIMER */
b0d623f7
A
275 &machport_filtops, /* EVFILT_MACHPORT */
276 &fs_filtops, /* EVFILT_FS */
277 &user_filtops, /* EVFILT_USER */
6d2010ae 278 &bad_filtops, /* unused */
316670eb 279#if VM_PRESSURE_EVENTS
6d2010ae 280 &vm_filtops, /* EVFILT_VM */
316670eb
A
281#else
282 &bad_filtops, /* EVFILT_VM */
283#endif
284 &file_filtops, /* EVFILT_SOCK */
55e303ae
A
285};
286
91447636
A
287/*
288 * kqueue/note lock attributes and implementations
289 *
290 * kqueues have locks, while knotes have use counts
291 * Most of the knote state is guarded by the object lock.
292 * the knote "inuse" count and status use the kqueue lock.
293 */
294lck_grp_attr_t * kq_lck_grp_attr;
295lck_grp_t * kq_lck_grp;
296lck_attr_t * kq_lck_attr;
297
298static inline void
299kqlock(struct kqueue *kq)
300{
301 lck_spin_lock(&kq->kq_lock);
302}
303
304static inline void
305kqunlock(struct kqueue *kq)
306{
307 lck_spin_unlock(&kq->kq_lock);
308}
309
310/*
311 * Convert a kq lock to a knote use referece.
312 *
313 * If the knote is being dropped, we can't get
314 * a use reference, so just return with it
315 * still locked.
316 *
317 * - kq locked at entry
318 * - unlock on exit if we get the use reference
319 */
320static int
321kqlock2knoteuse(struct kqueue *kq, struct knote *kn)
322{
323 if (kn->kn_status & KN_DROPPING)
324 return 0;
325 kn->kn_inuse++;
326 kqunlock(kq);
327 return 1;
328 }
329
330/*
b0d623f7
A
331 * Convert a kq lock to a knote use referece,
332 * but wait for attach and drop events to complete.
91447636
A
333 *
334 * If the knote is being dropped, we can't get
335 * a use reference, so just return with it
336 * still locked.
337 *
338 * - kq locked at entry
339 * - kq always unlocked on exit
340 */
341static int
342kqlock2knoteusewait(struct kqueue *kq, struct knote *kn)
343{
b0d623f7
A
344 if ((kn->kn_status & (KN_DROPPING | KN_ATTACHING)) != 0) {
345 kn->kn_status |= KN_USEWAIT;
346 wait_queue_assert_wait((wait_queue_t)kq->kq_wqs, &kn->kn_status, THREAD_UNINT, 0);
91447636
A
347 kqunlock(kq);
348 thread_block(THREAD_CONTINUE_NULL);
349 return 0;
350 }
b0d623f7
A
351 kn->kn_inuse++;
352 kqunlock(kq);
91447636
A
353 return 1;
354 }
355
b0d623f7 356
91447636
A
357/*
358 * Convert from a knote use reference back to kq lock.
359 *
360 * Drop a use reference and wake any waiters if
361 * this is the last one.
362 *
363 * The exit return indicates if the knote is
364 * still alive - but the kqueue lock is taken
365 * unconditionally.
366 */
367static int
368knoteuse2kqlock(struct kqueue *kq, struct knote *kn)
369{
370 kqlock(kq);
b0d623f7
A
371 if (--kn->kn_inuse == 0) {
372 if ((kn->kn_status & KN_ATTACHING) != 0) {
373 kn->kn_status &= ~KN_ATTACHING;
374 }
375 if ((kn->kn_status & KN_USEWAIT) != 0) {
376 kn->kn_status &= ~KN_USEWAIT;
377 wait_queue_wakeup_all((wait_queue_t)kq->kq_wqs, &kn->kn_status, THREAD_AWAKENED);
378 }
91447636
A
379 }
380 return ((kn->kn_status & KN_DROPPING) == 0);
381 }
382
383/*
384 * Convert a kq lock to a knote drop referece.
385 *
386 * If the knote is in use, wait for the use count
387 * to subside. We first mark our intention to drop
388 * it - keeping other users from "piling on."
389 * If we are too late, we have to wait for the
390 * other drop to complete.
391 *
392 * - kq locked at entry
393 * - always unlocked on exit.
394 * - caller can't hold any locks that would prevent
395 * the other dropper from completing.
396 */
397static int
398kqlock2knotedrop(struct kqueue *kq, struct knote *kn)
399{
b0d623f7 400 int oktodrop;
91447636 401
b0d623f7
A
402 oktodrop = ((kn->kn_status & (KN_DROPPING | KN_ATTACHING)) == 0);
403 kn->kn_status |= KN_DROPPING;
404 if (oktodrop) {
405 if (kn->kn_inuse == 0) {
91447636 406 kqunlock(kq);
b0d623f7
A
407 return oktodrop;
408 }
91447636 409 }
b0d623f7
A
410 kn->kn_status |= KN_USEWAIT;
411 wait_queue_assert_wait((wait_queue_t)kq->kq_wqs, &kn->kn_status, THREAD_UNINT, 0);
412 kqunlock(kq);
413 thread_block(THREAD_CONTINUE_NULL);
414 return oktodrop;
91447636
A
415}
416
417/*
418 * Release a knote use count reference.
419 */
420static void
421knote_put(struct knote *kn)
422{
423 struct kqueue *kq = kn->kn_kq;
424
425 kqlock(kq);
b0d623f7
A
426 if (--kn->kn_inuse == 0) {
427 if ((kn->kn_status & KN_USEWAIT) != 0) {
428 kn->kn_status &= ~KN_USEWAIT;
429 wait_queue_wakeup_all((wait_queue_t)kq->kq_wqs, &kn->kn_status, THREAD_AWAKENED);
430 }
91447636
A
431 }
432 kqunlock(kq);
433 }
434
55e303ae
A
435static int
436filt_fileattach(struct knote *kn)
437{
438
2d21ac55 439 return (fo_kqfilter(kn->kn_fp, kn, vfs_context_current()));
55e303ae
A
440}
441
91447636
A
442#define f_flag f_fglob->fg_flag
443#define f_type f_fglob->fg_type
444#define f_msgcount f_fglob->fg_msgcount
445#define f_cred f_fglob->fg_cred
446#define f_ops f_fglob->fg_ops
447#define f_offset f_fglob->fg_offset
448#define f_data f_fglob->fg_data
449
55e303ae
A
450static void
451filt_kqdetach(struct knote *kn)
452{
453 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
454
91447636 455 kqlock(kq);
55e303ae 456 KNOTE_DETACH(&kq->kq_sel.si_note, kn);
91447636 457 kqunlock(kq);
55e303ae
A
458}
459
460/*ARGSUSED*/
461static int
91447636 462filt_kqueue(struct knote *kn, __unused long hint)
55e303ae
A
463{
464 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
465
466 kn->kn_data = kq->kq_count;
467 return (kn->kn_data > 0);
468}
469
470static int
471filt_procattach(struct knote *kn)
472{
473 struct proc *p;
2d21ac55
A
474
475 assert(PID_MAX < NOTE_PDATAMASK);
91447636 476
2d21ac55
A
477 if ((kn->kn_sfflags & (NOTE_TRACK | NOTE_TRACKERR | NOTE_CHILD)) != 0)
478 return(ENOTSUP);
0c530ab8 479
2d21ac55 480 p = proc_find(kn->kn_id);
91447636 481 if (p == NULL) {
55e303ae 482 return (ESRCH);
91447636 483 }
55e303ae 484
99c3a104
A
485 const int NoteExitStatusBits = NOTE_EXIT | NOTE_EXITSTATUS;
486
487 if ((kn->kn_sfflags & NoteExitStatusBits) == NoteExitStatusBits)
488 do {
489 pid_t selfpid = proc_selfpid();
490
491 if (p->p_ppid == selfpid)
492 break; /* parent => ok */
493
494 if ((p->p_lflag & P_LTRACED) != 0 &&
495 (p->p_oppid == selfpid))
496 break; /* parent-in-waiting => ok */
497
6d2010ae 498 proc_rele(p);
99c3a104
A
499 return (EACCES);
500 } while (0);
6d2010ae 501
2d21ac55
A
502 proc_klist_lock();
503
504 kn->kn_flags |= EV_CLEAR; /* automatically set */
505 kn->kn_ptr.p_proc = p; /* store the proc handle */
55e303ae 506
55e303ae
A
507 KNOTE_ATTACH(&p->p_klist, kn);
508
2d21ac55
A
509 proc_klist_unlock();
510
511 proc_rele(p);
91447636 512
55e303ae
A
513 return (0);
514}
515
516/*
517 * The knote may be attached to a different process, which may exit,
0c530ab8 518 * leaving nothing for the knote to be attached to. In that case,
2d21ac55 519 * the pointer to the process will have already been nulled out.
55e303ae
A
520 */
521static void
522filt_procdetach(struct knote *kn)
523{
91447636 524 struct proc *p;
91447636 525
2d21ac55
A
526 proc_klist_lock();
527
528 p = kn->kn_ptr.p_proc;
529 if (p != PROC_NULL) {
530 kn->kn_ptr.p_proc = PROC_NULL;
91447636 531 KNOTE_DETACH(&p->p_klist, kn);
0c530ab8 532 }
2d21ac55
A
533
534 proc_klist_unlock();
55e303ae
A
535}
536
537static int
538filt_proc(struct knote *kn, long hint)
539{
2d21ac55 540 /* hint is 0 when called from above */
0c530ab8
A
541 if (hint != 0) {
542 u_int event;
55e303ae 543
2d21ac55 544 /* ALWAYS CALLED WITH proc_klist_lock when (hint != 0) */
55e303ae 545
0c530ab8
A
546 /*
547 * mask off extra data
548 */
549 event = (u_int)hint & NOTE_PCTRLMASK;
4452a7af 550
0c530ab8
A
551 /*
552 * if the user is interested in this event, record it.
553 */
554 if (kn->kn_sfflags & event)
555 kn->kn_fflags |= event;
55e303ae 556
2d21ac55
A
557 if (event == NOTE_REAP || (event == NOTE_EXIT && !(kn->kn_sfflags & NOTE_REAP))) {
558 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
0c530ab8 559 }
6d2010ae
A
560 if ((event == NOTE_EXIT) && ((kn->kn_sfflags & NOTE_EXITSTATUS) != 0)) {
561 kn->kn_fflags |= NOTE_EXITSTATUS;
562 kn->kn_data = (hint & NOTE_PDATAMASK);
563 }
564 if ((event == NOTE_RESOURCEEND) && ((kn->kn_sfflags & NOTE_RESOURCEEND) != 0)) {
565 kn->kn_fflags |= NOTE_RESOURCEEND;
566 kn->kn_data = (hint & NOTE_PDATAMASK);
567 }
316670eb
A
568#if CONFIG_EMBEDDED
569 /* If the event is one of the APPSTATE events,remove the rest */
570 if (((event & NOTE_APPALLSTATES) != 0) && ((kn->kn_sfflags & NOTE_APPALLSTATES) != 0)) {
571 /* only one state at a time */
572 kn->kn_fflags &= ~NOTE_APPALLSTATES;
573 kn->kn_fflags |= event;
574 }
575#endif /* CONFIG_EMBEDDED */
0c530ab8 576 }
6601e61a 577
2d21ac55
A
578 /* atomic check, no locking need when called from above */
579 return (kn->kn_fflags != 0);
55e303ae
A
580}
581
316670eb 582#if VM_PRESSURE_EVENTS
6d2010ae
A
583/*
584 * Virtual memory kevents
585 *
586 * author: Matt Jacobson [matthew_jacobson@apple.com]
587 */
588
589static int
590filt_vmattach(struct knote *kn)
591{
592 /*
593 * The note will be cleared once the information has been flushed to the client.
594 * If there is still pressure, we will be re-alerted.
595 */
596 kn->kn_flags |= EV_CLEAR;
597
598 return vm_knote_register(kn);
599}
600
601static void
602filt_vmdetach(struct knote *kn)
603{
604 vm_knote_unregister(kn);
605}
606
607static int
608filt_vm(struct knote *kn, long hint)
609{
610 /* hint == 0 means this is just an alive? check (always true) */
611 if (hint != 0) {
316670eb
A
612 const pid_t pid = (pid_t)hint;
613 if ((kn->kn_sfflags & NOTE_VM_PRESSURE) && (kn->kn_kq->kq_p->p_pid == pid)) {
614 kn->kn_fflags |= NOTE_VM_PRESSURE;
6d2010ae
A
615 }
616 }
617
618 return (kn->kn_fflags != 0);
619}
316670eb 620#endif /* VM_PRESSURE_EVENTS */
b0d623f7 621
91447636 622/*
b0d623f7
A
623 * filt_timervalidate - process data from user
624 *
625 * Converts to either interval or deadline format.
626 *
91447636
A
627 * The saved-data field in the knote contains the
628 * time value. The saved filter-flags indicates
629 * the unit of measurement.
630 *
b0d623f7
A
631 * After validation, either the saved-data field
632 * contains the interval in absolute time, or ext[0]
633 * contains the expected deadline. If that deadline
634 * is in the past, ext[0] is 0.
635 *
636 * Returns EINVAL for unrecognized units of time.
637 *
638 * Timer filter lock is held.
639 *
91447636
A
640 */
641static int
b0d623f7 642filt_timervalidate(struct knote *kn)
91447636
A
643{
644 uint64_t multiplier;
645 uint64_t raw;
646
647 switch (kn->kn_sfflags & (NOTE_SECONDS|NOTE_USECONDS|NOTE_NSECONDS)) {
648 case NOTE_SECONDS:
649 multiplier = NSEC_PER_SEC;
650 break;
651 case NOTE_USECONDS:
652 multiplier = NSEC_PER_USEC;
653 break;
654 case NOTE_NSECONDS:
655 multiplier = 1;
656 break;
657 case 0: /* milliseconds (default) */
658 multiplier = NSEC_PER_SEC / 1000;
659 break;
660 default:
661 return EINVAL;
662 }
b0d623f7 663
91447636 664 nanoseconds_to_absolutetime((uint64_t)kn->kn_sdata * multiplier, &raw);
b0d623f7
A
665
666 kn->kn_ext[0] = 0;
667 kn->kn_sdata = 0;
668
669 if (kn->kn_sfflags & NOTE_ABSOLUTE) {
670 clock_sec_t seconds;
671 clock_nsec_t nanoseconds;
91447636
A
672 uint64_t now;
673
674 clock_get_calendar_nanotime(&seconds, &nanoseconds);
b0d623f7
A
675 nanoseconds_to_absolutetime((uint64_t)seconds * NSEC_PER_SEC +
676 nanoseconds, &now);
677
678 if (raw < now) {
679 /* time has already passed */
680 kn->kn_ext[0] = 0;
681 } else {
682 raw -= now;
683 clock_absolutetime_interval_to_deadline(raw,
684 &kn->kn_ext[0]);
91447636 685 }
b0d623f7
A
686 } else {
687 kn->kn_sdata = raw;
688 }
689
91447636
A
690 return 0;
691}
692
b0d623f7
A
693/*
694 * filt_timerupdate - compute the next deadline
695 *
696 * Repeating timers store their interval in kn_sdata. Absolute
697 * timers have already calculated the deadline, stored in ext[0].
698 *
699 * On return, the next deadline (or zero if no deadline is needed)
700 * is stored in kn_ext[0].
701 *
702 * Timer filter lock is held.
703 */
704static void
705filt_timerupdate(struct knote *kn)
706{
707 /* if there's no interval, deadline is just in kn_ext[0] */
708 if (kn->kn_sdata == 0)
709 return;
710
711 /* if timer hasn't fired before, fire in interval nsecs */
712 if (kn->kn_ext[0] == 0) {
713 clock_absolutetime_interval_to_deadline(kn->kn_sdata,
714 &kn->kn_ext[0]);
715 } else {
716 /*
717 * If timer has fired before, schedule the next pop
718 * relative to the last intended deadline.
719 *
720 * We could check for whether the deadline has expired,
721 * but the thread call layer can handle that.
722 */
723 kn->kn_ext[0] += kn->kn_sdata;
724 }
725}
726
91447636
A
727/*
728 * filt_timerexpire - the timer callout routine
729 *
730 * Just propagate the timer event into the knote
731 * filter routine (by going through the knote
732 * synchronization point). Pass a hint to
733 * indicate this is a real event, not just a
734 * query from above.
735 */
55e303ae 736static void
91447636 737filt_timerexpire(void *knx, __unused void *spare)
55e303ae 738{
91447636 739 struct klist timer_list;
55e303ae 740 struct knote *kn = knx;
91447636 741
b0d623f7
A
742 filt_timerlock();
743
744 kn->kn_hookid &= ~TIMER_RUNNING;
745
91447636
A
746 /* no "object" for timers, so fake a list */
747 SLIST_INIT(&timer_list);
748 SLIST_INSERT_HEAD(&timer_list, kn, kn_selnext);
749 KNOTE(&timer_list, 1);
b0d623f7
A
750
751 /* if someone is waiting for timer to pop */
752 if (kn->kn_hookid & TIMER_CANCELWAIT) {
753 struct kqueue *kq = kn->kn_kq;
754 wait_queue_wakeup_all((wait_queue_t)kq->kq_wqs, &kn->kn_hook,
755 THREAD_AWAKENED);
756 }
757
758 filt_timerunlock();
759}
760
761/*
762 * Cancel a running timer (or wait for the pop).
763 * Timer filter lock is held.
764 */
765static void
766filt_timercancel(struct knote *kn)
767{
768 struct kqueue *kq = kn->kn_kq;
769 thread_call_t callout = kn->kn_hook;
770 boolean_t cancelled;
771
772 if (kn->kn_hookid & TIMER_RUNNING) {
773 /* cancel the callout if we can */
774 cancelled = thread_call_cancel(callout);
775 if (cancelled) {
776 kn->kn_hookid &= ~TIMER_RUNNING;
777 } else {
778 /* we have to wait for the expire routine. */
779 kn->kn_hookid |= TIMER_CANCELWAIT;
780 wait_queue_assert_wait((wait_queue_t)kq->kq_wqs,
781 &kn->kn_hook, THREAD_UNINT, 0);
782 filt_timerunlock();
783 thread_block(THREAD_CONTINUE_NULL);
784 filt_timerlock();
785 assert((kn->kn_hookid & TIMER_RUNNING) == 0);
786 }
787 }
55e303ae
A
788}
789
790/*
b0d623f7 791 * Allocate a thread call for the knote's lifetime, and kick off the timer.
55e303ae
A
792 */
793static int
794filt_timerattach(struct knote *kn)
795{
91447636 796 thread_call_t callout;
91447636 797 int error;
55e303ae 798
b0d623f7
A
799 callout = thread_call_allocate(filt_timerexpire, kn);
800 if (NULL == callout)
801 return (ENOMEM);
55e303ae 802
b0d623f7
A
803 filt_timerlock();
804 error = filt_timervalidate(kn);
805 if (error) {
806 filt_timerunlock();
807 return (error);
91447636 808 }
55e303ae 809
b0d623f7
A
810 kn->kn_hook = (void*)callout;
811 kn->kn_hookid = 0;
55e303ae 812
91447636
A
813 /* absolute=EV_ONESHOT */
814 if (kn->kn_sfflags & NOTE_ABSOLUTE)
815 kn->kn_flags |= EV_ONESHOT;
816
b0d623f7
A
817 filt_timerupdate(kn);
818 if (kn->kn_ext[0]) {
91447636 819 kn->kn_flags |= EV_CLEAR;
b0d623f7
A
820 thread_call_enter_delayed(callout, kn->kn_ext[0]);
821 kn->kn_hookid |= TIMER_RUNNING;
91447636
A
822 } else {
823 /* fake immediate */
b0d623f7 824 kn->kn_data = 1;
91447636 825 }
b0d623f7 826
91447636 827 filt_timerunlock();
55e303ae
A
828 return (0);
829}
830
b0d623f7
A
831/*
832 * Shut down the timer if it's running, and free the callout.
833 */
55e303ae
A
834static void
835filt_timerdetach(struct knote *kn)
836{
91447636
A
837 thread_call_t callout;
838
839 filt_timerlock();
91447636 840
b0d623f7
A
841 callout = (thread_call_t)kn->kn_hook;
842 filt_timercancel(kn);
843
91447636 844 filt_timerunlock();
b0d623f7
A
845
846 thread_call_free(callout);
55e303ae
A
847}
848
91447636
A
849
850
55e303ae 851static int
b0d623f7 852filt_timer(struct knote *kn, long hint)
55e303ae 853{
91447636
A
854 int result;
855
856 if (hint) {
b0d623f7 857 /* real timer pop -- timer lock held by filt_timerexpire */
91447636 858
91447636
A
859 kn->kn_data++;
860
b0d623f7
A
861 if (((kn->kn_hookid & TIMER_CANCELWAIT) == 0) &&
862 ((kn->kn_flags & EV_ONESHOT) == 0)) {
55e303ae 863
b0d623f7
A
864 /* evaluate next time to fire */
865 filt_timerupdate(kn);
91447636 866
b0d623f7 867 if (kn->kn_ext[0]) {
91447636 868 /* keep the callout and re-arm */
b0d623f7
A
869 thread_call_enter_delayed(kn->kn_hook,
870 kn->kn_ext[0]);
871 kn->kn_hookid |= TIMER_RUNNING;
91447636
A
872 }
873 }
91447636
A
874
875 return 1;
876 }
877
878 /* user-query */
879 filt_timerlock();
880
b0d623f7 881 result = (kn->kn_data != 0);
91447636 882
b0d623f7
A
883 filt_timerunlock();
884 return result;
885}
886
887
888/*
889 * filt_timertouch - update knote with new user input
890 *
891 * Cancel and restart the timer based on new user data. When
892 * the user picks up a knote, clear the count of how many timer
893 * pops have gone off (in kn_data).
894 */
895static void
896filt_timertouch(struct knote *kn, struct kevent64_s *kev, long type)
897{
898 int error;
899 filt_timerlock();
900
901 switch (type) {
902 case EVENT_REGISTER:
903 /* cancel current call */
904 filt_timercancel(kn);
905
906 /* recalculate deadline */
907 kn->kn_sdata = kev->data;
908 kn->kn_sfflags = kev->fflags;
909
910 error = filt_timervalidate(kn);
91447636 911 if (error) {
b0d623f7 912 /* no way to report error, so mark it in the knote */
91447636
A
913 kn->kn_flags |= EV_ERROR;
914 kn->kn_data = error;
b0d623f7
A
915 break;
916 }
917
918 /* start timer if necessary */
919 filt_timerupdate(kn);
920 if (kn->kn_ext[0]) {
921 thread_call_enter_delayed(kn->kn_hook, kn->kn_ext[0]);
922 kn->kn_hookid |= TIMER_RUNNING;
923 } else {
924 /* pretend the timer has fired */
925 kn->kn_data = 1;
91447636 926 }
91447636 927
b0d623f7
A
928 break;
929
930 case EVENT_PROCESS:
931 /* reset the timer pop count in kn_data */
932 *kev = kn->kn_kevent;
933 kev->ext[0] = 0;
934 kn->kn_data = 0;
935 if (kn->kn_flags & EV_CLEAR)
936 kn->kn_fflags = 0;
937 break;
938 default:
939 panic("filt_timertouch() - invalid type (%ld)", type);
940 break;
941 }
91447636 942
91447636 943 filt_timerunlock();
91447636
A
944}
945
946static void
947filt_timerlock(void)
948{
949 lck_mtx_lock(&_filt_timerlock);
950}
951
952static void
953filt_timerunlock(void)
954{
955 lck_mtx_unlock(&_filt_timerlock);
55e303ae 956}
55e303ae 957
b0d623f7
A
958static int
959filt_userattach(struct knote *kn)
960{
961 /* EVFILT_USER knotes are not attached to anything in the kernel */
962 kn->kn_hook = NULL;
6d2010ae 963 if (kn->kn_fflags & NOTE_TRIGGER) {
b0d623f7
A
964 kn->kn_hookid = 1;
965 } else {
966 kn->kn_hookid = 0;
967 }
968 return 0;
969}
970
971static void
972filt_userdetach(__unused struct knote *kn)
973{
974 /* EVFILT_USER knotes are not attached to anything in the kernel */
975}
976
977static int
978filt_user(struct knote *kn, __unused long hint)
979{
980 return kn->kn_hookid;
981}
982
983static void
984filt_usertouch(struct knote *kn, struct kevent64_s *kev, long type)
985{
6d2010ae 986 uint32_t ffctrl;
b0d623f7
A
987 switch (type) {
988 case EVENT_REGISTER:
6d2010ae 989 if (kev->fflags & NOTE_TRIGGER) {
b0d623f7
A
990 kn->kn_hookid = 1;
991 }
992
993 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
994 kev->fflags &= NOTE_FFLAGSMASK;
995 switch (ffctrl) {
996 case NOTE_FFNOP:
997 break;
998 case NOTE_FFAND:
999 OSBitAndAtomic(kev->fflags, &kn->kn_sfflags);
1000 break;
1001 case NOTE_FFOR:
1002 OSBitOrAtomic(kev->fflags, &kn->kn_sfflags);
1003 break;
1004 case NOTE_FFCOPY:
1005 kn->kn_sfflags = kev->fflags;
1006 break;
1007 }
1008 kn->kn_sdata = kev->data;
1009 break;
1010 case EVENT_PROCESS:
1011 *kev = kn->kn_kevent;
1012 kev->fflags = (volatile UInt32)kn->kn_sfflags;
1013 kev->data = kn->kn_sdata;
1014 if (kn->kn_flags & EV_CLEAR) {
1015 kn->kn_hookid = 0;
1016 kn->kn_data = 0;
1017 kn->kn_fflags = 0;
1018 }
1019 break;
1020 default:
1021 panic("filt_usertouch() - invalid type (%ld)", type);
1022 break;
1023 }
1024}
1025
55e303ae
A
1026/*
1027 * JMM - placeholder for not-yet-implemented filters
1028 */
1029static int
91447636 1030filt_badattach(__unused struct knote *kn)
55e303ae 1031{
91447636 1032 return(ENOTSUP);
55e303ae
A
1033}
1034
55e303ae 1035
91447636
A
1036struct kqueue *
1037kqueue_alloc(struct proc *p)
1038{
1039 struct filedesc *fdp = p->p_fd;
1040 struct kqueue *kq;
1041
1042 MALLOC_ZONE(kq, struct kqueue *, sizeof(struct kqueue), M_KQUEUE, M_WAITOK);
1043 if (kq != NULL) {
b0d623f7
A
1044 wait_queue_set_t wqs;
1045
1046 wqs = wait_queue_set_alloc(SYNC_POLICY_FIFO | SYNC_POLICY_PREPOST);
1047 if (wqs != NULL) {
1048 bzero(kq, sizeof(struct kqueue));
1049 lck_spin_init(&kq->kq_lock, kq_lck_grp, kq_lck_attr);
1050 TAILQ_INIT(&kq->kq_head);
1051 kq->kq_wqs = wqs;
1052 kq->kq_p = p;
1053 } else {
1054 FREE_ZONE(kq, sizeof(struct kqueue), M_KQUEUE);
1055 }
91447636
A
1056 }
1057
1058 if (fdp->fd_knlistsize < 0) {
1059 proc_fdlock(p);
1060 if (fdp->fd_knlistsize < 0)
1061 fdp->fd_knlistsize = 0; /* this process has had a kq */
1062 proc_fdunlock(p);
1063 }
1064
1065 return kq;
1066}
1067
1068
1069/*
1070 * kqueue_dealloc - detach all knotes from a kqueue and free it
1071 *
1072 * We walk each list looking for knotes referencing this
1073 * this kqueue. If we find one, we try to drop it. But
1074 * if we fail to get a drop reference, that will wait
1075 * until it is dropped. So, we can just restart again
1076 * safe in the assumption that the list will eventually
1077 * not contain any more references to this kqueue (either
1078 * we dropped them all, or someone else did).
1079 *
1080 * Assumes no new events are being added to the kqueue.
1081 * Nothing locked on entry or exit.
1082 */
1083void
2d21ac55 1084kqueue_dealloc(struct kqueue *kq)
55e303ae 1085{
2d21ac55 1086 struct proc *p = kq->kq_p;
55e303ae 1087 struct filedesc *fdp = p->p_fd;
91447636
A
1088 struct knote *kn;
1089 int i;
1090
1091 proc_fdlock(p);
1092 for (i = 0; i < fdp->fd_knlistsize; i++) {
1093 kn = SLIST_FIRST(&fdp->fd_knlist[i]);
1094 while (kn != NULL) {
1095 if (kq == kn->kn_kq) {
1096 kqlock(kq);
1097 proc_fdunlock(p);
1098 /* drop it ourselves or wait */
1099 if (kqlock2knotedrop(kq, kn)) {
1100 kn->kn_fop->f_detach(kn);
1101 knote_drop(kn, p);
1102 }
1103 proc_fdlock(p);
1104 /* start over at beginning of list */
1105 kn = SLIST_FIRST(&fdp->fd_knlist[i]);
1106 continue;
1107 }
1108 kn = SLIST_NEXT(kn, kn_link);
1109 }
1110 }
1111 if (fdp->fd_knhashmask != 0) {
1112 for (i = 0; i < (int)fdp->fd_knhashmask + 1; i++) {
1113 kn = SLIST_FIRST(&fdp->fd_knhash[i]);
1114 while (kn != NULL) {
1115 if (kq == kn->kn_kq) {
1116 kqlock(kq);
1117 proc_fdunlock(p);
1118 /* drop it ourselves or wait */
1119 if (kqlock2knotedrop(kq, kn)) {
1120 kn->kn_fop->f_detach(kn);
1121 knote_drop(kn, p);
1122 }
1123 proc_fdlock(p);
1124 /* start over at beginning of list */
1125 kn = SLIST_FIRST(&fdp->fd_knhash[i]);
1126 continue;
1127 }
1128 kn = SLIST_NEXT(kn, kn_link);
1129 }
1130 }
1131 }
1132 proc_fdunlock(p);
b0d623f7
A
1133
1134 /*
1135 * before freeing the wait queue set for this kqueue,
1136 * make sure it is unlinked from all its containing (select) sets.
1137 */
1138 wait_queue_unlink_all((wait_queue_t)kq->kq_wqs);
1139 wait_queue_set_free(kq->kq_wqs);
91447636
A
1140 lck_spin_destroy(&kq->kq_lock, kq_lck_grp);
1141 FREE_ZONE(kq, sizeof(struct kqueue), M_KQUEUE);
1142}
1143
1144int
b0d623f7 1145kqueue(struct proc *p, __unused struct kqueue_args *uap, int32_t *retval)
91447636 1146{
55e303ae 1147 struct kqueue *kq;
91447636 1148 struct fileproc *fp;
55e303ae
A
1149 int fd, error;
1150
2d21ac55 1151 error = falloc(p, &fp, &fd, vfs_context_current());
91447636 1152 if (error) {
55e303ae 1153 return (error);
91447636
A
1154 }
1155
1156 kq = kqueue_alloc(p);
1157 if (kq == NULL) {
1158 fp_free(p, fd, fp);
1159 return (ENOMEM);
1160 }
1161
55e303ae
A
1162 fp->f_flag = FREAD | FWRITE;
1163 fp->f_type = DTYPE_KQUEUE;
1164 fp->f_ops = &kqueueops;
55e303ae 1165 fp->f_data = (caddr_t)kq;
91447636
A
1166
1167 proc_fdlock(p);
6601e61a 1168 procfdtbl_releasefd(p, fd, NULL);
91447636
A
1169 fp_drop(p, fd, fp, 1);
1170 proc_fdunlock(p);
1171
55e303ae 1172 *retval = fd;
55e303ae
A
1173 return (error);
1174}
1175
91447636 1176static int
b0d623f7 1177kevent_copyin(user_addr_t *addrp, struct kevent64_s *kevp, struct proc *p, int iskev64)
55e303ae 1178{
91447636
A
1179 int advance;
1180 int error;
55e303ae 1181
b0d623f7
A
1182 if (iskev64) {
1183 advance = sizeof(struct kevent64_s);
1184 error = copyin(*addrp, (caddr_t)kevp, advance);
1185 } else if (IS_64BIT_PROCESS(p)) {
1186 struct user64_kevent kev64;
1187 bzero(kevp, sizeof(struct kevent64_s));
91447636
A
1188
1189 advance = sizeof(kev64);
1190 error = copyin(*addrp, (caddr_t)&kev64, advance);
55e303ae 1191 if (error)
91447636 1192 return error;
b0d623f7 1193 kevp->ident = kev64.ident;
91447636
A
1194 kevp->filter = kev64.filter;
1195 kevp->flags = kev64.flags;
1196 kevp->fflags = kev64.fflags;
b0d623f7 1197 kevp->data = kev64.data;
91447636
A
1198 kevp->udata = kev64.udata;
1199 } else {
b0d623f7
A
1200 struct user32_kevent kev32;
1201 bzero(kevp, sizeof(struct kevent64_s));
1202
1203 advance = sizeof(kev32);
1204 error = copyin(*addrp, (caddr_t)&kev32, advance);
1205 if (error)
1206 return error;
1207 kevp->ident = (uintptr_t)kev32.ident;
1208 kevp->filter = kev32.filter;
1209 kevp->flags = kev32.flags;
1210 kevp->fflags = kev32.fflags;
1211 kevp->data = (intptr_t)kev32.data;
1212 kevp->udata = CAST_USER_ADDR_T(kev32.udata);
55e303ae 1213 }
91447636
A
1214 if (!error)
1215 *addrp += advance;
1216 return error;
1217}
55e303ae 1218
91447636 1219static int
b0d623f7 1220kevent_copyout(struct kevent64_s *kevp, user_addr_t *addrp, struct proc *p, int iskev64)
91447636
A
1221{
1222 int advance;
1223 int error;
1224
b0d623f7
A
1225 if (iskev64) {
1226 advance = sizeof(struct kevent64_s);
1227 error = copyout((caddr_t)kevp, *addrp, advance);
1228 } else if (IS_64BIT_PROCESS(p)) {
1229 struct user64_kevent kev64;
91447636 1230
2d21ac55
A
1231 /*
1232 * deal with the special case of a user-supplied
1233 * value of (uintptr_t)-1.
1234 */
1235 kev64.ident = (kevp->ident == (uintptr_t)-1) ?
1236 (uint64_t)-1LL : (uint64_t)kevp->ident;
1237
91447636
A
1238 kev64.filter = kevp->filter;
1239 kev64.flags = kevp->flags;
1240 kev64.fflags = kevp->fflags;
1241 kev64.data = (int64_t) kevp->data;
1242 kev64.udata = kevp->udata;
1243 advance = sizeof(kev64);
1244 error = copyout((caddr_t)&kev64, *addrp, advance);
1245 } else {
b0d623f7
A
1246 struct user32_kevent kev32;
1247
1248 kev32.ident = (uint32_t)kevp->ident;
1249 kev32.filter = kevp->filter;
1250 kev32.flags = kevp->flags;
1251 kev32.fflags = kevp->fflags;
1252 kev32.data = (int32_t)kevp->data;
1253 kev32.udata = kevp->udata;
1254 advance = sizeof(kev32);
1255 error = copyout((caddr_t)&kev32, *addrp, advance);
91447636
A
1256 }
1257 if (!error)
1258 *addrp += advance;
1259 return error;
1260}
55e303ae 1261
91447636
A
1262/*
1263 * kevent_continue - continue a kevent syscall after blocking
1264 *
1265 * assume we inherit a use count on the kq fileglob.
1266 */
55e303ae 1267
91447636
A
1268static void
1269kevent_continue(__unused struct kqueue *kq, void *data, int error)
1270{
1271 struct _kevent *cont_args;
1272 struct fileproc *fp;
b0d623f7 1273 int32_t *retval;
91447636
A
1274 int noutputs;
1275 int fd;
1276 struct proc *p = current_proc();
1277
1278 cont_args = (struct _kevent *)data;
1279 noutputs = cont_args->eventout;
1280 retval = cont_args->retval;
1281 fd = cont_args->fd;
1282 fp = cont_args->fp;
1283
1284 fp_drop(p, fd, fp, 0);
1285
1286 /* don't restart after signals... */
1287 if (error == ERESTART)
1288 error = EINTR;
1289 else if (error == EWOULDBLOCK)
1290 error = 0;
1291 if (error == 0)
1292 *retval = noutputs;
1293 unix_syscall_return(error);
1294}
55e303ae 1295
91447636
A
1296/*
1297 * kevent - [syscall] register and wait for kernel events
1298 *
1299 */
91447636 1300int
b0d623f7
A
1301kevent(struct proc *p, struct kevent_args *uap, int32_t *retval)
1302{
1303 return kevent_internal(p,
1304 0,
1305 uap->changelist,
1306 uap->nchanges,
1307 uap->eventlist,
1308 uap->nevents,
1309 uap->fd,
1310 uap->timeout,
1311 0, /* no flags from old kevent() call */
1312 retval);
1313}
1314
1315int
1316kevent64(struct proc *p, struct kevent64_args *uap, int32_t *retval)
1317{
1318 return kevent_internal(p,
1319 1,
1320 uap->changelist,
1321 uap->nchanges,
1322 uap->eventlist,
1323 uap->nevents,
1324 uap->fd,
1325 uap->timeout,
1326 uap->flags,
1327 retval);
1328}
91447636 1329
b0d623f7
A
1330static int
1331kevent_internal(struct proc *p, int iskev64, user_addr_t changelist,
1332 int nchanges, user_addr_t ueventlist, int nevents, int fd,
1333 user_addr_t utimeout, __unused unsigned int flags,
1334 int32_t *retval)
1335{
91447636
A
1336 struct _kevent *cont_args;
1337 uthread_t ut;
1338 struct kqueue *kq;
1339 struct fileproc *fp;
b0d623f7 1340 struct kevent64_s kev;
91447636
A
1341 int error, noutputs;
1342 struct timeval atv;
1343
1344 /* convert timeout to absolute - if we have one */
b0d623f7 1345 if (utimeout != USER_ADDR_NULL) {
91447636 1346 struct timeval rtv;
b0d623f7
A
1347 if (IS_64BIT_PROCESS(p)) {
1348 struct user64_timespec ts;
1349 error = copyin(utimeout, &ts, sizeof(ts));
91447636
A
1350 if ((ts.tv_sec & 0xFFFFFFFF00000000ull) != 0)
1351 error = EINVAL;
1352 else
1353 TIMESPEC_TO_TIMEVAL(&rtv, &ts);
1354 } else {
b0d623f7
A
1355 struct user32_timespec ts;
1356 error = copyin(utimeout, &ts, sizeof(ts));
91447636
A
1357 TIMESPEC_TO_TIMEVAL(&rtv, &ts);
1358 }
55e303ae 1359 if (error)
91447636
A
1360 return error;
1361 if (itimerfix(&rtv))
1362 return EINVAL;
1363 getmicrouptime(&atv);
1364 timevaladd(&atv, &rtv);
1365 } else {
1366 atv.tv_sec = 0;
1367 atv.tv_usec = 0;
1368 }
55e303ae 1369
91447636
A
1370 /* get a usecount for the kq itself */
1371 if ((error = fp_getfkq(p, fd, &fp, &kq)) != 0)
1372 return(error);
b0d623f7
A
1373
1374 /* each kq should only be used for events of one type */
1375 kqlock(kq);
1376 if (kq->kq_state & (KQ_KEV32 | KQ_KEV64)) {
1377 if (((iskev64 && (kq->kq_state & KQ_KEV32)) ||
1378 (!iskev64 && (kq->kq_state & KQ_KEV64)))) {
1379 error = EINVAL;
1380 kqunlock(kq);
1381 goto errorout;
1382 }
1383 } else {
1384 kq->kq_state |= (iskev64 ? KQ_KEV64 : KQ_KEV32);
1385 }
1386 kqunlock(kq);
91447636
A
1387
1388 /* register all the change requests the user provided... */
1389 noutputs = 0;
3a60a9f5 1390 while (nchanges > 0 && error == 0) {
b0d623f7 1391 error = kevent_copyin(&changelist, &kev, p, iskev64);
91447636
A
1392 if (error)
1393 break;
1394
1395 kev.flags &= ~EV_SYSFLAGS;
1396 error = kevent_register(kq, &kev, p);
2d21ac55 1397 if ((error || (kev.flags & EV_RECEIPT)) && nevents > 0) {
91447636
A
1398 kev.flags = EV_ERROR;
1399 kev.data = error;
b0d623f7 1400 error = kevent_copyout(&kev, &ueventlist, p, iskev64);
3a60a9f5
A
1401 if (error == 0) {
1402 nevents--;
1403 noutputs++;
1404 }
55e303ae 1405 }
91447636 1406 nchanges--;
55e303ae
A
1407 }
1408
91447636
A
1409 /* store the continuation/completion data in the uthread */
1410 ut = (uthread_t)get_bsdthread_info(current_thread());
b0d623f7 1411 cont_args = &ut->uu_kevent.ss_kevent;
91447636
A
1412 cont_args->fp = fp;
1413 cont_args->fd = fd;
1414 cont_args->retval = retval;
1415 cont_args->eventlist = ueventlist;
1416 cont_args->eventcount = nevents;
1417 cont_args->eventout = noutputs;
b0d623f7 1418 cont_args->eventsize = iskev64;
91447636
A
1419
1420 if (nevents > 0 && noutputs == 0 && error == 0)
b0d623f7 1421 error = kqueue_scan(kq, kevent_callback,
91447636
A
1422 kevent_continue, cont_args,
1423 &atv, p);
1424 kevent_continue(kq, cont_args, error);
b0d623f7
A
1425
1426errorout:
1427 fp_drop(p, fd, fp, 0);
91447636
A
1428 return error;
1429}
1430
1431
1432/*
1433 * kevent_callback - callback for each individual event
1434 *
1435 * called with nothing locked
1436 * caller holds a reference on the kqueue
1437 */
1438
1439static int
b0d623f7
A
1440kevent_callback(__unused struct kqueue *kq, struct kevent64_s *kevp,
1441 void *data)
91447636
A
1442{
1443 struct _kevent *cont_args;
1444 int error;
b0d623f7 1445 int iskev64;
91447636
A
1446
1447 cont_args = (struct _kevent *)data;
2d21ac55 1448 assert(cont_args->eventout < cont_args->eventcount);
91447636 1449
b0d623f7
A
1450 iskev64 = cont_args->eventsize;
1451
91447636
A
1452 /*
1453 * Copy out the appropriate amount of event data for this user.
1454 */
b0d623f7 1455 error = kevent_copyout(kevp, &cont_args->eventlist, current_proc(), iskev64);
91447636
A
1456
1457 /*
1458 * If there isn't space for additional events, return
1459 * a harmless error to stop the processing here
1460 */
1461 if (error == 0 && ++cont_args->eventout == cont_args->eventcount)
1462 error = EWOULDBLOCK;
1463 return error;
55e303ae
A
1464}
1465
b0d623f7
A
1466/*
1467 * kevent_description - format a description of a kevent for diagnostic output
1468 *
1469 * called with a 128-byte string buffer
1470 */
1471
1472char *
1473kevent_description(struct kevent64_s *kevp, char *s, size_t n)
1474{
1475 snprintf(s, n,
1476 "kevent="
1477 "{.ident=%#llx, .filter=%d, .flags=%#x, .fflags=%#x, .data=%#llx, .udata=%#llx, .ext[0]=%#llx, .ext[1]=%#llx}",
1478 kevp->ident,
1479 kevp->filter,
1480 kevp->flags,
1481 kevp->fflags,
1482 kevp->data,
1483 kevp->udata,
1484 kevp->ext[0],
1485 kevp->ext[1]);
1486 return s;
1487}
1488
91447636
A
1489/*
1490 * kevent_register - add a new event to a kqueue
1491 *
1492 * Creates a mapping between the event source and
1493 * the kqueue via a knote data structure.
1494 *
1495 * Because many/most the event sources are file
1496 * descriptor related, the knote is linked off
1497 * the filedescriptor table for quick access.
1498 *
1499 * called with nothing locked
1500 * caller holds a reference on the kqueue
1501 */
1502
55e303ae 1503int
b0d623f7 1504kevent_register(struct kqueue *kq, struct kevent64_s *kev, __unused struct proc *ctxp)
55e303ae 1505{
2d21ac55
A
1506 struct proc *p = kq->kq_p;
1507 struct filedesc *fdp = p->p_fd;
55e303ae 1508 struct filterops *fops;
91447636 1509 struct fileproc *fp = NULL;
55e303ae 1510 struct knote *kn = NULL;
91447636 1511 int error = 0;
55e303ae
A
1512
1513 if (kev->filter < 0) {
1514 if (kev->filter + EVFILT_SYSCOUNT < 0)
1515 return (EINVAL);
1516 fops = sysfilt_ops[~kev->filter]; /* to 0-base index */
1517 } else {
1518 /*
1519 * XXX
1520 * filter attach routine is responsible for insuring that
1521 * the identifier can be attached to it.
1522 */
1523 printf("unknown filter: %d\n", kev->filter);
1524 return (EINVAL);
1525 }
1526
b0d623f7 1527 restart:
91447636 1528 /* this iocount needs to be dropped if it is not registered */
b0d623f7
A
1529 proc_fdlock(p);
1530 if (fops->f_isfd && (error = fp_lookup(p, kev->ident, &fp, 1)) != 0) {
1531 proc_fdunlock(p);
91447636 1532 return(error);
b0d623f7 1533 }
55e303ae 1534
91447636
A
1535 if (fops->f_isfd) {
1536 /* fd-based knotes are linked off the fd table */
1537 if (kev->ident < (u_int)fdp->fd_knlistsize) {
55e303ae
A
1538 SLIST_FOREACH(kn, &fdp->fd_knlist[kev->ident], kn_link)
1539 if (kq == kn->kn_kq &&
1540 kev->filter == kn->kn_filter)
1541 break;
1542 }
1543 } else {
91447636 1544 /* hash non-fd knotes here too */
55e303ae
A
1545 if (fdp->fd_knhashmask != 0) {
1546 struct klist *list;
1547
1548 list = &fdp->fd_knhash[
1549 KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
1550 SLIST_FOREACH(kn, list, kn_link)
1551 if (kev->ident == kn->kn_id &&
1552 kq == kn->kn_kq &&
1553 kev->filter == kn->kn_filter)
1554 break;
1555 }
1556 }
1557
91447636
A
1558 /*
1559 * kn now contains the matching knote, or NULL if no match
1560 */
1561 if (kn == NULL) {
1562 if ((kev->flags & (EV_ADD|EV_DELETE)) == EV_ADD) {
1563 kn = knote_alloc();
1564 if (kn == NULL) {
1565 proc_fdunlock(p);
1566 error = ENOMEM;
1567 goto done;
1568 }
1569 kn->kn_fp = fp;
1570 kn->kn_kq = kq;
1571 kn->kn_tq = &kq->kq_head;
1572 kn->kn_fop = fops;
1573 kn->kn_sfflags = kev->fflags;
1574 kn->kn_sdata = kev->data;
1575 kev->fflags = 0;
1576 kev->data = 0;
1577 kn->kn_kevent = *kev;
1578 kn->kn_inuse = 1; /* for f_attach() */
b0d623f7 1579 kn->kn_status = KN_ATTACHING;
91447636
A
1580
1581 /* before anyone can find it */
1582 if (kev->flags & EV_DISABLE)
1583 kn->kn_status |= KN_DISABLED;
1584
1585 error = knote_fdpattach(kn, fdp, p);
1586 proc_fdunlock(p);
1587
1588 if (error) {
1589 knote_free(kn);
1590 goto done;
1591 }
1592
1593 /*
1594 * apply reference count to knote structure, and
1595 * do not release it at the end of this routine.
1596 */
1597 fp = NULL;
1598
b0d623f7
A
1599 error = fops->f_attach(kn);
1600
b0d623f7 1601 kqlock(kq);
6d2010ae 1602
7e4a7d39
A
1603 if (error != 0) {
1604 /*
1605 * Failed to attach correctly, so drop.
1606 * All other possible users/droppers
1607 * have deferred to us.
1608 */
b0d623f7
A
1609 kn->kn_status |= KN_DROPPING;
1610 kqunlock(kq);
91447636
A
1611 knote_drop(kn, p);
1612 goto done;
7e4a7d39
A
1613 } else if (kn->kn_status & KN_DROPPING) {
1614 /*
1615 * Attach succeeded, but someone else
1616 * deferred their drop - now we have
1617 * to do it for them (after detaching).
1618 */
1619 kqunlock(kq);
1620 kn->kn_fop->f_detach(kn);
1621 knote_drop(kn, p);
1622 goto done;
91447636 1623 }
b0d623f7
A
1624 kn->kn_status &= ~KN_ATTACHING;
1625 kqunlock(kq);
91447636
A
1626 } else {
1627 proc_fdunlock(p);
1628 error = ENOENT;
1629 goto done;
1630 }
1631 } else {
1632 /* existing knote - get kqueue lock */
1633 kqlock(kq);
1634 proc_fdunlock(p);
1635
1636 if (kev->flags & EV_DELETE) {
1637 knote_dequeue(kn);
1638 kn->kn_status |= KN_DISABLED;
1639 if (kqlock2knotedrop(kq, kn)) {
1640 kn->kn_fop->f_detach(kn);
1641 knote_drop(kn, p);
1642 }
1643 goto done;
1644 }
1645
1646 /* update status flags for existing knote */
1647 if (kev->flags & EV_DISABLE) {
1648 knote_dequeue(kn);
1649 kn->kn_status |= KN_DISABLED;
1650 } else if (kev->flags & EV_ENABLE) {
1651 kn->kn_status &= ~KN_DISABLED;
1652 if (kn->kn_status & KN_ACTIVE)
1653 knote_enqueue(kn);
1654 }
1655
b7266188
A
1656 /*
1657 * The user may change some filter values after the
1658 * initial EV_ADD, but doing so will not reset any
1659 * filter which have already been triggered.
1660 */
1661 kn->kn_kevent.udata = kev->udata;
1662 if (fops->f_isfd || fops->f_touch == NULL) {
1663 kn->kn_sfflags = kev->fflags;
1664 kn->kn_sdata = kev->data;
1665 }
1666
91447636
A
1667 /*
1668 * If somebody is in the middle of dropping this
1669 * knote - go find/insert a new one. But we have
b0d623f7
A
1670 * wait for this one to go away first. Attaches
1671 * running in parallel may also drop/modify the
1672 * knote. Wait for those to complete as well and
1673 * then start over if we encounter one.
91447636 1674 */
b0d623f7
A
1675 if (!kqlock2knoteusewait(kq, kn)) {
1676 /* kqueue, proc_fdlock both unlocked */
91447636 1677 goto restart;
b0d623f7 1678 }
91447636
A
1679
1680 /*
b7266188
A
1681 * Call touch routine to notify filter of changes
1682 * in filter values.
91447636 1683 */
b0d623f7
A
1684 if (!fops->f_isfd && fops->f_touch != NULL)
1685 fops->f_touch(kn, kev, EVENT_REGISTER);
91447636 1686 }
91447636 1687 /* still have use ref on knote */
b0d623f7
A
1688
1689 /*
1690 * If the knote is not marked to always stay enqueued,
1691 * invoke the filter routine to see if it should be
1692 * enqueued now.
1693 */
1694 if ((kn->kn_status & KN_STAYQUEUED) == 0 && kn->kn_fop->f_event(kn, 0)) {
91447636 1695 if (knoteuse2kqlock(kq, kn))
b0d623f7 1696 knote_activate(kn, 1);
91447636
A
1697 kqunlock(kq);
1698 } else {
1699 knote_put(kn);
1700 }
1701
1702done:
1703 if (fp != NULL)
1704 fp_drop(p, kev->ident, fp, 0);
1705 return (error);
1706}
1707
b0d623f7
A
1708
1709/*
1710 * knote_process - process a triggered event
1711 *
1712 * Validate that it is really still a triggered event
1713 * by calling the filter routines (if necessary). Hold
1714 * a use reference on the knote to avoid it being detached.
1715 * If it is still considered triggered, invoke the callback
1716 * routine provided and move it to the provided inprocess
1717 * queue.
1718 *
1719 * caller holds a reference on the kqueue.
1720 * kqueue locked on entry and exit - but may be dropped
1721 */
1722static int
1723knote_process(struct knote *kn,
1724 kevent_callback_t callback,
1725 void *data,
1726 struct kqtailq *inprocessp,
1727 struct proc *p)
1728{
1729 struct kqueue *kq = kn->kn_kq;
1730 struct kevent64_s kev;
1731 int touch;
1732 int result;
1733 int error;
1734
1735 /*
1736 * Determine the kevent state we want to return.
1737 *
1738 * Some event states need to be revalidated before returning
1739 * them, others we take the snapshot at the time the event
1740 * was enqueued.
1741 *
1742 * Events with non-NULL f_touch operations must be touched.
1743 * Triggered events must fill in kev for the callback.
1744 *
1745 * Convert our lock to a use-count and call the event's
1746 * filter routine(s) to update.
1747 */
1748 if ((kn->kn_status & KN_DISABLED) != 0) {
1749 result = 0;
1750 touch = 0;
1751 } else {
1752 int revalidate;
1753
1754 result = 1;
1755 revalidate = ((kn->kn_status & KN_STAYQUEUED) != 0 ||
1756 (kn->kn_flags & EV_ONESHOT) == 0);
1757 touch = (!kn->kn_fop->f_isfd && kn->kn_fop->f_touch != NULL);
1758
1759 if (revalidate || touch) {
1760 if (revalidate)
1761 knote_deactivate(kn);
1762
1763 /* call the filter/touch routines with just a ref */
1764 if (kqlock2knoteuse(kq, kn)) {
1765
1766 /* if we have to revalidate, call the filter */
1767 if (revalidate) {
1768 result = kn->kn_fop->f_event(kn, 0);
1769 }
1770
1771 /* capture the kevent data - using touch if specified */
b7266188
A
1772 if (result && touch) {
1773 kn->kn_fop->f_touch(kn, &kev, EVENT_PROCESS);
b0d623f7 1774 }
b7266188 1775
b0d623f7
A
1776 /* convert back to a kqlock - bail if the knote went away */
1777 if (!knoteuse2kqlock(kq, kn)) {
1778 return EJUSTRETURN;
1779 } else if (result) {
1780 /* if revalidated as alive, make sure it's active */
1781 if (!(kn->kn_status & KN_ACTIVE)) {
1782 knote_activate(kn, 0);
1783 }
b7266188
A
1784
1785 /* capture all events that occurred during filter */
1786 if (!touch) {
1787 kev = kn->kn_kevent;
1788 }
1789
b0d623f7
A
1790 } else if ((kn->kn_status & KN_STAYQUEUED) == 0) {
1791 /* was already dequeued, so just bail on this one */
1792 return EJUSTRETURN;
1793 }
1794 } else {
1795 return EJUSTRETURN;
1796 }
1797 } else {
1798 kev = kn->kn_kevent;
1799 }
1800 }
1801
1802 /* move knote onto inprocess queue */
1803 assert(kn->kn_tq == &kq->kq_head);
1804 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1805 kn->kn_tq = inprocessp;
1806 TAILQ_INSERT_TAIL(inprocessp, kn, kn_tqe);
1807
1808 /*
1809 * Determine how to dispatch the knote for future event handling.
1810 * not-fired: just return (do not callout).
1811 * One-shot: deactivate it.
1812 * Clear: deactivate and clear the state.
1813 * Dispatch: don't clear state, just deactivate it and mark it disabled.
1814 * All others: just leave where they are.
1815 */
1816
1817 if (result == 0) {
1818 return EJUSTRETURN;
b7266188 1819 } else if ((kn->kn_flags & EV_ONESHOT) != 0) {
b0d623f7
A
1820 knote_deactivate(kn);
1821 if (kqlock2knotedrop(kq, kn)) {
1822 kn->kn_fop->f_detach(kn);
1823 knote_drop(kn, p);
1824 }
b7266188
A
1825 } else if ((kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) != 0) {
1826 if ((kn->kn_flags & EV_DISPATCH) != 0) {
1827 /* deactivate and disable all dispatch knotes */
1828 knote_deactivate(kn);
1829 kn->kn_status |= KN_DISABLED;
1830 } else if (!touch || kn->kn_fflags == 0) {
1831 /* only deactivate if nothing since the touch */
1832 knote_deactivate(kn);
1833 }
1834 if (!touch && (kn->kn_flags & EV_CLEAR) != 0) {
1835 /* manually clear non-touch knotes */
b0d623f7
A
1836 kn->kn_data = 0;
1837 kn->kn_fflags = 0;
1838 }
b0d623f7
A
1839 kqunlock(kq);
1840 } else {
1841 /*
1842 * leave on inprocess queue. We'll
1843 * move all the remaining ones back
1844 * the kq queue and wakeup any
1845 * waiters when we are done.
1846 */
1847 kqunlock(kq);
1848 }
1849
1850 /* callback to handle each event as we find it */
1851 error = (callback)(kq, &kev, data);
1852
1853 kqlock(kq);
1854 return error;
1855}
1856
6d2010ae
A
1857/*
1858 * Return 0 to indicate that processing should proceed,
1859 * -1 if there is nothing to process.
1860 *
1861 * Called with kqueue locked and returns the same way,
1862 * but may drop lock temporarily.
1863 */
1864static int
1865kqueue_begin_processing(struct kqueue *kq)
1866{
1867 for (;;) {
1868 if (kq->kq_count == 0) {
1869 return -1;
1870 }
1871
1872 /* if someone else is processing the queue, wait */
1873 if (kq->kq_nprocess != 0) {
1874 wait_queue_assert_wait((wait_queue_t)kq->kq_wqs, &kq->kq_nprocess, THREAD_UNINT, 0);
1875 kq->kq_state |= KQ_PROCWAIT;
1876 kqunlock(kq);
1877 thread_block(THREAD_CONTINUE_NULL);
1878 kqlock(kq);
1879 } else {
1880 kq->kq_nprocess = 1;
1881 return 0;
1882 }
1883 }
1884}
1885
1886/*
1887 * Called with kqueue lock held.
1888 */
1889static void
1890kqueue_end_processing(struct kqueue *kq)
1891{
1892 kq->kq_nprocess = 0;
1893 if (kq->kq_state & KQ_PROCWAIT) {
1894 kq->kq_state &= ~KQ_PROCWAIT;
1895 wait_queue_wakeup_all((wait_queue_t)kq->kq_wqs, &kq->kq_nprocess, THREAD_AWAKENED);
1896 }
1897}
b0d623f7 1898
91447636 1899/*
b0d623f7 1900 * kqueue_process - process the triggered events in a kqueue
91447636
A
1901 *
1902 * Walk the queued knotes and validate that they are
1903 * really still triggered events by calling the filter
1904 * routines (if necessary). Hold a use reference on
1905 * the knote to avoid it being detached. For each event
1906 * that is still considered triggered, invoke the
1907 * callback routine provided.
1908 *
1909 * caller holds a reference on the kqueue.
1910 * kqueue locked on entry and exit - but may be dropped
b0d623f7 1911 * kqueue list locked (held for duration of call)
91447636
A
1912 */
1913
1914static int
b0d623f7 1915kqueue_process(struct kqueue *kq,
91447636
A
1916 kevent_callback_t callback,
1917 void *data,
1918 int *countp,
1919 struct proc *p)
1920{
b0d623f7 1921 struct kqtailq inprocess;
91447636 1922 struct knote *kn;
91447636
A
1923 int nevents;
1924 int error;
1925
b0d623f7 1926 TAILQ_INIT(&inprocess);
6d2010ae
A
1927
1928 if (kqueue_begin_processing(kq) == -1) {
91447636 1929 *countp = 0;
6d2010ae 1930 /* Nothing to process */
91447636
A
1931 return 0;
1932 }
1933
b0d623f7
A
1934 /*
1935 * Clear any pre-posted status from previous runs, so we only
1936 * detect events that occur during this run.
1937 */
1938 wait_queue_sub_clearrefs(kq->kq_wqs);
1939
1940 /*
1941 * loop through the enqueued knotes, processing each one and
1942 * revalidating those that need it. As they are processed,
1943 * they get moved to the inprocess queue (so the loop can end).
1944 */
91447636
A
1945 error = 0;
1946 nevents = 0;
b0d623f7 1947
91447636
A
1948 while (error == 0 &&
1949 (kn = TAILQ_FIRST(&kq->kq_head)) != NULL) {
b0d623f7
A
1950 error = knote_process(kn, callback, data, &inprocess, p);
1951 if (error == EJUSTRETURN)
1952 error = 0;
1953 else
1954 nevents++;
55e303ae
A
1955 }
1956
91447636
A
1957 /*
1958 * With the kqueue still locked, move any knotes
b0d623f7 1959 * remaining on the inprocess queue back to the
91447636
A
1960 * kq's queue and wake up any waiters.
1961 */
b0d623f7
A
1962 while ((kn = TAILQ_FIRST(&inprocess)) != NULL) {
1963 assert(kn->kn_tq == &inprocess);
1964 TAILQ_REMOVE(&inprocess, kn, kn_tqe);
91447636
A
1965 kn->kn_tq = &kq->kq_head;
1966 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
55e303ae 1967 }
6d2010ae
A
1968
1969 kqueue_end_processing(kq);
55e303ae 1970
91447636
A
1971 *countp = nevents;
1972 return error;
55e303ae
A
1973}
1974
91447636
A
1975
1976static void
b0d623f7 1977kqueue_scan_continue(void *data, wait_result_t wait_result)
55e303ae 1978{
b0d623f7
A
1979 thread_t self = current_thread();
1980 uthread_t ut = (uthread_t)get_bsdthread_info(self);
1981 struct _kqueue_scan * cont_args = &ut->uu_kevent.ss_kqueue_scan;
91447636
A
1982 struct kqueue *kq = (struct kqueue *)data;
1983 int error;
1984 int count;
1985
1986 /* convert the (previous) wait_result to a proper error */
1987 switch (wait_result) {
1988 case THREAD_AWAKENED:
1989 kqlock(kq);
b0d623f7 1990 error = kqueue_process(kq, cont_args->call, cont_args, &count, current_proc());
91447636 1991 if (error == 0 && count == 0) {
b0d623f7
A
1992 wait_queue_assert_wait((wait_queue_t)kq->kq_wqs, KQ_EVENT,
1993 THREAD_ABORTSAFE, cont_args->deadline);
91447636
A
1994 kq->kq_state |= KQ_SLEEP;
1995 kqunlock(kq);
b0d623f7 1996 thread_block_parameter(kqueue_scan_continue, kq);
91447636 1997 /* NOTREACHED */
55e303ae 1998 }
91447636
A
1999 kqunlock(kq);
2000 break;
2001 case THREAD_TIMED_OUT:
2002 error = EWOULDBLOCK;
2003 break;
2004 case THREAD_INTERRUPTED:
2005 error = EINTR;
2006 break;
2007 default:
2008 panic("kevent_scan_cont() - invalid wait_result (%d)", wait_result);
2009 error = 0;
55e303ae 2010 }
91447636
A
2011
2012 /* call the continuation with the results */
2013 assert(cont_args->cont != NULL);
2014 (cont_args->cont)(kq, cont_args->data, error);
2015}
55e303ae 2016
55e303ae 2017
91447636 2018/*
b0d623f7 2019 * kqueue_scan - scan and wait for events in a kqueue
91447636
A
2020 *
2021 * Process the triggered events in a kqueue.
2022 *
2023 * If there are no events triggered arrange to
2024 * wait for them. If the caller provided a
2025 * continuation routine, then kevent_scan will
2026 * also.
2027 *
2028 * The callback routine must be valid.
2029 * The caller must hold a use-count reference on the kq.
2030 */
55e303ae 2031
91447636 2032int
b0d623f7 2033kqueue_scan(struct kqueue *kq,
91447636 2034 kevent_callback_t callback,
b0d623f7 2035 kqueue_continue_t continuation,
91447636
A
2036 void *data,
2037 struct timeval *atvp,
2038 struct proc *p)
2039{
2040 thread_continue_t cont = THREAD_CONTINUE_NULL;
2041 uint64_t deadline;
2042 int error;
2043 int first;
55e303ae 2044
91447636 2045 assert(callback != NULL);
55e303ae 2046
91447636
A
2047 first = 1;
2048 for (;;) {
2049 wait_result_t wait_result;
2050 int count;
2051
2052 /*
2053 * Make a pass through the kq to find events already
b0d623f7 2054 * triggered.
91447636
A
2055 */
2056 kqlock(kq);
b0d623f7 2057 error = kqueue_process(kq, callback, data, &count, p);
91447636
A
2058 if (error || count)
2059 break; /* lock still held */
2060
2061 /* looks like we have to consider blocking */
2062 if (first) {
2063 first = 0;
2064 /* convert the timeout to a deadline once */
2065 if (atvp->tv_sec || atvp->tv_usec) {
91447636
A
2066 uint64_t now;
2067
2068 clock_get_uptime(&now);
2069 nanoseconds_to_absolutetime((uint64_t)atvp->tv_sec * NSEC_PER_SEC +
2070 atvp->tv_usec * NSEC_PER_USEC,
2071 &deadline);
2072 if (now >= deadline) {
2073 /* non-blocking call */
2074 error = EWOULDBLOCK;
2075 break; /* lock still held */
2076 }
2077 deadline -= now;
2078 clock_absolutetime_interval_to_deadline(deadline, &deadline);
55e303ae 2079 } else {
91447636
A
2080 deadline = 0; /* block forever */
2081 }
2082
2083 if (continuation) {
2084 uthread_t ut = (uthread_t)get_bsdthread_info(current_thread());
b0d623f7 2085 struct _kqueue_scan *cont_args = &ut->uu_kevent.ss_kqueue_scan;
91447636
A
2086
2087 cont_args->call = callback;
2088 cont_args->cont = continuation;
2089 cont_args->deadline = deadline;
2090 cont_args->data = data;
b0d623f7 2091 cont = kqueue_scan_continue;
55e303ae
A
2092 }
2093 }
91447636
A
2094
2095 /* go ahead and wait */
b0d623f7 2096 wait_queue_assert_wait((wait_queue_t)kq->kq_wqs, KQ_EVENT, THREAD_ABORTSAFE, deadline);
91447636
A
2097 kq->kq_state |= KQ_SLEEP;
2098 kqunlock(kq);
2099 wait_result = thread_block_parameter(cont, kq);
2100 /* NOTREACHED if (continuation != NULL) */
2101
2102 switch (wait_result) {
2103 case THREAD_AWAKENED:
2104 continue;
2105 case THREAD_TIMED_OUT:
2106 return EWOULDBLOCK;
2107 case THREAD_INTERRUPTED:
2108 return EINTR;
2109 default:
2110 panic("kevent_scan - bad wait_result (%d)",
2111 wait_result);
2112 error = 0;
2113 }
55e303ae 2114 }
91447636
A
2115 kqunlock(kq);
2116 return error;
55e303ae
A
2117}
2118
91447636 2119
55e303ae
A
2120/*
2121 * XXX
2122 * This could be expanded to call kqueue_scan, if desired.
2123 */
2124/*ARGSUSED*/
2125static int
91447636
A
2126kqueue_read(__unused struct fileproc *fp,
2127 __unused struct uio *uio,
91447636 2128 __unused int flags,
2d21ac55 2129 __unused vfs_context_t ctx)
55e303ae
A
2130{
2131 return (ENXIO);
2132}
2133
2134/*ARGSUSED*/
2135static int
91447636
A
2136kqueue_write(__unused struct fileproc *fp,
2137 __unused struct uio *uio,
91447636 2138 __unused int flags,
2d21ac55 2139 __unused vfs_context_t ctx)
55e303ae
A
2140{
2141 return (ENXIO);
2142}
2143
2144/*ARGSUSED*/
2145static int
91447636
A
2146kqueue_ioctl(__unused struct fileproc *fp,
2147 __unused u_long com,
2148 __unused caddr_t data,
2d21ac55 2149 __unused vfs_context_t ctx)
55e303ae
A
2150{
2151 return (ENOTTY);
2152}
2153
2154/*ARGSUSED*/
2155static int
b0d623f7 2156kqueue_select(struct fileproc *fp, int which, void *wql, __unused vfs_context_t ctx)
55e303ae
A
2157{
2158 struct kqueue *kq = (struct kqueue *)fp->f_data;
6d2010ae
A
2159 struct knote *kn;
2160 struct kqtailq inprocessq;
2161 int retnum = 0;
2162
b0d623f7
A
2163 if (which != FREAD)
2164 return 0;
2165
6d2010ae
A
2166 TAILQ_INIT(&inprocessq);
2167
b0d623f7
A
2168 kqlock(kq);
2169 /*
2170 * If this is the first pass, link the wait queue associated with the
2171 * the kqueue onto the wait queue set for the select(). Normally we
2172 * use selrecord() for this, but it uses the wait queue within the
2173 * selinfo structure and we need to use the main one for the kqueue to
2174 * catch events from KN_STAYQUEUED sources. So we do the linkage manually.
2175 * (The select() call will unlink them when it ends).
2176 */
2177 if (wql != NULL) {
2178 thread_t cur_act = current_thread();
2179 struct uthread * ut = get_bsdthread_info(cur_act);
2180
2181 kq->kq_state |= KQ_SEL;
2182 wait_queue_link_noalloc((wait_queue_t)kq->kq_wqs, ut->uu_wqset,
2183 (wait_queue_link_t)wql);
2184 }
2185
6d2010ae
A
2186 if (kqueue_begin_processing(kq) == -1) {
2187 kqunlock(kq);
2188 return 0;
2189 }
b0d623f7 2190
6d2010ae 2191 if (kq->kq_count != 0) {
b0d623f7
A
2192 /*
2193 * there is something queued - but it might be a
2194 * KN_STAYQUEUED knote, which may or may not have
2195 * any events pending. So, we have to walk the
2196 * list of knotes to see, and peek at the stay-
2197 * queued ones to be really sure.
2198 */
6d2010ae
A
2199 while ((kn = (struct knote*)TAILQ_FIRST(&kq->kq_head)) != NULL) {
2200 if ((kn->kn_status & KN_STAYQUEUED) == 0) {
2201 retnum = 1;
2202 goto out;
b0d623f7 2203 }
6d2010ae
A
2204
2205 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2206 TAILQ_INSERT_TAIL(&inprocessq, kn, kn_tqe);
2207
2208 if (kqlock2knoteuse(kq, kn)) {
2209 unsigned peek;
2210
2211 peek = kn->kn_fop->f_peek(kn);
2212 if (knoteuse2kqlock(kq, kn)) {
2213 if (peek > 0) {
2214 retnum = 1;
2215 goto out;
2216 }
2217 } else {
2218 retnum = 0;
2219 }
2220 }
55e303ae 2221 }
b0d623f7
A
2222 }
2223
6d2010ae
A
2224out:
2225 /* Return knotes to active queue */
2226 while ((kn = TAILQ_FIRST(&inprocessq)) != NULL) {
2227 TAILQ_REMOVE(&inprocessq, kn, kn_tqe);
2228 kn->kn_tq = &kq->kq_head;
2229 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
55e303ae 2230 }
b0d623f7 2231
6d2010ae 2232 kqueue_end_processing(kq);
b0d623f7 2233 kqunlock(kq);
6d2010ae 2234 return retnum;
55e303ae
A
2235}
2236
91447636
A
2237/*
2238 * kqueue_close -
2239 */
55e303ae
A
2240/*ARGSUSED*/
2241static int
2d21ac55 2242kqueue_close(struct fileglob *fg, __unused vfs_context_t ctx)
55e303ae 2243{
91447636 2244 struct kqueue *kq = (struct kqueue *)fg->fg_data;
55e303ae 2245
2d21ac55 2246 kqueue_dealloc(kq);
91447636 2247 fg->fg_data = NULL;
55e303ae
A
2248 return (0);
2249}
2250
2251/*ARGSUSED*/
91447636
A
2252/*
2253 * The callers has taken a use-count reference on this kqueue and will donate it
2254 * to the kqueue we are being added to. This keeps the kqueue from closing until
2255 * that relationship is torn down.
2256 */
55e303ae 2257static int
2d21ac55 2258kqueue_kqfilter(__unused struct fileproc *fp, struct knote *kn, __unused vfs_context_t ctx)
55e303ae
A
2259{
2260 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
2d21ac55 2261 struct kqueue *parentkq = kn->kn_kq;
55e303ae 2262
2d21ac55
A
2263 if (parentkq == kq ||
2264 kn->kn_filter != EVFILT_READ)
55e303ae
A
2265 return (1);
2266
2d21ac55
A
2267 /*
2268 * We have to avoid creating a cycle when nesting kqueues
2269 * inside another. Rather than trying to walk the whole
2270 * potential DAG of nested kqueues, we just use a simple
2271 * ceiling protocol. When a kqueue is inserted into another,
2272 * we check that the (future) parent is not already nested
2273 * into another kqueue at a lower level than the potenial
2274 * child (because it could indicate a cycle). If that test
2275 * passes, we just mark the nesting levels accordingly.
2276 */
2277
2278 kqlock(parentkq);
2279 if (parentkq->kq_level > 0 &&
2280 parentkq->kq_level < kq->kq_level)
2281 {
2282 kqunlock(parentkq);
2283 return (1);
2284 } else {
2285 /* set parent level appropriately */
2286 if (parentkq->kq_level == 0)
2287 parentkq->kq_level = 2;
2288 if (parentkq->kq_level < kq->kq_level + 1)
2289 parentkq->kq_level = kq->kq_level + 1;
2290 kqunlock(parentkq);
2291
2292 kn->kn_fop = &kqread_filtops;
2293 kqlock(kq);
2294 KNOTE_ATTACH(&kq->kq_sel.si_note, kn);
2295 /* indicate nesting in child, if needed */
2296 if (kq->kq_level == 0)
2297 kq->kq_level = 1;
2298 kqunlock(kq);
2299 return (0);
2300 }
55e303ae
A
2301}
2302
b0d623f7
A
2303/*
2304 * kqueue_drain - called when kq is closed
2305 */
2306/*ARGSUSED*/
2307static int
2308kqueue_drain(struct fileproc *fp, __unused vfs_context_t ctx)
2309{
2310 struct kqueue *kq = (struct kqueue *)fp->f_fglob->fg_data;
2311 kqlock(kq);
2312 kqueue_wakeup(kq, 1);
2313 kqunlock(kq);
2314 return 0;
2315}
2316
55e303ae
A
2317/*ARGSUSED*/
2318int
2d21ac55 2319kqueue_stat(struct fileproc *fp, void *ub, int isstat64, __unused vfs_context_t ctx)
55e303ae 2320{
2d21ac55 2321
55e303ae 2322 struct kqueue *kq = (struct kqueue *)fp->f_data;
2d21ac55 2323 if (isstat64 != 0) {
b0d623f7
A
2324 struct stat64 *sb64 = (struct stat64 *)ub;
2325
2d21ac55
A
2326 bzero((void *)sb64, sizeof(*sb64));
2327 sb64->st_size = kq->kq_count;
b0d623f7
A
2328 if (kq->kq_state & KQ_KEV64)
2329 sb64->st_blksize = sizeof(struct kevent64_s);
2330 else
2331 sb64->st_blksize = sizeof(struct kevent);
2d21ac55
A
2332 sb64->st_mode = S_IFIFO;
2333 } else {
b0d623f7
A
2334 struct stat *sb = (struct stat *)ub;
2335
2d21ac55
A
2336 bzero((void *)sb, sizeof(*sb));
2337 sb->st_size = kq->kq_count;
b0d623f7
A
2338 if (kq->kq_state & KQ_KEV64)
2339 sb->st_blksize = sizeof(struct kevent64_s);
2340 else
2341 sb->st_blksize = sizeof(struct kevent);
2d21ac55
A
2342 sb->st_mode = S_IFIFO;
2343 }
55e303ae 2344
55e303ae
A
2345 return (0);
2346}
2347
91447636
A
2348/*
2349 * Called with the kqueue locked
2350 */
55e303ae 2351static void
b0d623f7 2352kqueue_wakeup(struct kqueue *kq, int closed)
55e303ae 2353{
b0d623f7
A
2354 if ((kq->kq_state & (KQ_SLEEP | KQ_SEL)) != 0 || kq->kq_nprocess > 0) {
2355 kq->kq_state &= ~(KQ_SLEEP | KQ_SEL);
2356 wait_queue_wakeup_all((wait_queue_t)kq->kq_wqs, KQ_EVENT,
2357 (closed) ? THREAD_INTERRUPTED : THREAD_AWAKENED);
91447636 2358 }
55e303ae
A
2359}
2360
2361void
2362klist_init(struct klist *list)
2363{
2364 SLIST_INIT(list);
2365}
2366
91447636 2367
55e303ae 2368/*
91447636
A
2369 * Query/Post each knote in the object's list
2370 *
2371 * The object lock protects the list. It is assumed
2372 * that the filter/event routine for the object can
2373 * determine that the object is already locked (via
b0d623f7 2374 * the hint) and not deadlock itself.
91447636
A
2375 *
2376 * The object lock should also hold off pending
2377 * detach/drop operations. But we'll prevent it here
2378 * too - just in case.
55e303ae
A
2379 */
2380void
2381knote(struct klist *list, long hint)
2382{
2383 struct knote *kn;
2384
91447636
A
2385 SLIST_FOREACH(kn, list, kn_selnext) {
2386 struct kqueue *kq = kn->kn_kq;
2387
2388 kqlock(kq);
2389 if (kqlock2knoteuse(kq, kn)) {
2390 int result;
2391
2392 /* call the event with only a use count */
2393 result = kn->kn_fop->f_event(kn, hint);
2394
2395 /* if its not going away and triggered */
2396 if (knoteuse2kqlock(kq, kn) && result)
b0d623f7 2397 knote_activate(kn, 1);
91447636
A
2398 /* lock held again */
2399 }
2400 kqunlock(kq);
2401 }
55e303ae
A
2402}
2403
2404/*
2405 * attach a knote to the specified list. Return true if this is the first entry.
91447636 2406 * The list is protected by whatever lock the object it is associated with uses.
55e303ae
A
2407 */
2408int
2409knote_attach(struct klist *list, struct knote *kn)
2410{
2411 int ret = SLIST_EMPTY(list);
2412 SLIST_INSERT_HEAD(list, kn, kn_selnext);
2413 return ret;
2414}
2415
2416/*
2417 * detach a knote from the specified list. Return true if that was the last entry.
91447636 2418 * The list is protected by whatever lock the object it is associated with uses.
55e303ae
A
2419 */
2420int
2421knote_detach(struct klist *list, struct knote *kn)
2422{
2423 SLIST_REMOVE(list, kn, knote, kn_selnext);
2424 return SLIST_EMPTY(list);
2425}
2426
b0d623f7
A
2427/*
2428 * For a given knote, link a provided wait queue directly with the kqueue.
2429 * Wakeups will happen via recursive wait queue support. But nothing will move
2430 * the knote to the active list at wakeup (nothing calls knote()). Instead,
2431 * we permanently enqueue them here.
2432 *
2433 * kqueue and knote references are held by caller.
316670eb
A
2434 *
2435 * caller provides the wait queue link structure.
b0d623f7
A
2436 */
2437int
316670eb 2438knote_link_wait_queue(struct knote *kn, struct wait_queue *wq, wait_queue_link_t wql)
b0d623f7
A
2439{
2440 struct kqueue *kq = kn->kn_kq;
2441 kern_return_t kr;
2442
316670eb 2443 kr = wait_queue_link_noalloc(wq, kq->kq_wqs, wql);
b0d623f7 2444 if (kr == KERN_SUCCESS) {
6d2010ae 2445 knote_markstayqueued(kn);
b0d623f7
A
2446 return 0;
2447 } else {
316670eb 2448 return EINVAL;
b0d623f7
A
2449 }
2450}
2451
2452/*
2453 * Unlink the provided wait queue from the kqueue associated with a knote.
2454 * Also remove it from the magic list of directly attached knotes.
2455 *
2456 * Note that the unlink may have already happened from the other side, so
2457 * ignore any failures to unlink and just remove it from the kqueue list.
316670eb
A
2458 *
2459 * On success, caller is responsible for the link structure
b0d623f7 2460 */
316670eb
A
2461int
2462knote_unlink_wait_queue(struct knote *kn, struct wait_queue *wq, wait_queue_link_t *wqlp)
b0d623f7
A
2463{
2464 struct kqueue *kq = kn->kn_kq;
316670eb 2465 kern_return_t kr;
b0d623f7 2466
316670eb 2467 kr = wait_queue_unlink_nofree(wq, kq->kq_wqs, wqlp);
b0d623f7
A
2468 kqlock(kq);
2469 kn->kn_status &= ~KN_STAYQUEUED;
2470 knote_dequeue(kn);
2471 kqunlock(kq);
316670eb 2472 return (kr != KERN_SUCCESS) ? EINVAL : 0;
b0d623f7
A
2473}
2474
55e303ae 2475/*
91447636
A
2476 * remove all knotes referencing a specified fd
2477 *
2478 * Essentially an inlined knote_remove & knote_drop
2479 * when we know for sure that the thing is a file
2480 *
2481 * Entered with the proc_fd lock already held.
2482 * It returns the same way, but may drop it temporarily.
55e303ae
A
2483 */
2484void
91447636 2485knote_fdclose(struct proc *p, int fd)
55e303ae 2486{
91447636
A
2487 struct filedesc *fdp = p->p_fd;
2488 struct klist *list;
55e303ae
A
2489 struct knote *kn;
2490
91447636 2491 list = &fdp->fd_knlist[fd];
55e303ae 2492 while ((kn = SLIST_FIRST(list)) != NULL) {
91447636 2493 struct kqueue *kq = kn->kn_kq;
55e303ae 2494
2d21ac55
A
2495 if (kq->kq_p != p)
2496 panic("knote_fdclose: proc mismatch (kq->kq_p=%p != p=%p)", kq->kq_p, p);
2497
91447636
A
2498 kqlock(kq);
2499 proc_fdunlock(p);
2500
2501 /*
2502 * Convert the lock to a drop ref.
2503 * If we get it, go ahead and drop it.
2504 * Otherwise, we waited for it to
2505 * be dropped by the other guy, so
2506 * it is safe to move on in the list.
2507 */
2508 if (kqlock2knotedrop(kq, kn)) {
2509 kn->kn_fop->f_detach(kn);
2510 knote_drop(kn, p);
2511 }
2512
2513 proc_fdlock(p);
55e303ae 2514
91447636
A
2515 /* the fd tables may have changed - start over */
2516 list = &fdp->fd_knlist[fd];
2517 }
55e303ae
A
2518}
2519
91447636
A
2520/* proc_fdlock held on entry (and exit) */
2521static int
316670eb 2522knote_fdpattach(struct knote *kn, struct filedesc *fdp, struct proc *p)
55e303ae 2523{
91447636 2524 struct klist *list = NULL;
55e303ae
A
2525
2526 if (! kn->kn_fop->f_isfd) {
2527 if (fdp->fd_knhashmask == 0)
2d21ac55 2528 fdp->fd_knhash = hashinit(CONFIG_KN_HASHSIZE, M_KQUEUE,
55e303ae
A
2529 &fdp->fd_knhashmask);
2530 list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
91447636
A
2531 } else {
2532 if ((u_int)fdp->fd_knlistsize <= kn->kn_id) {
2533 u_int size = 0;
2534
316670eb
A
2535 if (kn->kn_id >= (uint64_t)p->p_rlimit[RLIMIT_NOFILE].rlim_cur
2536 || kn->kn_id >= (uint64_t)maxfiles)
2537 return (EINVAL);
2538
91447636
A
2539 /* have to grow the fd_knlist */
2540 size = fdp->fd_knlistsize;
2541 while (size <= kn->kn_id)
2542 size += KQEXTENT;
316670eb
A
2543
2544 if (size >= (UINT_MAX/sizeof(struct klist *)))
2545 return (EINVAL);
2546
91447636
A
2547 MALLOC(list, struct klist *,
2548 size * sizeof(struct klist *), M_KQUEUE, M_WAITOK);
2549 if (list == NULL)
2550 return (ENOMEM);
2551
2552 bcopy((caddr_t)fdp->fd_knlist, (caddr_t)list,
2553 fdp->fd_knlistsize * sizeof(struct klist *));
2554 bzero((caddr_t)list +
2555 fdp->fd_knlistsize * sizeof(struct klist *),
2556 (size - fdp->fd_knlistsize) * sizeof(struct klist *));
55e303ae 2557 FREE(fdp->fd_knlist, M_KQUEUE);
91447636
A
2558 fdp->fd_knlist = list;
2559 fdp->fd_knlistsize = size;
2560 }
2561 list = &fdp->fd_knlist[kn->kn_id];
55e303ae 2562 }
55e303ae 2563 SLIST_INSERT_HEAD(list, kn, kn_link);
91447636 2564 return (0);
55e303ae
A
2565}
2566
91447636
A
2567
2568
55e303ae
A
2569/*
2570 * should be called at spl == 0, since we don't want to hold spl
2571 * while calling fdrop and free.
2572 */
2573static void
2d21ac55 2574knote_drop(struct knote *kn, __unused struct proc *ctxp)
55e303ae 2575{
91447636 2576 struct kqueue *kq = kn->kn_kq;
2d21ac55
A
2577 struct proc *p = kq->kq_p;
2578 struct filedesc *fdp = p->p_fd;
55e303ae 2579 struct klist *list;
b0d623f7 2580 int needswakeup;
55e303ae 2581
91447636 2582 proc_fdlock(p);
55e303ae
A
2583 if (kn->kn_fop->f_isfd)
2584 list = &fdp->fd_knlist[kn->kn_id];
2585 else
2586 list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
2587
2588 SLIST_REMOVE(list, kn, knote, kn_link);
91447636
A
2589 kqlock(kq);
2590 knote_dequeue(kn);
b0d623f7 2591 needswakeup = (kn->kn_status & KN_USEWAIT);
91447636
A
2592 kqunlock(kq);
2593 proc_fdunlock(p);
2594
b0d623f7
A
2595 if (needswakeup)
2596 wait_queue_wakeup_all((wait_queue_t)kq->kq_wqs, &kn->kn_status, THREAD_AWAKENED);
2597
55e303ae 2598 if (kn->kn_fop->f_isfd)
91447636
A
2599 fp_drop(p, kn->kn_id, kn->kn_fp, 0);
2600
55e303ae
A
2601 knote_free(kn);
2602}
2603
91447636
A
2604/* called with kqueue lock held */
2605static void
b0d623f7 2606knote_activate(struct knote *kn, int propagate)
91447636
A
2607{
2608 struct kqueue *kq = kn->kn_kq;
2609
2610 kn->kn_status |= KN_ACTIVE;
2611 knote_enqueue(kn);
b0d623f7
A
2612 kqueue_wakeup(kq, 0);
2613
2614 /* this is a real event: wake up the parent kq, too */
2615 if (propagate)
2616 KNOTE(&kq->kq_sel.si_note, 0);
2617}
91447636
A
2618
2619/* called with kqueue lock held */
2620static void
2621knote_deactivate(struct knote *kn)
2622{
2623 kn->kn_status &= ~KN_ACTIVE;
2624 knote_dequeue(kn);
2625}
55e303ae 2626
91447636 2627/* called with kqueue lock held */
55e303ae
A
2628static void
2629knote_enqueue(struct knote *kn)
2630{
b0d623f7
A
2631 if ((kn->kn_status & (KN_QUEUED | KN_STAYQUEUED)) == KN_STAYQUEUED ||
2632 (kn->kn_status & (KN_QUEUED | KN_STAYQUEUED | KN_DISABLED)) == 0) {
91447636 2633 struct kqtailq *tq = kn->kn_tq;
b0d623f7 2634 struct kqueue *kq = kn->kn_kq;
55e303ae 2635
91447636
A
2636 TAILQ_INSERT_TAIL(tq, kn, kn_tqe);
2637 kn->kn_status |= KN_QUEUED;
2638 kq->kq_count++;
2639 }
55e303ae
A
2640}
2641
91447636 2642/* called with kqueue lock held */
55e303ae
A
2643static void
2644knote_dequeue(struct knote *kn)
2645{
2646 struct kqueue *kq = kn->kn_kq;
55e303ae 2647
b0d623f7 2648 if ((kn->kn_status & (KN_QUEUED | KN_STAYQUEUED)) == KN_QUEUED) {
91447636 2649 struct kqtailq *tq = kn->kn_tq;
55e303ae 2650
91447636
A
2651 TAILQ_REMOVE(tq, kn, kn_tqe);
2652 kn->kn_tq = &kq->kq_head;
2653 kn->kn_status &= ~KN_QUEUED;
2654 kq->kq_count--;
2655 }
55e303ae
A
2656}
2657
2658void
2659knote_init(void)
2660{
2661 knote_zone = zinit(sizeof(struct knote), 8192*sizeof(struct knote), 8192, "knote zone");
91447636
A
2662
2663 /* allocate kq lock group attribute and group */
2664 kq_lck_grp_attr= lck_grp_attr_alloc_init();
91447636
A
2665
2666 kq_lck_grp = lck_grp_alloc_init("kqueue", kq_lck_grp_attr);
2667
2668 /* Allocate kq lock attribute */
2669 kq_lck_attr = lck_attr_alloc_init();
91447636
A
2670
2671 /* Initialize the timer filter lock */
2672 lck_mtx_init(&_filt_timerlock, kq_lck_grp, kq_lck_attr);
316670eb
A
2673
2674#if VM_PRESSURE_EVENTS
2675 /* Initialize the vm pressure list lock */
2676 vm_pressure_init(kq_lck_grp, kq_lck_attr);
2677#endif
55e303ae
A
2678}
2679SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL)
2680
2681static struct knote *
2682knote_alloc(void)
2683{
2684 return ((struct knote *)zalloc(knote_zone));
2685}
2686
2687static void
2688knote_free(struct knote *kn)
2689{
91447636 2690 zfree(knote_zone, kn);
55e303ae
A
2691}
2692
2d21ac55 2693#if SOCKETS
1c79356b
A
2694#include <sys/param.h>
2695#include <sys/socket.h>
2696#include <sys/protosw.h>
2697#include <sys/domain.h>
2698#include <sys/mbuf.h>
2699#include <sys/kern_event.h>
2700#include <sys/malloc.h>
9bccf70c
A
2701#include <sys/sys_domain.h>
2702#include <sys/syslog.h>
1c79356b
A
2703
2704
91447636
A
2705static int kev_attach(struct socket *so, int proto, struct proc *p);
2706static int kev_detach(struct socket *so);
2707static int kev_control(struct socket *so, u_long cmd, caddr_t data, struct ifnet *ifp, struct proc *p);
2708
2709struct pr_usrreqs event_usrreqs = {
2710 pru_abort_notsupp, pru_accept_notsupp, kev_attach, pru_bind_notsupp, pru_connect_notsupp,
2711 pru_connect2_notsupp, kev_control, kev_detach, pru_disconnect_notsupp,
2712 pru_listen_notsupp, pru_peeraddr_notsupp, pru_rcvd_notsupp, pru_rcvoob_notsupp,
2713 pru_send_notsupp, pru_sense_null, pru_shutdown_notsupp, pru_sockaddr_notsupp,
2714 pru_sosend_notsupp, soreceive, pru_sopoll_notsupp
2715};
1c79356b
A
2716
2717struct protosw eventsw[] = {
2718 {
b0d623f7
A
2719 .pr_type = SOCK_RAW,
2720 .pr_domain = &systemdomain,
2721 .pr_protocol = SYSPROTO_EVENT,
2722 .pr_flags = PR_ATOMIC,
2723 .pr_usrreqs = &event_usrreqs,
1c79356b
A
2724 }
2725};
2726
2727static
2728struct kern_event_head kern_event_head;
2729
b0d623f7 2730static u_int32_t static_event_id = 0;
91447636 2731struct domain *sysdom = &systemdomain;
2d21ac55 2732static lck_mtx_t *sys_mtx;
1c79356b 2733
9bccf70c
A
2734/*
2735 * Install the protosw's for the NKE manager. Invoked at
2736 * extension load time
2737 */
2738int
2739kern_event_init(void)
2740{
2741 int retval;
2742
91447636
A
2743 if ((retval = net_add_proto(eventsw, &systemdomain)) != 0) {
2744 log(LOG_WARNING, "Can't install kernel events protocol (%d)\n", retval);
2745 return(retval);
2746 }
2d21ac55
A
2747
2748 /*
2749 * Use the domain mutex for all system event sockets
2750 */
2751 sys_mtx = sysdom->dom_mtx;
91447636
A
2752
2753 return(KERN_SUCCESS);
9bccf70c
A
2754}
2755
91447636
A
2756static int
2757kev_attach(struct socket *so, __unused int proto, __unused struct proc *p)
1c79356b
A
2758{
2759 int error;
2760 struct kern_event_pcb *ev_pcb;
2761
55e303ae
A
2762 error = soreserve(so, KEV_SNDSPACE, KEV_RECVSPACE);
2763 if (error)
2764 return error;
2765
91447636 2766 MALLOC(ev_pcb, struct kern_event_pcb *, sizeof(struct kern_event_pcb), M_PCB, M_WAITOK);
1c79356b
A
2767 if (ev_pcb == 0)
2768 return ENOBUFS;
2769
2770 ev_pcb->ev_socket = so;
2771 ev_pcb->vendor_code_filter = 0xffffffff;
2772
2773 so->so_pcb = (caddr_t) ev_pcb;
2d21ac55 2774 lck_mtx_lock(sys_mtx);
1c79356b 2775 LIST_INSERT_HEAD(&kern_event_head, ev_pcb, ev_link);
2d21ac55 2776 lck_mtx_unlock(sys_mtx);
1c79356b
A
2777
2778 return 0;
2779}
2780
2781
91447636
A
2782static int
2783kev_detach(struct socket *so)
1c79356b
A
2784{
2785 struct kern_event_pcb *ev_pcb = (struct kern_event_pcb *) so->so_pcb;
2786
55e303ae 2787 if (ev_pcb != 0) {
91447636 2788 LIST_REMOVE(ev_pcb, ev_link);
91447636
A
2789 FREE(ev_pcb, M_PCB);
2790 so->so_pcb = 0;
2791 so->so_flags |= SOF_PCBCLEARING;
55e303ae 2792 }
1c79356b
A
2793
2794 return 0;
2795}
2796
91447636 2797/*
2d21ac55 2798 * For now, kev_vendor_code and mbuf_tags use the same
91447636
A
2799 * mechanism.
2800 */
91447636
A
2801
2802errno_t kev_vendor_code_find(
2803 const char *string,
2d21ac55 2804 u_int32_t *out_vendor_code)
91447636
A
2805{
2806 if (strlen(string) >= KEV_VENDOR_CODE_MAX_STR_LEN) {
2807 return EINVAL;
2808 }
b0d623f7 2809 return net_str_id_find_internal(string, out_vendor_code, NSI_VENDOR_CODE, 1);
91447636
A
2810}
2811
91447636
A
2812errno_t kev_msg_post(struct kev_msg *event_msg)
2813{
2d21ac55 2814 mbuf_tag_id_t min_vendor, max_vendor;
91447636 2815
b0d623f7 2816 net_str_id_first_last(&min_vendor, &max_vendor, NSI_VENDOR_CODE);
91447636
A
2817
2818 if (event_msg == NULL)
2819 return EINVAL;
2820
2821 /* Limit third parties to posting events for registered vendor codes only */
2822 if (event_msg->vendor_code < min_vendor ||
2823 event_msg->vendor_code > max_vendor)
2824 {
2825 return EINVAL;
2826 }
2827
2828 return kev_post_msg(event_msg);
2829}
2830
1c79356b
A
2831
2832int kev_post_msg(struct kev_msg *event_msg)
2833{
2834 struct mbuf *m, *m2;
2835 struct kern_event_pcb *ev_pcb;
2836 struct kern_event_msg *ev;
2837 char *tmp;
b0d623f7 2838 u_int32_t total_size;
1c79356b
A
2839 int i;
2840
91447636
A
2841 /* Verify the message is small enough to fit in one mbuf w/o cluster */
2842 total_size = KEV_MSG_HEADER_SIZE;
2843
2844 for (i = 0; i < 5; i++) {
2845 if (event_msg->dv[i].data_length == 0)
2846 break;
2847 total_size += event_msg->dv[i].data_length;
2848 }
2849
2850 if (total_size > MLEN) {
2851 return EMSGSIZE;
2852 }
1c79356b
A
2853
2854 m = m_get(M_DONTWAIT, MT_DATA);
2855 if (m == 0)
2856 return ENOBUFS;
2857
2858 ev = mtod(m, struct kern_event_msg *);
2859 total_size = KEV_MSG_HEADER_SIZE;
2860
2861 tmp = (char *) &ev->event_data[0];
2862 for (i = 0; i < 5; i++) {
2863 if (event_msg->dv[i].data_length == 0)
2864 break;
2865
2866 total_size += event_msg->dv[i].data_length;
2867 bcopy(event_msg->dv[i].data_ptr, tmp,
2868 event_msg->dv[i].data_length);
2869 tmp += event_msg->dv[i].data_length;
2870 }
2871
1c79356b
A
2872 ev->id = ++static_event_id;
2873 ev->total_size = total_size;
2874 ev->vendor_code = event_msg->vendor_code;
2875 ev->kev_class = event_msg->kev_class;
2876 ev->kev_subclass = event_msg->kev_subclass;
2877 ev->event_code = event_msg->event_code;
2878
2879 m->m_len = total_size;
2d21ac55 2880 lck_mtx_lock(sys_mtx);
1c79356b
A
2881 for (ev_pcb = LIST_FIRST(&kern_event_head);
2882 ev_pcb;
2883 ev_pcb = LIST_NEXT(ev_pcb, ev_link)) {
2884
2885 if (ev_pcb->vendor_code_filter != KEV_ANY_VENDOR) {
2886 if (ev_pcb->vendor_code_filter != ev->vendor_code)
2887 continue;
2888
2889 if (ev_pcb->class_filter != KEV_ANY_CLASS) {
2890 if (ev_pcb->class_filter != ev->kev_class)
2891 continue;
2892
2893 if ((ev_pcb->subclass_filter != KEV_ANY_SUBCLASS) &&
2894 (ev_pcb->subclass_filter != ev->kev_subclass))
2895 continue;
2896 }
2897 }
2898
2899 m2 = m_copym(m, 0, m->m_len, M_NOWAIT);
2900 if (m2 == 0) {
2901 m_free(m);
2d21ac55 2902 lck_mtx_unlock(sys_mtx);
1c79356b
A
2903 return ENOBUFS;
2904 }
2d21ac55 2905 /* the socket is already locked because we hold the sys_mtx here */
91447636
A
2906 if (sbappendrecord(&ev_pcb->ev_socket->so_rcv, m2))
2907 sorwakeup(ev_pcb->ev_socket);
1c79356b
A
2908 }
2909
1c79356b 2910 m_free(m);
2d21ac55 2911 lck_mtx_unlock(sys_mtx);
1c79356b
A
2912 return 0;
2913}
2914
91447636
A
2915static int
2916kev_control(struct socket *so,
2917 u_long cmd,
2918 caddr_t data,
2919 __unused struct ifnet *ifp,
2920 __unused struct proc *p)
1c79356b 2921{
91447636
A
2922 struct kev_request *kev_req = (struct kev_request *) data;
2923 struct kern_event_pcb *ev_pcb;
2924 struct kev_vendor_code *kev_vendor;
b0d623f7 2925 u_int32_t *id_value = (u_int32_t *) data;
91447636
A
2926
2927
2928 switch (cmd) {
2929
2930 case SIOCGKEVID:
2931 *id_value = static_event_id;
2932 break;
2933
2934 case SIOCSKEVFILT:
2935 ev_pcb = (struct kern_event_pcb *) so->so_pcb;
2936 ev_pcb->vendor_code_filter = kev_req->vendor_code;
2937 ev_pcb->class_filter = kev_req->kev_class;
2938 ev_pcb->subclass_filter = kev_req->kev_subclass;
2939 break;
2940
2941 case SIOCGKEVFILT:
2942 ev_pcb = (struct kern_event_pcb *) so->so_pcb;
2943 kev_req->vendor_code = ev_pcb->vendor_code_filter;
2944 kev_req->kev_class = ev_pcb->class_filter;
2945 kev_req->kev_subclass = ev_pcb->subclass_filter;
2946 break;
2947
2948 case SIOCGKEVVENDOR:
2949 kev_vendor = (struct kev_vendor_code*)data;
2950
2951 /* Make sure string is NULL terminated */
2952 kev_vendor->vendor_string[KEV_VENDOR_CODE_MAX_STR_LEN-1] = 0;
b0d623f7
A
2953
2954 return net_str_id_find_internal(kev_vendor->vendor_string,
2955 &kev_vendor->vendor_code, NSI_VENDOR_CODE, 0);
91447636
A
2956
2957 default:
2958 return ENOTSUP;
2959 }
2960
2961 return 0;
1c79356b
A
2962}
2963
2d21ac55 2964#endif /* SOCKETS */
1c79356b 2965
1c79356b 2966
0c530ab8
A
2967int
2968fill_kqueueinfo(struct kqueue *kq, struct kqueue_info * kinfo)
2969{
2d21ac55 2970 struct vinfo_stat * st;
0c530ab8
A
2971
2972 /* No need for the funnel as fd is kept alive */
2973
2974 st = &kinfo->kq_stat;
2975
2d21ac55 2976 st->vst_size = kq->kq_count;
b0d623f7
A
2977 if (kq->kq_state & KQ_KEV64)
2978 st->vst_blksize = sizeof(struct kevent64_s);
2979 else
2980 st->vst_blksize = sizeof(struct kevent);
2d21ac55 2981 st->vst_mode = S_IFIFO;
0c530ab8
A
2982 if (kq->kq_state & KQ_SEL)
2983 kinfo->kq_state |= PROC_KQUEUE_SELECT;
2984 if (kq->kq_state & KQ_SLEEP)
2985 kinfo->kq_state |= PROC_KQUEUE_SLEEP;
2986
2987 return(0);
2988}
1c79356b 2989
6d2010ae
A
2990
2991void
2992knote_markstayqueued(struct knote *kn)
2993{
2994 kqlock(kn->kn_kq);
2995 kn->kn_status |= KN_STAYQUEUED;
2996 knote_enqueue(kn);
2997 kqunlock(kn->kn_kq);
2998}