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