]> git.saurik.com Git - apple/xnu.git/blob - bsd/kern/kern_event.c
xnu-2050.7.9.tar.gz
[apple/xnu.git] / bsd / kern / kern_event.c
1 /*
2 * Copyright (c) 2000-2011 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 *
28 */
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 */
54 /*
55 * @(#)kern_event.c 1.0 (3/31/2000)
56 */
57 #include <stdint.h>
58
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/filedesc.h>
62 #include <sys/kernel.h>
63 #include <sys/proc_internal.h>
64 #include <sys/kauth.h>
65 #include <sys/malloc.h>
66 #include <sys/unistd.h>
67 #include <sys/file_internal.h>
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>
79 #include <sys/sysproto.h>
80 #include <sys/user.h>
81 #include <sys/vnode_internal.h>
82 #include <string.h>
83 #include <sys/proc_info.h>
84
85 #include <kern/lock.h>
86 #include <kern/clock.h>
87 #include <kern/thread_call.h>
88 #include <kern/sched_prim.h>
89 #include <kern/zalloc.h>
90 #include <kern/assert.h>
91
92 #include <libkern/libkern.h>
93 #include "net/net_str_id.h"
94
95 #include <mach/task.h>
96
97 #if VM_PRESSURE_EVENTS
98 #include <kern/vm_pressure.h>
99 #endif
100
101 MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
102
103 #define KQ_EVENT NULL
104
105 static inline void kqlock(struct kqueue *kq);
106 static inline void kqunlock(struct kqueue *kq);
107
108 static int kqlock2knoteuse(struct kqueue *kq, struct knote *kn);
109 static int kqlock2knoteusewait(struct kqueue *kq, struct knote *kn);
110 static int kqlock2knotedrop(struct kqueue *kq, struct knote *kn);
111 static int knoteuse2kqlock(struct kqueue *kq, struct knote *kn);
112
113 static void kqueue_wakeup(struct kqueue *kq, int closed);
114 static int kqueue_read(struct fileproc *fp, struct uio *uio,
115 int flags, vfs_context_t ctx);
116 static int kqueue_write(struct fileproc *fp, struct uio *uio,
117 int flags, vfs_context_t ctx);
118 static int kqueue_ioctl(struct fileproc *fp, u_long com, caddr_t data,
119 vfs_context_t ctx);
120 static int kqueue_select(struct fileproc *fp, int which, void *wql,
121 vfs_context_t ctx);
122 static int kqueue_close(struct fileglob *fg, vfs_context_t ctx);
123 static int kqueue_kqfilter(struct fileproc *fp, struct knote *kn, vfs_context_t ctx);
124 static int kqueue_drain(struct fileproc *fp, vfs_context_t ctx);
125 extern int kqueue_stat(struct fileproc *fp, void *ub, int isstat64, vfs_context_t ctx);
126
127 static struct fileops kqueueops = {
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,
135 };
136
137 static 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);
140 static int kevent_copyin(user_addr_t *addrp, struct kevent64_s *kevp, struct proc *p, int iskev64);
141 static int kevent_copyout(struct kevent64_s *kevp, user_addr_t *addrp, struct proc *p, int iskev64);
142 char * kevent_description(struct kevent64_s *kevp, char *s, size_t n);
143
144 static int kevent_callback(struct kqueue *kq, struct kevent64_s *kevp, void *data);
145 static void kevent_continue(struct kqueue *kq, void *data, int error);
146 static void kqueue_scan_continue(void *contp, wait_result_t wait_result);
147 static int kqueue_process(struct kqueue *kq, kevent_callback_t callback,
148 void *data, int *countp, struct proc *p);
149 static int kqueue_begin_processing(struct kqueue *kq);
150 static void kqueue_end_processing(struct kqueue *kq);
151 static int knote_process(struct knote *kn, kevent_callback_t callback,
152 void *data, struct kqtailq *inprocessp, struct proc *p);
153 static void knote_put(struct knote *kn);
154 static int knote_fdpattach(struct knote *kn, struct filedesc *fdp, struct proc *p);
155 static void knote_drop(struct knote *kn, struct proc *p);
156 static void knote_activate(struct knote *kn, int);
157 static void knote_deactivate(struct knote *kn);
158 static void knote_enqueue(struct knote *kn);
159 static void knote_dequeue(struct knote *kn);
160 static struct knote *knote_alloc(void);
161 static void knote_free(struct knote *kn);
162
163 static int filt_fileattach(struct knote *kn);
164 static struct filterops file_filtops = {
165 .f_isfd = 1,
166 .f_attach = filt_fileattach,
167 };
168
169 static void filt_kqdetach(struct knote *kn);
170 static int filt_kqueue(struct knote *kn, long hint);
171 static struct filterops kqread_filtops = {
172 .f_isfd = 1,
173 .f_detach = filt_kqdetach,
174 .f_event = filt_kqueue,
175 };
176
177 /*
178 * placeholder for not-yet-implemented filters
179 */
180 static int filt_badattach(struct knote *kn);
181 static struct filterops bad_filtops = {
182 .f_attach = filt_badattach,
183 };
184
185 static int filt_procattach(struct knote *kn);
186 static void filt_procdetach(struct knote *kn);
187 static int filt_proc(struct knote *kn, long hint);
188 static struct filterops proc_filtops = {
189 .f_attach = filt_procattach,
190 .f_detach = filt_procdetach,
191 .f_event = filt_proc,
192 };
193
194 #if VM_PRESSURE_EVENTS
195 static int filt_vmattach(struct knote *kn);
196 static void filt_vmdetach(struct knote *kn);
197 static int filt_vm(struct knote *kn, long hint);
198 static struct filterops vm_filtops = {
199 .f_attach = filt_vmattach,
200 .f_detach = filt_vmdetach,
201 .f_event = filt_vm,
202 };
203 #endif /* VM_PRESSURE_EVENTS */
204
205 extern struct filterops fs_filtops;
206
207 extern struct filterops sig_filtops;
208
209 /* Timer filter */
210 static int filt_timerattach(struct knote *kn);
211 static void filt_timerdetach(struct knote *kn);
212 static int filt_timer(struct knote *kn, long hint);
213 static void filt_timertouch(struct knote *kn, struct kevent64_s *kev,
214 long type);
215 static 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 };
221
222 /* Helpers */
223
224 static void filt_timerexpire(void *knx, void *param1);
225 static int filt_timervalidate(struct knote *kn);
226 static void filt_timerupdate(struct knote *kn);
227 static void filt_timercancel(struct knote *kn);
228
229 #define TIMER_RUNNING 0x1
230 #define TIMER_CANCELWAIT 0x2
231
232 static lck_mtx_t _filt_timerlock;
233 static void filt_timerlock(void);
234 static void filt_timerunlock(void);
235
236 static zone_t knote_zone;
237
238 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
239
240 #if 0
241 extern struct filterops aio_filtops;
242 #endif
243
244 /* Mach portset filter */
245 extern struct filterops machport_filtops;
246
247 /* User filter */
248 static int filt_userattach(struct knote *kn);
249 static void filt_userdetach(struct knote *kn);
250 static int filt_user(struct knote *kn, long hint);
251 static void filt_usertouch(struct knote *kn, struct kevent64_s *kev,
252 long type);
253 static 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
260 /*
261 * Table for for all system-defined filters.
262 */
263 static 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 */
274 &timer_filtops, /* EVFILT_TIMER */
275 &machport_filtops, /* EVFILT_MACHPORT */
276 &fs_filtops, /* EVFILT_FS */
277 &user_filtops, /* EVFILT_USER */
278 &bad_filtops, /* unused */
279 #if VM_PRESSURE_EVENTS
280 &vm_filtops, /* EVFILT_VM */
281 #else
282 &bad_filtops, /* EVFILT_VM */
283 #endif
284 &file_filtops, /* EVFILT_SOCK */
285 };
286
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 */
294 lck_grp_attr_t * kq_lck_grp_attr;
295 lck_grp_t * kq_lck_grp;
296 lck_attr_t * kq_lck_attr;
297
298 static inline void
299 kqlock(struct kqueue *kq)
300 {
301 lck_spin_lock(&kq->kq_lock);
302 }
303
304 static inline void
305 kqunlock(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 */
320 static int
321 kqlock2knoteuse(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 /*
331 * Convert a kq lock to a knote use referece,
332 * but wait for attach and drop events to complete.
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 */
341 static int
342 kqlock2knoteusewait(struct kqueue *kq, struct knote *kn)
343 {
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);
347 kqunlock(kq);
348 thread_block(THREAD_CONTINUE_NULL);
349 return 0;
350 }
351 kn->kn_inuse++;
352 kqunlock(kq);
353 return 1;
354 }
355
356
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 */
367 static int
368 knoteuse2kqlock(struct kqueue *kq, struct knote *kn)
369 {
370 kqlock(kq);
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 }
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 */
397 static int
398 kqlock2knotedrop(struct kqueue *kq, struct knote *kn)
399 {
400 int oktodrop;
401
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) {
406 kqunlock(kq);
407 return oktodrop;
408 }
409 }
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;
415 }
416
417 /*
418 * Release a knote use count reference.
419 */
420 static void
421 knote_put(struct knote *kn)
422 {
423 struct kqueue *kq = kn->kn_kq;
424
425 kqlock(kq);
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 }
431 }
432 kqunlock(kq);
433 }
434
435 static int
436 filt_fileattach(struct knote *kn)
437 {
438
439 return (fo_kqfilter(kn->kn_fp, kn, vfs_context_current()));
440 }
441
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
450 static void
451 filt_kqdetach(struct knote *kn)
452 {
453 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
454
455 kqlock(kq);
456 KNOTE_DETACH(&kq->kq_sel.si_note, kn);
457 kqunlock(kq);
458 }
459
460 /*ARGSUSED*/
461 static int
462 filt_kqueue(struct knote *kn, __unused long hint)
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
470 static int
471 filt_procattach(struct knote *kn)
472 {
473 struct proc *p;
474 pid_t selfpid = (pid_t)0;
475
476 assert(PID_MAX < NOTE_PDATAMASK);
477
478 if ((kn->kn_sfflags & (NOTE_TRACK | NOTE_TRACKERR | NOTE_CHILD)) != 0)
479 return(ENOTSUP);
480
481 p = proc_find(kn->kn_id);
482 if (p == NULL) {
483 return (ESRCH);
484 }
485
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
496 proc_klist_lock();
497
498 kn->kn_flags |= EV_CLEAR; /* automatically set */
499 kn->kn_ptr.p_proc = p; /* store the proc handle */
500
501 KNOTE_ATTACH(&p->p_klist, kn);
502
503 proc_klist_unlock();
504
505 proc_rele(p);
506
507 return (0);
508 }
509
510 /*
511 * The knote may be attached to a different process, which may exit,
512 * leaving nothing for the knote to be attached to. In that case,
513 * the pointer to the process will have already been nulled out.
514 */
515 static void
516 filt_procdetach(struct knote *kn)
517 {
518 struct proc *p;
519
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;
525 KNOTE_DETACH(&p->p_klist, kn);
526 }
527
528 proc_klist_unlock();
529 }
530
531 static int
532 filt_proc(struct knote *kn, long hint)
533 {
534 /* hint is 0 when called from above */
535 if (hint != 0) {
536 u_int event;
537
538 /* ALWAYS CALLED WITH proc_klist_lock when (hint != 0) */
539
540 /*
541 * mask off extra data
542 */
543 event = (u_int)hint & NOTE_PCTRLMASK;
544
545 /*
546 * if the user is interested in this event, record it.
547 */
548 if (kn->kn_sfflags & event)
549 kn->kn_fflags |= event;
550
551 if (event == NOTE_REAP || (event == NOTE_EXIT && !(kn->kn_sfflags & NOTE_REAP))) {
552 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
553 }
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 }
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 */
570 }
571
572 /* atomic check, no locking need when called from above */
573 return (kn->kn_fflags != 0);
574 }
575
576 #if VM_PRESSURE_EVENTS
577 /*
578 * Virtual memory kevents
579 *
580 * author: Matt Jacobson [matthew_jacobson@apple.com]
581 */
582
583 static int
584 filt_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
595 static void
596 filt_vmdetach(struct knote *kn)
597 {
598 vm_knote_unregister(kn);
599 }
600
601 static int
602 filt_vm(struct knote *kn, long hint)
603 {
604 /* hint == 0 means this is just an alive? check (always true) */
605 if (hint != 0) {
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;
609 }
610 }
611
612 return (kn->kn_fflags != 0);
613 }
614 #endif /* VM_PRESSURE_EVENTS */
615
616 /*
617 * filt_timervalidate - process data from user
618 *
619 * Converts to either interval or deadline format.
620 *
621 * The saved-data field in the knote contains the
622 * time value. The saved filter-flags indicates
623 * the unit of measurement.
624 *
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 *
634 */
635 static int
636 filt_timervalidate(struct knote *kn)
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 }
657
658 nanoseconds_to_absolutetime((uint64_t)kn->kn_sdata * multiplier, &raw);
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;
666 uint64_t now;
667
668 clock_get_calendar_nanotime(&seconds, &nanoseconds);
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]);
679 }
680 } else {
681 kn->kn_sdata = raw;
682 }
683
684 return 0;
685 }
686
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 */
698 static void
699 filt_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
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 */
730 static void
731 filt_timerexpire(void *knx, __unused void *spare)
732 {
733 struct klist timer_list;
734 struct knote *kn = knx;
735
736 filt_timerlock();
737
738 kn->kn_hookid &= ~TIMER_RUNNING;
739
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);
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 */
759 static void
760 filt_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 }
782 }
783
784 /*
785 * Allocate a thread call for the knote's lifetime, and kick off the timer.
786 */
787 static int
788 filt_timerattach(struct knote *kn)
789 {
790 thread_call_t callout;
791 int error;
792
793 callout = thread_call_allocate(filt_timerexpire, kn);
794 if (NULL == callout)
795 return (ENOMEM);
796
797 filt_timerlock();
798 error = filt_timervalidate(kn);
799 if (error) {
800 filt_timerunlock();
801 return (error);
802 }
803
804 kn->kn_hook = (void*)callout;
805 kn->kn_hookid = 0;
806
807 /* absolute=EV_ONESHOT */
808 if (kn->kn_sfflags & NOTE_ABSOLUTE)
809 kn->kn_flags |= EV_ONESHOT;
810
811 filt_timerupdate(kn);
812 if (kn->kn_ext[0]) {
813 kn->kn_flags |= EV_CLEAR;
814 thread_call_enter_delayed(callout, kn->kn_ext[0]);
815 kn->kn_hookid |= TIMER_RUNNING;
816 } else {
817 /* fake immediate */
818 kn->kn_data = 1;
819 }
820
821 filt_timerunlock();
822 return (0);
823 }
824
825 /*
826 * Shut down the timer if it's running, and free the callout.
827 */
828 static void
829 filt_timerdetach(struct knote *kn)
830 {
831 thread_call_t callout;
832
833 filt_timerlock();
834
835 callout = (thread_call_t)kn->kn_hook;
836 filt_timercancel(kn);
837
838 filt_timerunlock();
839
840 thread_call_free(callout);
841 }
842
843
844
845 static int
846 filt_timer(struct knote *kn, long hint)
847 {
848 int result;
849
850 if (hint) {
851 /* real timer pop -- timer lock held by filt_timerexpire */
852
853 kn->kn_data++;
854
855 if (((kn->kn_hookid & TIMER_CANCELWAIT) == 0) &&
856 ((kn->kn_flags & EV_ONESHOT) == 0)) {
857
858 /* evaluate next time to fire */
859 filt_timerupdate(kn);
860
861 if (kn->kn_ext[0]) {
862 /* keep the callout and re-arm */
863 thread_call_enter_delayed(kn->kn_hook,
864 kn->kn_ext[0]);
865 kn->kn_hookid |= TIMER_RUNNING;
866 }
867 }
868
869 return 1;
870 }
871
872 /* user-query */
873 filt_timerlock();
874
875 result = (kn->kn_data != 0);
876
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 */
889 static void
890 filt_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);
905 if (error) {
906 /* no way to report error, so mark it in the knote */
907 kn->kn_flags |= EV_ERROR;
908 kn->kn_data = error;
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;
920 }
921
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 }
936
937 filt_timerunlock();
938 }
939
940 static void
941 filt_timerlock(void)
942 {
943 lck_mtx_lock(&_filt_timerlock);
944 }
945
946 static void
947 filt_timerunlock(void)
948 {
949 lck_mtx_unlock(&_filt_timerlock);
950 }
951
952 static int
953 filt_userattach(struct knote *kn)
954 {
955 /* EVFILT_USER knotes are not attached to anything in the kernel */
956 kn->kn_hook = NULL;
957 if (kn->kn_fflags & NOTE_TRIGGER) {
958 kn->kn_hookid = 1;
959 } else {
960 kn->kn_hookid = 0;
961 }
962 return 0;
963 }
964
965 static void
966 filt_userdetach(__unused struct knote *kn)
967 {
968 /* EVFILT_USER knotes are not attached to anything in the kernel */
969 }
970
971 static int
972 filt_user(struct knote *kn, __unused long hint)
973 {
974 return kn->kn_hookid;
975 }
976
977 static void
978 filt_usertouch(struct knote *kn, struct kevent64_s *kev, long type)
979 {
980 uint32_t ffctrl;
981 switch (type) {
982 case EVENT_REGISTER:
983 if (kev->fflags & NOTE_TRIGGER) {
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
1020 /*
1021 * JMM - placeholder for not-yet-implemented filters
1022 */
1023 static int
1024 filt_badattach(__unused struct knote *kn)
1025 {
1026 return(ENOTSUP);
1027 }
1028
1029
1030 struct kqueue *
1031 kqueue_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) {
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 }
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 */
1077 void
1078 kqueue_dealloc(struct kqueue *kq)
1079 {
1080 struct proc *p = kq->kq_p;
1081 struct filedesc *fdp = p->p_fd;
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);
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);
1134 lck_spin_destroy(&kq->kq_lock, kq_lck_grp);
1135 FREE_ZONE(kq, sizeof(struct kqueue), M_KQUEUE);
1136 }
1137
1138 int
1139 kqueue(struct proc *p, __unused struct kqueue_args *uap, int32_t *retval)
1140 {
1141 struct kqueue *kq;
1142 struct fileproc *fp;
1143 int fd, error;
1144
1145 error = falloc(p, &fp, &fd, vfs_context_current());
1146 if (error) {
1147 return (error);
1148 }
1149
1150 kq = kqueue_alloc(p);
1151 if (kq == NULL) {
1152 fp_free(p, fd, fp);
1153 return (ENOMEM);
1154 }
1155
1156 fp->f_flag = FREAD | FWRITE;
1157 fp->f_type = DTYPE_KQUEUE;
1158 fp->f_ops = &kqueueops;
1159 fp->f_data = (caddr_t)kq;
1160
1161 proc_fdlock(p);
1162 procfdtbl_releasefd(p, fd, NULL);
1163 fp_drop(p, fd, fp, 1);
1164 proc_fdunlock(p);
1165
1166 *retval = fd;
1167 return (error);
1168 }
1169
1170 static int
1171 kevent_copyin(user_addr_t *addrp, struct kevent64_s *kevp, struct proc *p, int iskev64)
1172 {
1173 int advance;
1174 int error;
1175
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));
1182
1183 advance = sizeof(kev64);
1184 error = copyin(*addrp, (caddr_t)&kev64, advance);
1185 if (error)
1186 return error;
1187 kevp->ident = kev64.ident;
1188 kevp->filter = kev64.filter;
1189 kevp->flags = kev64.flags;
1190 kevp->fflags = kev64.fflags;
1191 kevp->data = kev64.data;
1192 kevp->udata = kev64.udata;
1193 } else {
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);
1207 }
1208 if (!error)
1209 *addrp += advance;
1210 return error;
1211 }
1212
1213 static int
1214 kevent_copyout(struct kevent64_s *kevp, user_addr_t *addrp, struct proc *p, int iskev64)
1215 {
1216 int advance;
1217 int error;
1218
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;
1224
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
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 {
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);
1250 }
1251 if (!error)
1252 *addrp += advance;
1253 return error;
1254 }
1255
1256 /*
1257 * kevent_continue - continue a kevent syscall after blocking
1258 *
1259 * assume we inherit a use count on the kq fileglob.
1260 */
1261
1262 static void
1263 kevent_continue(__unused struct kqueue *kq, void *data, int error)
1264 {
1265 struct _kevent *cont_args;
1266 struct fileproc *fp;
1267 int32_t *retval;
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 }
1289
1290 /*
1291 * kevent - [syscall] register and wait for kernel events
1292 *
1293 */
1294 int
1295 kevent(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
1309 int
1310 kevent64(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 }
1323
1324 static int
1325 kevent_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 {
1330 struct _kevent *cont_args;
1331 uthread_t ut;
1332 struct kqueue *kq;
1333 struct fileproc *fp;
1334 struct kevent64_s kev;
1335 int error, noutputs;
1336 struct timeval atv;
1337
1338 /* convert timeout to absolute - if we have one */
1339 if (utimeout != USER_ADDR_NULL) {
1340 struct timeval rtv;
1341 if (IS_64BIT_PROCESS(p)) {
1342 struct user64_timespec ts;
1343 error = copyin(utimeout, &ts, sizeof(ts));
1344 if ((ts.tv_sec & 0xFFFFFFFF00000000ull) != 0)
1345 error = EINVAL;
1346 else
1347 TIMESPEC_TO_TIMEVAL(&rtv, &ts);
1348 } else {
1349 struct user32_timespec ts;
1350 error = copyin(utimeout, &ts, sizeof(ts));
1351 TIMESPEC_TO_TIMEVAL(&rtv, &ts);
1352 }
1353 if (error)
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 }
1363
1364 /* get a usecount for the kq itself */
1365 if ((error = fp_getfkq(p, fd, &fp, &kq)) != 0)
1366 return(error);
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);
1381
1382 /* register all the change requests the user provided... */
1383 noutputs = 0;
1384 while (nchanges > 0 && error == 0) {
1385 error = kevent_copyin(&changelist, &kev, p, iskev64);
1386 if (error)
1387 break;
1388
1389 kev.flags &= ~EV_SYSFLAGS;
1390 error = kevent_register(kq, &kev, p);
1391 if ((error || (kev.flags & EV_RECEIPT)) && nevents > 0) {
1392 kev.flags = EV_ERROR;
1393 kev.data = error;
1394 error = kevent_copyout(&kev, &ueventlist, p, iskev64);
1395 if (error == 0) {
1396 nevents--;
1397 noutputs++;
1398 }
1399 }
1400 nchanges--;
1401 }
1402
1403 /* store the continuation/completion data in the uthread */
1404 ut = (uthread_t)get_bsdthread_info(current_thread());
1405 cont_args = &ut->uu_kevent.ss_kevent;
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;
1412 cont_args->eventsize = iskev64;
1413
1414 if (nevents > 0 && noutputs == 0 && error == 0)
1415 error = kqueue_scan(kq, kevent_callback,
1416 kevent_continue, cont_args,
1417 &atv, p);
1418 kevent_continue(kq, cont_args, error);
1419
1420 errorout:
1421 fp_drop(p, fd, fp, 0);
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
1433 static int
1434 kevent_callback(__unused struct kqueue *kq, struct kevent64_s *kevp,
1435 void *data)
1436 {
1437 struct _kevent *cont_args;
1438 int error;
1439 int iskev64;
1440
1441 cont_args = (struct _kevent *)data;
1442 assert(cont_args->eventout < cont_args->eventcount);
1443
1444 iskev64 = cont_args->eventsize;
1445
1446 /*
1447 * Copy out the appropriate amount of event data for this user.
1448 */
1449 error = kevent_copyout(kevp, &cont_args->eventlist, current_proc(), iskev64);
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;
1458 }
1459
1460 /*
1461 * kevent_description - format a description of a kevent for diagnostic output
1462 *
1463 * called with a 128-byte string buffer
1464 */
1465
1466 char *
1467 kevent_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
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
1497 int
1498 kevent_register(struct kqueue *kq, struct kevent64_s *kev, __unused struct proc *ctxp)
1499 {
1500 struct proc *p = kq->kq_p;
1501 struct filedesc *fdp = p->p_fd;
1502 struct filterops *fops;
1503 struct fileproc *fp = NULL;
1504 struct knote *kn = NULL;
1505 int error = 0;
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
1521 restart:
1522 /* this iocount needs to be dropped if it is not registered */
1523 proc_fdlock(p);
1524 if (fops->f_isfd && (error = fp_lookup(p, kev->ident, &fp, 1)) != 0) {
1525 proc_fdunlock(p);
1526 return(error);
1527 }
1528
1529 if (fops->f_isfd) {
1530 /* fd-based knotes are linked off the fd table */
1531 if (kev->ident < (u_int)fdp->fd_knlistsize) {
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 {
1538 /* hash non-fd knotes here too */
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
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() */
1573 kn->kn_status = KN_ATTACHING;
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
1593 error = fops->f_attach(kn);
1594
1595 kqlock(kq);
1596
1597 if (error != 0) {
1598 /*
1599 * Failed to attach correctly, so drop.
1600 * All other possible users/droppers
1601 * have deferred to us.
1602 */
1603 kn->kn_status |= KN_DROPPING;
1604 kqunlock(kq);
1605 knote_drop(kn, p);
1606 goto done;
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;
1617 }
1618 kn->kn_status &= ~KN_ATTACHING;
1619 kqunlock(kq);
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
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
1661 /*
1662 * If somebody is in the middle of dropping this
1663 * knote - go find/insert a new one. But we have
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.
1668 */
1669 if (!kqlock2knoteusewait(kq, kn)) {
1670 /* kqueue, proc_fdlock both unlocked */
1671 goto restart;
1672 }
1673
1674 /*
1675 * Call touch routine to notify filter of changes
1676 * in filter values.
1677 */
1678 if (!fops->f_isfd && fops->f_touch != NULL)
1679 fops->f_touch(kn, kev, EVENT_REGISTER);
1680 }
1681 /* still have use ref on knote */
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)) {
1689 if (knoteuse2kqlock(kq, kn))
1690 knote_activate(kn, 1);
1691 kqunlock(kq);
1692 } else {
1693 knote_put(kn);
1694 }
1695
1696 done:
1697 if (fp != NULL)
1698 fp_drop(p, kev->ident, fp, 0);
1699 return (error);
1700 }
1701
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 */
1716 static int
1717 knote_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 */
1766 if (result && touch) {
1767 kn->kn_fop->f_touch(kn, &kev, EVENT_PROCESS);
1768 }
1769
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 }
1778
1779 /* capture all events that occurred during filter */
1780 if (!touch) {
1781 kev = kn->kn_kevent;
1782 }
1783
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;
1813 } else if ((kn->kn_flags & EV_ONESHOT) != 0) {
1814 knote_deactivate(kn);
1815 if (kqlock2knotedrop(kq, kn)) {
1816 kn->kn_fop->f_detach(kn);
1817 knote_drop(kn, p);
1818 }
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 */
1830 kn->kn_data = 0;
1831 kn->kn_fflags = 0;
1832 }
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
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 */
1858 static int
1859 kqueue_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 */
1883 static void
1884 kqueue_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 }
1892
1893 /*
1894 * kqueue_process - process the triggered events in a kqueue
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
1905 * kqueue list locked (held for duration of call)
1906 */
1907
1908 static int
1909 kqueue_process(struct kqueue *kq,
1910 kevent_callback_t callback,
1911 void *data,
1912 int *countp,
1913 struct proc *p)
1914 {
1915 struct kqtailq inprocess;
1916 struct knote *kn;
1917 int nevents;
1918 int error;
1919
1920 TAILQ_INIT(&inprocess);
1921
1922 if (kqueue_begin_processing(kq) == -1) {
1923 *countp = 0;
1924 /* Nothing to process */
1925 return 0;
1926 }
1927
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 */
1939 error = 0;
1940 nevents = 0;
1941
1942 while (error == 0 &&
1943 (kn = TAILQ_FIRST(&kq->kq_head)) != NULL) {
1944 error = knote_process(kn, callback, data, &inprocess, p);
1945 if (error == EJUSTRETURN)
1946 error = 0;
1947 else
1948 nevents++;
1949 }
1950
1951 /*
1952 * With the kqueue still locked, move any knotes
1953 * remaining on the inprocess queue back to the
1954 * kq's queue and wake up any waiters.
1955 */
1956 while ((kn = TAILQ_FIRST(&inprocess)) != NULL) {
1957 assert(kn->kn_tq == &inprocess);
1958 TAILQ_REMOVE(&inprocess, kn, kn_tqe);
1959 kn->kn_tq = &kq->kq_head;
1960 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1961 }
1962
1963 kqueue_end_processing(kq);
1964
1965 *countp = nevents;
1966 return error;
1967 }
1968
1969
1970 static void
1971 kqueue_scan_continue(void *data, wait_result_t wait_result)
1972 {
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;
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);
1984 error = kqueue_process(kq, cont_args->call, cont_args, &count, current_proc());
1985 if (error == 0 && count == 0) {
1986 wait_queue_assert_wait((wait_queue_t)kq->kq_wqs, KQ_EVENT,
1987 THREAD_ABORTSAFE, cont_args->deadline);
1988 kq->kq_state |= KQ_SLEEP;
1989 kqunlock(kq);
1990 thread_block_parameter(kqueue_scan_continue, kq);
1991 /* NOTREACHED */
1992 }
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;
2004 }
2005
2006 /* call the continuation with the results */
2007 assert(cont_args->cont != NULL);
2008 (cont_args->cont)(kq, cont_args->data, error);
2009 }
2010
2011
2012 /*
2013 * kqueue_scan - scan and wait for events in a kqueue
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 */
2025
2026 int
2027 kqueue_scan(struct kqueue *kq,
2028 kevent_callback_t callback,
2029 kqueue_continue_t continuation,
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;
2038
2039 assert(callback != NULL);
2040
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
2048 * triggered.
2049 */
2050 kqlock(kq);
2051 error = kqueue_process(kq, callback, data, &count, p);
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) {
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);
2073 } else {
2074 deadline = 0; /* block forever */
2075 }
2076
2077 if (continuation) {
2078 uthread_t ut = (uthread_t)get_bsdthread_info(current_thread());
2079 struct _kqueue_scan *cont_args = &ut->uu_kevent.ss_kqueue_scan;
2080
2081 cont_args->call = callback;
2082 cont_args->cont = continuation;
2083 cont_args->deadline = deadline;
2084 cont_args->data = data;
2085 cont = kqueue_scan_continue;
2086 }
2087 }
2088
2089 /* go ahead and wait */
2090 wait_queue_assert_wait((wait_queue_t)kq->kq_wqs, KQ_EVENT, THREAD_ABORTSAFE, deadline);
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 }
2108 }
2109 kqunlock(kq);
2110 return error;
2111 }
2112
2113
2114 /*
2115 * XXX
2116 * This could be expanded to call kqueue_scan, if desired.
2117 */
2118 /*ARGSUSED*/
2119 static int
2120 kqueue_read(__unused struct fileproc *fp,
2121 __unused struct uio *uio,
2122 __unused int flags,
2123 __unused vfs_context_t ctx)
2124 {
2125 return (ENXIO);
2126 }
2127
2128 /*ARGSUSED*/
2129 static int
2130 kqueue_write(__unused struct fileproc *fp,
2131 __unused struct uio *uio,
2132 __unused int flags,
2133 __unused vfs_context_t ctx)
2134 {
2135 return (ENXIO);
2136 }
2137
2138 /*ARGSUSED*/
2139 static int
2140 kqueue_ioctl(__unused struct fileproc *fp,
2141 __unused u_long com,
2142 __unused caddr_t data,
2143 __unused vfs_context_t ctx)
2144 {
2145 return (ENOTTY);
2146 }
2147
2148 /*ARGSUSED*/
2149 static int
2150 kqueue_select(struct fileproc *fp, int which, void *wql, __unused vfs_context_t ctx)
2151 {
2152 struct kqueue *kq = (struct kqueue *)fp->f_data;
2153 struct knote *kn;
2154 struct kqtailq inprocessq;
2155 int retnum = 0;
2156
2157 if (which != FREAD)
2158 return 0;
2159
2160 TAILQ_INIT(&inprocessq);
2161
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
2180 if (kqueue_begin_processing(kq) == -1) {
2181 kqunlock(kq);
2182 return 0;
2183 }
2184
2185 if (kq->kq_count != 0) {
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 */
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;
2197 }
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 }
2215 }
2216 }
2217
2218 out:
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);
2224 }
2225
2226 kqueue_end_processing(kq);
2227 kqunlock(kq);
2228 return retnum;
2229 }
2230
2231 /*
2232 * kqueue_close -
2233 */
2234 /*ARGSUSED*/
2235 static int
2236 kqueue_close(struct fileglob *fg, __unused vfs_context_t ctx)
2237 {
2238 struct kqueue *kq = (struct kqueue *)fg->fg_data;
2239
2240 kqueue_dealloc(kq);
2241 fg->fg_data = NULL;
2242 return (0);
2243 }
2244
2245 /*ARGSUSED*/
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 */
2251 static int
2252 kqueue_kqfilter(__unused struct fileproc *fp, struct knote *kn, __unused vfs_context_t ctx)
2253 {
2254 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
2255 struct kqueue *parentkq = kn->kn_kq;
2256
2257 if (parentkq == kq ||
2258 kn->kn_filter != EVFILT_READ)
2259 return (1);
2260
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 }
2295 }
2296
2297 /*
2298 * kqueue_drain - called when kq is closed
2299 */
2300 /*ARGSUSED*/
2301 static int
2302 kqueue_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
2311 /*ARGSUSED*/
2312 int
2313 kqueue_stat(struct fileproc *fp, void *ub, int isstat64, __unused vfs_context_t ctx)
2314 {
2315
2316 struct kqueue *kq = (struct kqueue *)fp->f_data;
2317 if (isstat64 != 0) {
2318 struct stat64 *sb64 = (struct stat64 *)ub;
2319
2320 bzero((void *)sb64, sizeof(*sb64));
2321 sb64->st_size = kq->kq_count;
2322 if (kq->kq_state & KQ_KEV64)
2323 sb64->st_blksize = sizeof(struct kevent64_s);
2324 else
2325 sb64->st_blksize = sizeof(struct kevent);
2326 sb64->st_mode = S_IFIFO;
2327 } else {
2328 struct stat *sb = (struct stat *)ub;
2329
2330 bzero((void *)sb, sizeof(*sb));
2331 sb->st_size = kq->kq_count;
2332 if (kq->kq_state & KQ_KEV64)
2333 sb->st_blksize = sizeof(struct kevent64_s);
2334 else
2335 sb->st_blksize = sizeof(struct kevent);
2336 sb->st_mode = S_IFIFO;
2337 }
2338
2339 return (0);
2340 }
2341
2342 /*
2343 * Called with the kqueue locked
2344 */
2345 static void
2346 kqueue_wakeup(struct kqueue *kq, int closed)
2347 {
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);
2352 }
2353 }
2354
2355 void
2356 klist_init(struct klist *list)
2357 {
2358 SLIST_INIT(list);
2359 }
2360
2361
2362 /*
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
2368 * the hint) and not deadlock itself.
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.
2373 */
2374 void
2375 knote(struct klist *list, long hint)
2376 {
2377 struct knote *kn;
2378
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)
2391 knote_activate(kn, 1);
2392 /* lock held again */
2393 }
2394 kqunlock(kq);
2395 }
2396 }
2397
2398 /*
2399 * attach a knote to the specified list. Return true if this is the first entry.
2400 * The list is protected by whatever lock the object it is associated with uses.
2401 */
2402 int
2403 knote_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.
2412 * The list is protected by whatever lock the object it is associated with uses.
2413 */
2414 int
2415 knote_detach(struct klist *list, struct knote *kn)
2416 {
2417 SLIST_REMOVE(list, kn, knote, kn_selnext);
2418 return SLIST_EMPTY(list);
2419 }
2420
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.
2428 *
2429 * caller provides the wait queue link structure.
2430 */
2431 int
2432 knote_link_wait_queue(struct knote *kn, struct wait_queue *wq, wait_queue_link_t wql)
2433 {
2434 struct kqueue *kq = kn->kn_kq;
2435 kern_return_t kr;
2436
2437 kr = wait_queue_link_noalloc(wq, kq->kq_wqs, wql);
2438 if (kr == KERN_SUCCESS) {
2439 knote_markstayqueued(kn);
2440 return 0;
2441 } else {
2442 return EINVAL;
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.
2452 *
2453 * On success, caller is responsible for the link structure
2454 */
2455 int
2456 knote_unlink_wait_queue(struct knote *kn, struct wait_queue *wq, wait_queue_link_t *wqlp)
2457 {
2458 struct kqueue *kq = kn->kn_kq;
2459 kern_return_t kr;
2460
2461 kr = wait_queue_unlink_nofree(wq, kq->kq_wqs, wqlp);
2462 kqlock(kq);
2463 kn->kn_status &= ~KN_STAYQUEUED;
2464 knote_dequeue(kn);
2465 kqunlock(kq);
2466 return (kr != KERN_SUCCESS) ? EINVAL : 0;
2467 }
2468
2469 /*
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.
2477 */
2478 void
2479 knote_fdclose(struct proc *p, int fd)
2480 {
2481 struct filedesc *fdp = p->p_fd;
2482 struct klist *list;
2483 struct knote *kn;
2484
2485 list = &fdp->fd_knlist[fd];
2486 while ((kn = SLIST_FIRST(list)) != NULL) {
2487 struct kqueue *kq = kn->kn_kq;
2488
2489 if (kq->kq_p != p)
2490 panic("knote_fdclose: proc mismatch (kq->kq_p=%p != p=%p)", kq->kq_p, p);
2491
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);
2508
2509 /* the fd tables may have changed - start over */
2510 list = &fdp->fd_knlist[fd];
2511 }
2512 }
2513
2514 /* proc_fdlock held on entry (and exit) */
2515 static int
2516 knote_fdpattach(struct knote *kn, struct filedesc *fdp, struct proc *p)
2517 {
2518 struct klist *list = NULL;
2519
2520 if (! kn->kn_fop->f_isfd) {
2521 if (fdp->fd_knhashmask == 0)
2522 fdp->fd_knhash = hashinit(CONFIG_KN_HASHSIZE, M_KQUEUE,
2523 &fdp->fd_knhashmask);
2524 list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
2525 } else {
2526 if ((u_int)fdp->fd_knlistsize <= kn->kn_id) {
2527 u_int size = 0;
2528
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
2533 /* have to grow the fd_knlist */
2534 size = fdp->fd_knlistsize;
2535 while (size <= kn->kn_id)
2536 size += KQEXTENT;
2537
2538 if (size >= (UINT_MAX/sizeof(struct klist *)))
2539 return (EINVAL);
2540
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 *));
2551 FREE(fdp->fd_knlist, M_KQUEUE);
2552 fdp->fd_knlist = list;
2553 fdp->fd_knlistsize = size;
2554 }
2555 list = &fdp->fd_knlist[kn->kn_id];
2556 }
2557 SLIST_INSERT_HEAD(list, kn, kn_link);
2558 return (0);
2559 }
2560
2561
2562
2563 /*
2564 * should be called at spl == 0, since we don't want to hold spl
2565 * while calling fdrop and free.
2566 */
2567 static void
2568 knote_drop(struct knote *kn, __unused struct proc *ctxp)
2569 {
2570 struct kqueue *kq = kn->kn_kq;
2571 struct proc *p = kq->kq_p;
2572 struct filedesc *fdp = p->p_fd;
2573 struct klist *list;
2574 int needswakeup;
2575
2576 proc_fdlock(p);
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);
2583 kqlock(kq);
2584 knote_dequeue(kn);
2585 needswakeup = (kn->kn_status & KN_USEWAIT);
2586 kqunlock(kq);
2587 proc_fdunlock(p);
2588
2589 if (needswakeup)
2590 wait_queue_wakeup_all((wait_queue_t)kq->kq_wqs, &kn->kn_status, THREAD_AWAKENED);
2591
2592 if (kn->kn_fop->f_isfd)
2593 fp_drop(p, kn->kn_id, kn->kn_fp, 0);
2594
2595 knote_free(kn);
2596 }
2597
2598 /* called with kqueue lock held */
2599 static void
2600 knote_activate(struct knote *kn, int propagate)
2601 {
2602 struct kqueue *kq = kn->kn_kq;
2603
2604 kn->kn_status |= KN_ACTIVE;
2605 knote_enqueue(kn);
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 }
2612
2613 /* called with kqueue lock held */
2614 static void
2615 knote_deactivate(struct knote *kn)
2616 {
2617 kn->kn_status &= ~KN_ACTIVE;
2618 knote_dequeue(kn);
2619 }
2620
2621 /* called with kqueue lock held */
2622 static void
2623 knote_enqueue(struct knote *kn)
2624 {
2625 if ((kn->kn_status & (KN_QUEUED | KN_STAYQUEUED)) == KN_STAYQUEUED ||
2626 (kn->kn_status & (KN_QUEUED | KN_STAYQUEUED | KN_DISABLED)) == 0) {
2627 struct kqtailq *tq = kn->kn_tq;
2628 struct kqueue *kq = kn->kn_kq;
2629
2630 TAILQ_INSERT_TAIL(tq, kn, kn_tqe);
2631 kn->kn_status |= KN_QUEUED;
2632 kq->kq_count++;
2633 }
2634 }
2635
2636 /* called with kqueue lock held */
2637 static void
2638 knote_dequeue(struct knote *kn)
2639 {
2640 struct kqueue *kq = kn->kn_kq;
2641
2642 if ((kn->kn_status & (KN_QUEUED | KN_STAYQUEUED)) == KN_QUEUED) {
2643 struct kqtailq *tq = kn->kn_tq;
2644
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 }
2650 }
2651
2652 void
2653 knote_init(void)
2654 {
2655 knote_zone = zinit(sizeof(struct knote), 8192*sizeof(struct knote), 8192, "knote zone");
2656
2657 /* allocate kq lock group attribute and group */
2658 kq_lck_grp_attr= lck_grp_attr_alloc_init();
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();
2664
2665 /* Initialize the timer filter lock */
2666 lck_mtx_init(&_filt_timerlock, kq_lck_grp, kq_lck_attr);
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
2672 }
2673 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL)
2674
2675 static struct knote *
2676 knote_alloc(void)
2677 {
2678 return ((struct knote *)zalloc(knote_zone));
2679 }
2680
2681 static void
2682 knote_free(struct knote *kn)
2683 {
2684 zfree(knote_zone, kn);
2685 }
2686
2687 #if SOCKETS
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>
2695 #include <sys/sys_domain.h>
2696 #include <sys/syslog.h>
2697
2698
2699 static int kev_attach(struct socket *so, int proto, struct proc *p);
2700 static int kev_detach(struct socket *so);
2701 static int kev_control(struct socket *so, u_long cmd, caddr_t data, struct ifnet *ifp, struct proc *p);
2702
2703 struct 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 };
2710
2711 struct protosw eventsw[] = {
2712 {
2713 .pr_type = SOCK_RAW,
2714 .pr_domain = &systemdomain,
2715 .pr_protocol = SYSPROTO_EVENT,
2716 .pr_flags = PR_ATOMIC,
2717 .pr_usrreqs = &event_usrreqs,
2718 }
2719 };
2720
2721 static
2722 struct kern_event_head kern_event_head;
2723
2724 static u_int32_t static_event_id = 0;
2725 struct domain *sysdom = &systemdomain;
2726 static lck_mtx_t *sys_mtx;
2727
2728 /*
2729 * Install the protosw's for the NKE manager. Invoked at
2730 * extension load time
2731 */
2732 int
2733 kern_event_init(void)
2734 {
2735 int retval;
2736
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 }
2741
2742 /*
2743 * Use the domain mutex for all system event sockets
2744 */
2745 sys_mtx = sysdom->dom_mtx;
2746
2747 return(KERN_SUCCESS);
2748 }
2749
2750 static int
2751 kev_attach(struct socket *so, __unused int proto, __unused struct proc *p)
2752 {
2753 int error;
2754 struct kern_event_pcb *ev_pcb;
2755
2756 error = soreserve(so, KEV_SNDSPACE, KEV_RECVSPACE);
2757 if (error)
2758 return error;
2759
2760 MALLOC(ev_pcb, struct kern_event_pcb *, sizeof(struct kern_event_pcb), M_PCB, M_WAITOK);
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;
2768 lck_mtx_lock(sys_mtx);
2769 LIST_INSERT_HEAD(&kern_event_head, ev_pcb, ev_link);
2770 lck_mtx_unlock(sys_mtx);
2771
2772 return 0;
2773 }
2774
2775
2776 static int
2777 kev_detach(struct socket *so)
2778 {
2779 struct kern_event_pcb *ev_pcb = (struct kern_event_pcb *) so->so_pcb;
2780
2781 if (ev_pcb != 0) {
2782 LIST_REMOVE(ev_pcb, ev_link);
2783 FREE(ev_pcb, M_PCB);
2784 so->so_pcb = 0;
2785 so->so_flags |= SOF_PCBCLEARING;
2786 }
2787
2788 return 0;
2789 }
2790
2791 /*
2792 * For now, kev_vendor_code and mbuf_tags use the same
2793 * mechanism.
2794 */
2795
2796 errno_t kev_vendor_code_find(
2797 const char *string,
2798 u_int32_t *out_vendor_code)
2799 {
2800 if (strlen(string) >= KEV_VENDOR_CODE_MAX_STR_LEN) {
2801 return EINVAL;
2802 }
2803 return net_str_id_find_internal(string, out_vendor_code, NSI_VENDOR_CODE, 1);
2804 }
2805
2806 errno_t kev_msg_post(struct kev_msg *event_msg)
2807 {
2808 mbuf_tag_id_t min_vendor, max_vendor;
2809
2810 net_str_id_first_last(&min_vendor, &max_vendor, NSI_VENDOR_CODE);
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
2825
2826 int 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;
2832 u_int32_t total_size;
2833 int i;
2834
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 }
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
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;
2874 lck_mtx_lock(sys_mtx);
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);
2896 lck_mtx_unlock(sys_mtx);
2897 return ENOBUFS;
2898 }
2899 /* the socket is already locked because we hold the sys_mtx here */
2900 if (sbappendrecord(&ev_pcb->ev_socket->so_rcv, m2))
2901 sorwakeup(ev_pcb->ev_socket);
2902 }
2903
2904 m_free(m);
2905 lck_mtx_unlock(sys_mtx);
2906 return 0;
2907 }
2908
2909 static int
2910 kev_control(struct socket *so,
2911 u_long cmd,
2912 caddr_t data,
2913 __unused struct ifnet *ifp,
2914 __unused struct proc *p)
2915 {
2916 struct kev_request *kev_req = (struct kev_request *) data;
2917 struct kern_event_pcb *ev_pcb;
2918 struct kev_vendor_code *kev_vendor;
2919 u_int32_t *id_value = (u_int32_t *) data;
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;
2947
2948 return net_str_id_find_internal(kev_vendor->vendor_string,
2949 &kev_vendor->vendor_code, NSI_VENDOR_CODE, 0);
2950
2951 default:
2952 return ENOTSUP;
2953 }
2954
2955 return 0;
2956 }
2957
2958 #endif /* SOCKETS */
2959
2960
2961 int
2962 fill_kqueueinfo(struct kqueue *kq, struct kqueue_info * kinfo)
2963 {
2964 struct vinfo_stat * st;
2965
2966 /* No need for the funnel as fd is kept alive */
2967
2968 st = &kinfo->kq_stat;
2969
2970 st->vst_size = kq->kq_count;
2971 if (kq->kq_state & KQ_KEV64)
2972 st->vst_blksize = sizeof(struct kevent64_s);
2973 else
2974 st->vst_blksize = sizeof(struct kevent);
2975 st->vst_mode = S_IFIFO;
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 }
2983
2984
2985 void
2986 knote_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 }