kern_event.c revision 1.86 1 /* $NetBSD: kern_event.c,v 1.86 2016/04/04 20:47:57 christos Exp $ */
2
3 /*-
4 * Copyright (c) 2008, 2009 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Andrew Doran.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 /*-
33 * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon (at) FreeBSD.org>
34 * All rights reserved.
35 *
36 * Redistribution and use in source and binary forms, with or without
37 * modification, are permitted provided that the following conditions
38 * are met:
39 * 1. Redistributions of source code must retain the above copyright
40 * notice, this list of conditions and the following disclaimer.
41 * 2. Redistributions in binary form must reproduce the above copyright
42 * notice, this list of conditions and the following disclaimer in the
43 * documentation and/or other materials provided with the distribution.
44 *
45 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
46 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
49 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55 * SUCH DAMAGE.
56 *
57 * FreeBSD: src/sys/kern/kern_event.c,v 1.27 2001/07/05 17:10:44 rwatson Exp
58 */
59
60 #include <sys/cdefs.h>
61 __KERNEL_RCSID(0, "$NetBSD: kern_event.c,v 1.86 2016/04/04 20:47:57 christos Exp $");
62
63 #include <sys/param.h>
64 #include <sys/systm.h>
65 #include <sys/kernel.h>
66 #include <sys/wait.h>
67 #include <sys/proc.h>
68 #include <sys/file.h>
69 #include <sys/select.h>
70 #include <sys/queue.h>
71 #include <sys/event.h>
72 #include <sys/eventvar.h>
73 #include <sys/poll.h>
74 #include <sys/kmem.h>
75 #include <sys/stat.h>
76 #include <sys/filedesc.h>
77 #include <sys/syscallargs.h>
78 #include <sys/kauth.h>
79 #include <sys/conf.h>
80 #include <sys/atomic.h>
81
82 static int kqueue_scan(file_t *, size_t, struct kevent *,
83 const struct timespec *, register_t *,
84 const struct kevent_ops *, struct kevent *,
85 size_t);
86 static int kqueue_ioctl(file_t *, u_long, void *);
87 static int kqueue_fcntl(file_t *, u_int, void *);
88 static int kqueue_poll(file_t *, int);
89 static int kqueue_kqfilter(file_t *, struct knote *);
90 static int kqueue_stat(file_t *, struct stat *);
91 static int kqueue_close(file_t *);
92 static int kqueue_register(struct kqueue *, struct kevent *);
93 static void kqueue_doclose(struct kqueue *, struct klist *, int);
94
95 static void knote_detach(struct knote *, filedesc_t *fdp, bool);
96 static void knote_enqueue(struct knote *);
97 static void knote_activate(struct knote *);
98
99 static void filt_kqdetach(struct knote *);
100 static int filt_kqueue(struct knote *, long hint);
101 static int filt_procattach(struct knote *);
102 static void filt_procdetach(struct knote *);
103 static int filt_proc(struct knote *, long hint);
104 static int filt_fileattach(struct knote *);
105 static void filt_timerexpire(void *x);
106 static int filt_timerattach(struct knote *);
107 static void filt_timerdetach(struct knote *);
108 static int filt_timer(struct knote *, long hint);
109
110 static const struct fileops kqueueops = {
111 .fo_read = (void *)enxio,
112 .fo_write = (void *)enxio,
113 .fo_ioctl = kqueue_ioctl,
114 .fo_fcntl = kqueue_fcntl,
115 .fo_poll = kqueue_poll,
116 .fo_stat = kqueue_stat,
117 .fo_close = kqueue_close,
118 .fo_kqfilter = kqueue_kqfilter,
119 .fo_restart = fnullop_restart,
120 };
121
122 static const struct filterops kqread_filtops =
123 { 1, NULL, filt_kqdetach, filt_kqueue };
124 static const struct filterops proc_filtops =
125 { 0, filt_procattach, filt_procdetach, filt_proc };
126 static const struct filterops file_filtops =
127 { 1, filt_fileattach, NULL, NULL };
128 static const struct filterops timer_filtops =
129 { 0, filt_timerattach, filt_timerdetach, filt_timer };
130
131 static u_int kq_ncallouts = 0;
132 static int kq_calloutmax = (4 * 1024);
133
134 #define KN_HASHSIZE 64 /* XXX should be tunable */
135 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
136
137 extern const struct filterops sig_filtops;
138
139 /*
140 * Table for for all system-defined filters.
141 * These should be listed in the numeric order of the EVFILT_* defines.
142 * If filtops is NULL, the filter isn't implemented in NetBSD.
143 * End of list is when name is NULL.
144 *
145 * Note that 'refcnt' is meaningless for built-in filters.
146 */
147 struct kfilter {
148 const char *name; /* name of filter */
149 uint32_t filter; /* id of filter */
150 unsigned refcnt; /* reference count */
151 const struct filterops *filtops;/* operations for filter */
152 size_t namelen; /* length of name string */
153 };
154
155 /* System defined filters */
156 static struct kfilter sys_kfilters[] = {
157 { "EVFILT_READ", EVFILT_READ, 0, &file_filtops, 0 },
158 { "EVFILT_WRITE", EVFILT_WRITE, 0, &file_filtops, 0, },
159 { "EVFILT_AIO", EVFILT_AIO, 0, NULL, 0 },
160 { "EVFILT_VNODE", EVFILT_VNODE, 0, &file_filtops, 0 },
161 { "EVFILT_PROC", EVFILT_PROC, 0, &proc_filtops, 0 },
162 { "EVFILT_SIGNAL", EVFILT_SIGNAL, 0, &sig_filtops, 0 },
163 { "EVFILT_TIMER", EVFILT_TIMER, 0, &timer_filtops, 0 },
164 { NULL, 0, 0, NULL, 0 },
165 };
166
167 /* User defined kfilters */
168 static struct kfilter *user_kfilters; /* array */
169 static int user_kfilterc; /* current offset */
170 static int user_kfiltermaxc; /* max size so far */
171 static size_t user_kfiltersz; /* size of allocated memory */
172
173 /* Locks */
174 static krwlock_t kqueue_filter_lock; /* lock on filter lists */
175 static kmutex_t kqueue_misc_lock; /* miscellaneous */
176
177 static kauth_listener_t kqueue_listener;
178
179 static int
180 kqueue_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
181 void *arg0, void *arg1, void *arg2, void *arg3)
182 {
183 struct proc *p;
184 int result;
185
186 result = KAUTH_RESULT_DEFER;
187 p = arg0;
188
189 if (action != KAUTH_PROCESS_KEVENT_FILTER)
190 return result;
191
192 if ((kauth_cred_getuid(p->p_cred) != kauth_cred_getuid(cred) ||
193 ISSET(p->p_flag, PK_SUGID)))
194 return result;
195
196 result = KAUTH_RESULT_ALLOW;
197
198 return result;
199 }
200
201 /*
202 * Initialize the kqueue subsystem.
203 */
204 void
205 kqueue_init(void)
206 {
207
208 rw_init(&kqueue_filter_lock);
209 mutex_init(&kqueue_misc_lock, MUTEX_DEFAULT, IPL_NONE);
210
211 kqueue_listener = kauth_listen_scope(KAUTH_SCOPE_PROCESS,
212 kqueue_listener_cb, NULL);
213 }
214
215 /*
216 * Find kfilter entry by name, or NULL if not found.
217 */
218 static struct kfilter *
219 kfilter_byname_sys(const char *name)
220 {
221 int i;
222
223 KASSERT(rw_lock_held(&kqueue_filter_lock));
224
225 for (i = 0; sys_kfilters[i].name != NULL; i++) {
226 if (strcmp(name, sys_kfilters[i].name) == 0)
227 return &sys_kfilters[i];
228 }
229 return NULL;
230 }
231
232 static struct kfilter *
233 kfilter_byname_user(const char *name)
234 {
235 int i;
236
237 KASSERT(rw_lock_held(&kqueue_filter_lock));
238
239 /* user filter slots have a NULL name if previously deregistered */
240 for (i = 0; i < user_kfilterc ; i++) {
241 if (user_kfilters[i].name != NULL &&
242 strcmp(name, user_kfilters[i].name) == 0)
243 return &user_kfilters[i];
244 }
245 return NULL;
246 }
247
248 static struct kfilter *
249 kfilter_byname(const char *name)
250 {
251 struct kfilter *kfilter;
252
253 KASSERT(rw_lock_held(&kqueue_filter_lock));
254
255 if ((kfilter = kfilter_byname_sys(name)) != NULL)
256 return kfilter;
257
258 return kfilter_byname_user(name);
259 }
260
261 /*
262 * Find kfilter entry by filter id, or NULL if not found.
263 * Assumes entries are indexed in filter id order, for speed.
264 */
265 static struct kfilter *
266 kfilter_byfilter(uint32_t filter)
267 {
268 struct kfilter *kfilter;
269
270 KASSERT(rw_lock_held(&kqueue_filter_lock));
271
272 if (filter < EVFILT_SYSCOUNT) /* it's a system filter */
273 kfilter = &sys_kfilters[filter];
274 else if (user_kfilters != NULL &&
275 filter < EVFILT_SYSCOUNT + user_kfilterc)
276 /* it's a user filter */
277 kfilter = &user_kfilters[filter - EVFILT_SYSCOUNT];
278 else
279 return (NULL); /* out of range */
280 KASSERT(kfilter->filter == filter); /* sanity check! */
281 return (kfilter);
282 }
283
284 /*
285 * Register a new kfilter. Stores the entry in user_kfilters.
286 * Returns 0 if operation succeeded, or an appropriate errno(2) otherwise.
287 * If retfilter != NULL, the new filterid is returned in it.
288 */
289 int
290 kfilter_register(const char *name, const struct filterops *filtops,
291 int *retfilter)
292 {
293 struct kfilter *kfilter;
294 size_t len;
295 int i;
296
297 if (name == NULL || name[0] == '\0' || filtops == NULL)
298 return (EINVAL); /* invalid args */
299
300 rw_enter(&kqueue_filter_lock, RW_WRITER);
301 if (kfilter_byname(name) != NULL) {
302 rw_exit(&kqueue_filter_lock);
303 return (EEXIST); /* already exists */
304 }
305 if (user_kfilterc > 0xffffffff - EVFILT_SYSCOUNT) {
306 rw_exit(&kqueue_filter_lock);
307 return (EINVAL); /* too many */
308 }
309
310 for (i = 0; i < user_kfilterc; i++) {
311 kfilter = &user_kfilters[i];
312 if (kfilter->name == NULL) {
313 /* Previously deregistered slot. Reuse. */
314 goto reuse;
315 }
316 }
317
318 /* check if need to grow user_kfilters */
319 if (user_kfilterc + 1 > user_kfiltermaxc) {
320 /* Grow in KFILTER_EXTENT chunks. */
321 user_kfiltermaxc += KFILTER_EXTENT;
322 len = user_kfiltermaxc * sizeof(*kfilter);
323 kfilter = kmem_alloc(len, KM_SLEEP);
324 memset((char *)kfilter + user_kfiltersz, 0, len - user_kfiltersz);
325 if (user_kfilters != NULL) {
326 memcpy(kfilter, user_kfilters, user_kfiltersz);
327 kmem_free(user_kfilters, user_kfiltersz);
328 }
329 user_kfiltersz = len;
330 user_kfilters = kfilter;
331 }
332 /* Adding new slot */
333 kfilter = &user_kfilters[user_kfilterc++];
334 reuse:
335 kfilter->namelen = strlen(name) + 1;
336 kfilter->name = kmem_alloc(kfilter->namelen, KM_SLEEP);
337 memcpy(__UNCONST(kfilter->name), name, kfilter->namelen);
338
339 kfilter->filter = (kfilter - user_kfilters) + EVFILT_SYSCOUNT;
340
341 kfilter->filtops = kmem_alloc(sizeof(*filtops), KM_SLEEP);
342 memcpy(__UNCONST(kfilter->filtops), filtops, sizeof(*filtops));
343
344 if (retfilter != NULL)
345 *retfilter = kfilter->filter;
346 rw_exit(&kqueue_filter_lock);
347
348 return (0);
349 }
350
351 /*
352 * Unregister a kfilter previously registered with kfilter_register.
353 * This retains the filter id, but clears the name and frees filtops (filter
354 * operations), so that the number isn't reused during a boot.
355 * Returns 0 if operation succeeded, or an appropriate errno(2) otherwise.
356 */
357 int
358 kfilter_unregister(const char *name)
359 {
360 struct kfilter *kfilter;
361
362 if (name == NULL || name[0] == '\0')
363 return (EINVAL); /* invalid name */
364
365 rw_enter(&kqueue_filter_lock, RW_WRITER);
366 if (kfilter_byname_sys(name) != NULL) {
367 rw_exit(&kqueue_filter_lock);
368 return (EINVAL); /* can't detach system filters */
369 }
370
371 kfilter = kfilter_byname_user(name);
372 if (kfilter == NULL) {
373 rw_exit(&kqueue_filter_lock);
374 return (ENOENT);
375 }
376 if (kfilter->refcnt != 0) {
377 rw_exit(&kqueue_filter_lock);
378 return (EBUSY);
379 }
380
381 /* Cast away const (but we know it's safe. */
382 kmem_free(__UNCONST(kfilter->name), kfilter->namelen);
383 kfilter->name = NULL; /* mark as `not implemented' */
384
385 if (kfilter->filtops != NULL) {
386 /* Cast away const (but we know it's safe. */
387 kmem_free(__UNCONST(kfilter->filtops),
388 sizeof(*kfilter->filtops));
389 kfilter->filtops = NULL; /* mark as `not implemented' */
390 }
391 rw_exit(&kqueue_filter_lock);
392
393 return (0);
394 }
395
396
397 /*
398 * Filter attach method for EVFILT_READ and EVFILT_WRITE on normal file
399 * descriptors. Calls fileops kqfilter method for given file descriptor.
400 */
401 static int
402 filt_fileattach(struct knote *kn)
403 {
404 file_t *fp;
405
406 fp = kn->kn_obj;
407
408 return (*fp->f_ops->fo_kqfilter)(fp, kn);
409 }
410
411 /*
412 * Filter detach method for EVFILT_READ on kqueue descriptor.
413 */
414 static void
415 filt_kqdetach(struct knote *kn)
416 {
417 struct kqueue *kq;
418
419 kq = ((file_t *)kn->kn_obj)->f_kqueue;
420
421 mutex_spin_enter(&kq->kq_lock);
422 SLIST_REMOVE(&kq->kq_sel.sel_klist, kn, knote, kn_selnext);
423 mutex_spin_exit(&kq->kq_lock);
424 }
425
426 /*
427 * Filter event method for EVFILT_READ on kqueue descriptor.
428 */
429 /*ARGSUSED*/
430 static int
431 filt_kqueue(struct knote *kn, long hint)
432 {
433 struct kqueue *kq;
434 int rv;
435
436 kq = ((file_t *)kn->kn_obj)->f_kqueue;
437
438 if (hint != NOTE_SUBMIT)
439 mutex_spin_enter(&kq->kq_lock);
440 kn->kn_data = kq->kq_count;
441 rv = (kn->kn_data > 0);
442 if (hint != NOTE_SUBMIT)
443 mutex_spin_exit(&kq->kq_lock);
444
445 return rv;
446 }
447
448 /*
449 * Filter attach method for EVFILT_PROC.
450 */
451 static int
452 filt_procattach(struct knote *kn)
453 {
454 struct proc *p;
455 struct lwp *curl;
456
457 curl = curlwp;
458
459 mutex_enter(proc_lock);
460 if (kn->kn_flags & EV_FLAG1) {
461 /*
462 * NOTE_TRACK attaches to the child process too early
463 * for proc_find, so do a raw look up and check the state
464 * explicitly.
465 */
466 p = proc_find_raw(kn->kn_id);
467 if (p != NULL && p->p_stat != SIDL)
468 p = NULL;
469 } else {
470 p = proc_find(kn->kn_id);
471 }
472
473 if (p == NULL) {
474 mutex_exit(proc_lock);
475 return ESRCH;
476 }
477
478 /*
479 * Fail if it's not owned by you, or the last exec gave us
480 * setuid/setgid privs (unless you're root).
481 */
482 mutex_enter(p->p_lock);
483 mutex_exit(proc_lock);
484 if (kauth_authorize_process(curl->l_cred, KAUTH_PROCESS_KEVENT_FILTER,
485 p, NULL, NULL, NULL) != 0) {
486 mutex_exit(p->p_lock);
487 return EACCES;
488 }
489
490 kn->kn_obj = p;
491 kn->kn_flags |= EV_CLEAR; /* automatically set */
492
493 /*
494 * internal flag indicating registration done by kernel
495 */
496 if (kn->kn_flags & EV_FLAG1) {
497 kn->kn_data = kn->kn_sdata; /* ppid */
498 kn->kn_fflags = NOTE_CHILD;
499 kn->kn_flags &= ~EV_FLAG1;
500 }
501 SLIST_INSERT_HEAD(&p->p_klist, kn, kn_selnext);
502 mutex_exit(p->p_lock);
503
504 return 0;
505 }
506
507 /*
508 * Filter detach method for EVFILT_PROC.
509 *
510 * The knote may be attached to a different process, which may exit,
511 * leaving nothing for the knote to be attached to. So when the process
512 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
513 * it will be deleted when read out. However, as part of the knote deletion,
514 * this routine is called, so a check is needed to avoid actually performing
515 * a detach, because the original process might not exist any more.
516 */
517 static void
518 filt_procdetach(struct knote *kn)
519 {
520 struct proc *p;
521
522 if (kn->kn_status & KN_DETACHED)
523 return;
524
525 p = kn->kn_obj;
526
527 mutex_enter(p->p_lock);
528 SLIST_REMOVE(&p->p_klist, kn, knote, kn_selnext);
529 mutex_exit(p->p_lock);
530 }
531
532 /*
533 * Filter event method for EVFILT_PROC.
534 */
535 static int
536 filt_proc(struct knote *kn, long hint)
537 {
538 u_int event, fflag;
539 struct kevent kev;
540 struct kqueue *kq;
541 int error;
542
543 event = (u_int)hint & NOTE_PCTRLMASK;
544 kq = kn->kn_kq;
545 fflag = 0;
546
547 /* If the user is interested in this event, record it. */
548 if (kn->kn_sfflags & event)
549 fflag |= event;
550
551 if (event == NOTE_EXIT) {
552 struct proc *p = kn->kn_obj;
553
554 if (p != NULL)
555 kn->kn_data = P_WAITSTATUS(p);
556 /*
557 * Process is gone, so flag the event as finished.
558 *
559 * Detach the knote from watched process and mark
560 * it as such. We can't leave this to kqueue_scan(),
561 * since the process might not exist by then. And we
562 * have to do this now, since psignal KNOTE() is called
563 * also for zombies and we might end up reading freed
564 * memory if the kevent would already be picked up
565 * and knote g/c'ed.
566 */
567 filt_procdetach(kn);
568
569 mutex_spin_enter(&kq->kq_lock);
570 kn->kn_status |= KN_DETACHED;
571 /* Mark as ONESHOT, so that the knote it g/c'ed when read */
572 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
573 kn->kn_fflags |= fflag;
574 mutex_spin_exit(&kq->kq_lock);
575
576 return 1;
577 }
578
579 mutex_spin_enter(&kq->kq_lock);
580 if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
581 /*
582 * Process forked, and user wants to track the new process,
583 * so attach a new knote to it, and immediately report an
584 * event with the parent's pid. Register knote with new
585 * process.
586 */
587 kev.ident = hint & NOTE_PDATAMASK; /* pid */
588 kev.filter = kn->kn_filter;
589 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
590 kev.fflags = kn->kn_sfflags;
591 kev.data = kn->kn_id; /* parent */
592 kev.udata = kn->kn_kevent.udata; /* preserve udata */
593 mutex_spin_exit(&kq->kq_lock);
594 error = kqueue_register(kq, &kev);
595 mutex_spin_enter(&kq->kq_lock);
596 if (error != 0)
597 kn->kn_fflags |= NOTE_TRACKERR;
598 }
599 kn->kn_fflags |= fflag;
600 fflag = kn->kn_fflags;
601 mutex_spin_exit(&kq->kq_lock);
602
603 return fflag != 0;
604 }
605
606 static void
607 filt_timerexpire(void *knx)
608 {
609 struct knote *kn = knx;
610 int tticks;
611
612 mutex_enter(&kqueue_misc_lock);
613 kn->kn_data++;
614 knote_activate(kn);
615 if ((kn->kn_flags & EV_ONESHOT) == 0) {
616 tticks = mstohz(kn->kn_sdata);
617 if (tticks <= 0)
618 tticks = 1;
619 callout_schedule((callout_t *)kn->kn_hook, tticks);
620 }
621 mutex_exit(&kqueue_misc_lock);
622 }
623
624 /*
625 * data contains amount of time to sleep, in milliseconds
626 */
627 static int
628 filt_timerattach(struct knote *kn)
629 {
630 callout_t *calloutp;
631 struct kqueue *kq;
632 int tticks;
633
634 tticks = mstohz(kn->kn_sdata);
635
636 /* if the supplied value is under our resolution, use 1 tick */
637 if (tticks == 0) {
638 if (kn->kn_sdata == 0)
639 return EINVAL;
640 tticks = 1;
641 }
642
643 if (atomic_inc_uint_nv(&kq_ncallouts) >= kq_calloutmax ||
644 (calloutp = kmem_alloc(sizeof(*calloutp), KM_NOSLEEP)) == NULL) {
645 atomic_dec_uint(&kq_ncallouts);
646 return ENOMEM;
647 }
648 callout_init(calloutp, CALLOUT_MPSAFE);
649
650 kq = kn->kn_kq;
651 mutex_spin_enter(&kq->kq_lock);
652 kn->kn_flags |= EV_CLEAR; /* automatically set */
653 kn->kn_hook = calloutp;
654 mutex_spin_exit(&kq->kq_lock);
655
656 callout_reset(calloutp, tticks, filt_timerexpire, kn);
657
658 return (0);
659 }
660
661 static void
662 filt_timerdetach(struct knote *kn)
663 {
664 callout_t *calloutp;
665
666 calloutp = (callout_t *)kn->kn_hook;
667 callout_halt(calloutp, NULL);
668 callout_destroy(calloutp);
669 kmem_free(calloutp, sizeof(*calloutp));
670 atomic_dec_uint(&kq_ncallouts);
671 }
672
673 static int
674 filt_timer(struct knote *kn, long hint)
675 {
676 int rv;
677
678 mutex_enter(&kqueue_misc_lock);
679 rv = (kn->kn_data != 0);
680 mutex_exit(&kqueue_misc_lock);
681
682 return rv;
683 }
684
685 /*
686 * filt_seltrue:
687 *
688 * This filter "event" routine simulates seltrue().
689 */
690 int
691 filt_seltrue(struct knote *kn, long hint)
692 {
693
694 /*
695 * We don't know how much data can be read/written,
696 * but we know that it *can* be. This is about as
697 * good as select/poll does as well.
698 */
699 kn->kn_data = 0;
700 return (1);
701 }
702
703 /*
704 * This provides full kqfilter entry for device switch tables, which
705 * has same effect as filter using filt_seltrue() as filter method.
706 */
707 static void
708 filt_seltruedetach(struct knote *kn)
709 {
710 /* Nothing to do */
711 }
712
713 const struct filterops seltrue_filtops =
714 { 1, NULL, filt_seltruedetach, filt_seltrue };
715
716 int
717 seltrue_kqfilter(dev_t dev, struct knote *kn)
718 {
719 switch (kn->kn_filter) {
720 case EVFILT_READ:
721 case EVFILT_WRITE:
722 kn->kn_fop = &seltrue_filtops;
723 break;
724 default:
725 return (EINVAL);
726 }
727
728 /* Nothing more to do */
729 return (0);
730 }
731
732 /*
733 * kqueue(2) system call.
734 */
735 static int
736 kqueue1(struct lwp *l, int flags, register_t *retval)
737 {
738 struct kqueue *kq;
739 file_t *fp;
740 int fd, error;
741
742 if ((error = fd_allocfile(&fp, &fd)) != 0)
743 return error;
744 fp->f_flag = FREAD | FWRITE | (flags & (FNONBLOCK|FNOSIGPIPE));
745 fp->f_type = DTYPE_KQUEUE;
746 fp->f_ops = &kqueueops;
747 kq = kmem_zalloc(sizeof(*kq), KM_SLEEP);
748 mutex_init(&kq->kq_lock, MUTEX_DEFAULT, IPL_SCHED);
749 cv_init(&kq->kq_cv, "kqueue");
750 selinit(&kq->kq_sel);
751 TAILQ_INIT(&kq->kq_head);
752 fp->f_kqueue = kq;
753 *retval = fd;
754 kq->kq_fdp = curlwp->l_fd;
755 fd_set_exclose(l, fd, (flags & O_CLOEXEC) != 0);
756 fd_affix(curproc, fp, fd);
757 return error;
758 }
759
760 /*
761 * kqueue(2) system call.
762 */
763 int
764 sys_kqueue(struct lwp *l, const void *v, register_t *retval)
765 {
766 return kqueue1(l, 0, retval);
767 }
768
769 int
770 sys_kqueue1(struct lwp *l, const struct sys_kqueue1_args *uap,
771 register_t *retval)
772 {
773 /* {
774 syscallarg(int) flags;
775 } */
776 return kqueue1(l, SCARG(uap, flags), retval);
777 }
778
779 /*
780 * kevent(2) system call.
781 */
782 int
783 kevent_fetch_changes(void *ctx, const struct kevent *changelist,
784 struct kevent *changes, size_t index, int n)
785 {
786
787 return copyin(changelist + index, changes, n * sizeof(*changes));
788 }
789
790 int
791 kevent_put_events(void *ctx, struct kevent *events,
792 struct kevent *eventlist, size_t index, int n)
793 {
794
795 return copyout(events, eventlist + index, n * sizeof(*events));
796 }
797
798 static const struct kevent_ops kevent_native_ops = {
799 .keo_private = NULL,
800 .keo_fetch_timeout = copyin,
801 .keo_fetch_changes = kevent_fetch_changes,
802 .keo_put_events = kevent_put_events,
803 };
804
805 int
806 sys___kevent50(struct lwp *l, const struct sys___kevent50_args *uap,
807 register_t *retval)
808 {
809 /* {
810 syscallarg(int) fd;
811 syscallarg(const struct kevent *) changelist;
812 syscallarg(size_t) nchanges;
813 syscallarg(struct kevent *) eventlist;
814 syscallarg(size_t) nevents;
815 syscallarg(const struct timespec *) timeout;
816 } */
817
818 return kevent1(retval, SCARG(uap, fd), SCARG(uap, changelist),
819 SCARG(uap, nchanges), SCARG(uap, eventlist), SCARG(uap, nevents),
820 SCARG(uap, timeout), &kevent_native_ops);
821 }
822
823 int
824 kevent1(register_t *retval, int fd,
825 const struct kevent *changelist, size_t nchanges,
826 struct kevent *eventlist, size_t nevents,
827 const struct timespec *timeout,
828 const struct kevent_ops *keops)
829 {
830 struct kevent *kevp;
831 struct kqueue *kq;
832 struct timespec ts;
833 size_t i, n, ichange;
834 int nerrors, error;
835 struct kevent kevbuf[KQ_NEVENTS]; /* approx 300 bytes on 64-bit */
836 file_t *fp;
837
838 /* check that we're dealing with a kq */
839 fp = fd_getfile(fd);
840 if (fp == NULL)
841 return (EBADF);
842
843 if (fp->f_type != DTYPE_KQUEUE) {
844 fd_putfile(fd);
845 return (EBADF);
846 }
847
848 if (timeout != NULL) {
849 error = (*keops->keo_fetch_timeout)(timeout, &ts, sizeof(ts));
850 if (error)
851 goto done;
852 timeout = &ts;
853 }
854
855 kq = fp->f_kqueue;
856 nerrors = 0;
857 ichange = 0;
858
859 /* traverse list of events to register */
860 while (nchanges > 0) {
861 n = MIN(nchanges, __arraycount(kevbuf));
862 error = (*keops->keo_fetch_changes)(keops->keo_private,
863 changelist, kevbuf, ichange, n);
864 if (error)
865 goto done;
866 for (i = 0; i < n; i++) {
867 kevp = &kevbuf[i];
868 kevp->flags &= ~EV_SYSFLAGS;
869 /* register each knote */
870 error = kqueue_register(kq, kevp);
871 if (error || (kevp->flags & EV_RECEIPT)) {
872 if (nevents != 0) {
873 kevp->flags = EV_ERROR;
874 kevp->data = error;
875 error = (*keops->keo_put_events)
876 (keops->keo_private, kevp,
877 eventlist, nerrors, 1);
878 if (error)
879 goto done;
880 nevents--;
881 nerrors++;
882 } else {
883 goto done;
884 }
885 }
886 }
887 nchanges -= n; /* update the results */
888 ichange += n;
889 }
890 if (nerrors) {
891 *retval = nerrors;
892 error = 0;
893 goto done;
894 }
895
896 /* actually scan through the events */
897 error = kqueue_scan(fp, nevents, eventlist, timeout, retval, keops,
898 kevbuf, __arraycount(kevbuf));
899 done:
900 fd_putfile(fd);
901 return (error);
902 }
903
904 /*
905 * Register a given kevent kev onto the kqueue
906 */
907 static int
908 kqueue_register(struct kqueue *kq, struct kevent *kev)
909 {
910 struct kfilter *kfilter;
911 filedesc_t *fdp;
912 file_t *fp;
913 fdfile_t *ff;
914 struct knote *kn, *newkn;
915 struct klist *list;
916 int error, fd, rv;
917
918 fdp = kq->kq_fdp;
919 fp = NULL;
920 kn = NULL;
921 error = 0;
922 fd = 0;
923
924 newkn = kmem_zalloc(sizeof(*newkn), KM_SLEEP);
925
926 rw_enter(&kqueue_filter_lock, RW_READER);
927 kfilter = kfilter_byfilter(kev->filter);
928 if (kfilter == NULL || kfilter->filtops == NULL) {
929 /* filter not found nor implemented */
930 rw_exit(&kqueue_filter_lock);
931 kmem_free(newkn, sizeof(*newkn));
932 return (EINVAL);
933 }
934
935 /* search if knote already exists */
936 if (kfilter->filtops->f_isfd) {
937 /* monitoring a file descriptor */
938 fd = kev->ident;
939 if ((fp = fd_getfile(fd)) == NULL) {
940 rw_exit(&kqueue_filter_lock);
941 kmem_free(newkn, sizeof(*newkn));
942 return EBADF;
943 }
944 mutex_enter(&fdp->fd_lock);
945 ff = fdp->fd_dt->dt_ff[fd];
946 if (fd <= fdp->fd_lastkqfile) {
947 SLIST_FOREACH(kn, &ff->ff_knlist, kn_link) {
948 if (kq == kn->kn_kq &&
949 kev->filter == kn->kn_filter)
950 break;
951 }
952 }
953 } else {
954 /*
955 * not monitoring a file descriptor, so
956 * lookup knotes in internal hash table
957 */
958 mutex_enter(&fdp->fd_lock);
959 if (fdp->fd_knhashmask != 0) {
960 list = &fdp->fd_knhash[
961 KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
962 SLIST_FOREACH(kn, list, kn_link) {
963 if (kev->ident == kn->kn_id &&
964 kq == kn->kn_kq &&
965 kev->filter == kn->kn_filter)
966 break;
967 }
968 }
969 }
970
971 /*
972 * kn now contains the matching knote, or NULL if no match
973 */
974 if (kev->flags & EV_ADD) {
975 if (kn == NULL) {
976 /* create new knote */
977 kn = newkn;
978 newkn = NULL;
979 kn->kn_obj = fp;
980 kn->kn_id = kev->ident;
981 kn->kn_kq = kq;
982 kn->kn_fop = kfilter->filtops;
983 kn->kn_kfilter = kfilter;
984 kn->kn_sfflags = kev->fflags;
985 kn->kn_sdata = kev->data;
986 kev->fflags = 0;
987 kev->data = 0;
988 kn->kn_kevent = *kev;
989
990 KASSERT(kn->kn_fop != NULL);
991 /*
992 * apply reference count to knote structure, and
993 * do not release it at the end of this routine.
994 */
995 fp = NULL;
996
997 if (!kn->kn_fop->f_isfd) {
998 /*
999 * If knote is not on an fd, store on
1000 * internal hash table.
1001 */
1002 if (fdp->fd_knhashmask == 0) {
1003 /* XXXAD can block with fd_lock held */
1004 fdp->fd_knhash = hashinit(KN_HASHSIZE,
1005 HASH_LIST, true,
1006 &fdp->fd_knhashmask);
1007 }
1008 list = &fdp->fd_knhash[KN_HASH(kn->kn_id,
1009 fdp->fd_knhashmask)];
1010 } else {
1011 /* Otherwise, knote is on an fd. */
1012 list = (struct klist *)
1013 &fdp->fd_dt->dt_ff[kn->kn_id]->ff_knlist;
1014 if ((int)kn->kn_id > fdp->fd_lastkqfile)
1015 fdp->fd_lastkqfile = kn->kn_id;
1016 }
1017 SLIST_INSERT_HEAD(list, kn, kn_link);
1018
1019 KERNEL_LOCK(1, NULL); /* XXXSMP */
1020 error = (*kfilter->filtops->f_attach)(kn);
1021 KERNEL_UNLOCK_ONE(NULL); /* XXXSMP */
1022 if (error != 0) {
1023 #ifdef DIAGNOSTIC
1024 printf("%s: event not supported for file type"
1025 " %d\n", __func__, fp ? fp->f_type : -1);
1026 #endif
1027 /* knote_detach() drops fdp->fd_lock */
1028 knote_detach(kn, fdp, false);
1029 goto done;
1030 }
1031 atomic_inc_uint(&kfilter->refcnt);
1032 } else {
1033 /*
1034 * The user may change some filter values after the
1035 * initial EV_ADD, but doing so will not reset any
1036 * filter which have already been triggered.
1037 */
1038 kn->kn_sfflags = kev->fflags;
1039 kn->kn_sdata = kev->data;
1040 kn->kn_kevent.udata = kev->udata;
1041 }
1042 /*
1043 * We can get here if we are trying to attach
1044 * an event to a file descriptor that does not
1045 * support events, and the attach routine is
1046 * broken and does not return an error.
1047 */
1048 KASSERT(kn->kn_fop != NULL);
1049 KASSERT(kn->kn_fop->f_event != NULL);
1050 KERNEL_LOCK(1, NULL); /* XXXSMP */
1051 rv = (*kn->kn_fop->f_event)(kn, 0);
1052 KERNEL_UNLOCK_ONE(NULL); /* XXXSMP */
1053 if (rv)
1054 knote_activate(kn);
1055 } else {
1056 if (kn == NULL) {
1057 error = ENOENT;
1058 mutex_exit(&fdp->fd_lock);
1059 goto done;
1060 }
1061 if (kev->flags & EV_DELETE) {
1062 /* knote_detach() drops fdp->fd_lock */
1063 knote_detach(kn, fdp, true);
1064 goto done;
1065 }
1066 }
1067
1068 /* disable knote */
1069 if ((kev->flags & EV_DISABLE)) {
1070 mutex_spin_enter(&kq->kq_lock);
1071 if ((kn->kn_status & KN_DISABLED) == 0)
1072 kn->kn_status |= KN_DISABLED;
1073 mutex_spin_exit(&kq->kq_lock);
1074 }
1075
1076 /* enable knote */
1077 if ((kev->flags & EV_ENABLE)) {
1078 knote_enqueue(kn);
1079 }
1080 mutex_exit(&fdp->fd_lock);
1081 done:
1082 rw_exit(&kqueue_filter_lock);
1083 if (newkn != NULL)
1084 kmem_free(newkn, sizeof(*newkn));
1085 if (fp != NULL)
1086 fd_putfile(fd);
1087 return (error);
1088 }
1089
1090 #if defined(DEBUG)
1091 static void
1092 kq_check(struct kqueue *kq)
1093 {
1094 const struct knote *kn;
1095 int count;
1096 int nmarker;
1097
1098 KASSERT(mutex_owned(&kq->kq_lock));
1099 KASSERT(kq->kq_count >= 0);
1100
1101 count = 0;
1102 nmarker = 0;
1103 TAILQ_FOREACH(kn, &kq->kq_head, kn_tqe) {
1104 if ((kn->kn_status & (KN_MARKER | KN_QUEUED)) == 0) {
1105 panic("%s: kq=%p kn=%p inconsist 1", __func__, kq, kn);
1106 }
1107 if ((kn->kn_status & KN_MARKER) == 0) {
1108 if (kn->kn_kq != kq) {
1109 panic("%s: kq=%p kn=%p inconsist 2",
1110 __func__, kq, kn);
1111 }
1112 if ((kn->kn_status & KN_ACTIVE) == 0) {
1113 panic("%s: kq=%p kn=%p: not active",
1114 __func__, kq, kn);
1115 }
1116 count++;
1117 if (count > kq->kq_count) {
1118 goto bad;
1119 }
1120 } else {
1121 nmarker++;
1122 #if 0
1123 if (nmarker > 10000) {
1124 panic("%s: kq=%p too many markers: %d != %d, "
1125 "nmarker=%d",
1126 __func__, kq, kq->kq_count, count, nmarker);
1127 }
1128 #endif
1129 }
1130 }
1131 if (kq->kq_count != count) {
1132 bad:
1133 panic("%s: kq=%p inconsist 3: %d != %d, nmarker=%d",
1134 __func__, kq, kq->kq_count, count, nmarker);
1135 }
1136 }
1137 #else /* defined(DEBUG) */
1138 #define kq_check(a) /* nothing */
1139 #endif /* defined(DEBUG) */
1140
1141 /*
1142 * Scan through the list of events on fp (for a maximum of maxevents),
1143 * returning the results in to ulistp. Timeout is determined by tsp; if
1144 * NULL, wait indefinitely, if 0 valued, perform a poll, otherwise wait
1145 * as appropriate.
1146 */
1147 static int
1148 kqueue_scan(file_t *fp, size_t maxevents, struct kevent *ulistp,
1149 const struct timespec *tsp, register_t *retval,
1150 const struct kevent_ops *keops, struct kevent *kevbuf,
1151 size_t kevcnt)
1152 {
1153 struct kqueue *kq;
1154 struct kevent *kevp;
1155 struct timespec ats, sleepts;
1156 struct knote *kn, *marker, morker;
1157 size_t count, nkev, nevents;
1158 int timeout, error, rv;
1159 filedesc_t *fdp;
1160
1161 fdp = curlwp->l_fd;
1162 kq = fp->f_kqueue;
1163 count = maxevents;
1164 nkev = nevents = error = 0;
1165 if (count == 0) {
1166 *retval = 0;
1167 return 0;
1168 }
1169
1170 if (tsp) { /* timeout supplied */
1171 ats = *tsp;
1172 if (inittimeleft(&ats, &sleepts) == -1) {
1173 *retval = maxevents;
1174 return EINVAL;
1175 }
1176 timeout = tstohz(&ats);
1177 if (timeout <= 0)
1178 timeout = -1; /* do poll */
1179 } else {
1180 /* no timeout, wait forever */
1181 timeout = 0;
1182 }
1183
1184 memset(&morker, 0, sizeof(morker));
1185 marker = &morker;
1186 marker->kn_status = KN_MARKER;
1187 mutex_spin_enter(&kq->kq_lock);
1188 retry:
1189 kevp = kevbuf;
1190 if (kq->kq_count == 0) {
1191 if (timeout >= 0) {
1192 error = cv_timedwait_sig(&kq->kq_cv,
1193 &kq->kq_lock, timeout);
1194 if (error == 0) {
1195 if (tsp == NULL || (timeout =
1196 gettimeleft(&ats, &sleepts)) > 0)
1197 goto retry;
1198 } else {
1199 /* don't restart after signals... */
1200 if (error == ERESTART)
1201 error = EINTR;
1202 if (error == EWOULDBLOCK)
1203 error = 0;
1204 }
1205 }
1206 } else {
1207 /* mark end of knote list */
1208 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1209
1210 while (count != 0) {
1211 kn = TAILQ_FIRST(&kq->kq_head); /* get next knote */
1212 while ((kn->kn_status & KN_MARKER) != 0) {
1213 if (kn == marker) {
1214 /* it's our marker, stop */
1215 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1216 if (count < maxevents || (tsp != NULL &&
1217 (timeout = gettimeleft(&ats,
1218 &sleepts)) <= 0))
1219 goto done;
1220 goto retry;
1221 }
1222 /* someone else's marker. */
1223 kn = TAILQ_NEXT(kn, kn_tqe);
1224 }
1225 kq_check(kq);
1226 kq->kq_count--;
1227 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1228 kn->kn_status &= ~KN_QUEUED;
1229 kn->kn_status |= KN_BUSY;
1230 kq_check(kq);
1231 if (kn->kn_status & KN_DISABLED) {
1232 kn->kn_status &= ~KN_BUSY;
1233 /* don't want disabled events */
1234 continue;
1235 }
1236 if ((kn->kn_flags & EV_ONESHOT) == 0) {
1237 mutex_spin_exit(&kq->kq_lock);
1238 KASSERT(kn->kn_fop != NULL);
1239 KASSERT(kn->kn_fop->f_event != NULL);
1240 KERNEL_LOCK(1, NULL); /* XXXSMP */
1241 rv = (*kn->kn_fop->f_event)(kn, 0);
1242 KERNEL_UNLOCK_ONE(NULL); /* XXXSMP */
1243 mutex_spin_enter(&kq->kq_lock);
1244 /* Re-poll if note was re-enqueued. */
1245 if ((kn->kn_status & KN_QUEUED) != 0) {
1246 kn->kn_status &= ~KN_BUSY;
1247 continue;
1248 }
1249 if (rv == 0) {
1250 /*
1251 * non-ONESHOT event that hasn't
1252 * triggered again, so de-queue.
1253 */
1254 kn->kn_status &= ~(KN_ACTIVE|KN_BUSY);
1255 continue;
1256 }
1257 }
1258 /* XXXAD should be got from f_event if !oneshot. */
1259 *kevp++ = kn->kn_kevent;
1260 nkev++;
1261 if (kn->kn_flags & EV_ONESHOT) {
1262 /* delete ONESHOT events after retrieval */
1263 mutex_spin_exit(&kq->kq_lock);
1264 mutex_enter(&fdp->fd_lock);
1265 kn->kn_status &= ~KN_BUSY;
1266 knote_detach(kn, fdp, true);
1267 mutex_spin_enter(&kq->kq_lock);
1268 } else if (kn->kn_flags & EV_CLEAR) {
1269 /* clear state after retrieval */
1270 kn->kn_data = 0;
1271 kn->kn_fflags = 0;
1272 kn->kn_status &= ~(KN_QUEUED|KN_ACTIVE|KN_BUSY);
1273 } else if (kn->kn_flags & EV_DISPATCH) {
1274 kn->kn_status |= KN_DISABLED;
1275 kn->kn_status &= ~(KN_QUEUED|KN_ACTIVE|KN_BUSY);
1276 } else {
1277 /* add event back on list */
1278 kq_check(kq);
1279 kn->kn_status |= KN_QUEUED;
1280 kn->kn_status &= ~KN_BUSY;
1281 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1282 kq->kq_count++;
1283 kq_check(kq);
1284 }
1285 if (nkev == kevcnt) {
1286 /* do copyouts in kevcnt chunks */
1287 mutex_spin_exit(&kq->kq_lock);
1288 error = (*keops->keo_put_events)
1289 (keops->keo_private,
1290 kevbuf, ulistp, nevents, nkev);
1291 mutex_spin_enter(&kq->kq_lock);
1292 nevents += nkev;
1293 nkev = 0;
1294 kevp = kevbuf;
1295 }
1296 count--;
1297 if (error != 0 || count == 0) {
1298 /* remove marker */
1299 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1300 break;
1301 }
1302 }
1303 }
1304 done:
1305 mutex_spin_exit(&kq->kq_lock);
1306 if (nkev != 0) {
1307 /* copyout remaining events */
1308 error = (*keops->keo_put_events)(keops->keo_private,
1309 kevbuf, ulistp, nevents, nkev);
1310 }
1311 *retval = maxevents - count;
1312
1313 return error;
1314 }
1315
1316 /*
1317 * fileops ioctl method for a kqueue descriptor.
1318 *
1319 * Two ioctls are currently supported. They both use struct kfilter_mapping:
1320 * KFILTER_BYNAME find name for filter, and return result in
1321 * name, which is of size len.
1322 * KFILTER_BYFILTER find filter for name. len is ignored.
1323 */
1324 /*ARGSUSED*/
1325 static int
1326 kqueue_ioctl(file_t *fp, u_long com, void *data)
1327 {
1328 struct kfilter_mapping *km;
1329 const struct kfilter *kfilter;
1330 char *name;
1331 int error;
1332
1333 km = data;
1334 error = 0;
1335 name = kmem_alloc(KFILTER_MAXNAME, KM_SLEEP);
1336
1337 switch (com) {
1338 case KFILTER_BYFILTER: /* convert filter -> name */
1339 rw_enter(&kqueue_filter_lock, RW_READER);
1340 kfilter = kfilter_byfilter(km->filter);
1341 if (kfilter != NULL) {
1342 strlcpy(name, kfilter->name, KFILTER_MAXNAME);
1343 rw_exit(&kqueue_filter_lock);
1344 error = copyoutstr(name, km->name, km->len, NULL);
1345 } else {
1346 rw_exit(&kqueue_filter_lock);
1347 error = ENOENT;
1348 }
1349 break;
1350
1351 case KFILTER_BYNAME: /* convert name -> filter */
1352 error = copyinstr(km->name, name, KFILTER_MAXNAME, NULL);
1353 if (error) {
1354 break;
1355 }
1356 rw_enter(&kqueue_filter_lock, RW_READER);
1357 kfilter = kfilter_byname(name);
1358 if (kfilter != NULL)
1359 km->filter = kfilter->filter;
1360 else
1361 error = ENOENT;
1362 rw_exit(&kqueue_filter_lock);
1363 break;
1364
1365 default:
1366 error = ENOTTY;
1367 break;
1368
1369 }
1370 kmem_free(name, KFILTER_MAXNAME);
1371 return (error);
1372 }
1373
1374 /*
1375 * fileops fcntl method for a kqueue descriptor.
1376 */
1377 static int
1378 kqueue_fcntl(file_t *fp, u_int com, void *data)
1379 {
1380
1381 return (ENOTTY);
1382 }
1383
1384 /*
1385 * fileops poll method for a kqueue descriptor.
1386 * Determine if kqueue has events pending.
1387 */
1388 static int
1389 kqueue_poll(file_t *fp, int events)
1390 {
1391 struct kqueue *kq;
1392 int revents;
1393
1394 kq = fp->f_kqueue;
1395
1396 revents = 0;
1397 if (events & (POLLIN | POLLRDNORM)) {
1398 mutex_spin_enter(&kq->kq_lock);
1399 if (kq->kq_count != 0) {
1400 revents |= events & (POLLIN | POLLRDNORM);
1401 } else {
1402 selrecord(curlwp, &kq->kq_sel);
1403 }
1404 kq_check(kq);
1405 mutex_spin_exit(&kq->kq_lock);
1406 }
1407
1408 return revents;
1409 }
1410
1411 /*
1412 * fileops stat method for a kqueue descriptor.
1413 * Returns dummy info, with st_size being number of events pending.
1414 */
1415 static int
1416 kqueue_stat(file_t *fp, struct stat *st)
1417 {
1418 struct kqueue *kq;
1419
1420 kq = fp->f_kqueue;
1421
1422 memset(st, 0, sizeof(*st));
1423 st->st_size = kq->kq_count;
1424 st->st_blksize = sizeof(struct kevent);
1425 st->st_mode = S_IFIFO;
1426
1427 return 0;
1428 }
1429
1430 static void
1431 kqueue_doclose(struct kqueue *kq, struct klist *list, int fd)
1432 {
1433 struct knote *kn;
1434 filedesc_t *fdp;
1435
1436 fdp = kq->kq_fdp;
1437
1438 KASSERT(mutex_owned(&fdp->fd_lock));
1439
1440 for (kn = SLIST_FIRST(list); kn != NULL;) {
1441 if (kq != kn->kn_kq) {
1442 kn = SLIST_NEXT(kn, kn_link);
1443 continue;
1444 }
1445 knote_detach(kn, fdp, true);
1446 mutex_enter(&fdp->fd_lock);
1447 kn = SLIST_FIRST(list);
1448 }
1449 }
1450
1451
1452 /*
1453 * fileops close method for a kqueue descriptor.
1454 */
1455 static int
1456 kqueue_close(file_t *fp)
1457 {
1458 struct kqueue *kq;
1459 filedesc_t *fdp;
1460 fdfile_t *ff;
1461 int i;
1462
1463 kq = fp->f_kqueue;
1464 fp->f_kqueue = NULL;
1465 fp->f_type = 0;
1466 fdp = curlwp->l_fd;
1467
1468 mutex_enter(&fdp->fd_lock);
1469 for (i = 0; i <= fdp->fd_lastkqfile; i++) {
1470 if ((ff = fdp->fd_dt->dt_ff[i]) == NULL)
1471 continue;
1472 kqueue_doclose(kq, (struct klist *)&ff->ff_knlist, i);
1473 }
1474 if (fdp->fd_knhashmask != 0) {
1475 for (i = 0; i < fdp->fd_knhashmask + 1; i++) {
1476 kqueue_doclose(kq, &fdp->fd_knhash[i], -1);
1477 }
1478 }
1479 mutex_exit(&fdp->fd_lock);
1480
1481 KASSERT(kq->kq_count == 0);
1482 mutex_destroy(&kq->kq_lock);
1483 cv_destroy(&kq->kq_cv);
1484 seldestroy(&kq->kq_sel);
1485 kmem_free(kq, sizeof(*kq));
1486
1487 return (0);
1488 }
1489
1490 /*
1491 * struct fileops kqfilter method for a kqueue descriptor.
1492 * Event triggered when monitored kqueue changes.
1493 */
1494 static int
1495 kqueue_kqfilter(file_t *fp, struct knote *kn)
1496 {
1497 struct kqueue *kq;
1498
1499 kq = ((file_t *)kn->kn_obj)->f_kqueue;
1500
1501 KASSERT(fp == kn->kn_obj);
1502
1503 if (kn->kn_filter != EVFILT_READ)
1504 return 1;
1505
1506 kn->kn_fop = &kqread_filtops;
1507 mutex_enter(&kq->kq_lock);
1508 SLIST_INSERT_HEAD(&kq->kq_sel.sel_klist, kn, kn_selnext);
1509 mutex_exit(&kq->kq_lock);
1510
1511 return 0;
1512 }
1513
1514
1515 /*
1516 * Walk down a list of knotes, activating them if their event has
1517 * triggered. The caller's object lock (e.g. device driver lock)
1518 * must be held.
1519 */
1520 void
1521 knote(struct klist *list, long hint)
1522 {
1523 struct knote *kn, *tmpkn;
1524
1525 SLIST_FOREACH_SAFE(kn, list, kn_selnext, tmpkn) {
1526 KASSERT(kn->kn_fop != NULL);
1527 KASSERT(kn->kn_fop->f_event != NULL);
1528 if ((*kn->kn_fop->f_event)(kn, hint))
1529 knote_activate(kn);
1530 }
1531 }
1532
1533 /*
1534 * Remove all knotes referencing a specified fd
1535 */
1536 void
1537 knote_fdclose(int fd)
1538 {
1539 struct klist *list;
1540 struct knote *kn;
1541 filedesc_t *fdp;
1542
1543 fdp = curlwp->l_fd;
1544 list = (struct klist *)&fdp->fd_dt->dt_ff[fd]->ff_knlist;
1545 mutex_enter(&fdp->fd_lock);
1546 while ((kn = SLIST_FIRST(list)) != NULL) {
1547 knote_detach(kn, fdp, true);
1548 mutex_enter(&fdp->fd_lock);
1549 }
1550 mutex_exit(&fdp->fd_lock);
1551 }
1552
1553 /*
1554 * Drop knote. Called with fdp->fd_lock held, and will drop before
1555 * returning.
1556 */
1557 static void
1558 knote_detach(struct knote *kn, filedesc_t *fdp, bool dofop)
1559 {
1560 struct klist *list;
1561 struct kqueue *kq;
1562
1563 kq = kn->kn_kq;
1564
1565 KASSERT((kn->kn_status & KN_MARKER) == 0);
1566 KASSERT(mutex_owned(&fdp->fd_lock));
1567
1568 KASSERT(kn->kn_fop != NULL);
1569 /* Remove from monitored object. */
1570 if (dofop) {
1571 KASSERT(kn->kn_fop->f_detach != NULL);
1572 KERNEL_LOCK(1, NULL); /* XXXSMP */
1573 (*kn->kn_fop->f_detach)(kn);
1574 KERNEL_UNLOCK_ONE(NULL); /* XXXSMP */
1575 }
1576
1577 /* Remove from descriptor table. */
1578 if (kn->kn_fop->f_isfd)
1579 list = (struct klist *)&fdp->fd_dt->dt_ff[kn->kn_id]->ff_knlist;
1580 else
1581 list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
1582
1583 SLIST_REMOVE(list, kn, knote, kn_link);
1584
1585 /* Remove from kqueue. */
1586 again:
1587 mutex_spin_enter(&kq->kq_lock);
1588 if ((kn->kn_status & KN_QUEUED) != 0) {
1589 kq_check(kq);
1590 kq->kq_count--;
1591 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1592 kn->kn_status &= ~KN_QUEUED;
1593 kq_check(kq);
1594 } else if (kn->kn_status & KN_BUSY) {
1595 mutex_spin_exit(&kq->kq_lock);
1596 goto again;
1597 }
1598 mutex_spin_exit(&kq->kq_lock);
1599
1600 mutex_exit(&fdp->fd_lock);
1601 if (kn->kn_fop->f_isfd)
1602 fd_putfile(kn->kn_id);
1603 atomic_dec_uint(&kn->kn_kfilter->refcnt);
1604 kmem_free(kn, sizeof(*kn));
1605 }
1606
1607 /*
1608 * Queue new event for knote.
1609 */
1610 static void
1611 knote_enqueue(struct knote *kn)
1612 {
1613 struct kqueue *kq;
1614
1615 KASSERT((kn->kn_status & KN_MARKER) == 0);
1616
1617 kq = kn->kn_kq;
1618
1619 mutex_spin_enter(&kq->kq_lock);
1620 if ((kn->kn_status & KN_DISABLED) != 0) {
1621 kn->kn_status &= ~KN_DISABLED;
1622 }
1623 if ((kn->kn_status & (KN_ACTIVE | KN_QUEUED)) == KN_ACTIVE) {
1624 kq_check(kq);
1625 kn->kn_status |= KN_QUEUED;
1626 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1627 kq->kq_count++;
1628 kq_check(kq);
1629 cv_broadcast(&kq->kq_cv);
1630 selnotify(&kq->kq_sel, 0, NOTE_SUBMIT);
1631 }
1632 mutex_spin_exit(&kq->kq_lock);
1633 }
1634 /*
1635 * Queue new event for knote.
1636 */
1637 static void
1638 knote_activate(struct knote *kn)
1639 {
1640 struct kqueue *kq;
1641
1642 KASSERT((kn->kn_status & KN_MARKER) == 0);
1643
1644 kq = kn->kn_kq;
1645
1646 mutex_spin_enter(&kq->kq_lock);
1647 kn->kn_status |= KN_ACTIVE;
1648 if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) {
1649 kq_check(kq);
1650 kn->kn_status |= KN_QUEUED;
1651 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1652 kq->kq_count++;
1653 kq_check(kq);
1654 cv_broadcast(&kq->kq_cv);
1655 selnotify(&kq->kq_sel, 0, NOTE_SUBMIT);
1656 }
1657 mutex_spin_exit(&kq->kq_lock);
1658 }
1659