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