]> git.saurik.com Git - apple/xnu.git/blob - bsd/kern/kern_event.c
6bc84137c321faccf14151711f9b4989cff444c8
[apple/xnu.git] / bsd / kern / kern_event.c
1 /*
2 * Copyright (c) 2000-2015 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 #include <sys/codesign.h>
85 #include <sys/pthread_shims.h>
86
87 #include <kern/locks.h>
88 #include <kern/clock.h>
89 #include <kern/thread_call.h>
90 #include <kern/sched_prim.h>
91 #include <kern/waitq.h>
92 #include <kern/zalloc.h>
93 #include <kern/kalloc.h>
94 #include <kern/assert.h>
95
96 #include <libkern/libkern.h>
97 #include "net/net_str_id.h"
98
99 #include <mach/task.h>
100
101 #if VM_PRESSURE_EVENTS
102 #include <kern/vm_pressure.h>
103 #endif
104
105 #if CONFIG_MEMORYSTATUS
106 #include <sys/kern_memorystatus.h>
107 #endif
108
109 MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
110
111 #define KQ_EVENT NO_EVENT64
112
113 static inline void kqlock(struct kqueue *kq);
114 static inline void kqunlock(struct kqueue *kq);
115
116 static int kqlock2knoteuse(struct kqueue *kq, struct knote *kn);
117 static int kqlock2knoteusewait(struct kqueue *kq, struct knote *kn);
118 static int kqlock2knotedrop(struct kqueue *kq, struct knote *kn);
119 static int knoteuse2kqlock(struct kqueue *kq, struct knote *kn);
120
121 static void kqueue_wakeup(struct kqueue *kq, int closed);
122 static int kqueue_read(struct fileproc *fp, struct uio *uio,
123 int flags, vfs_context_t ctx);
124 static int kqueue_write(struct fileproc *fp, struct uio *uio,
125 int flags, vfs_context_t ctx);
126 static int kqueue_ioctl(struct fileproc *fp, u_long com, caddr_t data,
127 vfs_context_t ctx);
128 static int kqueue_select(struct fileproc *fp, int which, void *wq_link_id,
129 vfs_context_t ctx);
130 static int kqueue_close(struct fileglob *fg, vfs_context_t ctx);
131 static int kqueue_kqfilter(struct fileproc *fp, struct knote *kn,
132 vfs_context_t ctx);
133 static int kqueue_drain(struct fileproc *fp, vfs_context_t ctx);
134
135 static const struct fileops kqueueops = {
136 .fo_type = DTYPE_KQUEUE,
137 .fo_read = kqueue_read,
138 .fo_write = kqueue_write,
139 .fo_ioctl = kqueue_ioctl,
140 .fo_select = kqueue_select,
141 .fo_close = kqueue_close,
142 .fo_kqfilter = kqueue_kqfilter,
143 .fo_drain = kqueue_drain,
144 };
145
146 static int kevent_internal(struct proc *p, int fd,
147 user_addr_t changelist, int nchanges,
148 user_addr_t eventlist, int nevents,
149 user_addr_t data_out, user_size_t *data_available,
150 unsigned int flags, user_addr_t utimeout,
151 kqueue_continue_t continuation,
152 int32_t *retval);
153 static int kevent_copyin(user_addr_t *addrp, struct kevent_internal_s *kevp,
154 struct proc *p, unsigned int flags);
155 static int kevent_copyout(struct kevent_internal_s *kevp, user_addr_t *addrp,
156 struct proc *p, unsigned int flags);
157 char * kevent_description(struct kevent_internal_s *kevp, char *s, size_t n);
158
159 static int kevent_callback(struct kqueue *kq, struct kevent_internal_s *kevp,
160 void *data);
161 static void kevent_continue(struct kqueue *kq, void *data, int error);
162 static void kqueue_scan_continue(void *contp, wait_result_t wait_result);
163 static int kqueue_process(struct kqueue *kq, kevent_callback_t callback,
164 void *data, int *countp, struct proc *p);
165 static int kqueue_begin_processing(struct kqueue *kq);
166 static void kqueue_end_processing(struct kqueue *kq);
167 static int knote_process(struct knote *kn, kevent_callback_t callback,
168 void *data, struct kqtailq *inprocessp, struct proc *p);
169 static void knote_put(struct knote *kn);
170 static int knote_fdpattach(struct knote *kn, struct filedesc *fdp,
171 struct proc *p);
172 static void knote_drop(struct knote *kn, struct proc *p);
173 static void knote_activate(struct knote *kn, int);
174 static void knote_deactivate(struct knote *kn);
175 static void knote_enqueue(struct knote *kn);
176 static void knote_dequeue(struct knote *kn);
177 static struct knote *knote_alloc(void);
178 static void knote_free(struct knote *kn);
179
180 static int filt_fileattach(struct knote *kn);
181 static struct filterops file_filtops = {
182 .f_isfd = 1,
183 .f_attach = filt_fileattach,
184 };
185
186 static void filt_kqdetach(struct knote *kn);
187 static int filt_kqueue(struct knote *kn, long hint);
188 static struct filterops kqread_filtops = {
189 .f_isfd = 1,
190 .f_detach = filt_kqdetach,
191 .f_event = filt_kqueue,
192 };
193
194 /* placeholder for not-yet-implemented filters */
195 static int filt_badattach(struct knote *kn);
196 static struct filterops bad_filtops = {
197 .f_attach = filt_badattach,
198 };
199
200 static int filt_procattach(struct knote *kn);
201 static void filt_procdetach(struct knote *kn);
202 static int filt_proc(struct knote *kn, long hint);
203 static struct filterops proc_filtops = {
204 .f_attach = filt_procattach,
205 .f_detach = filt_procdetach,
206 .f_event = filt_proc,
207 };
208
209 #if VM_PRESSURE_EVENTS
210 static int filt_vmattach(struct knote *kn);
211 static void filt_vmdetach(struct knote *kn);
212 static int filt_vm(struct knote *kn, long hint);
213 static struct filterops vm_filtops = {
214 .f_attach = filt_vmattach,
215 .f_detach = filt_vmdetach,
216 .f_event = filt_vm,
217 };
218 #endif /* VM_PRESSURE_EVENTS */
219
220 #if CONFIG_MEMORYSTATUS
221 extern struct filterops memorystatus_filtops;
222 #endif /* CONFIG_MEMORYSTATUS */
223
224 extern struct filterops fs_filtops;
225
226 extern struct filterops sig_filtops;
227
228 /* Timer filter */
229 static int filt_timerattach(struct knote *kn);
230 static void filt_timerdetach(struct knote *kn);
231 static int filt_timer(struct knote *kn, long hint);
232 static void filt_timertouch(struct knote *kn, struct kevent_internal_s *kev,
233 long type);
234 static struct filterops timer_filtops = {
235 .f_attach = filt_timerattach,
236 .f_detach = filt_timerdetach,
237 .f_event = filt_timer,
238 .f_touch = filt_timertouch,
239 };
240
241 /* Helpers */
242 static void filt_timerexpire(void *knx, void *param1);
243 static int filt_timervalidate(struct knote *kn);
244 static void filt_timerupdate(struct knote *kn);
245 static void filt_timercancel(struct knote *kn);
246
247 #define TIMER_RUNNING 0x1
248 #define TIMER_CANCELWAIT 0x2
249
250 static lck_mtx_t _filt_timerlock;
251 static void filt_timerlock(void);
252 static void filt_timerunlock(void);
253
254 static zone_t knote_zone;
255
256 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
257
258 #if 0
259 extern struct filterops aio_filtops;
260 #endif
261
262 /* Mach portset filter */
263 extern struct filterops machport_filtops;
264
265 /* User filter */
266 static int filt_userattach(struct knote *kn);
267 static void filt_userdetach(struct knote *kn);
268 static int filt_user(struct knote *kn, long hint);
269 static void filt_usertouch(struct knote *kn, struct kevent_internal_s *kev,
270 long type);
271 static struct filterops user_filtops = {
272 .f_attach = filt_userattach,
273 .f_detach = filt_userdetach,
274 .f_event = filt_user,
275 .f_touch = filt_usertouch,
276 };
277
278 /*
279 * Table for all system-defined filters.
280 */
281 static struct filterops *sysfilt_ops[] = {
282 &file_filtops, /* EVFILT_READ */
283 &file_filtops, /* EVFILT_WRITE */
284 #if 0
285 &aio_filtops, /* EVFILT_AIO */
286 #else
287 &bad_filtops, /* EVFILT_AIO */
288 #endif
289 &file_filtops, /* EVFILT_VNODE */
290 &proc_filtops, /* EVFILT_PROC */
291 &sig_filtops, /* EVFILT_SIGNAL */
292 &timer_filtops, /* EVFILT_TIMER */
293 &machport_filtops, /* EVFILT_MACHPORT */
294 &fs_filtops, /* EVFILT_FS */
295 &user_filtops, /* EVFILT_USER */
296 &bad_filtops, /* unused */
297 #if VM_PRESSURE_EVENTS
298 &vm_filtops, /* EVFILT_VM */
299 #else
300 &bad_filtops, /* EVFILT_VM */
301 #endif
302 &file_filtops, /* EVFILT_SOCK */
303 #if CONFIG_MEMORYSTATUS
304 &memorystatus_filtops, /* EVFILT_MEMORYSTATUS */
305 #else
306 &bad_filtops, /* EVFILT_MEMORYSTATUS */
307 #endif
308 };
309
310 /*
311 * kqueue/note lock attributes and implementations
312 *
313 * kqueues have locks, while knotes have use counts
314 * Most of the knote state is guarded by the object lock.
315 * the knote "inuse" count and status use the kqueue lock.
316 */
317 lck_grp_attr_t * kq_lck_grp_attr;
318 lck_grp_t * kq_lck_grp;
319 lck_attr_t * kq_lck_attr;
320
321 static inline void
322 kqlock(struct kqueue *kq)
323 {
324 lck_spin_lock(&kq->kq_lock);
325 }
326
327 static inline void
328 kqunlock(struct kqueue *kq)
329 {
330 lck_spin_unlock(&kq->kq_lock);
331 }
332
333 /*
334 * Convert a kq lock to a knote use referece.
335 *
336 * If the knote is being dropped, we can't get
337 * a use reference, so just return with it
338 * still locked.
339 * - kq locked at entry
340 * - unlock on exit if we get the use reference
341 */
342 static int
343 kqlock2knoteuse(struct kqueue *kq, struct knote *kn)
344 {
345 if (kn->kn_status & KN_DROPPING)
346 return (0);
347 kn->kn_inuse++;
348 kqunlock(kq);
349 return (1);
350 }
351
352 /*
353 * Convert a kq lock to a knote use referece,
354 * but wait for attach and drop events to complete.
355 *
356 * If the knote is being dropped, we can't get
357 * a use reference, so just return with it
358 * still locked.
359 * - kq locked at entry
360 * - kq always unlocked on exit
361 */
362 static int
363 kqlock2knoteusewait(struct kqueue *kq, struct knote *kn)
364 {
365 if ((kn->kn_status & (KN_DROPPING | KN_ATTACHING)) != 0) {
366 kn->kn_status |= KN_USEWAIT;
367 waitq_assert_wait64((struct waitq *)kq->kq_wqs,
368 CAST_EVENT64_T(&kn->kn_status),
369 THREAD_UNINT, TIMEOUT_WAIT_FOREVER);
370 kqunlock(kq);
371 thread_block(THREAD_CONTINUE_NULL);
372 return (0);
373 }
374 kn->kn_inuse++;
375 kqunlock(kq);
376 return (1);
377 }
378
379 /*
380 * Convert from a knote use reference back to kq lock.
381 *
382 * Drop a use reference and wake any waiters if
383 * this is the last one.
384 *
385 * The exit return indicates if the knote is
386 * still alive - but the kqueue lock is taken
387 * unconditionally.
388 */
389 static int
390 knoteuse2kqlock(struct kqueue *kq, struct knote *kn)
391 {
392 kqlock(kq);
393 if (--kn->kn_inuse == 0) {
394 if ((kn->kn_status & KN_ATTACHING) != 0) {
395 kn->kn_status &= ~KN_ATTACHING;
396 }
397 if ((kn->kn_status & KN_USEWAIT) != 0) {
398 kn->kn_status &= ~KN_USEWAIT;
399 waitq_wakeup64_all((struct waitq *)kq->kq_wqs,
400 CAST_EVENT64_T(&kn->kn_status),
401 THREAD_AWAKENED,
402 WAITQ_ALL_PRIORITIES);
403 }
404 }
405 return ((kn->kn_status & KN_DROPPING) == 0);
406 }
407
408 /*
409 * Convert a kq lock to a knote drop reference.
410 *
411 * If the knote is in use, wait for the use count
412 * to subside. We first mark our intention to drop
413 * it - keeping other users from "piling on."
414 * If we are too late, we have to wait for the
415 * other drop to complete.
416 *
417 * - kq locked at entry
418 * - always unlocked on exit.
419 * - caller can't hold any locks that would prevent
420 * the other dropper from completing.
421 */
422 static int
423 kqlock2knotedrop(struct kqueue *kq, struct knote *kn)
424 {
425 int oktodrop;
426
427 oktodrop = ((kn->kn_status & (KN_DROPPING | KN_ATTACHING)) == 0);
428 kn->kn_status &= ~KN_STAYQUEUED;
429 kn->kn_status |= KN_DROPPING;
430 if (oktodrop) {
431 if (kn->kn_inuse == 0) {
432 kqunlock(kq);
433 return (oktodrop);
434 }
435 }
436 kn->kn_status |= KN_USEWAIT;
437 waitq_assert_wait64((struct waitq *)kq->kq_wqs,
438 CAST_EVENT64_T(&kn->kn_status),
439 THREAD_UNINT, TIMEOUT_WAIT_FOREVER);
440 kqunlock(kq);
441 thread_block(THREAD_CONTINUE_NULL);
442 return (oktodrop);
443 }
444
445 /*
446 * Release a knote use count reference.
447 */
448 static void
449 knote_put(struct knote *kn)
450 {
451 struct kqueue *kq = kn->kn_kq;
452
453 kqlock(kq);
454 if (--kn->kn_inuse == 0) {
455 if ((kn->kn_status & KN_USEWAIT) != 0) {
456 kn->kn_status &= ~KN_USEWAIT;
457 waitq_wakeup64_all((struct waitq *)kq->kq_wqs,
458 CAST_EVENT64_T(&kn->kn_status),
459 THREAD_AWAKENED,
460 WAITQ_ALL_PRIORITIES);
461 }
462 }
463 kqunlock(kq);
464 }
465
466 static int
467 filt_fileattach(struct knote *kn)
468 {
469 return (fo_kqfilter(kn->kn_fp, kn, vfs_context_current()));
470 }
471
472 #define f_flag f_fglob->fg_flag
473 #define f_msgcount f_fglob->fg_msgcount
474 #define f_cred f_fglob->fg_cred
475 #define f_ops f_fglob->fg_ops
476 #define f_offset f_fglob->fg_offset
477 #define f_data f_fglob->fg_data
478
479 static void
480 filt_kqdetach(struct knote *kn)
481 {
482 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
483
484 kqlock(kq);
485 KNOTE_DETACH(&kq->kq_sel.si_note, kn);
486 kqunlock(kq);
487 }
488
489 /*ARGSUSED*/
490 static int
491 filt_kqueue(struct knote *kn, __unused long hint)
492 {
493 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
494
495 kn->kn_data = kq->kq_count;
496 return (kn->kn_data > 0);
497 }
498
499 static int
500 filt_procattach(struct knote *kn)
501 {
502 struct proc *p;
503
504 assert(PID_MAX < NOTE_PDATAMASK);
505
506 if ((kn->kn_sfflags & (NOTE_TRACK | NOTE_TRACKERR | NOTE_CHILD)) != 0)
507 return (ENOTSUP);
508
509 p = proc_find(kn->kn_id);
510 if (p == NULL) {
511 return (ESRCH);
512 }
513
514 const int NoteExitStatusBits = NOTE_EXIT | NOTE_EXITSTATUS;
515
516 if ((kn->kn_sfflags & NoteExitStatusBits) == NoteExitStatusBits)
517 do {
518 pid_t selfpid = proc_selfpid();
519
520 if (p->p_ppid == selfpid)
521 break; /* parent => ok */
522
523 if ((p->p_lflag & P_LTRACED) != 0 &&
524 (p->p_oppid == selfpid))
525 break; /* parent-in-waiting => ok */
526
527 proc_rele(p);
528 return (EACCES);
529 } while (0);
530
531 proc_klist_lock();
532
533 kn->kn_flags |= EV_CLEAR; /* automatically set */
534 kn->kn_ptr.p_proc = p; /* store the proc handle */
535
536 KNOTE_ATTACH(&p->p_klist, kn);
537
538 proc_klist_unlock();
539
540 proc_rele(p);
541
542 return (0);
543 }
544
545 /*
546 * The knote may be attached to a different process, which may exit,
547 * leaving nothing for the knote to be attached to. In that case,
548 * the pointer to the process will have already been nulled out.
549 */
550 static void
551 filt_procdetach(struct knote *kn)
552 {
553 struct proc *p;
554
555 proc_klist_lock();
556
557 p = kn->kn_ptr.p_proc;
558 if (p != PROC_NULL) {
559 kn->kn_ptr.p_proc = PROC_NULL;
560 KNOTE_DETACH(&p->p_klist, kn);
561 }
562
563 proc_klist_unlock();
564 }
565
566 static int
567 filt_proc(struct knote *kn, long hint)
568 {
569 /*
570 * Note: a lot of bits in hint may be obtained from the knote
571 * To free some of those bits, see <rdar://problem/12592988> Freeing up
572 * bits in hint for filt_proc
573 */
574 /* hint is 0 when called from above */
575 if (hint != 0) {
576 u_int event;
577
578 /* ALWAYS CALLED WITH proc_klist_lock when (hint != 0) */
579
580 /*
581 * mask off extra data
582 */
583 event = (u_int)hint & NOTE_PCTRLMASK;
584
585 /*
586 * termination lifecycle events can happen while a debugger
587 * has reparented a process, in which case notifications
588 * should be quashed except to the tracing parent. When
589 * the debugger reaps the child (either via wait4(2) or
590 * process exit), the child will be reparented to the original
591 * parent and these knotes re-fired.
592 */
593 if (event & NOTE_EXIT) {
594 if ((kn->kn_ptr.p_proc->p_oppid != 0)
595 && (kn->kn_kq->kq_p->p_pid != kn->kn_ptr.p_proc->p_ppid)) {
596 /*
597 * This knote is not for the current ptrace(2) parent, ignore.
598 */
599 return 0;
600 }
601 }
602
603 /*
604 * if the user is interested in this event, record it.
605 */
606 if (kn->kn_sfflags & event)
607 kn->kn_fflags |= event;
608
609 #pragma clang diagnostic push
610 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
611 if ((event == NOTE_REAP) || ((event == NOTE_EXIT) && !(kn->kn_sfflags & NOTE_REAP))) {
612 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
613 }
614 #pragma clang diagnostic pop
615
616
617 /*
618 * The kernel has a wrapper in place that returns the same data
619 * as is collected here, in kn_data. Any changes to how
620 * NOTE_EXITSTATUS and NOTE_EXIT_DETAIL are collected
621 * should also be reflected in the proc_pidnoteexit() wrapper.
622 */
623 if (event == NOTE_EXIT) {
624 kn->kn_data = 0;
625 if ((kn->kn_sfflags & NOTE_EXITSTATUS) != 0) {
626 kn->kn_fflags |= NOTE_EXITSTATUS;
627 kn->kn_data |= (hint & NOTE_PDATAMASK);
628 }
629 if ((kn->kn_sfflags & NOTE_EXIT_DETAIL) != 0) {
630 kn->kn_fflags |= NOTE_EXIT_DETAIL;
631 if ((kn->kn_ptr.p_proc->p_lflag &
632 P_LTERM_DECRYPTFAIL) != 0) {
633 kn->kn_data |= NOTE_EXIT_DECRYPTFAIL;
634 }
635 if ((kn->kn_ptr.p_proc->p_lflag &
636 P_LTERM_JETSAM) != 0) {
637 kn->kn_data |= NOTE_EXIT_MEMORY;
638 switch (kn->kn_ptr.p_proc->p_lflag &
639 P_JETSAM_MASK) {
640 case P_JETSAM_VMPAGESHORTAGE:
641 kn->kn_data |= NOTE_EXIT_MEMORY_VMPAGESHORTAGE;
642 break;
643 case P_JETSAM_VMTHRASHING:
644 kn->kn_data |= NOTE_EXIT_MEMORY_VMTHRASHING;
645 break;
646 case P_JETSAM_FCTHRASHING:
647 kn->kn_data |= NOTE_EXIT_MEMORY_FCTHRASHING;
648 break;
649 case P_JETSAM_VNODE:
650 kn->kn_data |= NOTE_EXIT_MEMORY_VNODE;
651 break;
652 case P_JETSAM_HIWAT:
653 kn->kn_data |= NOTE_EXIT_MEMORY_HIWAT;
654 break;
655 case P_JETSAM_PID:
656 kn->kn_data |= NOTE_EXIT_MEMORY_PID;
657 break;
658 case P_JETSAM_IDLEEXIT:
659 kn->kn_data |= NOTE_EXIT_MEMORY_IDLE;
660 break;
661 }
662 }
663 if ((kn->kn_ptr.p_proc->p_csflags &
664 CS_KILLED) != 0) {
665 kn->kn_data |= NOTE_EXIT_CSERROR;
666 }
667 }
668 }
669 }
670
671 /* atomic check, no locking need when called from above */
672 return (kn->kn_fflags != 0);
673 }
674
675 #if VM_PRESSURE_EVENTS
676 /*
677 * Virtual memory kevents
678 *
679 * author: Matt Jacobson [matthew_jacobson@apple.com]
680 */
681
682 static int
683 filt_vmattach(struct knote *kn)
684 {
685 /*
686 * The note will be cleared once the information has been flushed to
687 * the client. If there is still pressure, we will be re-alerted.
688 */
689 kn->kn_flags |= EV_CLEAR;
690 return (vm_knote_register(kn));
691 }
692
693 static void
694 filt_vmdetach(struct knote *kn)
695 {
696 vm_knote_unregister(kn);
697 }
698
699 static int
700 filt_vm(struct knote *kn, long hint)
701 {
702 /* hint == 0 means this is just an alive? check (always true) */
703 if (hint != 0) {
704 const pid_t pid = (pid_t)hint;
705 if ((kn->kn_sfflags & NOTE_VM_PRESSURE) &&
706 (kn->kn_kq->kq_p->p_pid == pid)) {
707 kn->kn_fflags |= NOTE_VM_PRESSURE;
708 }
709 }
710
711 return (kn->kn_fflags != 0);
712 }
713 #endif /* VM_PRESSURE_EVENTS */
714
715 /*
716 * filt_timervalidate - process data from user
717 *
718 * Converts to either interval or deadline format.
719 *
720 * The saved-data field in the knote contains the
721 * time value. The saved filter-flags indicates
722 * the unit of measurement.
723 *
724 * After validation, either the saved-data field
725 * contains the interval in absolute time, or ext[0]
726 * contains the expected deadline. If that deadline
727 * is in the past, ext[0] is 0.
728 *
729 * Returns EINVAL for unrecognized units of time.
730 *
731 * Timer filter lock is held.
732 *
733 */
734 static int
735 filt_timervalidate(struct knote *kn)
736 {
737 uint64_t multiplier;
738 uint64_t raw = 0;
739
740 switch (kn->kn_sfflags & (NOTE_SECONDS|NOTE_USECONDS|NOTE_NSECONDS)) {
741 case NOTE_SECONDS:
742 multiplier = NSEC_PER_SEC;
743 break;
744 case NOTE_USECONDS:
745 multiplier = NSEC_PER_USEC;
746 break;
747 case NOTE_NSECONDS:
748 multiplier = 1;
749 break;
750 case 0: /* milliseconds (default) */
751 multiplier = NSEC_PER_SEC / 1000;
752 break;
753 default:
754 return (EINVAL);
755 }
756
757 /* transform the slop delta(leeway) in kn_ext[1] if passed to same time scale */
758 if(kn->kn_sfflags & NOTE_LEEWAY){
759 nanoseconds_to_absolutetime((uint64_t)kn->kn_ext[1] * multiplier, &raw);
760 kn->kn_ext[1] = raw;
761 }
762
763 nanoseconds_to_absolutetime((uint64_t)kn->kn_sdata * multiplier, &raw);
764
765 kn->kn_ext[0] = 0;
766 kn->kn_sdata = 0;
767
768 if (kn->kn_sfflags & NOTE_ABSOLUTE) {
769 clock_sec_t seconds;
770 clock_nsec_t nanoseconds;
771 uint64_t now;
772
773 clock_get_calendar_nanotime(&seconds, &nanoseconds);
774 nanoseconds_to_absolutetime((uint64_t)seconds * NSEC_PER_SEC +
775 nanoseconds, &now);
776
777 if (raw < now) {
778 /* time has already passed */
779 kn->kn_ext[0] = 0;
780 } else {
781 raw -= now;
782 clock_absolutetime_interval_to_deadline(raw,
783 &kn->kn_ext[0]);
784 }
785 } else {
786 kn->kn_sdata = raw;
787 }
788
789 return (0);
790 }
791
792 /*
793 * filt_timerupdate - compute the next deadline
794 *
795 * Repeating timers store their interval in kn_sdata. Absolute
796 * timers have already calculated the deadline, stored in ext[0].
797 *
798 * On return, the next deadline (or zero if no deadline is needed)
799 * is stored in kn_ext[0].
800 *
801 * Timer filter lock is held.
802 */
803 static void
804 filt_timerupdate(struct knote *kn)
805 {
806 /* if there's no interval, deadline is just in kn_ext[0] */
807 if (kn->kn_sdata == 0)
808 return;
809
810 /* if timer hasn't fired before, fire in interval nsecs */
811 if (kn->kn_ext[0] == 0) {
812 clock_absolutetime_interval_to_deadline(kn->kn_sdata,
813 &kn->kn_ext[0]);
814 } else {
815 /*
816 * If timer has fired before, schedule the next pop
817 * relative to the last intended deadline.
818 *
819 * We could check for whether the deadline has expired,
820 * but the thread call layer can handle that.
821 */
822 kn->kn_ext[0] += kn->kn_sdata;
823 }
824 }
825
826 /*
827 * filt_timerexpire - the timer callout routine
828 *
829 * Just propagate the timer event into the knote
830 * filter routine (by going through the knote
831 * synchronization point). Pass a hint to
832 * indicate this is a real event, not just a
833 * query from above.
834 */
835 static void
836 filt_timerexpire(void *knx, __unused void *spare)
837 {
838 struct klist timer_list;
839 struct knote *kn = knx;
840
841 filt_timerlock();
842
843 kn->kn_hookid &= ~TIMER_RUNNING;
844
845 /* no "object" for timers, so fake a list */
846 SLIST_INIT(&timer_list);
847 SLIST_INSERT_HEAD(&timer_list, kn, kn_selnext);
848 KNOTE(&timer_list, 1);
849
850 /* if someone is waiting for timer to pop */
851 if (kn->kn_hookid & TIMER_CANCELWAIT) {
852 struct kqueue *kq = kn->kn_kq;
853 waitq_wakeup64_all((struct waitq *)kq->kq_wqs,
854 CAST_EVENT64_T(&kn->kn_hook),
855 THREAD_AWAKENED,
856 WAITQ_ALL_PRIORITIES);
857 }
858
859 filt_timerunlock();
860 }
861
862 /*
863 * Cancel a running timer (or wait for the pop).
864 * Timer filter lock is held.
865 */
866 static void
867 filt_timercancel(struct knote *kn)
868 {
869 struct kqueue *kq = kn->kn_kq;
870 thread_call_t callout = kn->kn_hook;
871 boolean_t cancelled;
872
873 if (kn->kn_hookid & TIMER_RUNNING) {
874 /* cancel the callout if we can */
875 cancelled = thread_call_cancel(callout);
876 if (cancelled) {
877 kn->kn_hookid &= ~TIMER_RUNNING;
878 } else {
879 /* we have to wait for the expire routine. */
880 kn->kn_hookid |= TIMER_CANCELWAIT;
881 waitq_assert_wait64((struct waitq *)kq->kq_wqs,
882 CAST_EVENT64_T(&kn->kn_hook),
883 THREAD_UNINT, TIMEOUT_WAIT_FOREVER);
884 filt_timerunlock();
885 thread_block(THREAD_CONTINUE_NULL);
886 filt_timerlock();
887 assert((kn->kn_hookid & TIMER_RUNNING) == 0);
888 }
889 }
890 }
891
892 /*
893 * Allocate a thread call for the knote's lifetime, and kick off the timer.
894 */
895 static int
896 filt_timerattach(struct knote *kn)
897 {
898 thread_call_t callout;
899 int error;
900
901 callout = thread_call_allocate(filt_timerexpire, kn);
902 if (NULL == callout)
903 return (ENOMEM);
904
905 filt_timerlock();
906 error = filt_timervalidate(kn);
907 if (error != 0) {
908 filt_timerunlock();
909 thread_call_free(callout);
910 return (error);
911 }
912
913 kn->kn_hook = (void*)callout;
914 kn->kn_hookid = 0;
915
916 /* absolute=EV_ONESHOT */
917 if (kn->kn_sfflags & NOTE_ABSOLUTE)
918 kn->kn_flags |= EV_ONESHOT;
919
920 filt_timerupdate(kn);
921 if (kn->kn_ext[0]) {
922 kn->kn_flags |= EV_CLEAR;
923 unsigned int timer_flags = 0;
924 if (kn->kn_sfflags & NOTE_CRITICAL)
925 timer_flags |= THREAD_CALL_DELAY_USER_CRITICAL;
926 else if (kn->kn_sfflags & NOTE_BACKGROUND)
927 timer_flags |= THREAD_CALL_DELAY_USER_BACKGROUND;
928 else
929 timer_flags |= THREAD_CALL_DELAY_USER_NORMAL;
930
931 if (kn->kn_sfflags & NOTE_LEEWAY)
932 timer_flags |= THREAD_CALL_DELAY_LEEWAY;
933
934 thread_call_enter_delayed_with_leeway(callout, NULL,
935 kn->kn_ext[0], kn->kn_ext[1], timer_flags);
936
937 kn->kn_hookid |= TIMER_RUNNING;
938 } else {
939 /* fake immediate */
940 kn->kn_data = 1;
941 }
942
943 filt_timerunlock();
944 return (0);
945 }
946
947 /*
948 * Shut down the timer if it's running, and free the callout.
949 */
950 static void
951 filt_timerdetach(struct knote *kn)
952 {
953 thread_call_t callout;
954
955 filt_timerlock();
956
957 callout = (thread_call_t)kn->kn_hook;
958 filt_timercancel(kn);
959
960 filt_timerunlock();
961
962 thread_call_free(callout);
963 }
964
965
966
967 static int
968 filt_timer(struct knote *kn, long hint)
969 {
970 int result;
971
972 if (hint) {
973 /* real timer pop -- timer lock held by filt_timerexpire */
974 kn->kn_data++;
975
976 if (((kn->kn_hookid & TIMER_CANCELWAIT) == 0) &&
977 ((kn->kn_flags & EV_ONESHOT) == 0)) {
978
979 /* evaluate next time to fire */
980 filt_timerupdate(kn);
981
982 if (kn->kn_ext[0]) {
983 unsigned int timer_flags = 0;
984
985 /* keep the callout and re-arm */
986 if (kn->kn_sfflags & NOTE_CRITICAL)
987 timer_flags |= THREAD_CALL_DELAY_USER_CRITICAL;
988 else if (kn->kn_sfflags & NOTE_BACKGROUND)
989 timer_flags |= THREAD_CALL_DELAY_USER_BACKGROUND;
990 else
991 timer_flags |= THREAD_CALL_DELAY_USER_NORMAL;
992
993 if (kn->kn_sfflags & NOTE_LEEWAY)
994 timer_flags |= THREAD_CALL_DELAY_LEEWAY;
995
996 thread_call_enter_delayed_with_leeway(kn->kn_hook, NULL,
997 kn->kn_ext[0], kn->kn_ext[1], timer_flags);
998
999 kn->kn_hookid |= TIMER_RUNNING;
1000 }
1001 }
1002
1003 return (1);
1004 }
1005
1006 /* user-query */
1007 filt_timerlock();
1008
1009 result = (kn->kn_data != 0);
1010
1011 filt_timerunlock();
1012
1013 return (result);
1014 }
1015
1016
1017 /*
1018 * filt_timertouch - update knote with new user input
1019 *
1020 * Cancel and restart the timer based on new user data. When
1021 * the user picks up a knote, clear the count of how many timer
1022 * pops have gone off (in kn_data).
1023 */
1024 static void
1025 filt_timertouch(struct knote *kn, struct kevent_internal_s *kev, long type)
1026 {
1027 int error;
1028 filt_timerlock();
1029
1030 switch (type) {
1031 case EVENT_REGISTER:
1032 /* cancel current call */
1033 filt_timercancel(kn);
1034
1035 /* recalculate deadline */
1036 kn->kn_sdata = kev->data;
1037 kn->kn_sfflags = kev->fflags;
1038 kn->kn_ext[0] = kev->ext[0];
1039 kn->kn_ext[1] = kev->ext[1];
1040
1041 error = filt_timervalidate(kn);
1042 if (error) {
1043 /* no way to report error, so mark it in the knote */
1044 kn->kn_flags |= EV_ERROR;
1045 kn->kn_data = error;
1046 break;
1047 }
1048
1049 /* start timer if necessary */
1050 filt_timerupdate(kn);
1051
1052 if (kn->kn_ext[0]) {
1053 unsigned int timer_flags = 0;
1054 if (kn->kn_sfflags & NOTE_CRITICAL)
1055 timer_flags |= THREAD_CALL_DELAY_USER_CRITICAL;
1056 else if (kn->kn_sfflags & NOTE_BACKGROUND)
1057 timer_flags |= THREAD_CALL_DELAY_USER_BACKGROUND;
1058 else
1059 timer_flags |= THREAD_CALL_DELAY_USER_NORMAL;
1060
1061 if (kn->kn_sfflags & NOTE_LEEWAY)
1062 timer_flags |= THREAD_CALL_DELAY_LEEWAY;
1063
1064 thread_call_enter_delayed_with_leeway(kn->kn_hook, NULL,
1065 kn->kn_ext[0], kn->kn_ext[1], timer_flags);
1066
1067 kn->kn_hookid |= TIMER_RUNNING;
1068 } else {
1069 /* pretend the timer has fired */
1070 kn->kn_data = 1;
1071 }
1072
1073 break;
1074
1075 case EVENT_PROCESS:
1076 /* reset the timer pop count in kn_data */
1077 *kev = kn->kn_kevent;
1078 kev->ext[0] = 0;
1079 kn->kn_data = 0;
1080 if (kn->kn_flags & EV_CLEAR)
1081 kn->kn_fflags = 0;
1082 break;
1083 default:
1084 panic("%s: - invalid type (%ld)", __func__, type);
1085 break;
1086 }
1087
1088 filt_timerunlock();
1089 }
1090
1091 static void
1092 filt_timerlock(void)
1093 {
1094 lck_mtx_lock(&_filt_timerlock);
1095 }
1096
1097 static void
1098 filt_timerunlock(void)
1099 {
1100 lck_mtx_unlock(&_filt_timerlock);
1101 }
1102
1103 static int
1104 filt_userattach(struct knote *kn)
1105 {
1106 /* EVFILT_USER knotes are not attached to anything in the kernel */
1107 kn->kn_hook = NULL;
1108 if (kn->kn_fflags & NOTE_TRIGGER) {
1109 kn->kn_hookid = 1;
1110 } else {
1111 kn->kn_hookid = 0;
1112 }
1113 return (0);
1114 }
1115
1116 static void
1117 filt_userdetach(__unused struct knote *kn)
1118 {
1119 /* EVFILT_USER knotes are not attached to anything in the kernel */
1120 }
1121
1122 static int
1123 filt_user(struct knote *kn, __unused long hint)
1124 {
1125 return (kn->kn_hookid);
1126 }
1127
1128 static void
1129 filt_usertouch(struct knote *kn, struct kevent_internal_s *kev, long type)
1130 {
1131 uint32_t ffctrl;
1132 switch (type) {
1133 case EVENT_REGISTER:
1134 if (kev->fflags & NOTE_TRIGGER) {
1135 kn->kn_hookid = 1;
1136 }
1137
1138 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
1139 kev->fflags &= NOTE_FFLAGSMASK;
1140 switch (ffctrl) {
1141 case NOTE_FFNOP:
1142 break;
1143 case NOTE_FFAND:
1144 OSBitAndAtomic(kev->fflags, &kn->kn_sfflags);
1145 break;
1146 case NOTE_FFOR:
1147 OSBitOrAtomic(kev->fflags, &kn->kn_sfflags);
1148 break;
1149 case NOTE_FFCOPY:
1150 kn->kn_sfflags = kev->fflags;
1151 break;
1152 }
1153 kn->kn_sdata = kev->data;
1154 break;
1155 case EVENT_PROCESS:
1156 *kev = kn->kn_kevent;
1157 kev->fflags = (volatile UInt32)kn->kn_sfflags;
1158 kev->data = kn->kn_sdata;
1159 if (kn->kn_flags & EV_CLEAR) {
1160 kn->kn_hookid = 0;
1161 kn->kn_data = 0;
1162 kn->kn_fflags = 0;
1163 }
1164 break;
1165 default:
1166 panic("%s: - invalid type (%ld)", __func__, type);
1167 break;
1168 }
1169 }
1170
1171 /*
1172 * JMM - placeholder for not-yet-implemented filters
1173 */
1174 static int
1175 filt_badattach(__unused struct knote *kn)
1176 {
1177 return (ENOTSUP);
1178 }
1179
1180 struct kqueue *
1181 kqueue_alloc(struct proc *p)
1182 {
1183 struct filedesc *fdp = p->p_fd;
1184 struct kqueue *kq;
1185
1186 MALLOC_ZONE(kq, struct kqueue *, sizeof (struct kqueue), M_KQUEUE,
1187 M_WAITOK);
1188 if (kq != NULL) {
1189 struct waitq_set *wqs;
1190
1191 wqs = waitq_set_alloc(SYNC_POLICY_FIFO | SYNC_POLICY_PREPOST | SYNC_POLICY_DISABLE_IRQ);
1192 if (wqs != NULL) {
1193 bzero(kq, sizeof (struct kqueue));
1194 lck_spin_init(&kq->kq_lock, kq_lck_grp, kq_lck_attr);
1195 TAILQ_INIT(&kq->kq_head);
1196 kq->kq_wqs = wqs;
1197 kq->kq_p = p;
1198 } else {
1199 FREE_ZONE(kq, sizeof (struct kqueue), M_KQUEUE);
1200 kq = NULL;
1201 }
1202 }
1203
1204 if (fdp->fd_knlistsize < 0) {
1205 proc_fdlock(p);
1206 if (fdp->fd_knlistsize < 0)
1207 fdp->fd_knlistsize = 0; /* this process has had a kq */
1208 proc_fdunlock(p);
1209 }
1210
1211 return (kq);
1212 }
1213
1214 /*
1215 * kqueue_dealloc - detach all knotes from a kqueue and free it
1216 *
1217 * We walk each list looking for knotes referencing this
1218 * this kqueue. If we find one, we try to drop it. But
1219 * if we fail to get a drop reference, that will wait
1220 * until it is dropped. So, we can just restart again
1221 * safe in the assumption that the list will eventually
1222 * not contain any more references to this kqueue (either
1223 * we dropped them all, or someone else did).
1224 *
1225 * Assumes no new events are being added to the kqueue.
1226 * Nothing locked on entry or exit.
1227 */
1228 void
1229 kqueue_dealloc(struct kqueue *kq)
1230 {
1231 struct proc *p;
1232 struct filedesc *fdp;
1233 struct knote *kn;
1234 int i;
1235
1236 if (kq == NULL)
1237 return;
1238
1239 p = kq->kq_p;
1240 fdp = p->p_fd;
1241
1242 proc_fdlock(p);
1243 for (i = 0; i < fdp->fd_knlistsize; i++) {
1244 kn = SLIST_FIRST(&fdp->fd_knlist[i]);
1245 while (kn != NULL) {
1246 if (kq == kn->kn_kq) {
1247 kqlock(kq);
1248 proc_fdunlock(p);
1249 /* drop it ourselves or wait */
1250 if (kqlock2knotedrop(kq, kn)) {
1251 kn->kn_fop->f_detach(kn);
1252 knote_drop(kn, p);
1253 }
1254 proc_fdlock(p);
1255 /* start over at beginning of list */
1256 kn = SLIST_FIRST(&fdp->fd_knlist[i]);
1257 continue;
1258 }
1259 kn = SLIST_NEXT(kn, kn_link);
1260 }
1261 }
1262 if (fdp->fd_knhashmask != 0) {
1263 for (i = 0; i < (int)fdp->fd_knhashmask + 1; i++) {
1264 kn = SLIST_FIRST(&fdp->fd_knhash[i]);
1265 while (kn != NULL) {
1266 if (kq == kn->kn_kq) {
1267 kqlock(kq);
1268 proc_fdunlock(p);
1269 /* drop it ourselves or wait */
1270 if (kqlock2knotedrop(kq, kn)) {
1271 kn->kn_fop->f_detach(kn);
1272 knote_drop(kn, p);
1273 }
1274 proc_fdlock(p);
1275 /* start over at beginning of list */
1276 kn = SLIST_FIRST(&fdp->fd_knhash[i]);
1277 continue;
1278 }
1279 kn = SLIST_NEXT(kn, kn_link);
1280 }
1281 }
1282 }
1283 proc_fdunlock(p);
1284
1285 /*
1286 * waitq_set_free() clears all preposts and also remove the KQ's
1287 * waitq set from any select sets to which it may belong.
1288 */
1289 waitq_set_free(kq->kq_wqs);
1290 kq->kq_wqs = NULL;
1291 lck_spin_destroy(&kq->kq_lock, kq_lck_grp);
1292 FREE_ZONE(kq, sizeof (struct kqueue), M_KQUEUE);
1293 }
1294
1295 int
1296 kqueue_body(struct proc *p, fp_allocfn_t fp_zalloc, void *cra, int32_t *retval)
1297 {
1298 struct kqueue *kq;
1299 struct fileproc *fp;
1300 int fd, error;
1301
1302 error = falloc_withalloc(p,
1303 &fp, &fd, vfs_context_current(), fp_zalloc, cra);
1304 if (error) {
1305 return (error);
1306 }
1307
1308 kq = kqueue_alloc(p);
1309 if (kq == NULL) {
1310 fp_free(p, fd, fp);
1311 return (ENOMEM);
1312 }
1313
1314 fp->f_flag = FREAD | FWRITE;
1315 fp->f_ops = &kqueueops;
1316 fp->f_data = kq;
1317
1318 proc_fdlock(p);
1319 *fdflags(p, fd) |= UF_EXCLOSE;
1320 procfdtbl_releasefd(p, fd, NULL);
1321 fp_drop(p, fd, fp, 1);
1322 proc_fdunlock(p);
1323
1324 *retval = fd;
1325 return (error);
1326 }
1327
1328 int
1329 kqueue(struct proc *p, __unused struct kqueue_args *uap, int32_t *retval)
1330 {
1331 return (kqueue_body(p, fileproc_alloc_init, NULL, retval));
1332 }
1333
1334 static int
1335 kevent_copyin(user_addr_t *addrp, struct kevent_internal_s *kevp, struct proc *p,
1336 unsigned int flags)
1337 {
1338 int advance;
1339 int error;
1340
1341 if (flags & KEVENT_FLAG_LEGACY32) {
1342 bzero(kevp, sizeof (*kevp));
1343
1344 if (IS_64BIT_PROCESS(p)) {
1345 struct user64_kevent kev64;
1346
1347 advance = sizeof (kev64);
1348 error = copyin(*addrp, (caddr_t)&kev64, advance);
1349 if (error)
1350 return (error);
1351 kevp->ident = kev64.ident;
1352 kevp->filter = kev64.filter;
1353 kevp->flags = kev64.flags;
1354 kevp->udata = kev64.udata;
1355 kevp->fflags = kev64.fflags;
1356 kevp->data = kev64.data;
1357 } else {
1358 struct user32_kevent kev32;
1359
1360 advance = sizeof (kev32);
1361 error = copyin(*addrp, (caddr_t)&kev32, advance);
1362 if (error)
1363 return (error);
1364 kevp->ident = (uintptr_t)kev32.ident;
1365 kevp->filter = kev32.filter;
1366 kevp->flags = kev32.flags;
1367 kevp->udata = CAST_USER_ADDR_T(kev32.udata);
1368 kevp->fflags = kev32.fflags;
1369 kevp->data = (intptr_t)kev32.data;
1370 }
1371 } else if (flags & KEVENT_FLAG_LEGACY64) {
1372 struct kevent64_s kev64;
1373
1374 bzero(kevp, sizeof (*kevp));
1375
1376 advance = sizeof (struct kevent64_s);
1377 error = copyin(*addrp, (caddr_t)&kev64, advance);
1378 if (error)
1379 return(error);
1380 kevp->ident = kev64.ident;
1381 kevp->filter = kev64.filter;
1382 kevp->flags = kev64.flags;
1383 kevp->udata = kev64.udata;
1384 kevp->fflags = kev64.fflags;
1385 kevp->data = kev64.data;
1386 kevp->ext[0] = kev64.ext[0];
1387 kevp->ext[1] = kev64.ext[1];
1388
1389 } else {
1390 struct kevent_qos_s kevqos;
1391
1392 bzero(kevp, sizeof (*kevp));
1393
1394 advance = sizeof (struct kevent_qos_s);
1395 error = copyin(*addrp, (caddr_t)&kevqos, advance);
1396 if (error)
1397 return error;
1398 kevp->ident = kevqos.ident;
1399 kevp->filter = kevqos.filter;
1400 kevp->flags = kevqos.flags;
1401 kevp->udata = kevqos.udata;
1402 kevp->fflags = kevqos.fflags;
1403 kevp->data = kevqos.data;
1404 kevp->ext[0] = kevqos.ext[0];
1405 kevp->ext[1] = kevqos.ext[1];
1406 }
1407 if (!error)
1408 *addrp += advance;
1409 return (error);
1410 }
1411
1412 static int
1413 kevent_copyout(struct kevent_internal_s *kevp, user_addr_t *addrp, struct proc *p,
1414 unsigned int flags)
1415 {
1416 user_addr_t addr = *addrp;
1417 int advance;
1418 int error;
1419
1420 if (flags & KEVENT_FLAG_LEGACY32) {
1421 assert((flags & KEVENT_FLAG_STACK_EVENTS) == 0);
1422
1423 if (IS_64BIT_PROCESS(p)) {
1424 struct user64_kevent kev64;
1425
1426 /*
1427 * deal with the special case of a user-supplied
1428 * value of (uintptr_t)-1.
1429 */
1430 kev64.ident = (kevp->ident == (uintptr_t)-1) ?
1431 (uint64_t)-1LL : (uint64_t)kevp->ident;
1432
1433 kev64.filter = kevp->filter;
1434 kev64.flags = kevp->flags;
1435 kev64.fflags = kevp->fflags;
1436 kev64.data = (int64_t) kevp->data;
1437 kev64.udata = kevp->udata;
1438 advance = sizeof (kev64);
1439 error = copyout((caddr_t)&kev64, addr, advance);
1440 } else {
1441 struct user32_kevent kev32;
1442
1443 kev32.ident = (uint32_t)kevp->ident;
1444 kev32.filter = kevp->filter;
1445 kev32.flags = kevp->flags;
1446 kev32.fflags = kevp->fflags;
1447 kev32.data = (int32_t)kevp->data;
1448 kev32.udata = kevp->udata;
1449 advance = sizeof (kev32);
1450 error = copyout((caddr_t)&kev32, addr, advance);
1451 }
1452 } else if (flags & KEVENT_FLAG_LEGACY64) {
1453 struct kevent64_s kev64;
1454
1455 advance = sizeof (struct kevent64_s);
1456 if (flags & KEVENT_FLAG_STACK_EVENTS) {
1457 addr -= advance;
1458 }
1459 kev64.ident = kevp->ident;
1460 kev64.filter = kevp->filter;
1461 kev64.flags = kevp->flags;
1462 kev64.fflags = kevp->fflags;
1463 kev64.data = (int64_t) kevp->data;
1464 kev64.udata = kevp->udata;
1465 kev64.ext[0] = kevp->ext[0];
1466 kev64.ext[1] = kevp->ext[1];
1467 error = copyout((caddr_t)&kev64, addr, advance);
1468 } else {
1469 struct kevent_qos_s kevqos;
1470
1471 bzero(&kevqos, sizeof (struct kevent_qos_s));
1472 advance = sizeof (struct kevent_qos_s);
1473 if (flags & KEVENT_FLAG_STACK_EVENTS) {
1474 addr -= advance;
1475 }
1476 kevqos.ident = kevp->ident;
1477 kevqos.filter = kevp->filter;
1478 kevqos.flags = kevp->flags;
1479 kevqos.fflags = kevp->fflags;
1480 kevqos.data = (int64_t) kevp->data;
1481 kevqos.udata = kevp->udata;
1482 kevqos.ext[0] = kevp->ext[0];
1483 kevqos.ext[1] = kevp->ext[1];
1484 error = copyout((caddr_t)&kevqos, addr, advance);
1485 }
1486 if (!error) {
1487 if (flags & KEVENT_FLAG_STACK_EVENTS)
1488 *addrp = addr;
1489 else
1490 *addrp = addr + advance;
1491 }
1492 return (error);
1493 }
1494
1495 /*
1496 * kevent_continue - continue a kevent syscall after blocking
1497 *
1498 * assume we inherit a use count on the kq fileglob.
1499 */
1500
1501 static void
1502 kevent_continue(__unused struct kqueue *kq, void *data, int error)
1503 {
1504 struct _kevent *cont_args;
1505 struct fileproc *fp;
1506 int32_t *retval;
1507 int noutputs;
1508 int fd;
1509 struct proc *p = current_proc();
1510
1511 cont_args = (struct _kevent *)data;
1512 noutputs = cont_args->eventout;
1513 retval = cont_args->retval;
1514 fd = cont_args->fd;
1515 fp = cont_args->fp;
1516
1517 if (fp != NULL)
1518 fp_drop(p, fd, fp, 0);
1519
1520 /* don't restart after signals... */
1521 if (error == ERESTART)
1522 error = EINTR;
1523 else if (error == EWOULDBLOCK)
1524 error = 0;
1525 if (error == 0)
1526 *retval = noutputs;
1527 unix_syscall_return(error);
1528 }
1529
1530 /*
1531 * kevent - [syscall] register and wait for kernel events
1532 *
1533 */
1534 int
1535 kevent(struct proc *p, struct kevent_args *uap, int32_t *retval)
1536 {
1537 unsigned int flags = KEVENT_FLAG_LEGACY32;
1538
1539 return kevent_internal(p,
1540 uap->fd,
1541 uap->changelist, uap->nchanges,
1542 uap->eventlist, uap->nevents,
1543 0ULL, 0ULL,
1544 flags,
1545 uap->timeout,
1546 kevent_continue,
1547 retval);
1548 }
1549
1550 int
1551 kevent64(struct proc *p, struct kevent64_args *uap, int32_t *retval)
1552 {
1553 unsigned int flags;
1554
1555 /* restrict to user flags and set legacy64 */
1556 flags = uap->flags & KEVENT_FLAG_USER;
1557 flags |= KEVENT_FLAG_LEGACY64;
1558
1559 return kevent_internal(p,
1560 uap->fd,
1561 uap->changelist, uap->nchanges,
1562 uap->eventlist, uap->nevents,
1563 0ULL, 0ULL,
1564 flags,
1565 uap->timeout,
1566 kevent_continue,
1567 retval);
1568 }
1569
1570 int
1571 kevent_qos(struct proc *p, struct kevent_qos_args *uap, int32_t *retval)
1572 {
1573 user_size_t usize = 0;
1574 user_size_t ssize;
1575 int error;
1576
1577 /* restrict to user flags */
1578 uap->flags &= KEVENT_FLAG_USER;
1579
1580 if (uap->data_available) {
1581 if (!IS_64BIT_PROCESS(p)) {
1582 uint32_t csize;
1583
1584 error = copyin(uap->data_available, (caddr_t)&csize, sizeof(csize));
1585 if (error)
1586 return error;
1587 usize = csize;
1588 } else {
1589 uint64_t csize;
1590 error = copyin(uap->data_available, (caddr_t)&csize, sizeof(csize));
1591 if (error)
1592 return error;
1593 usize = csize;
1594 }
1595 }
1596 ssize = usize;
1597
1598 error = kevent_internal(p,
1599 uap->fd,
1600 uap->changelist, uap->nchanges,
1601 uap->eventlist, uap->nevents,
1602 uap->data_out, &usize,
1603 uap->flags,
1604 0ULL,
1605 kevent_continue,
1606 retval);
1607
1608 if (error == 0 && uap->data_available && usize != ssize) {
1609 if (!IS_64BIT_PROCESS(p)) {
1610 uint32_t csize = (uint32_t)usize;
1611
1612 error = copyout((caddr_t)&csize, uap->data_available, sizeof(csize));
1613 } else {
1614 error = copyout((caddr_t)&usize, uap->data_available, sizeof(usize));
1615 }
1616 }
1617 return error;
1618 }
1619
1620 int
1621 kevent_qos_internal(struct proc *p, int fd,
1622 user_addr_t changelist, int nchanges,
1623 user_addr_t eventlist, int nevents,
1624 user_addr_t data_out, user_size_t *data_available,
1625 unsigned int flags,
1626 int32_t *retval)
1627 {
1628 return kevent_internal(p,
1629 fd,
1630 changelist, nchanges,
1631 eventlist, nevents,
1632 data_out, data_available,
1633 flags,
1634 0ULL,
1635 NULL,
1636 retval);
1637 }
1638
1639 static int
1640 kevent_internal(struct proc *p,
1641 int fd,
1642 user_addr_t changelist, int nchanges,
1643 user_addr_t ueventlist, int nevents,
1644 user_addr_t data_out, user_size_t *data_available,
1645 unsigned int flags,
1646 user_addr_t utimeout,
1647 kqueue_continue_t continuation,
1648 int32_t *retval)
1649 {
1650 struct _kevent *cont_args;
1651 uthread_t ut;
1652 struct kqueue *kq;
1653 struct fileproc *fp = NULL;
1654 struct kevent_internal_s kev;
1655 int error = 0, noutputs;
1656 struct timeval atv;
1657
1658 #if 1
1659 /* temporarily ignore these fields */
1660 (void)data_out;
1661 (void)data_available;
1662 #endif
1663
1664 /* prepare to deal with stack-wise allocation of out events */
1665 if (flags & KEVENT_FLAG_STACK_EVENTS) {
1666 int scale = ((flags & KEVENT_FLAG_LEGACY32) ?
1667 (IS_64BIT_PROCESS(p) ? sizeof(struct user64_kevent) :
1668 sizeof(struct user32_kevent)) :
1669 ((flags & KEVENT_FLAG_LEGACY64) ? sizeof(struct kevent64_s) :
1670 sizeof(struct kevent_qos_s)));
1671 ueventlist += nevents * scale;
1672 }
1673
1674 /* convert timeout to absolute - if we have one (and not immediate) */
1675 if (flags & KEVENT_FLAG_IMMEDIATE) {
1676 getmicrouptime(&atv);
1677 } else if (utimeout != USER_ADDR_NULL) {
1678 struct timeval rtv;
1679 if (IS_64BIT_PROCESS(p)) {
1680 struct user64_timespec ts;
1681 error = copyin(utimeout, &ts, sizeof(ts));
1682 if ((ts.tv_sec & 0xFFFFFFFF00000000ull) != 0)
1683 error = EINVAL;
1684 else
1685 TIMESPEC_TO_TIMEVAL(&rtv, &ts);
1686 } else {
1687 struct user32_timespec ts;
1688 error = copyin(utimeout, &ts, sizeof(ts));
1689 TIMESPEC_TO_TIMEVAL(&rtv, &ts);
1690 }
1691 if (error)
1692 return (error);
1693 if (itimerfix(&rtv))
1694 return (EINVAL);
1695 getmicrouptime(&atv);
1696 timevaladd(&atv, &rtv);
1697 } else {
1698 /* wait forever value */
1699 atv.tv_sec = 0;
1700 atv.tv_usec = 0;
1701 }
1702
1703 if (flags & KEVENT_FLAG_WORKQ) {
1704 /*
1705 * use the private kq associated with the proc workq.
1706 * Just being a thread within the process (and not
1707 * being the exit/exec thread) is enough to hold a
1708 * reference on this special kq.
1709 */
1710 kq = p->p_wqkqueue;
1711 if (kq == NULL) {
1712 struct kqueue *alloc_kq = kqueue_alloc(p);
1713 if (alloc_kq == NULL)
1714 return ENOMEM;
1715
1716 proc_fdlock(p);
1717 if (p->p_wqkqueue == NULL) {
1718 /*
1719 * The kq is marked as special -
1720 * with unique interactions with
1721 * the workq for this process.
1722 */
1723 alloc_kq->kq_state |= KQ_WORKQ;
1724 kq = p->p_wqkqueue = alloc_kq;
1725 proc_fdunlock(p);
1726 } else {
1727 proc_fdunlock(p);
1728 kq = p->p_wqkqueue;
1729 kqueue_dealloc(alloc_kq);
1730 }
1731 }
1732 } else {
1733 /* get a usecount for the kq itself */
1734 if ((error = fp_getfkq(p, fd, &fp, &kq)) != 0)
1735 return (error);
1736 }
1737
1738 /* each kq should only be used for events of one type */
1739 kqlock(kq);
1740 if (kq->kq_state & (KQ_KEV32 | KQ_KEV64 | KQ_KEV_QOS)) {
1741 if (flags & KEVENT_FLAG_LEGACY32) {
1742 if ((kq->kq_state & KQ_KEV32) == 0) {
1743 error = EINVAL;
1744 kqunlock(kq);
1745 goto errorout;
1746 }
1747 } else if (kq->kq_state & KQ_KEV32) {
1748 error = EINVAL;
1749 kqunlock(kq);
1750 goto errorout;
1751 }
1752 } else if (flags & KEVENT_FLAG_LEGACY32) {
1753 kq->kq_state |= KQ_KEV32;
1754 } else {
1755 /* JMM - set KQ_KEVQOS when we are ready for exclusive */
1756 kq->kq_state |= KQ_KEV64;
1757 }
1758 kqunlock(kq);
1759
1760 /* register all the change requests the user provided... */
1761 noutputs = 0;
1762 while (nchanges > 0 && error == 0) {
1763 error = kevent_copyin(&changelist, &kev, p, flags);
1764 if (error)
1765 break;
1766
1767 kev.flags &= ~EV_SYSFLAGS;
1768 error = kevent_register(kq, &kev, p);
1769 if ((error || (kev.flags & EV_RECEIPT)) && nevents > 0) {
1770 kev.flags = EV_ERROR;
1771 kev.data = error;
1772 error = kevent_copyout(&kev, &ueventlist, p, flags);
1773 if (error == 0) {
1774 nevents--;
1775 noutputs++;
1776 }
1777 }
1778 nchanges--;
1779 }
1780
1781 /* short-circuit the scan if we only want error events */
1782 if (flags & KEVENT_FLAG_ERROR_EVENTS)
1783 nevents = 0;
1784
1785 if (nevents > 0 && noutputs == 0 && error == 0) {
1786
1787 /* store the continuation/completion data in the uthread */
1788 ut = (uthread_t)get_bsdthread_info(current_thread());
1789 cont_args = &ut->uu_kevent.ss_kevent;
1790 cont_args->fp = fp;
1791 cont_args->fd = fd;
1792 cont_args->retval = retval;
1793 cont_args->eventlist = ueventlist;
1794 cont_args->eventcount = nevents;
1795 cont_args->eventout = noutputs;
1796 cont_args->eventflags = flags;
1797
1798 error = kqueue_scan(kq, kevent_callback,
1799 continuation, cont_args,
1800 &atv, p);
1801
1802 noutputs = cont_args->eventout;
1803 }
1804
1805 /* don't restart after signals... */
1806 if (error == ERESTART)
1807 error = EINTR;
1808 else if (error == EWOULDBLOCK)
1809 error = 0;
1810 if (error == 0)
1811 *retval = noutputs;
1812 errorout:
1813 if (fp != NULL)
1814 fp_drop(p, fd, fp, 0);
1815 return (error);
1816 }
1817
1818
1819 /*
1820 * kevent_callback - callback for each individual event
1821 *
1822 * called with nothing locked
1823 * caller holds a reference on the kqueue
1824 */
1825 static int
1826 kevent_callback(__unused struct kqueue *kq, struct kevent_internal_s *kevp,
1827 void *data)
1828 {
1829 struct _kevent *cont_args;
1830 int error;
1831
1832 cont_args = (struct _kevent *)data;
1833 assert(cont_args->eventout < cont_args->eventcount);
1834
1835 /*
1836 * Copy out the appropriate amount of event data for this user.
1837 */
1838 error = kevent_copyout(kevp, &cont_args->eventlist, current_proc(),
1839 cont_args->eventflags);
1840
1841 /*
1842 * If there isn't space for additional events, return
1843 * a harmless error to stop the processing here
1844 */
1845 if (error == 0 && ++cont_args->eventout == cont_args->eventcount)
1846 error = EWOULDBLOCK;
1847 return (error);
1848 }
1849
1850 /*
1851 * kevent_description - format a description of a kevent for diagnostic output
1852 *
1853 * called with a 256-byte string buffer
1854 */
1855
1856 char *
1857 kevent_description(struct kevent_internal_s *kevp, char *s, size_t n)
1858 {
1859 snprintf(s, n,
1860 "kevent="
1861 "{.ident=%#llx, .filter=%d, .flags=%#x, .udata=%#llx, .fflags=%#x, .data=%#llx, .ext[0]=%#llx, .ext[1]=%#llx}",
1862 kevp->ident,
1863 kevp->filter,
1864 kevp->flags,
1865 kevp->udata,
1866 kevp->fflags,
1867 kevp->data,
1868 kevp->ext[0],
1869 kevp->ext[1] );
1870
1871 return (s);
1872 }
1873
1874 /*
1875 * kevent_register - add a new event to a kqueue
1876 *
1877 * Creates a mapping between the event source and
1878 * the kqueue via a knote data structure.
1879 *
1880 * Because many/most the event sources are file
1881 * descriptor related, the knote is linked off
1882 * the filedescriptor table for quick access.
1883 *
1884 * called with nothing locked
1885 * caller holds a reference on the kqueue
1886 */
1887
1888 int
1889 kevent_register(struct kqueue *kq, struct kevent_internal_s *kev,
1890 __unused struct proc *ctxp)
1891 {
1892 struct proc *p = kq->kq_p;
1893 struct filedesc *fdp = p->p_fd;
1894 struct filterops *fops;
1895 struct fileproc *fp = NULL;
1896 struct knote *kn = NULL;
1897 struct klist *list;
1898 int error = 0;
1899
1900 if (kev->filter < 0) {
1901 if (kev->filter + EVFILT_SYSCOUNT < 0)
1902 return (EINVAL);
1903 fops = sysfilt_ops[~kev->filter]; /* to 0-base index */
1904 } else {
1905 return (EINVAL);
1906 }
1907
1908 restart:
1909 /* this iocount needs to be dropped if it is not registered */
1910 list = NULL;
1911 proc_fdlock(p);
1912
1913 /*
1914 * determine where to look for the knote
1915 */
1916 if (fops->f_isfd) {
1917 if ((error = fp_lookup(p, kev->ident, &fp, 1)) != 0) {
1918 proc_fdunlock(p);
1919 return (error);
1920 }
1921 /* fd-based knotes are linked off the fd table */
1922 if (kev->ident < (u_int)fdp->fd_knlistsize) {
1923 list = &fdp->fd_knlist[kev->ident];
1924 }
1925 } else if (fdp->fd_knhashmask != 0) {
1926 /* hash non-fd knotes here too */
1927 list = &fdp->fd_knhash[KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
1928 }
1929
1930 /*
1931 * scan the selected list looking for a match
1932 */
1933 if (list != NULL) {
1934 SLIST_FOREACH(kn, list, kn_link) {
1935 if (kq == kn->kn_kq &&
1936 kev->ident == kn->kn_id &&
1937 kev->filter == kn->kn_filter) {
1938 if (kev->flags & EV_UDATA_SPECIFIC) {
1939 if ((kn->kn_flags & EV_UDATA_SPECIFIC) &&
1940 kev->udata == kn->kn_udata) {
1941 break; /* matching udata-specific knote */
1942 }
1943 } else if ((kn->kn_flags & EV_UDATA_SPECIFIC) == 0) {
1944 break; /* matching non-udata-specific knote */
1945 }
1946 }
1947 }
1948 }
1949
1950 /*
1951 * kn now contains the matching knote, or NULL if no match
1952 */
1953 if (kn == NULL) {
1954 if ((kev->flags & (EV_ADD|EV_DELETE)) == EV_ADD) {
1955 kn = knote_alloc();
1956 if (kn == NULL) {
1957 proc_fdunlock(p);
1958 error = ENOMEM;
1959 goto done;
1960 }
1961 kn->kn_fp = fp;
1962 kn->kn_kq = kq;
1963 kn->kn_tq = &kq->kq_head;
1964 kn->kn_fop = fops;
1965 kn->kn_sfflags = kev->fflags;
1966 kn->kn_sdata = kev->data;
1967 kev->fflags = 0;
1968 kev->data = 0;
1969 kn->kn_kevent = *kev;
1970 kn->kn_inuse = 1; /* for f_attach() */
1971 kn->kn_status = KN_ATTACHING;
1972
1973 /* before anyone can find it */
1974 if (kev->flags & EV_DISABLE)
1975 kn->kn_status |= KN_DISABLED;
1976
1977 error = knote_fdpattach(kn, fdp, p);
1978 proc_fdunlock(p);
1979
1980 if (error) {
1981 knote_free(kn);
1982 goto done;
1983 }
1984
1985 /*
1986 * apply reference count to knote structure, and
1987 * do not release it at the end of this routine.
1988 */
1989 fp = NULL;
1990
1991 error = fops->f_attach(kn);
1992
1993 kqlock(kq);
1994
1995 if (error != 0) {
1996 /*
1997 * Failed to attach correctly, so drop.
1998 * All other possible users/droppers
1999 * have deferred to us.
2000 */
2001 kn->kn_status |= KN_DROPPING;
2002 kqunlock(kq);
2003 knote_drop(kn, p);
2004 goto done;
2005 } else if (kn->kn_status & KN_DROPPING) {
2006 /*
2007 * Attach succeeded, but someone else
2008 * deferred their drop - now we have
2009 * to do it for them (after detaching).
2010 */
2011 kqunlock(kq);
2012 kn->kn_fop->f_detach(kn);
2013 knote_drop(kn, p);
2014 goto done;
2015 }
2016 kn->kn_status &= ~KN_ATTACHING;
2017 kqunlock(kq);
2018 } else {
2019 proc_fdunlock(p);
2020 error = ENOENT;
2021 goto done;
2022 }
2023 } else {
2024 /* existing knote - get kqueue lock */
2025 kqlock(kq);
2026 proc_fdunlock(p);
2027
2028 if (kev->flags & EV_DELETE) {
2029 if ((kev->flags & EV_ENABLE) == 0 &&
2030 (kev->flags & EV_DISPATCH2) == EV_DISPATCH2 &&
2031 (kn->kn_status & KN_DISABLED) == KN_DISABLED) {
2032 /* mark for deferred drop */
2033 kn->kn_status |= KN_DEFERDROP;
2034 kqunlock(kq);
2035 error = EINPROGRESS;
2036 } else {
2037 knote_dequeue(kn);
2038 kn->kn_status |= KN_DISABLED;
2039 if (kqlock2knotedrop(kq, kn)) {
2040 kn->kn_fop->f_detach(kn);
2041 knote_drop(kn, p);
2042 } else {
2043 /* pretend we didn't find it */
2044 error = ENOENT;
2045 }
2046 }
2047 goto done;
2048 }
2049
2050 /* update status flags for existing knote */
2051 if (kev->flags & EV_DISABLE) {
2052 knote_dequeue(kn);
2053 kn->kn_status |= KN_DISABLED;
2054
2055 } else if ((kev->flags & EV_ENABLE) &&
2056 (kn->kn_status & KN_DISABLED)) {
2057 kn->kn_status &= ~KN_DISABLED;
2058
2059 /* handle deferred drop */
2060 if (kn->kn_status & KN_DEFERDROP) {
2061 kn->kn_status &= ~KN_DEFERDROP;
2062 kn->kn_flags |= (EV_DELETE | EV_ONESHOT);
2063 knote_activate(kn, 0);
2064 kqunlock(kq);
2065 goto done;
2066 }
2067
2068 if (kn->kn_status & KN_ACTIVE) {
2069 /* force re-activate if previously active */
2070 knote_activate(kn, 1);
2071 }
2072 }
2073
2074 /*
2075 * The user may change some filter values after the
2076 * initial EV_ADD, but doing so will not reset any
2077 * filter which have already been triggered.
2078 */
2079 kn->kn_kevent.udata = kev->udata;
2080 if (fops->f_isfd || fops->f_touch == NULL) {
2081 kn->kn_sfflags = kev->fflags;
2082 kn->kn_sdata = kev->data;
2083 }
2084
2085 /*
2086 * If somebody is in the middle of dropping this
2087 * knote - go find/insert a new one. But we have
2088 * wait for this one to go away first. Attaches
2089 * running in parallel may also drop/modify the
2090 * knote. Wait for those to complete as well and
2091 * then start over if we encounter one.
2092 */
2093 if (!kqlock2knoteusewait(kq, kn)) {
2094 /* kqueue, proc_fdlock both unlocked */
2095 goto restart;
2096 }
2097
2098 /*
2099 * Call touch routine to notify filter of changes
2100 * in filter values.
2101 */
2102 if (!fops->f_isfd && fops->f_touch != NULL)
2103 fops->f_touch(kn, kev, EVENT_REGISTER);
2104 }
2105 /* still have use ref on knote */
2106
2107 /*
2108 * Invoke the filter routine to see if it should be enqueued now.
2109 */
2110 #if 0
2111 if (kn->kn_fop->f_event(kn, 0)) {
2112 #else
2113 /*
2114 * JMM - temporary workaround until rdar://problem/19986199
2115 * This potentially results in extra wakeups for KN_STAYQUEUED event types,
2116 * but waking up only truly active ones (yet trying below to determine
2117 * active status, by invoking the filter routine, is having side-effects).
2118 */
2119 if ((kn->kn_status & KN_STAYQUEUED) || kn->kn_fop->f_event(kn, 0)) {
2120 #endif
2121 if (knoteuse2kqlock(kq, kn))
2122 knote_activate(kn, (kn->kn_status & KN_STAYQUEUED));
2123 kqunlock(kq);
2124 } else {
2125 knote_put(kn);
2126 }
2127
2128 done:
2129 if (fp != NULL)
2130 fp_drop(p, kev->ident, fp, 0);
2131 return (error);
2132 }
2133
2134
2135 /*
2136 * knote_process - process a triggered event
2137 *
2138 * Validate that it is really still a triggered event
2139 * by calling the filter routines (if necessary). Hold
2140 * a use reference on the knote to avoid it being detached.
2141 * If it is still considered triggered, invoke the callback
2142 * routine provided and move it to the provided inprocess
2143 * queue.
2144 *
2145 * caller holds a reference on the kqueue.
2146 * kqueue locked on entry and exit - but may be dropped
2147 */
2148 static int
2149 knote_process(struct knote *kn,
2150 kevent_callback_t callback,
2151 void *data,
2152 struct kqtailq *inprocessp,
2153 struct proc *p)
2154 {
2155 struct kqueue *kq = kn->kn_kq;
2156 struct kevent_internal_s kev;
2157 int touch;
2158 int result;
2159 int error;
2160
2161 /*
2162 * Determine the kevent state we want to return.
2163 *
2164 * Some event states need to be revalidated before returning
2165 * them, others we take the snapshot at the time the event
2166 * was enqueued.
2167 *
2168 * Events with non-NULL f_touch operations must be touched.
2169 * Triggered events must fill in kev for the callback.
2170 *
2171 * Convert our lock to a use-count and call the event's
2172 * filter routine(s) to update.
2173 */
2174 if ((kn->kn_status & KN_DISABLED) != 0) {
2175 result = 0;
2176 touch = 0;
2177 } else {
2178 int revalidate;
2179
2180 result = 1;
2181 revalidate = ((kn->kn_status & KN_STAYQUEUED) != 0 ||
2182 (kn->kn_flags & EV_ONESHOT) == 0);
2183 touch = (!kn->kn_fop->f_isfd && kn->kn_fop->f_touch != NULL);
2184
2185 if (revalidate || touch) {
2186 if (revalidate)
2187 knote_deactivate(kn);
2188
2189 /* call the filter/touch routines with just a ref */
2190 if (kqlock2knoteuse(kq, kn)) {
2191 /* if we have to revalidate, call the filter */
2192 if (revalidate) {
2193 result = kn->kn_fop->f_event(kn, 0);
2194 }
2195
2196 /*
2197 * capture the kevent data - using touch if
2198 * specified
2199 */
2200 if (result && touch) {
2201 kn->kn_fop->f_touch(kn, &kev,
2202 EVENT_PROCESS);
2203 }
2204 if (result && (kn->kn_status & KN_TOUCH))
2205 kn->kn_fop->f_touch(kn, &kev,
2206 EVENT_PROCESS);
2207
2208 /*
2209 * convert back to a kqlock - bail if the knote
2210 * went away
2211 */
2212 if (!knoteuse2kqlock(kq, kn)) {
2213 return (EJUSTRETURN);
2214 } else if (result) {
2215 /*
2216 * if revalidated as alive, make sure
2217 * it's active
2218 */
2219 knote_activate(kn, 0);
2220
2221 /*
2222 * capture all events that occurred
2223 * during filter
2224 */
2225 if (!touch) {
2226 kev = kn->kn_kevent;
2227 }
2228
2229 } else if ((kn->kn_status & KN_STAYQUEUED) == 0) {
2230 /*
2231 * was already dequeued, so just bail on
2232 * this one
2233 */
2234 return (EJUSTRETURN);
2235 }
2236 } else {
2237 return (EJUSTRETURN);
2238 }
2239 } else {
2240 kev = kn->kn_kevent;
2241 }
2242 }
2243
2244 /* move knote onto inprocess queue */
2245 assert(kn->kn_tq == &kq->kq_head);
2246 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2247 kn->kn_tq = inprocessp;
2248 TAILQ_INSERT_TAIL(inprocessp, kn, kn_tqe);
2249
2250 /*
2251 * Determine how to dispatch the knote for future event handling.
2252 * not-fired: just return (do not callout).
2253 * One-shot: If dispatch2, enter deferred-delete mode (unless this is
2254 * is the deferred delete event delivery itself). Otherwise,
2255 * deactivate and drop it.
2256 * Clear: deactivate and clear the state.
2257 * Dispatch: don't clear state, just deactivate it and mark it disabled.
2258 * All others: just leave where they are.
2259 */
2260
2261 if (result == 0) {
2262 return (EJUSTRETURN);
2263 } else if ((kn->kn_flags & EV_ONESHOT) != 0) {
2264 knote_deactivate(kn);
2265 if ((kn->kn_flags & (EV_DISPATCH2|EV_DELETE)) == EV_DISPATCH2) {
2266 /* defer dropping non-delete oneshot dispatch2 events */
2267 kn->kn_status |= (KN_DISABLED | KN_DEFERDROP);
2268 kqunlock(kq);
2269 } else if (kqlock2knotedrop(kq, kn)) {
2270 kn->kn_fop->f_detach(kn);
2271 knote_drop(kn, p);
2272 }
2273 } else if ((kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) != 0) {
2274 if ((kn->kn_flags & EV_DISPATCH) != 0) {
2275 /* deactivate and disable all dispatch knotes */
2276 knote_deactivate(kn);
2277 kn->kn_status |= KN_DISABLED;
2278 } else if (!touch || kn->kn_fflags == 0) {
2279 /* only deactivate if nothing since the touch */
2280 knote_deactivate(kn);
2281 }
2282 if (!touch && (kn->kn_flags & EV_CLEAR) != 0) {
2283 /* manually clear non-touch knotes */
2284 kn->kn_data = 0;
2285 kn->kn_fflags = 0;
2286 }
2287 kqunlock(kq);
2288 } else {
2289 /*
2290 * leave on inprocess queue. We'll
2291 * move all the remaining ones back
2292 * the kq queue and wakeup any
2293 * waiters when we are done.
2294 */
2295 kqunlock(kq);
2296 }
2297
2298 /* callback to handle each event as we find it */
2299 error = (callback)(kq, &kev, data);
2300
2301 kqlock(kq);
2302 return (error);
2303 }
2304
2305 /*
2306 * Return 0 to indicate that processing should proceed,
2307 * -1 if there is nothing to process.
2308 *
2309 * Called with kqueue locked and returns the same way,
2310 * but may drop lock temporarily.
2311 */
2312 static int
2313 kqueue_begin_processing(struct kqueue *kq)
2314 {
2315 for (;;) {
2316 if (kq->kq_count == 0) {
2317 return (-1);
2318 }
2319
2320 /* if someone else is processing the queue, wait */
2321 if (kq->kq_nprocess != 0) {
2322 waitq_assert_wait64((struct waitq *)kq->kq_wqs,
2323 CAST_EVENT64_T(&kq->kq_nprocess),
2324 THREAD_UNINT, TIMEOUT_WAIT_FOREVER);
2325 kq->kq_state |= KQ_PROCWAIT;
2326 kqunlock(kq);
2327 thread_block(THREAD_CONTINUE_NULL);
2328 kqlock(kq);
2329 } else {
2330 kq->kq_nprocess = 1;
2331 return (0);
2332 }
2333 }
2334 }
2335
2336 /*
2337 * Called with kqueue lock held.
2338 */
2339 static void
2340 kqueue_end_processing(struct kqueue *kq)
2341 {
2342 kq->kq_nprocess = 0;
2343 if (kq->kq_state & KQ_PROCWAIT) {
2344 kq->kq_state &= ~KQ_PROCWAIT;
2345 waitq_wakeup64_all((struct waitq *)kq->kq_wqs,
2346 CAST_EVENT64_T(&kq->kq_nprocess),
2347 THREAD_AWAKENED,
2348 WAITQ_ALL_PRIORITIES);
2349 }
2350 }
2351
2352 /*
2353 * kqueue_process - process the triggered events in a kqueue
2354 *
2355 * Walk the queued knotes and validate that they are
2356 * really still triggered events by calling the filter
2357 * routines (if necessary). Hold a use reference on
2358 * the knote to avoid it being detached. For each event
2359 * that is still considered triggered, invoke the
2360 * callback routine provided.
2361 *
2362 * caller holds a reference on the kqueue.
2363 * kqueue locked on entry and exit - but may be dropped
2364 * kqueue list locked (held for duration of call)
2365 */
2366
2367 static int
2368 kqueue_process(struct kqueue *kq,
2369 kevent_callback_t callback,
2370 void *data,
2371 int *countp,
2372 struct proc *p)
2373 {
2374 struct kqtailq inprocess;
2375 struct knote *kn;
2376 int nevents;
2377 int error;
2378
2379 TAILQ_INIT(&inprocess);
2380
2381 if (kqueue_begin_processing(kq) == -1) {
2382 *countp = 0;
2383 /* Nothing to process */
2384 return (0);
2385 }
2386
2387 /*
2388 * Clear any pre-posted status from previous runs, so we
2389 * only detect events that occur during this run.
2390 */
2391 waitq_set_clear_preposts(kq->kq_wqs);
2392
2393 /*
2394 * loop through the enqueued knotes, processing each one and
2395 * revalidating those that need it. As they are processed,
2396 * they get moved to the inprocess queue (so the loop can end).
2397 */
2398 error = 0;
2399 nevents = 0;
2400
2401 while (error == 0 &&
2402 (kn = TAILQ_FIRST(&kq->kq_head)) != NULL) {
2403 error = knote_process(kn, callback, data, &inprocess, p);
2404 if (error == EJUSTRETURN)
2405 error = 0;
2406 else
2407 nevents++;
2408 }
2409
2410 /*
2411 * With the kqueue still locked, move any knotes
2412 * remaining on the inprocess queue back to the
2413 * kq's queue and wake up any waiters.
2414 */
2415 while ((kn = TAILQ_FIRST(&inprocess)) != NULL) {
2416 assert(kn->kn_tq == &inprocess);
2417 TAILQ_REMOVE(&inprocess, kn, kn_tqe);
2418 kn->kn_tq = &kq->kq_head;
2419 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2420 }
2421
2422 kqueue_end_processing(kq);
2423
2424 *countp = nevents;
2425 return (error);
2426 }
2427
2428
2429 static void
2430 kqueue_scan_continue(void *data, wait_result_t wait_result)
2431 {
2432 thread_t self = current_thread();
2433 uthread_t ut = (uthread_t)get_bsdthread_info(self);
2434 struct _kqueue_scan * cont_args = &ut->uu_kevent.ss_kqueue_scan;
2435 struct kqueue *kq = (struct kqueue *)data;
2436 int error;
2437 int count;
2438
2439 /* convert the (previous) wait_result to a proper error */
2440 switch (wait_result) {
2441 case THREAD_AWAKENED:
2442 kqlock(kq);
2443 error = kqueue_process(kq, cont_args->call, cont_args, &count,
2444 current_proc());
2445 if (error == 0 && count == 0) {
2446 waitq_assert_wait64((struct waitq *)kq->kq_wqs,
2447 KQ_EVENT, THREAD_ABORTSAFE,
2448 cont_args->deadline);
2449 kq->kq_state |= KQ_SLEEP;
2450 kqunlock(kq);
2451 thread_block_parameter(kqueue_scan_continue, kq);
2452 /* NOTREACHED */
2453 }
2454 kqunlock(kq);
2455 break;
2456 case THREAD_TIMED_OUT:
2457 error = EWOULDBLOCK;
2458 break;
2459 case THREAD_INTERRUPTED:
2460 error = EINTR;
2461 break;
2462 default:
2463 panic("%s: - invalid wait_result (%d)", __func__,
2464 wait_result);
2465 error = 0;
2466 }
2467
2468 /* call the continuation with the results */
2469 assert(cont_args->cont != NULL);
2470 (cont_args->cont)(kq, cont_args->data, error);
2471 }
2472
2473
2474 /*
2475 * kqueue_scan - scan and wait for events in a kqueue
2476 *
2477 * Process the triggered events in a kqueue.
2478 *
2479 * If there are no events triggered arrange to
2480 * wait for them. If the caller provided a
2481 * continuation routine, then kevent_scan will
2482 * also.
2483 *
2484 * The callback routine must be valid.
2485 * The caller must hold a use-count reference on the kq.
2486 */
2487
2488 int
2489 kqueue_scan(struct kqueue *kq,
2490 kevent_callback_t callback,
2491 kqueue_continue_t continuation,
2492 void *data,
2493 struct timeval *atvp,
2494 struct proc *p)
2495 {
2496 thread_continue_t cont = THREAD_CONTINUE_NULL;
2497 uint64_t deadline;
2498 int error;
2499 int first;
2500
2501 assert(callback != NULL);
2502
2503 first = 1;
2504 for (;;) {
2505 wait_result_t wait_result;
2506 int count;
2507
2508 /*
2509 * Make a pass through the kq to find events already
2510 * triggered.
2511 */
2512 kqlock(kq);
2513 error = kqueue_process(kq, callback, data, &count, p);
2514 if (error || count)
2515 break; /* lock still held */
2516
2517 /* looks like we have to consider blocking */
2518 if (first) {
2519 first = 0;
2520 /* convert the timeout to a deadline once */
2521 if (atvp->tv_sec || atvp->tv_usec) {
2522 uint64_t now;
2523
2524 clock_get_uptime(&now);
2525 nanoseconds_to_absolutetime((uint64_t)atvp->tv_sec * NSEC_PER_SEC +
2526 atvp->tv_usec * (long)NSEC_PER_USEC,
2527 &deadline);
2528 if (now >= deadline) {
2529 /* non-blocking call */
2530 error = EWOULDBLOCK;
2531 break; /* lock still held */
2532 }
2533 deadline -= now;
2534 clock_absolutetime_interval_to_deadline(deadline, &deadline);
2535 } else {
2536 deadline = 0; /* block forever */
2537 }
2538
2539 if (continuation) {
2540 uthread_t ut = (uthread_t)get_bsdthread_info(current_thread());
2541 struct _kqueue_scan *cont_args = &ut->uu_kevent.ss_kqueue_scan;
2542
2543 cont_args->call = callback;
2544 cont_args->cont = continuation;
2545 cont_args->deadline = deadline;
2546 cont_args->data = data;
2547 cont = kqueue_scan_continue;
2548 }
2549 }
2550
2551 /* go ahead and wait */
2552 waitq_assert_wait64_leeway((struct waitq *)kq->kq_wqs,
2553 KQ_EVENT, THREAD_ABORTSAFE,
2554 TIMEOUT_URGENCY_USER_NORMAL,
2555 deadline, TIMEOUT_NO_LEEWAY);
2556 kq->kq_state |= KQ_SLEEP;
2557 kqunlock(kq);
2558 wait_result = thread_block_parameter(cont, kq);
2559 /* NOTREACHED if (continuation != NULL) */
2560
2561 switch (wait_result) {
2562 case THREAD_AWAKENED:
2563 continue;
2564 case THREAD_TIMED_OUT:
2565 return (EWOULDBLOCK);
2566 case THREAD_INTERRUPTED:
2567 return (EINTR);
2568 default:
2569 panic("%s: - bad wait_result (%d)", __func__,
2570 wait_result);
2571 error = 0;
2572 }
2573 }
2574 kqunlock(kq);
2575 return (error);
2576 }
2577
2578
2579 /*
2580 * XXX
2581 * This could be expanded to call kqueue_scan, if desired.
2582 */
2583 /*ARGSUSED*/
2584 static int
2585 kqueue_read(__unused struct fileproc *fp,
2586 __unused struct uio *uio,
2587 __unused int flags,
2588 __unused vfs_context_t ctx)
2589 {
2590 return (ENXIO);
2591 }
2592
2593 /*ARGSUSED*/
2594 static int
2595 kqueue_write(__unused struct fileproc *fp,
2596 __unused struct uio *uio,
2597 __unused int flags,
2598 __unused vfs_context_t ctx)
2599 {
2600 return (ENXIO);
2601 }
2602
2603 /*ARGSUSED*/
2604 static int
2605 kqueue_ioctl(__unused struct fileproc *fp,
2606 __unused u_long com,
2607 __unused caddr_t data,
2608 __unused vfs_context_t ctx)
2609 {
2610 return (ENOTTY);
2611 }
2612
2613 /*ARGSUSED*/
2614 static int
2615 kqueue_select(struct fileproc *fp, int which, void *wq_link_id,
2616 __unused vfs_context_t ctx)
2617 {
2618 struct kqueue *kq = (struct kqueue *)fp->f_data;
2619 struct knote *kn;
2620 struct kqtailq inprocessq;
2621 int retnum = 0;
2622
2623 if (which != FREAD)
2624 return (0);
2625
2626 TAILQ_INIT(&inprocessq);
2627
2628 kqlock(kq);
2629 /*
2630 * If this is the first pass, link the wait queue associated with the
2631 * the kqueue onto the wait queue set for the select(). Normally we
2632 * use selrecord() for this, but it uses the wait queue within the
2633 * selinfo structure and we need to use the main one for the kqueue to
2634 * catch events from KN_STAYQUEUED sources. So we do the linkage manually.
2635 * (The select() call will unlink them when it ends).
2636 */
2637 if (wq_link_id != NULL) {
2638 thread_t cur_act = current_thread();
2639 struct uthread * ut = get_bsdthread_info(cur_act);
2640
2641 kq->kq_state |= KQ_SEL;
2642 waitq_link((struct waitq *)kq->kq_wqs, ut->uu_wqset,
2643 WAITQ_SHOULD_LOCK, (uint64_t *)wq_link_id);
2644
2645 /* always consume the reserved link object */
2646 waitq_link_release(*(uint64_t *)wq_link_id);
2647 *(uint64_t *)wq_link_id = 0;
2648
2649 /*
2650 * selprocess() is expecting that we send it back the waitq
2651 * that was just added to the thread's waitq set. In order
2652 * to not change the selrecord() API (which is exported to
2653 * kexts), we pass this value back through the
2654 * void *wq_link_id pointer we were passed. We need to use
2655 * memcpy here because the pointer may not be properly aligned
2656 * on 32-bit systems.
2657 */
2658 memcpy(wq_link_id, (void *)&(kq->kq_wqs), sizeof(void *));
2659 }
2660
2661 if (kqueue_begin_processing(kq) == -1) {
2662 kqunlock(kq);
2663 return (0);
2664 }
2665
2666 if (kq->kq_count != 0) {
2667 /*
2668 * there is something queued - but it might be a
2669 * KN_STAYQUEUED knote, which may or may not have
2670 * any events pending. So, we have to walk the
2671 * list of knotes to see, and peek at the stay-
2672 * queued ones to be really sure.
2673 */
2674 while ((kn = (struct knote *)TAILQ_FIRST(&kq->kq_head)) != NULL) {
2675 if ((kn->kn_status & KN_STAYQUEUED) == 0) {
2676 retnum = 1;
2677 goto out;
2678 }
2679
2680 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2681 TAILQ_INSERT_TAIL(&inprocessq, kn, kn_tqe);
2682
2683 if (kqlock2knoteuse(kq, kn)) {
2684 unsigned peek;
2685
2686 peek = kn->kn_fop->f_peek(kn);
2687 if (knoteuse2kqlock(kq, kn)) {
2688 if (peek > 0) {
2689 retnum = 1;
2690 goto out;
2691 }
2692 } else {
2693 retnum = 0;
2694 }
2695 }
2696 }
2697 }
2698
2699 out:
2700 /* Return knotes to active queue */
2701 while ((kn = TAILQ_FIRST(&inprocessq)) != NULL) {
2702 TAILQ_REMOVE(&inprocessq, kn, kn_tqe);
2703 kn->kn_tq = &kq->kq_head;
2704 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2705 }
2706
2707 kqueue_end_processing(kq);
2708 kqunlock(kq);
2709 return (retnum);
2710 }
2711
2712 /*
2713 * kqueue_close -
2714 */
2715 /*ARGSUSED*/
2716 static int
2717 kqueue_close(struct fileglob *fg, __unused vfs_context_t ctx)
2718 {
2719 struct kqueue *kq = (struct kqueue *)fg->fg_data;
2720
2721 kqueue_dealloc(kq);
2722 fg->fg_data = NULL;
2723 return (0);
2724 }
2725
2726 /*ARGSUSED*/
2727 /*
2728 * The callers has taken a use-count reference on this kqueue and will donate it
2729 * to the kqueue we are being added to. This keeps the kqueue from closing until
2730 * that relationship is torn down.
2731 */
2732 static int
2733 kqueue_kqfilter(__unused struct fileproc *fp, struct knote *kn, __unused vfs_context_t ctx)
2734 {
2735 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
2736 struct kqueue *parentkq = kn->kn_kq;
2737
2738 if (parentkq == kq ||
2739 kn->kn_filter != EVFILT_READ)
2740 return (1);
2741
2742 /*
2743 * We have to avoid creating a cycle when nesting kqueues
2744 * inside another. Rather than trying to walk the whole
2745 * potential DAG of nested kqueues, we just use a simple
2746 * ceiling protocol. When a kqueue is inserted into another,
2747 * we check that the (future) parent is not already nested
2748 * into another kqueue at a lower level than the potenial
2749 * child (because it could indicate a cycle). If that test
2750 * passes, we just mark the nesting levels accordingly.
2751 */
2752
2753 kqlock(parentkq);
2754 if (parentkq->kq_level > 0 &&
2755 parentkq->kq_level < kq->kq_level)
2756 {
2757 kqunlock(parentkq);
2758 return (1);
2759 } else {
2760 /* set parent level appropriately */
2761 if (parentkq->kq_level == 0)
2762 parentkq->kq_level = 2;
2763 if (parentkq->kq_level < kq->kq_level + 1)
2764 parentkq->kq_level = kq->kq_level + 1;
2765 kqunlock(parentkq);
2766
2767 kn->kn_fop = &kqread_filtops;
2768 kqlock(kq);
2769 KNOTE_ATTACH(&kq->kq_sel.si_note, kn);
2770 /* indicate nesting in child, if needed */
2771 if (kq->kq_level == 0)
2772 kq->kq_level = 1;
2773 kqunlock(kq);
2774 return (0);
2775 }
2776 }
2777
2778 /*
2779 * kqueue_drain - called when kq is closed
2780 */
2781 /*ARGSUSED*/
2782 static int
2783 kqueue_drain(struct fileproc *fp, __unused vfs_context_t ctx)
2784 {
2785 struct kqueue *kq = (struct kqueue *)fp->f_fglob->fg_data;
2786 kqlock(kq);
2787 kqueue_wakeup(kq, 1);
2788 kqunlock(kq);
2789 return (0);
2790 }
2791
2792 /*ARGSUSED*/
2793 int
2794 kqueue_stat(struct kqueue *kq, void *ub, int isstat64, proc_t p)
2795 {
2796 kqlock(kq);
2797 if (isstat64 != 0) {
2798 struct stat64 *sb64 = (struct stat64 *)ub;
2799
2800 bzero((void *)sb64, sizeof(*sb64));
2801 sb64->st_size = kq->kq_count;
2802 if (kq->kq_state & KQ_KEV_QOS)
2803 sb64->st_blksize = sizeof(struct kevent_qos_s);
2804 else if (kq->kq_state & KQ_KEV64)
2805 sb64->st_blksize = sizeof(struct kevent64_s);
2806 else if (IS_64BIT_PROCESS(p))
2807 sb64->st_blksize = sizeof(struct user64_kevent);
2808 else
2809 sb64->st_blksize = sizeof(struct user32_kevent);
2810 sb64->st_mode = S_IFIFO;
2811 } else {
2812 struct stat *sb = (struct stat *)ub;
2813
2814 bzero((void *)sb, sizeof(*sb));
2815 sb->st_size = kq->kq_count;
2816 if (kq->kq_state & KQ_KEV_QOS)
2817 sb->st_blksize = sizeof(struct kevent_qos_s);
2818 else if (kq->kq_state & KQ_KEV64)
2819 sb->st_blksize = sizeof(struct kevent64_s);
2820 else if (IS_64BIT_PROCESS(p))
2821 sb->st_blksize = sizeof(struct user64_kevent);
2822 else
2823 sb->st_blksize = sizeof(struct user32_kevent);
2824 sb->st_mode = S_IFIFO;
2825 }
2826 kqunlock(kq);
2827 return (0);
2828 }
2829
2830 /*
2831 * Called with the kqueue locked
2832 */
2833 static void
2834 kqueue_wakeup(struct kqueue *kq, int closed)
2835 {
2836 wait_result_t res = THREAD_NOT_WAITING;
2837
2838 if ((kq->kq_state & (KQ_SLEEP | KQ_SEL)) != 0 || kq->kq_nprocess > 0) {
2839 kq->kq_state &= ~(KQ_SLEEP | KQ_SEL);
2840 res = waitq_wakeup64_all((struct waitq *)kq->kq_wqs, KQ_EVENT,
2841 (closed) ? THREAD_INTERRUPTED : THREAD_AWAKENED,
2842 WAITQ_ALL_PRIORITIES);
2843 }
2844
2845 /* request additional workq threads if appropriate */
2846 if (res == THREAD_NOT_WAITING && (kq->kq_state & KQ_WORKQ) &&
2847 pthread_functions != NULL && pthread_functions->workq_reqthreads != NULL) {
2848 /*
2849 * The special workq kq should be accumulating the counts of
2850 * queued sources on a pthread_priority_t basis and we should
2851 * be providing that here. For now, just hard-code a single
2852 * entry request at a fixed (default) QOS.
2853 */
2854 struct workq_reqthreads_req_s request = {
2855 .priority = 0x020004ff, /* legacy event manager */
2856 .count = kq->kq_count };
2857 thread_t wqthread;
2858
2859 wqthread = (*pthread_functions->workq_reqthreads)(kq->kq_p, 1, &request);
2860 assert(wqthread == THREAD_NULL);
2861 }
2862 }
2863
2864 void
2865 klist_init(struct klist *list)
2866 {
2867 SLIST_INIT(list);
2868 }
2869
2870
2871 /*
2872 * Query/Post each knote in the object's list
2873 *
2874 * The object lock protects the list. It is assumed
2875 * that the filter/event routine for the object can
2876 * determine that the object is already locked (via
2877 * the hint) and not deadlock itself.
2878 *
2879 * The object lock should also hold off pending
2880 * detach/drop operations. But we'll prevent it here
2881 * too - just in case.
2882 */
2883 void
2884 knote(struct klist *list, long hint)
2885 {
2886 struct knote *kn;
2887
2888 SLIST_FOREACH(kn, list, kn_selnext) {
2889 struct kqueue *kq = kn->kn_kq;
2890
2891 kqlock(kq);
2892 if (kqlock2knoteuse(kq, kn)) {
2893 int result;
2894
2895 /* call the event with only a use count */
2896 result = kn->kn_fop->f_event(kn, hint);
2897
2898 /* if its not going away and triggered */
2899 if (knoteuse2kqlock(kq, kn) && result)
2900 knote_activate(kn, 0);
2901 /* lock held again */
2902 }
2903 kqunlock(kq);
2904 }
2905 }
2906
2907 /*
2908 * attach a knote to the specified list. Return true if this is the first entry.
2909 * The list is protected by whatever lock the object it is associated with uses.
2910 */
2911 int
2912 knote_attach(struct klist *list, struct knote *kn)
2913 {
2914 int ret = SLIST_EMPTY(list);
2915 SLIST_INSERT_HEAD(list, kn, kn_selnext);
2916 return (ret);
2917 }
2918
2919 /*
2920 * detach a knote from the specified list. Return true if that was the last entry.
2921 * The list is protected by whatever lock the object it is associated with uses.
2922 */
2923 int
2924 knote_detach(struct klist *list, struct knote *kn)
2925 {
2926 SLIST_REMOVE(list, kn, knote, kn_selnext);
2927 return (SLIST_EMPTY(list));
2928 }
2929
2930 /*
2931 * For a given knote, link a provided wait queue directly with the kqueue.
2932 * Wakeups will happen via recursive wait queue support. But nothing will move
2933 * the knote to the active list at wakeup (nothing calls knote()). Instead,
2934 * we permanently enqueue them here.
2935 *
2936 * kqueue and knote references are held by caller.
2937 *
2938 * caller provides the wait queue link structure.
2939 */
2940 int
2941 knote_link_waitq(struct knote *kn, struct waitq *wq, uint64_t *reserved_link)
2942 {
2943 struct kqueue *kq = kn->kn_kq;
2944 kern_return_t kr;
2945
2946 kr = waitq_link(wq, kq->kq_wqs, WAITQ_SHOULD_LOCK, reserved_link);
2947 if (kr == KERN_SUCCESS) {
2948 knote_markstayqueued(kn);
2949 return (0);
2950 } else {
2951 return (EINVAL);
2952 }
2953 }
2954
2955 /*
2956 * Unlink the provided wait queue from the kqueue associated with a knote.
2957 * Also remove it from the magic list of directly attached knotes.
2958 *
2959 * Note that the unlink may have already happened from the other side, so
2960 * ignore any failures to unlink and just remove it from the kqueue list.
2961 *
2962 * On success, caller is responsible for the link structure
2963 */
2964 int
2965 knote_unlink_waitq(struct knote *kn, struct waitq *wq)
2966 {
2967 struct kqueue *kq = kn->kn_kq;
2968 kern_return_t kr;
2969
2970 kr = waitq_unlink(wq, kq->kq_wqs);
2971 knote_clearstayqueued(kn);
2972 return ((kr != KERN_SUCCESS) ? EINVAL : 0);
2973 }
2974
2975 /*
2976 * remove all knotes referencing a specified fd
2977 *
2978 * Essentially an inlined knote_remove & knote_drop
2979 * when we know for sure that the thing is a file
2980 *
2981 * Entered with the proc_fd lock already held.
2982 * It returns the same way, but may drop it temporarily.
2983 */
2984 void
2985 knote_fdclose(struct proc *p, int fd)
2986 {
2987 struct filedesc *fdp = p->p_fd;
2988 struct klist *list;
2989 struct knote *kn;
2990
2991 list = &fdp->fd_knlist[fd];
2992 while ((kn = SLIST_FIRST(list)) != NULL) {
2993 struct kqueue *kq = kn->kn_kq;
2994
2995 if (kq->kq_p != p)
2996 panic("%s: proc mismatch (kq->kq_p=%p != p=%p)",
2997 __func__, kq->kq_p, p);
2998
2999 kqlock(kq);
3000 proc_fdunlock(p);
3001
3002 /*
3003 * Convert the lock to a drop ref.
3004 * If we get it, go ahead and drop it.
3005 * Otherwise, we waited for it to
3006 * be dropped by the other guy, so
3007 * it is safe to move on in the list.
3008 */
3009 if (kqlock2knotedrop(kq, kn)) {
3010 kn->kn_fop->f_detach(kn);
3011 knote_drop(kn, p);
3012 }
3013
3014 proc_fdlock(p);
3015
3016 /* the fd tables may have changed - start over */
3017 list = &fdp->fd_knlist[fd];
3018 }
3019 }
3020
3021 /* proc_fdlock held on entry (and exit) */
3022 static int
3023 knote_fdpattach(struct knote *kn, struct filedesc *fdp, struct proc *p)
3024 {
3025 struct klist *list = NULL;
3026
3027 if (! kn->kn_fop->f_isfd) {
3028 if (fdp->fd_knhashmask == 0)
3029 fdp->fd_knhash = hashinit(CONFIG_KN_HASHSIZE, M_KQUEUE,
3030 &fdp->fd_knhashmask);
3031 list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
3032 } else {
3033 if ((u_int)fdp->fd_knlistsize <= kn->kn_id) {
3034 u_int size = 0;
3035
3036 if (kn->kn_id >= (uint64_t)p->p_rlimit[RLIMIT_NOFILE].rlim_cur
3037 || kn->kn_id >= (uint64_t)maxfiles)
3038 return (EINVAL);
3039
3040 /* have to grow the fd_knlist */
3041 size = fdp->fd_knlistsize;
3042 while (size <= kn->kn_id)
3043 size += KQEXTENT;
3044
3045 if (size >= (UINT_MAX/sizeof(struct klist *)))
3046 return (EINVAL);
3047
3048 MALLOC(list, struct klist *,
3049 size * sizeof(struct klist *), M_KQUEUE, M_WAITOK);
3050 if (list == NULL)
3051 return (ENOMEM);
3052
3053 bcopy((caddr_t)fdp->fd_knlist, (caddr_t)list,
3054 fdp->fd_knlistsize * sizeof(struct klist *));
3055 bzero((caddr_t)list +
3056 fdp->fd_knlistsize * sizeof(struct klist *),
3057 (size - fdp->fd_knlistsize) * sizeof(struct klist *));
3058 FREE(fdp->fd_knlist, M_KQUEUE);
3059 fdp->fd_knlist = list;
3060 fdp->fd_knlistsize = size;
3061 }
3062 list = &fdp->fd_knlist[kn->kn_id];
3063 }
3064 SLIST_INSERT_HEAD(list, kn, kn_link);
3065 return (0);
3066 }
3067
3068
3069
3070 /*
3071 * should be called at spl == 0, since we don't want to hold spl
3072 * while calling fdrop and free.
3073 */
3074 static void
3075 knote_drop(struct knote *kn, __unused struct proc *ctxp)
3076 {
3077 struct kqueue *kq = kn->kn_kq;
3078 struct proc *p = kq->kq_p;
3079 struct filedesc *fdp = p->p_fd;
3080 struct klist *list;
3081 int needswakeup;
3082
3083 proc_fdlock(p);
3084 if (kn->kn_fop->f_isfd)
3085 list = &fdp->fd_knlist[kn->kn_id];
3086 else
3087 list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
3088
3089 SLIST_REMOVE(list, kn, knote, kn_link);
3090 kqlock(kq);
3091 knote_dequeue(kn);
3092 needswakeup = (kn->kn_status & KN_USEWAIT);
3093 kqunlock(kq);
3094 proc_fdunlock(p);
3095
3096 if (needswakeup)
3097 waitq_wakeup64_all((struct waitq *)kq->kq_wqs,
3098 CAST_EVENT64_T(&kn->kn_status),
3099 THREAD_AWAKENED,
3100 WAITQ_ALL_PRIORITIES);
3101
3102 if (kn->kn_fop->f_isfd)
3103 fp_drop(p, kn->kn_id, kn->kn_fp, 0);
3104
3105 knote_free(kn);
3106 }
3107
3108 /* called with kqueue lock held */
3109 static void
3110 knote_activate(struct knote *kn, int force)
3111 {
3112 struct kqueue *kq = kn->kn_kq;
3113
3114 if (!force && (kn->kn_status & KN_ACTIVE))
3115 return;
3116
3117 kn->kn_status |= KN_ACTIVE;
3118 knote_enqueue(kn);
3119 kqueue_wakeup(kq, 0);
3120
3121 /* wake up the parent kq, too */
3122 KNOTE(&kq->kq_sel.si_note, 0);
3123 }
3124
3125 /* called with kqueue lock held */
3126 static void
3127 knote_deactivate(struct knote *kn)
3128 {
3129 kn->kn_status &= ~KN_ACTIVE;
3130 knote_dequeue(kn);
3131 }
3132
3133 /* called with kqueue lock held */
3134 static void
3135 knote_enqueue(struct knote *kn)
3136 {
3137 if ((kn->kn_status & (KN_QUEUED | KN_STAYQUEUED)) == KN_STAYQUEUED ||
3138 (kn->kn_status & (KN_QUEUED | KN_STAYQUEUED | KN_DISABLED)) == 0) {
3139 struct kqtailq *tq = kn->kn_tq;
3140 struct kqueue *kq = kn->kn_kq;
3141
3142 TAILQ_INSERT_TAIL(tq, kn, kn_tqe);
3143 kn->kn_status |= KN_QUEUED;
3144 kq->kq_count++;
3145 }
3146 }
3147
3148 /* called with kqueue lock held */
3149 static void
3150 knote_dequeue(struct knote *kn)
3151 {
3152 struct kqueue *kq = kn->kn_kq;
3153
3154 if ((kn->kn_status & (KN_QUEUED | KN_STAYQUEUED)) == KN_QUEUED) {
3155 struct kqtailq *tq = kn->kn_tq;
3156
3157 TAILQ_REMOVE(tq, kn, kn_tqe);
3158 kn->kn_tq = &kq->kq_head;
3159 kn->kn_status &= ~KN_QUEUED;
3160 kq->kq_count--;
3161 }
3162 }
3163
3164 void
3165 knote_init(void)
3166 {
3167 knote_zone = zinit(sizeof(struct knote), 8192*sizeof(struct knote),
3168 8192, "knote zone");
3169
3170 /* allocate kq lock group attribute and group */
3171 kq_lck_grp_attr = lck_grp_attr_alloc_init();
3172
3173 kq_lck_grp = lck_grp_alloc_init("kqueue", kq_lck_grp_attr);
3174
3175 /* Allocate kq lock attribute */
3176 kq_lck_attr = lck_attr_alloc_init();
3177
3178 /* Initialize the timer filter lock */
3179 lck_mtx_init(&_filt_timerlock, kq_lck_grp, kq_lck_attr);
3180
3181 #if VM_PRESSURE_EVENTS
3182 /* Initialize the vm pressure list lock */
3183 vm_pressure_init(kq_lck_grp, kq_lck_attr);
3184 #endif
3185
3186 #if CONFIG_MEMORYSTATUS
3187 /* Initialize the memorystatus list lock */
3188 memorystatus_kevent_init(kq_lck_grp, kq_lck_attr);
3189 #endif
3190 }
3191 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL)
3192
3193 static struct knote *
3194 knote_alloc(void)
3195 {
3196 return ((struct knote *)zalloc(knote_zone));
3197 }
3198
3199 static void
3200 knote_free(struct knote *kn)
3201 {
3202 zfree(knote_zone, kn);
3203 }
3204
3205 #if SOCKETS
3206 #include <sys/param.h>
3207 #include <sys/socket.h>
3208 #include <sys/protosw.h>
3209 #include <sys/domain.h>
3210 #include <sys/mbuf.h>
3211 #include <sys/kern_event.h>
3212 #include <sys/malloc.h>
3213 #include <sys/sys_domain.h>
3214 #include <sys/syslog.h>
3215
3216 #ifndef ROUNDUP64
3217 #define ROUNDUP64(x) P2ROUNDUP((x), sizeof (u_int64_t))
3218 #endif
3219
3220 #ifndef ADVANCE64
3221 #define ADVANCE64(p, n) (void*)((char *)(p) + ROUNDUP64(n))
3222 #endif
3223
3224 static lck_grp_attr_t *kev_lck_grp_attr;
3225 static lck_attr_t *kev_lck_attr;
3226 static lck_grp_t *kev_lck_grp;
3227 static decl_lck_rw_data(,kev_lck_data);
3228 static lck_rw_t *kev_rwlock = &kev_lck_data;
3229
3230 static int kev_attach(struct socket *so, int proto, struct proc *p);
3231 static int kev_detach(struct socket *so);
3232 static int kev_control(struct socket *so, u_long cmd, caddr_t data,
3233 struct ifnet *ifp, struct proc *p);
3234 static lck_mtx_t * event_getlock(struct socket *, int);
3235 static int event_lock(struct socket *, int, void *);
3236 static int event_unlock(struct socket *, int, void *);
3237
3238 static int event_sofreelastref(struct socket *);
3239 static void kev_delete(struct kern_event_pcb *);
3240
3241 static struct pr_usrreqs event_usrreqs = {
3242 .pru_attach = kev_attach,
3243 .pru_control = kev_control,
3244 .pru_detach = kev_detach,
3245 .pru_soreceive = soreceive,
3246 };
3247
3248 static struct protosw eventsw[] = {
3249 {
3250 .pr_type = SOCK_RAW,
3251 .pr_protocol = SYSPROTO_EVENT,
3252 .pr_flags = PR_ATOMIC,
3253 .pr_usrreqs = &event_usrreqs,
3254 .pr_lock = event_lock,
3255 .pr_unlock = event_unlock,
3256 .pr_getlock = event_getlock,
3257 }
3258 };
3259
3260 __private_extern__ int kevt_getstat SYSCTL_HANDLER_ARGS;
3261 __private_extern__ int kevt_pcblist SYSCTL_HANDLER_ARGS;
3262
3263 SYSCTL_NODE(_net_systm, OID_AUTO, kevt,
3264 CTLFLAG_RW|CTLFLAG_LOCKED, 0, "Kernel event family");
3265
3266 struct kevtstat kevtstat;
3267 SYSCTL_PROC(_net_systm_kevt, OID_AUTO, stats,
3268 CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0,
3269 kevt_getstat, "S,kevtstat", "");
3270
3271 SYSCTL_PROC(_net_systm_kevt, OID_AUTO, pcblist,
3272 CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0,
3273 kevt_pcblist, "S,xkevtpcb", "");
3274
3275 static lck_mtx_t *
3276 event_getlock(struct socket *so, int locktype)
3277 {
3278 #pragma unused(locktype)
3279 struct kern_event_pcb *ev_pcb = (struct kern_event_pcb *)so->so_pcb;
3280
3281 if (so->so_pcb != NULL) {
3282 if (so->so_usecount < 0)
3283 panic("%s: so=%p usecount=%d lrh= %s\n", __func__,
3284 so, so->so_usecount, solockhistory_nr(so));
3285 /* NOTREACHED */
3286 } else {
3287 panic("%s: so=%p NULL NO so_pcb %s\n", __func__,
3288 so, solockhistory_nr(so));
3289 /* NOTREACHED */
3290 }
3291 return (&ev_pcb->evp_mtx);
3292 }
3293
3294 static int
3295 event_lock(struct socket *so, int refcount, void *lr)
3296 {
3297 void *lr_saved;
3298
3299 if (lr == NULL)
3300 lr_saved = __builtin_return_address(0);
3301 else
3302 lr_saved = lr;
3303
3304 if (so->so_pcb != NULL) {
3305 lck_mtx_lock(&((struct kern_event_pcb *)so->so_pcb)->evp_mtx);
3306 } else {
3307 panic("%s: so=%p NO PCB! lr=%p lrh= %s\n", __func__,
3308 so, lr_saved, solockhistory_nr(so));
3309 /* NOTREACHED */
3310 }
3311
3312 if (so->so_usecount < 0) {
3313 panic("%s: so=%p so_pcb=%p lr=%p ref=%d lrh= %s\n", __func__,
3314 so, so->so_pcb, lr_saved, so->so_usecount,
3315 solockhistory_nr(so));
3316 /* NOTREACHED */
3317 }
3318
3319 if (refcount)
3320 so->so_usecount++;
3321
3322 so->lock_lr[so->next_lock_lr] = lr_saved;
3323 so->next_lock_lr = (so->next_lock_lr+1) % SO_LCKDBG_MAX;
3324 return (0);
3325 }
3326
3327 static int
3328 event_unlock(struct socket *so, int refcount, void *lr)
3329 {
3330 void *lr_saved;
3331 lck_mtx_t *mutex_held;
3332
3333 if (lr == NULL)
3334 lr_saved = __builtin_return_address(0);
3335 else
3336 lr_saved = lr;
3337
3338 if (refcount)
3339 so->so_usecount--;
3340
3341 if (so->so_usecount < 0) {
3342 panic("%s: so=%p usecount=%d lrh= %s\n", __func__,
3343 so, so->so_usecount, solockhistory_nr(so));
3344 /* NOTREACHED */
3345 }
3346 if (so->so_pcb == NULL) {
3347 panic("%s: so=%p NO PCB usecount=%d lr=%p lrh= %s\n", __func__,
3348 so, so->so_usecount, (void *)lr_saved,
3349 solockhistory_nr(so));
3350 /* NOTREACHED */
3351 }
3352 mutex_held = (&((struct kern_event_pcb *)so->so_pcb)->evp_mtx);
3353
3354 lck_mtx_assert(mutex_held, LCK_MTX_ASSERT_OWNED);
3355 so->unlock_lr[so->next_unlock_lr] = lr_saved;
3356 so->next_unlock_lr = (so->next_unlock_lr+1) % SO_LCKDBG_MAX;
3357
3358 if (so->so_usecount == 0) {
3359 VERIFY(so->so_flags & SOF_PCBCLEARING);
3360 event_sofreelastref(so);
3361 } else {
3362 lck_mtx_unlock(mutex_held);
3363 }
3364
3365 return (0);
3366 }
3367
3368 static int
3369 event_sofreelastref(struct socket *so)
3370 {
3371 struct kern_event_pcb *ev_pcb = (struct kern_event_pcb *)so->so_pcb;
3372
3373 lck_mtx_assert(&(ev_pcb->evp_mtx), LCK_MTX_ASSERT_OWNED);
3374
3375 so->so_pcb = NULL;
3376
3377 /*
3378 * Disable upcall in the event another thread is in kev_post_msg()
3379 * appending record to the receive socket buffer, since sbwakeup()
3380 * may release the socket lock otherwise.
3381 */
3382 so->so_rcv.sb_flags &= ~SB_UPCALL;
3383 so->so_snd.sb_flags &= ~SB_UPCALL;
3384 so->so_event = sonullevent;
3385 lck_mtx_unlock(&(ev_pcb->evp_mtx));
3386
3387 lck_mtx_assert(&(ev_pcb->evp_mtx), LCK_MTX_ASSERT_NOTOWNED);
3388 lck_rw_lock_exclusive(kev_rwlock);
3389 LIST_REMOVE(ev_pcb, evp_link);
3390 kevtstat.kes_pcbcount--;
3391 kevtstat.kes_gencnt++;
3392 lck_rw_done(kev_rwlock);
3393 kev_delete(ev_pcb);
3394
3395 sofreelastref(so, 1);
3396 return (0);
3397 }
3398
3399 static int event_proto_count = (sizeof (eventsw) / sizeof (struct protosw));
3400
3401 static
3402 struct kern_event_head kern_event_head;
3403
3404 static u_int32_t static_event_id = 0;
3405
3406 #define EVPCB_ZONE_MAX 65536
3407 #define EVPCB_ZONE_NAME "kerneventpcb"
3408 static struct zone *ev_pcb_zone;
3409
3410 /*
3411 * Install the protosw's for the NKE manager. Invoked at extension load time
3412 */
3413 void
3414 kern_event_init(struct domain *dp)
3415 {
3416 struct protosw *pr;
3417 int i;
3418
3419 VERIFY(!(dp->dom_flags & DOM_INITIALIZED));
3420 VERIFY(dp == systemdomain);
3421
3422 kev_lck_grp_attr = lck_grp_attr_alloc_init();
3423 if (kev_lck_grp_attr == NULL) {
3424 panic("%s: lck_grp_attr_alloc_init failed\n", __func__);
3425 /* NOTREACHED */
3426 }
3427
3428 kev_lck_grp = lck_grp_alloc_init("Kernel Event Protocol",
3429 kev_lck_grp_attr);
3430 if (kev_lck_grp == NULL) {
3431 panic("%s: lck_grp_alloc_init failed\n", __func__);
3432 /* NOTREACHED */
3433 }
3434
3435 kev_lck_attr = lck_attr_alloc_init();
3436 if (kev_lck_attr == NULL) {
3437 panic("%s: lck_attr_alloc_init failed\n", __func__);
3438 /* NOTREACHED */
3439 }
3440
3441 lck_rw_init(kev_rwlock, kev_lck_grp, kev_lck_attr);
3442 if (kev_rwlock == NULL) {
3443 panic("%s: lck_mtx_alloc_init failed\n", __func__);
3444 /* NOTREACHED */
3445 }
3446
3447 for (i = 0, pr = &eventsw[0]; i < event_proto_count; i++, pr++)
3448 net_add_proto(pr, dp, 1);
3449
3450 ev_pcb_zone = zinit(sizeof(struct kern_event_pcb),
3451 EVPCB_ZONE_MAX * sizeof(struct kern_event_pcb), 0, EVPCB_ZONE_NAME);
3452 if (ev_pcb_zone == NULL) {
3453 panic("%s: failed allocating ev_pcb_zone", __func__);
3454 /* NOTREACHED */
3455 }
3456 zone_change(ev_pcb_zone, Z_EXPAND, TRUE);
3457 zone_change(ev_pcb_zone, Z_CALLERACCT, TRUE);
3458 }
3459
3460 static int
3461 kev_attach(struct socket *so, __unused int proto, __unused struct proc *p)
3462 {
3463 int error = 0;
3464 struct kern_event_pcb *ev_pcb;
3465
3466 error = soreserve(so, KEV_SNDSPACE, KEV_RECVSPACE);
3467 if (error != 0)
3468 return (error);
3469
3470 if ((ev_pcb = (struct kern_event_pcb *)zalloc(ev_pcb_zone)) == NULL) {
3471 return (ENOBUFS);
3472 }
3473 bzero(ev_pcb, sizeof(struct kern_event_pcb));
3474 lck_mtx_init(&ev_pcb->evp_mtx, kev_lck_grp, kev_lck_attr);
3475
3476 ev_pcb->evp_socket = so;
3477 ev_pcb->evp_vendor_code_filter = 0xffffffff;
3478
3479 so->so_pcb = (caddr_t) ev_pcb;
3480 lck_rw_lock_exclusive(kev_rwlock);
3481 LIST_INSERT_HEAD(&kern_event_head, ev_pcb, evp_link);
3482 kevtstat.kes_pcbcount++;
3483 kevtstat.kes_gencnt++;
3484 lck_rw_done(kev_rwlock);
3485
3486 return (error);
3487 }
3488
3489 static void
3490 kev_delete(struct kern_event_pcb *ev_pcb)
3491 {
3492 VERIFY(ev_pcb != NULL);
3493 lck_mtx_destroy(&ev_pcb->evp_mtx, kev_lck_grp);
3494 zfree(ev_pcb_zone, ev_pcb);
3495 }
3496
3497 static int
3498 kev_detach(struct socket *so)
3499 {
3500 struct kern_event_pcb *ev_pcb = (struct kern_event_pcb *) so->so_pcb;
3501
3502 if (ev_pcb != NULL) {
3503 soisdisconnected(so);
3504 so->so_flags |= SOF_PCBCLEARING;
3505 }
3506
3507 return (0);
3508 }
3509
3510 /*
3511 * For now, kev_vendor_code and mbuf_tags use the same
3512 * mechanism.
3513 */
3514 errno_t kev_vendor_code_find(
3515 const char *string,
3516 u_int32_t *out_vendor_code)
3517 {
3518 if (strlen(string) >= KEV_VENDOR_CODE_MAX_STR_LEN) {
3519 return (EINVAL);
3520 }
3521 return (net_str_id_find_internal(string, out_vendor_code,
3522 NSI_VENDOR_CODE, 1));
3523 }
3524
3525 errno_t
3526 kev_msg_post(struct kev_msg *event_msg)
3527 {
3528 mbuf_tag_id_t min_vendor, max_vendor;
3529
3530 net_str_id_first_last(&min_vendor, &max_vendor, NSI_VENDOR_CODE);
3531
3532 if (event_msg == NULL)
3533 return (EINVAL);
3534
3535 /*
3536 * Limit third parties to posting events for registered vendor codes
3537 * only
3538 */
3539 if (event_msg->vendor_code < min_vendor ||
3540 event_msg->vendor_code > max_vendor) {
3541 OSIncrementAtomic64((SInt64 *)&kevtstat.kes_badvendor);
3542 return (EINVAL);
3543 }
3544 return (kev_post_msg(event_msg));
3545 }
3546
3547 int
3548 kev_post_msg(struct kev_msg *event_msg)
3549 {
3550 struct mbuf *m, *m2;
3551 struct kern_event_pcb *ev_pcb;
3552 struct kern_event_msg *ev;
3553 char *tmp;
3554 u_int32_t total_size;
3555 int i;
3556
3557 /* Verify the message is small enough to fit in one mbuf w/o cluster */
3558 total_size = KEV_MSG_HEADER_SIZE;
3559
3560 for (i = 0; i < 5; i++) {
3561 if (event_msg->dv[i].data_length == 0)
3562 break;
3563 total_size += event_msg->dv[i].data_length;
3564 }
3565
3566 if (total_size > MLEN) {
3567 OSIncrementAtomic64((SInt64 *)&kevtstat.kes_toobig);
3568 return (EMSGSIZE);
3569 }
3570
3571 m = m_get(M_DONTWAIT, MT_DATA);
3572 if (m == 0) {
3573 OSIncrementAtomic64((SInt64 *)&kevtstat.kes_nomem);
3574 return (ENOMEM);
3575 }
3576 ev = mtod(m, struct kern_event_msg *);
3577 total_size = KEV_MSG_HEADER_SIZE;
3578
3579 tmp = (char *) &ev->event_data[0];
3580 for (i = 0; i < 5; i++) {
3581 if (event_msg->dv[i].data_length == 0)
3582 break;
3583
3584 total_size += event_msg->dv[i].data_length;
3585 bcopy(event_msg->dv[i].data_ptr, tmp,
3586 event_msg->dv[i].data_length);
3587 tmp += event_msg->dv[i].data_length;
3588 }
3589
3590 ev->id = ++static_event_id;
3591 ev->total_size = total_size;
3592 ev->vendor_code = event_msg->vendor_code;
3593 ev->kev_class = event_msg->kev_class;
3594 ev->kev_subclass = event_msg->kev_subclass;
3595 ev->event_code = event_msg->event_code;
3596
3597 m->m_len = total_size;
3598 lck_rw_lock_shared(kev_rwlock);
3599 for (ev_pcb = LIST_FIRST(&kern_event_head);
3600 ev_pcb;
3601 ev_pcb = LIST_NEXT(ev_pcb, evp_link)) {
3602 lck_mtx_lock(&ev_pcb->evp_mtx);
3603 if (ev_pcb->evp_socket->so_pcb == NULL) {
3604 lck_mtx_unlock(&ev_pcb->evp_mtx);
3605 continue;
3606 }
3607 if (ev_pcb->evp_vendor_code_filter != KEV_ANY_VENDOR) {
3608 if (ev_pcb->evp_vendor_code_filter != ev->vendor_code) {
3609 lck_mtx_unlock(&ev_pcb->evp_mtx);
3610 continue;
3611 }
3612
3613 if (ev_pcb->evp_class_filter != KEV_ANY_CLASS) {
3614 if (ev_pcb->evp_class_filter != ev->kev_class) {
3615 lck_mtx_unlock(&ev_pcb->evp_mtx);
3616 continue;
3617 }
3618
3619 if ((ev_pcb->evp_subclass_filter !=
3620 KEV_ANY_SUBCLASS) &&
3621 (ev_pcb->evp_subclass_filter !=
3622 ev->kev_subclass)) {
3623 lck_mtx_unlock(&ev_pcb->evp_mtx);
3624 continue;
3625 }
3626 }
3627 }
3628
3629 m2 = m_copym(m, 0, m->m_len, M_NOWAIT);
3630 if (m2 == 0) {
3631 OSIncrementAtomic64((SInt64 *)&kevtstat.kes_nomem);
3632 m_free(m);
3633 lck_mtx_unlock(&ev_pcb->evp_mtx);
3634 lck_rw_done(kev_rwlock);
3635 return (ENOMEM);
3636 }
3637 if (sbappendrecord(&ev_pcb->evp_socket->so_rcv, m2)) {
3638 /*
3639 * We use "m" for the socket stats as it would be
3640 * unsafe to use "m2"
3641 */
3642 so_inc_recv_data_stat(ev_pcb->evp_socket,
3643 1, m->m_len, SO_TC_BE);
3644
3645 sorwakeup(ev_pcb->evp_socket);
3646 OSIncrementAtomic64((SInt64 *)&kevtstat.kes_posted);
3647 } else {
3648 OSIncrementAtomic64((SInt64 *)&kevtstat.kes_fullsock);
3649 }
3650 lck_mtx_unlock(&ev_pcb->evp_mtx);
3651 }
3652 m_free(m);
3653 lck_rw_done(kev_rwlock);
3654
3655 return (0);
3656 }
3657
3658 static int
3659 kev_control(struct socket *so,
3660 u_long cmd,
3661 caddr_t data,
3662 __unused struct ifnet *ifp,
3663 __unused struct proc *p)
3664 {
3665 struct kev_request *kev_req = (struct kev_request *) data;
3666 struct kern_event_pcb *ev_pcb;
3667 struct kev_vendor_code *kev_vendor;
3668 u_int32_t *id_value = (u_int32_t *) data;
3669
3670 switch (cmd) {
3671 case SIOCGKEVID:
3672 *id_value = static_event_id;
3673 break;
3674 case SIOCSKEVFILT:
3675 ev_pcb = (struct kern_event_pcb *) so->so_pcb;
3676 ev_pcb->evp_vendor_code_filter = kev_req->vendor_code;
3677 ev_pcb->evp_class_filter = kev_req->kev_class;
3678 ev_pcb->evp_subclass_filter = kev_req->kev_subclass;
3679 break;
3680 case SIOCGKEVFILT:
3681 ev_pcb = (struct kern_event_pcb *) so->so_pcb;
3682 kev_req->vendor_code = ev_pcb->evp_vendor_code_filter;
3683 kev_req->kev_class = ev_pcb->evp_class_filter;
3684 kev_req->kev_subclass = ev_pcb->evp_subclass_filter;
3685 break;
3686 case SIOCGKEVVENDOR:
3687 kev_vendor = (struct kev_vendor_code *)data;
3688 /* Make sure string is NULL terminated */
3689 kev_vendor->vendor_string[KEV_VENDOR_CODE_MAX_STR_LEN-1] = 0;
3690 return (net_str_id_find_internal(kev_vendor->vendor_string,
3691 &kev_vendor->vendor_code, NSI_VENDOR_CODE, 0));
3692 default:
3693 return (ENOTSUP);
3694 }
3695
3696 return (0);
3697 }
3698
3699 int
3700 kevt_getstat SYSCTL_HANDLER_ARGS
3701 {
3702 #pragma unused(oidp, arg1, arg2)
3703 int error = 0;
3704
3705 lck_rw_lock_shared(kev_rwlock);
3706
3707 if (req->newptr != USER_ADDR_NULL) {
3708 error = EPERM;
3709 goto done;
3710 }
3711 if (req->oldptr == USER_ADDR_NULL) {
3712 req->oldidx = sizeof(struct kevtstat);
3713 goto done;
3714 }
3715
3716 error = SYSCTL_OUT(req, &kevtstat,
3717 MIN(sizeof(struct kevtstat), req->oldlen));
3718 done:
3719 lck_rw_done(kev_rwlock);
3720
3721 return (error);
3722 }
3723
3724 __private_extern__ int
3725 kevt_pcblist SYSCTL_HANDLER_ARGS
3726 {
3727 #pragma unused(oidp, arg1, arg2)
3728 int error = 0;
3729 int n, i;
3730 struct xsystmgen xsg;
3731 void *buf = NULL;
3732 size_t item_size = ROUNDUP64(sizeof (struct xkevtpcb)) +
3733 ROUNDUP64(sizeof (struct xsocket_n)) +
3734 2 * ROUNDUP64(sizeof (struct xsockbuf_n)) +
3735 ROUNDUP64(sizeof (struct xsockstat_n));
3736 struct kern_event_pcb *ev_pcb;
3737
3738 buf = _MALLOC(item_size, M_TEMP, M_WAITOK | M_ZERO);
3739 if (buf == NULL)
3740 return (ENOMEM);
3741
3742 lck_rw_lock_shared(kev_rwlock);
3743
3744 n = kevtstat.kes_pcbcount;
3745
3746 if (req->oldptr == USER_ADDR_NULL) {
3747 req->oldidx = (n + n/8) * item_size;
3748 goto done;
3749 }
3750 if (req->newptr != USER_ADDR_NULL) {
3751 error = EPERM;
3752 goto done;
3753 }
3754 bzero(&xsg, sizeof (xsg));
3755 xsg.xg_len = sizeof (xsg);
3756 xsg.xg_count = n;
3757 xsg.xg_gen = kevtstat.kes_gencnt;
3758 xsg.xg_sogen = so_gencnt;
3759 error = SYSCTL_OUT(req, &xsg, sizeof (xsg));
3760 if (error) {
3761 goto done;
3762 }
3763 /*
3764 * We are done if there is no pcb
3765 */
3766 if (n == 0) {
3767 goto done;
3768 }
3769
3770 i = 0;
3771 for (i = 0, ev_pcb = LIST_FIRST(&kern_event_head);
3772 i < n && ev_pcb != NULL;
3773 i++, ev_pcb = LIST_NEXT(ev_pcb, evp_link)) {
3774 struct xkevtpcb *xk = (struct xkevtpcb *)buf;
3775 struct xsocket_n *xso = (struct xsocket_n *)
3776 ADVANCE64(xk, sizeof (*xk));
3777 struct xsockbuf_n *xsbrcv = (struct xsockbuf_n *)
3778 ADVANCE64(xso, sizeof (*xso));
3779 struct xsockbuf_n *xsbsnd = (struct xsockbuf_n *)
3780 ADVANCE64(xsbrcv, sizeof (*xsbrcv));
3781 struct xsockstat_n *xsostats = (struct xsockstat_n *)
3782 ADVANCE64(xsbsnd, sizeof (*xsbsnd));
3783
3784 bzero(buf, item_size);
3785
3786 lck_mtx_lock(&ev_pcb->evp_mtx);
3787
3788 xk->kep_len = sizeof(struct xkevtpcb);
3789 xk->kep_kind = XSO_EVT;
3790 xk->kep_evtpcb = (uint64_t)VM_KERNEL_ADDRPERM(ev_pcb);
3791 xk->kep_vendor_code_filter = ev_pcb->evp_vendor_code_filter;
3792 xk->kep_class_filter = ev_pcb->evp_class_filter;
3793 xk->kep_subclass_filter = ev_pcb->evp_subclass_filter;
3794
3795 sotoxsocket_n(ev_pcb->evp_socket, xso);
3796 sbtoxsockbuf_n(ev_pcb->evp_socket ?
3797 &ev_pcb->evp_socket->so_rcv : NULL, xsbrcv);
3798 sbtoxsockbuf_n(ev_pcb->evp_socket ?
3799 &ev_pcb->evp_socket->so_snd : NULL, xsbsnd);
3800 sbtoxsockstat_n(ev_pcb->evp_socket, xsostats);
3801
3802 lck_mtx_unlock(&ev_pcb->evp_mtx);
3803
3804 error = SYSCTL_OUT(req, buf, item_size);
3805 }
3806
3807 if (error == 0) {
3808 /*
3809 * Give the user an updated idea of our state.
3810 * If the generation differs from what we told
3811 * her before, she knows that something happened
3812 * while we were processing this request, and it
3813 * might be necessary to retry.
3814 */
3815 bzero(&xsg, sizeof (xsg));
3816 xsg.xg_len = sizeof (xsg);
3817 xsg.xg_count = n;
3818 xsg.xg_gen = kevtstat.kes_gencnt;
3819 xsg.xg_sogen = so_gencnt;
3820 error = SYSCTL_OUT(req, &xsg, sizeof (xsg));
3821 if (error) {
3822 goto done;
3823 }
3824 }
3825
3826 done:
3827 lck_rw_done(kev_rwlock);
3828
3829 return (error);
3830 }
3831
3832 #endif /* SOCKETS */
3833
3834
3835 int
3836 fill_kqueueinfo(struct kqueue *kq, struct kqueue_info * kinfo)
3837 {
3838 struct vinfo_stat * st;
3839
3840 st = &kinfo->kq_stat;
3841
3842 st->vst_size = kq->kq_count;
3843 if (kq->kq_state & KQ_KEV_QOS)
3844 st->vst_blksize = sizeof(struct kevent_qos_s);
3845 else if (kq->kq_state & KQ_KEV64)
3846 st->vst_blksize = sizeof(struct kevent64_s);
3847 else
3848 st->vst_blksize = sizeof(struct kevent);
3849 st->vst_mode = S_IFIFO;
3850
3851 /* flags exported to libproc as PROC_KQUEUE_* (sys/proc_info.h) */
3852 #define PROC_KQUEUE_MASK (KQ_SEL|KQ_SLEEP|KQ_KEV32|KQ_KEV64|KQ_KEV_QOS)
3853 kinfo->kq_state = kq->kq_state & PROC_KQUEUE_MASK;
3854
3855 return (0);
3856 }
3857
3858
3859 void
3860 knote_markstayqueued(struct knote *kn)
3861 {
3862 kqlock(kn->kn_kq);
3863 kn->kn_status |= KN_STAYQUEUED;
3864 knote_enqueue(kn);
3865 kqunlock(kn->kn_kq);
3866 }
3867
3868 void
3869 knote_clearstayqueued(struct knote *kn)
3870 {
3871 kqlock(kn->kn_kq);
3872 kn->kn_status &= ~KN_STAYQUEUED;
3873 knote_dequeue(kn);
3874 kqunlock(kn->kn_kq);
3875 }
3876
3877 static unsigned long
3878 kevent_extinfo_emit(struct kqueue *kq, struct knote *kn, struct kevent_extinfo *buf,
3879 unsigned long buflen, unsigned long nknotes)
3880 {
3881 struct kevent_qos_s kevqos;
3882 struct kevent_internal_s *kevp;
3883 for (; kn; kn = SLIST_NEXT(kn, kn_link)) {
3884 if (kq == kn->kn_kq) {
3885 if (nknotes < buflen) {
3886 struct kevent_extinfo *info = &buf[nknotes];
3887
3888 kqlock(kq);
3889 bzero(&kevqos, sizeof(kevqos));
3890 kevp = &(kn->kn_kevent);
3891
3892 kevqos.ident = kevp->ident;
3893 kevqos.filter = kevp->filter;
3894 kevqos.flags = kevp->flags;
3895 kevqos.fflags = kevp->fflags;
3896 kevqos.data = (int64_t) kevp->data;
3897 kevqos.udata = kevp->udata;
3898 kevqos.ext[0] = kevp->ext[0];
3899 kevqos.ext[1] = kevp->ext[1];
3900
3901 memcpy(&info->kqext_kev, &kevqos, sizeof(info->kqext_kev));
3902 info->kqext_sdata = kn->kn_sdata;
3903
3904 /* status flags exported to userspace/libproc */
3905 #define KQEXT_STATUS_MASK (KN_ACTIVE|KN_QUEUED|KN_DISABLED|KN_STAYQUEUED)
3906 info->kqext_status = kn->kn_status & KQEXT_STATUS_MASK;
3907 info->kqext_sfflags = kn->kn_sfflags;
3908
3909 kqunlock(kq);
3910 }
3911
3912 /* we return total number of knotes, which may be more than requested */
3913 nknotes++;
3914 }
3915 }
3916
3917 return nknotes;
3918 }
3919
3920 int
3921 pid_kqueue_extinfo(proc_t p, struct kqueue *kq, user_addr_t ubuf,
3922 uint32_t bufsize, int32_t *retval)
3923 {
3924 struct knote *kn;
3925 int i;
3926 int err = 0;
3927 struct filedesc *fdp = p->p_fd;
3928 unsigned long nknotes = 0;
3929 unsigned long buflen = bufsize / sizeof(struct kevent_extinfo);
3930 struct kevent_extinfo *kqext = NULL;
3931
3932 kqext = kalloc(buflen * sizeof(struct kevent_extinfo));
3933 if (kqext == NULL) {
3934 err = ENOMEM;
3935 goto out;
3936 }
3937 bzero(kqext, buflen * sizeof(struct kevent_extinfo));
3938
3939 proc_fdlock(p);
3940
3941 for (i = 0; i < fdp->fd_knlistsize; i++) {
3942 kn = SLIST_FIRST(&fdp->fd_knlist[i]);
3943 nknotes = kevent_extinfo_emit(kq, kn, kqext, buflen, nknotes);
3944 }
3945
3946 if (fdp->fd_knhashmask != 0) {
3947 for (i = 0; i < (int)fdp->fd_knhashmask + 1; i++) {
3948 kn = SLIST_FIRST(&fdp->fd_knhash[i]);
3949 nknotes = kevent_extinfo_emit(kq, kn, kqext, buflen, nknotes);
3950 }
3951 }
3952
3953 proc_fdunlock(p);
3954
3955 assert(bufsize >= sizeof(struct kevent_extinfo) * min(buflen, nknotes));
3956 err = copyout(kqext, ubuf, sizeof(struct kevent_extinfo) * min(buflen, nknotes));
3957
3958 out:
3959 if (kqext) {
3960 kfree(kqext, buflen * sizeof(struct kevent_extinfo));
3961 kqext = NULL;
3962 }
3963
3964 if (!err)
3965 *retval = nknotes;
3966 return err;
3967 }