kern_event.c revision 1.9 1 /* $NetBSD: kern_event.c,v 1.9 2003/02/21 20:57:09 jdolecek Exp $ */
2 /*-
3 * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon (at) FreeBSD.org>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 *
27 * $FreeBSD: src/sys/kern/kern_event.c,v 1.27 2001/07/05 17:10:44 rwatson Exp $
28 */
29
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/proc.h>
34 #include <sys/malloc.h>
35 #include <sys/unistd.h>
36 #include <sys/file.h>
37 #include <sys/fcntl.h>
38 #include <sys/select.h>
39 #include <sys/queue.h>
40 #include <sys/event.h>
41 #include <sys/eventvar.h>
42 #include <sys/poll.h>
43 #include <sys/pool.h>
44 #include <sys/protosw.h>
45 #include <sys/socket.h>
46 #include <sys/socketvar.h>
47 #include <sys/stat.h>
48 #include <sys/uio.h>
49 #include <sys/mount.h>
50 #include <sys/filedesc.h>
51 #include <sys/sa.h>
52 #include <sys/syscallargs.h>
53
54 static int kqueue_scan(struct file *fp, size_t maxevents,
55 struct kevent *ulistp, const struct timespec *timeout,
56 struct proc *p, register_t *retval);
57 static void kqueue_wakeup(struct kqueue *kq);
58
59 static int kqueue_read(struct file *fp, off_t *offset, struct uio *uio,
60 struct ucred *cred, int flags);
61 static int kqueue_write(struct file *fp, off_t *offset, struct uio *uio,
62 struct ucred *cred, int flags);
63 static int kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
64 struct proc *p);
65 static int kqueue_fcntl(struct file *fp, u_int com, caddr_t data,
66 struct proc *p);
67 static int kqueue_poll(struct file *fp, int events, struct proc *p);
68 static int kqueue_kqfilter(struct file *fp, struct knote *kn);
69 static int kqueue_stat(struct file *fp, struct stat *sp, struct proc *p);
70 static int kqueue_close(struct file *fp, struct proc *p);
71
72 static struct fileops kqueueops = {
73 kqueue_read, kqueue_write, kqueue_ioctl, kqueue_fcntl, kqueue_poll,
74 kqueue_stat, kqueue_close, kqueue_kqfilter
75 };
76
77 static void knote_attach(struct knote *kn, struct filedesc *fdp);
78 static void knote_drop(struct knote *kn, struct proc *p,
79 struct filedesc *fdp);
80 static void knote_enqueue(struct knote *kn);
81 static void knote_dequeue(struct knote *kn);
82
83 static void filt_kqdetach(struct knote *kn);
84 static int filt_kqueue(struct knote *kn, long hint);
85 static int filt_procattach(struct knote *kn);
86 static void filt_procdetach(struct knote *kn);
87 static int filt_proc(struct knote *kn, long hint);
88 static int filt_fileattach(struct knote *kn);
89 static void filt_timerexpire(void *knx);
90 static int filt_timerattach(struct knote *kn);
91 static void filt_timerdetach(struct knote *kn);
92 static int filt_timer(struct knote *kn, long hint);
93
94 static const struct filterops kqread_filtops =
95 { 1, NULL, filt_kqdetach, filt_kqueue };
96 static const struct filterops proc_filtops =
97 { 0, filt_procattach, filt_procdetach, filt_proc };
98 static const struct filterops file_filtops =
99 { 1, filt_fileattach, NULL, NULL };
100 static struct filterops timer_filtops =
101 { 0, filt_timerattach, filt_timerdetach, filt_timer };
102
103 struct pool kqueue_pool;
104 struct pool knote_pool;
105 static int kq_ncallouts = 0;
106 static int kq_calloutmax = (4 * 1024);
107
108 MALLOC_DEFINE(M_KEVENT, "kevent", "kevents/knotes");
109
110 #define KNOTE_ACTIVATE(kn) \
111 do { \
112 kn->kn_status |= KN_ACTIVE; \
113 if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
114 knote_enqueue(kn); \
115 } while(0)
116
117 #define KN_HASHSIZE 64 /* XXX should be tunable */
118 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
119
120 extern const struct filterops sig_filtops;
121
122 /*
123 * Table for for all system-defined filters.
124 * These should be listed in the numeric order of the EVFILT_* defines.
125 * If filtops is NULL, the filter isn't implemented in NetBSD.
126 * End of list is when name is NULL.
127 */
128 struct kfilter {
129 const char *name; /* name of filter */
130 uint32_t filter; /* id of filter */
131 const struct filterops *filtops;/* operations for filter */
132 };
133
134 /* System defined filters */
135 static const struct kfilter sys_kfilters[] = {
136 { "EVFILT_READ", EVFILT_READ, &file_filtops },
137 { "EVFILT_WRITE", EVFILT_WRITE, &file_filtops },
138 { "EVFILT_AIO", EVFILT_AIO, NULL },
139 { "EVFILT_VNODE", EVFILT_VNODE, &file_filtops },
140 { "EVFILT_PROC", EVFILT_PROC, &proc_filtops },
141 { "EVFILT_SIGNAL", EVFILT_SIGNAL, &sig_filtops },
142 { "EVFILT_TIMER", EVFILT_TIMER, &timer_filtops },
143 { NULL, 0, NULL }, /* end of list */
144 };
145
146 /* User defined kfilters */
147 static struct kfilter *user_kfilters; /* array */
148 static int user_kfilterc; /* current offset */
149 static int user_kfiltermaxc; /* max size so far */
150
151 /*
152 * kqueue_init:
153 *
154 * Initialize the kqueue/knote facility.
155 */
156 void
157 kqueue_init(void)
158 {
159
160 pool_init(&kqueue_pool, sizeof(struct kqueue), 0, 0, 0, "kqueuepl",
161 NULL);
162 pool_init(&knote_pool, sizeof(struct knote), 0, 0, 0, "knotepl",
163 NULL);
164 }
165
166 /*
167 * Find kfilter entry by name, or NULL if not found.
168 */
169 static const struct kfilter *
170 kfilter_byname_sys(const char *name)
171 {
172 int i;
173
174 for (i = 0; sys_kfilters[i].name != NULL; i++) {
175 if (strcmp(name, sys_kfilters[i].name) == 0)
176 return (&sys_kfilters[i]);
177 }
178 return (NULL);
179 }
180
181 static struct kfilter *
182 kfilter_byname_user(const char *name)
183 {
184 int i;
185
186 /* user_kfilters[] could be NULL if no filters were registered */
187 if (!user_kfilters)
188 return (NULL);
189
190 for (i = 0; user_kfilters[i].name != NULL; i++) {
191 if (user_kfilters[i].name != '\0' &&
192 strcmp(name, user_kfilters[i].name) == 0)
193 return (&user_kfilters[i]);
194 }
195 return (NULL);
196 }
197
198 static const struct kfilter *
199 kfilter_byname(const char *name)
200 {
201 const struct kfilter *kfilter;
202
203 if ((kfilter = kfilter_byname_sys(name)) != NULL)
204 return (kfilter);
205
206 return (kfilter_byname_user(name));
207 }
208
209 /*
210 * Find kfilter entry by filter id, or NULL if not found.
211 * Assumes entries are indexed in filter id order, for speed.
212 */
213 static const struct kfilter *
214 kfilter_byfilter(uint32_t filter)
215 {
216 const struct kfilter *kfilter;
217
218 if (filter < EVFILT_SYSCOUNT) /* it's a system filter */
219 kfilter = &sys_kfilters[filter];
220 else if (user_kfilters != NULL &&
221 filter < EVFILT_SYSCOUNT + user_kfilterc)
222 /* it's a user filter */
223 kfilter = &user_kfilters[filter - EVFILT_SYSCOUNT];
224 else
225 return (NULL); /* out of range */
226 KASSERT(kfilter->filter == filter); /* sanity check! */
227 return (kfilter);
228 }
229
230 /*
231 * Register a new kfilter. Stores the entry in user_kfilters.
232 * Returns 0 if operation succeeded, or an appropriate errno(2) otherwise.
233 * If retfilter != NULL, the new filterid is returned in it.
234 */
235 int
236 kfilter_register(const char *name, const struct filterops *filtops,
237 int *retfilter)
238 {
239 struct kfilter *kfilter;
240 void *space;
241 int len;
242
243 if (name == NULL || name[0] == '\0' || filtops == NULL)
244 return (EINVAL); /* invalid args */
245 if (kfilter_byname(name) != NULL)
246 return (EEXIST); /* already exists */
247 if (user_kfilterc > 0xffffffff - EVFILT_SYSCOUNT)
248 return (EINVAL); /* too many */
249
250 /* check if need to grow user_kfilters */
251 if (user_kfilterc + 1 > user_kfiltermaxc) {
252 /*
253 * Grow in KFILTER_EXTENT chunks. Use malloc(9), because we
254 * want to traverse user_kfilters as an array.
255 */
256 user_kfiltermaxc += KFILTER_EXTENT;
257 kfilter = malloc(user_kfiltermaxc * sizeof(struct filter *),
258 M_KEVENT, M_WAITOK);
259
260 /* copy existing user_kfilters */
261 if (user_kfilters != NULL)
262 memcpy((caddr_t)kfilter, (caddr_t)user_kfilters,
263 user_kfilterc * sizeof(struct kfilter *));
264 /* zero new sections */
265 memset((caddr_t)kfilter +
266 user_kfilterc * sizeof(struct kfilter *), 0,
267 (user_kfiltermaxc - user_kfilterc) *
268 sizeof(struct kfilter *));
269 /* switch to new kfilter */
270 if (user_kfilters != NULL)
271 free(user_kfilters, M_KEVENT);
272 user_kfilters = kfilter;
273 }
274 len = strlen(name) + 1; /* copy name */
275 space = malloc(len, M_KEVENT, M_WAITOK);
276 memcpy(space, name, len);
277 user_kfilters[user_kfilterc].name = space;
278
279 user_kfilters[user_kfilterc].filter = user_kfilterc + EVFILT_SYSCOUNT;
280
281 len = sizeof(struct filterops); /* copy filtops */
282 space = malloc(len, M_KEVENT, M_WAITOK);
283 memcpy(space, filtops, len);
284 user_kfilters[user_kfilterc].filtops = space;
285
286 if (retfilter != NULL)
287 *retfilter = user_kfilters[user_kfilterc].filter;
288 user_kfilterc++; /* finally, increment count */
289 return (0);
290 }
291
292 /*
293 * Unregister a kfilter previously registered with kfilter_register.
294 * This retains the filter id, but clears the name and frees filtops (filter
295 * operations), so that the number isn't reused during a boot.
296 * Returns 0 if operation succeeded, or an appropriate errno(2) otherwise.
297 */
298 int
299 kfilter_unregister(const char *name)
300 {
301 struct kfilter *kfilter;
302
303 if (name == NULL || name[0] == '\0')
304 return (EINVAL); /* invalid name */
305
306 if (kfilter_byname_sys(name) != NULL)
307 return (EINVAL); /* can't detach system filters */
308
309 kfilter = kfilter_byname_user(name);
310 if (kfilter == NULL) /* not found */
311 return (ENOENT);
312
313 if (kfilter->name[0] != '\0') {
314 /* XXX Cast away const (but we know it's safe. */
315 free((void *) kfilter->name, M_KEVENT);
316 kfilter->name = ""; /* mark as `not implemented' */
317 }
318 if (kfilter->filtops != NULL) {
319 /* XXX Cast away const (but we know it's safe. */
320 free((void *) kfilter->filtops, M_KEVENT);
321 kfilter->filtops = NULL; /* mark as `not implemented' */
322 }
323 return (0);
324 }
325
326
327 /*
328 * Filter attach method for EVFILT_READ and EVFILT_WRITE on normal file
329 * descriptors. Calls struct fileops kqfilter method for given file descriptor.
330 */
331 static int
332 filt_fileattach(struct knote *kn)
333 {
334 struct file *fp;
335
336 fp = kn->kn_fp;
337 return ((*fp->f_ops->fo_kqfilter)(fp, kn));
338 }
339
340 /*
341 * Filter detach method for EVFILT_READ on kqueue descriptor.
342 */
343 static void
344 filt_kqdetach(struct knote *kn)
345 {
346 struct kqueue *kq;
347
348 kq = (struct kqueue *)kn->kn_fp->f_data;
349 SLIST_REMOVE(&kq->kq_sel.sel_klist, kn, knote, kn_selnext);
350 }
351
352 /*
353 * Filter event method for EVFILT_READ on kqueue descriptor.
354 */
355 /*ARGSUSED*/
356 static int
357 filt_kqueue(struct knote *kn, long hint)
358 {
359 struct kqueue *kq;
360
361 kq = (struct kqueue *)kn->kn_fp->f_data;
362 kn->kn_data = kq->kq_count;
363 return (kn->kn_data > 0);
364 }
365
366 /*
367 * Filter attach method for EVFILT_PROC.
368 */
369 static int
370 filt_procattach(struct knote *kn)
371 {
372 struct proc *p;
373
374 p = pfind(kn->kn_id);
375 if (p == NULL)
376 return (ESRCH);
377
378 /*
379 * Fail if it's not owned by you, or the last exec gave us
380 * setuid/setgid privs (unless you're root).
381 */
382 if ((p->p_cred->p_ruid != curproc->p_cred->p_ruid ||
383 (p->p_flag & P_SUGID))
384 && suser(curproc->p_ucred, &curproc->p_acflag) != 0)
385 return (EACCES);
386
387 kn->kn_ptr.p_proc = p;
388 kn->kn_flags |= EV_CLEAR; /* automatically set */
389
390 /*
391 * internal flag indicating registration done by kernel
392 */
393 if (kn->kn_flags & EV_FLAG1) {
394 kn->kn_data = kn->kn_sdata; /* ppid */
395 kn->kn_fflags = NOTE_CHILD;
396 kn->kn_flags &= ~EV_FLAG1;
397 }
398
399 /* XXXSMP lock the process? */
400 SLIST_INSERT_HEAD(&p->p_klist, kn, kn_selnext);
401
402 return (0);
403 }
404
405 /*
406 * Filter detach method for EVFILT_PROC.
407 *
408 * The knote may be attached to a different process, which may exit,
409 * leaving nothing for the knote to be attached to. So when the process
410 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
411 * it will be deleted when read out. However, as part of the knote deletion,
412 * this routine is called, so a check is needed to avoid actually performing
413 * a detach, because the original process might not exist any more.
414 */
415 static void
416 filt_procdetach(struct knote *kn)
417 {
418 struct proc *p;
419
420 if (kn->kn_status & KN_DETACHED)
421 return;
422
423 p = kn->kn_ptr.p_proc;
424 KASSERT(p->p_stat == SDEAD || pfind(kn->kn_id) == p);
425
426 /* XXXSMP lock the process? */
427 SLIST_REMOVE(&p->p_klist, kn, knote, kn_selnext);
428 }
429
430 /*
431 * Filter event method for EVFILT_PROC.
432 */
433 static int
434 filt_proc(struct knote *kn, long hint)
435 {
436 u_int event;
437
438 /*
439 * mask off extra data
440 */
441 event = (u_int)hint & NOTE_PCTRLMASK;
442
443 /*
444 * if the user is interested in this event, record it.
445 */
446 if (kn->kn_sfflags & event)
447 kn->kn_fflags |= event;
448
449 /*
450 * process is gone, so flag the event as finished.
451 */
452 if (event == NOTE_EXIT) {
453 /*
454 * Detach the knote from watched process and mark
455 * it as such. We can't leave this to kqueue_scan(),
456 * since the process might not exist by then. And we
457 * have to do this now, since psignal KNOTE() is called
458 * also for zombies and we might end up reading freed
459 * memory if the kevent would already be picked up
460 * and knote g/c'ed.
461 */
462 kn->kn_fop->f_detach(kn);
463 kn->kn_status |= KN_DETACHED;
464
465 /* Mark as ONESHOT, so that the knote it g/c'ed when read */
466 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
467 return (1);
468 }
469
470 /*
471 * process forked, and user wants to track the new process,
472 * so attach a new knote to it, and immediately report an
473 * event with the parent's pid.
474 */
475 if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
476 struct kevent kev;
477 int error;
478
479 /*
480 * register knote with new process.
481 */
482 kev.ident = hint & NOTE_PDATAMASK; /* pid */
483 kev.filter = kn->kn_filter;
484 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
485 kev.fflags = kn->kn_sfflags;
486 kev.data = kn->kn_id; /* parent */
487 kev.udata = kn->kn_kevent.udata; /* preserve udata */
488 error = kqueue_register(kn->kn_kq, &kev, NULL);
489 if (error)
490 kn->kn_fflags |= NOTE_TRACKERR;
491 }
492
493 return (kn->kn_fflags != 0);
494 }
495
496 static void
497 filt_timerexpire(void *knx)
498 {
499 struct knote *kn = knx;
500 int tticks;
501
502 kn->kn_data++;
503 KNOTE_ACTIVATE(kn);
504
505 if ((kn->kn_flags & EV_ONESHOT) == 0) {
506 tticks = mstohz(kn->kn_sdata);
507 callout_schedule((struct callout *)kn->kn_hook, tticks);
508 }
509 }
510
511 /*
512 * data contains amount of time to sleep, in milliseconds
513 */
514 static int
515 filt_timerattach(struct knote *kn)
516 {
517 struct callout *calloutp;
518 int tticks;
519
520 if (kq_ncallouts >= kq_calloutmax)
521 return (ENOMEM);
522 kq_ncallouts++;
523
524 tticks = mstohz(kn->kn_sdata);
525
526 /* if the supplied value is under our resolution, use 1 tick */
527 if (tticks == 0) {
528 if (kn->kn_sdata == 0)
529 return (EINVAL);
530 tticks = 1;
531 }
532
533 kn->kn_flags |= EV_CLEAR; /* automatically set */
534 MALLOC(calloutp, struct callout *, sizeof(*calloutp),
535 M_KEVENT, 0);
536 callout_init(calloutp);
537 callout_reset(calloutp, tticks, filt_timerexpire, kn);
538 kn->kn_hook = calloutp;
539
540 return (0);
541 }
542
543 static void
544 filt_timerdetach(struct knote *kn)
545 {
546 struct callout *calloutp;
547
548 calloutp = (struct callout *)kn->kn_hook;
549 callout_stop(calloutp);
550 FREE(calloutp, M_KEVENT);
551 kq_ncallouts--;
552 }
553
554 static int
555 filt_timer(struct knote *kn, long hint)
556 {
557 return (kn->kn_data != 0);
558 }
559
560 /*
561 * filt_seltrue:
562 *
563 * This filter "event" routine simulates seltrue().
564 */
565 int
566 filt_seltrue(struct knote *kn, long hint)
567 {
568
569 /*
570 * We don't know how much data can be read/written,
571 * but we know that it *can* be. This is about as
572 * good as select/poll does as well.
573 */
574 kn->kn_data = 0;
575 return (1);
576 }
577
578 /*
579 * This provides full kqfilter entry for device switch tables, which
580 * has same effect as filter using filt_seltrue() as filter method.
581 */
582 static void
583 filt_seltruedetach(struct knote *kn)
584 {
585 /* Nothing to do */
586 }
587
588 static const struct filterops seltrue_filtops =
589 { 1, NULL, filt_seltruedetach, filt_seltrue };
590
591 int
592 seltrue_kqfilter(dev_t dev, struct knote *kn)
593 {
594 switch (kn->kn_filter) {
595 case EVFILT_READ:
596 case EVFILT_WRITE:
597 kn->kn_fop = &seltrue_filtops;
598 break;
599 default:
600 return (1);
601 }
602
603 /* Nothing more to do */
604 return (0);
605 }
606
607 /*
608 * kqueue(2) system call.
609 */
610 int
611 sys_kqueue(struct lwp *l, void *v, register_t *retval)
612 {
613 struct filedesc *fdp;
614 struct kqueue *kq;
615 struct file *fp;
616 struct proc *p;
617 int fd, error;
618
619 p = l->l_proc;
620 fdp = p->p_fd;
621 error = falloc(p, &fp, &fd); /* setup a new file descriptor */
622 if (error)
623 return (error);
624 fp->f_flag = FREAD | FWRITE;
625 fp->f_type = DTYPE_KQUEUE;
626 fp->f_ops = &kqueueops;
627 kq = pool_get(&kqueue_pool, PR_WAITOK);
628 memset((char *)kq, 0, sizeof(struct kqueue));
629 TAILQ_INIT(&kq->kq_head);
630 fp->f_data = (caddr_t)kq; /* store the kqueue with the fp */
631 *retval = fd;
632 if (fdp->fd_knlistsize < 0)
633 fdp->fd_knlistsize = 0; /* this process has a kq */
634 kq->kq_fdp = fdp;
635 FILE_SET_MATURE(fp);
636 FILE_UNUSE(fp, p); /* falloc() does FILE_USE() */
637 return (error);
638 }
639
640 /*
641 * kevent(2) system call.
642 */
643 int
644 sys_kevent(struct lwp *l, void *v, register_t *retval)
645 {
646 struct sys_kevent_args /* {
647 syscallarg(int) fd;
648 syscallarg(const struct kevent *) changelist;
649 syscallarg(size_t) nchanges;
650 syscallarg(struct kevent *) eventlist;
651 syscallarg(size_t) nevents;
652 syscallarg(const struct timespec *) timeout;
653 } */ *uap = v;
654 struct kevent *kevp;
655 struct kqueue *kq;
656 struct file *fp;
657 struct timespec ts;
658 struct proc *p;
659 size_t i, n;
660 int nerrors, error;
661
662 p = l->l_proc;
663 /* check that we're dealing with a kq */
664 fp = fd_getfile(p->p_fd, SCARG(uap, fd));
665 if (!fp || fp->f_type != DTYPE_KQUEUE)
666 return (EBADF);
667
668 FILE_USE(fp);
669
670 if (SCARG(uap, timeout) != NULL) {
671 error = copyin(SCARG(uap, timeout), &ts, sizeof(ts));
672 if (error)
673 goto done;
674 SCARG(uap, timeout) = &ts;
675 }
676
677 kq = (struct kqueue *)fp->f_data;
678 nerrors = 0;
679
680 /* traverse list of events to register */
681 while (SCARG(uap, nchanges) > 0) {
682 /* copyin a maximum of KQ_EVENTS at each pass */
683 n = MIN(SCARG(uap, nchanges), KQ_NEVENTS);
684 error = copyin(SCARG(uap, changelist), kq->kq_kev,
685 n * sizeof(struct kevent));
686 if (error)
687 goto done;
688 for (i = 0; i < n; i++) {
689 kevp = &kq->kq_kev[i];
690 kevp->flags &= ~EV_SYSFLAGS;
691 /* register each knote */
692 error = kqueue_register(kq, kevp, p);
693 if (error) {
694 if (SCARG(uap, nevents) != 0) {
695 kevp->flags = EV_ERROR;
696 kevp->data = error;
697 error = copyout((caddr_t)kevp,
698 (caddr_t)SCARG(uap, eventlist),
699 sizeof(*kevp));
700 if (error)
701 goto done;
702 SCARG(uap, eventlist)++;
703 SCARG(uap, nevents)--;
704 nerrors++;
705 } else {
706 goto done;
707 }
708 }
709 }
710 SCARG(uap, nchanges) -= n; /* update the results */
711 SCARG(uap, changelist) += n;
712 }
713 if (nerrors) {
714 *retval = nerrors;
715 error = 0;
716 goto done;
717 }
718
719 /* actually scan through the events */
720 error = kqueue_scan(fp, SCARG(uap, nevents), SCARG(uap, eventlist),
721 SCARG(uap, timeout), p, retval);
722 done:
723 FILE_UNUSE(fp, p);
724 return (error);
725 }
726
727 /*
728 * Register a given kevent kev onto the kqueue
729 */
730 int
731 kqueue_register(struct kqueue *kq, struct kevent *kev, struct proc *p)
732 {
733 const struct kfilter *kfilter;
734 struct filedesc *fdp;
735 struct file *fp;
736 struct knote *kn;
737 int s, error;
738
739 fdp = kq->kq_fdp;
740 fp = NULL;
741 kn = NULL;
742 error = 0;
743 kfilter = kfilter_byfilter(kev->filter);
744 if (kfilter == NULL || kfilter->filtops == NULL) {
745 /* filter not found nor implemented */
746 return (EINVAL);
747 }
748
749 /* search if knote already exists */
750 if (kfilter->filtops->f_isfd) {
751 /* monitoring a file descriptor */
752 if ((fp = fd_getfile(fdp, kev->ident)) == NULL)
753 return (EBADF); /* validate descriptor */
754 FILE_USE(fp);
755
756 if (kev->ident < fdp->fd_knlistsize) {
757 SLIST_FOREACH(kn, &fdp->fd_knlist[kev->ident], kn_link)
758 if (kq == kn->kn_kq &&
759 kev->filter == kn->kn_filter)
760 break;
761 }
762 } else {
763 /*
764 * not monitoring a file descriptor, so
765 * lookup knotes in internal hash table
766 */
767 if (fdp->fd_knhashmask != 0) {
768 struct klist *list;
769
770 list = &fdp->fd_knhash[
771 KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
772 SLIST_FOREACH(kn, list, kn_link)
773 if (kev->ident == kn->kn_id &&
774 kq == kn->kn_kq &&
775 kev->filter == kn->kn_filter)
776 break;
777 }
778 }
779
780 if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
781 error = ENOENT; /* filter not found */
782 goto done;
783 }
784
785 /*
786 * kn now contains the matching knote, or NULL if no match
787 */
788 if (kev->flags & EV_ADD) {
789 /* add knote */
790
791 if (kn == NULL) {
792 /* create new knote */
793 kn = pool_get(&knote_pool, PR_WAITOK);
794 if (kn == NULL) {
795 error = ENOMEM;
796 goto done;
797 }
798 kn->kn_fp = fp;
799 kn->kn_kq = kq;
800 kn->kn_fop = kfilter->filtops;
801
802 /*
803 * apply reference count to knote structure, and
804 * do not release it at the end of this routine.
805 */
806 fp = NULL;
807
808 kn->kn_sfflags = kev->fflags;
809 kn->kn_sdata = kev->data;
810 kev->fflags = 0;
811 kev->data = 0;
812 kn->kn_kevent = *kev;
813
814 knote_attach(kn, fdp);
815 if ((error = kfilter->filtops->f_attach(kn)) != 0) {
816 knote_drop(kn, p, fdp);
817 goto done;
818 }
819 } else {
820 /* modify existing knote */
821
822 /*
823 * The user may change some filter values after the
824 * initial EV_ADD, but doing so will not reset any
825 * filter which have already been triggered.
826 */
827 kn->kn_sfflags = kev->fflags;
828 kn->kn_sdata = kev->data;
829 kn->kn_kevent.udata = kev->udata;
830 }
831
832 s = splhigh();
833 if (kn->kn_fop->f_event(kn, 0))
834 KNOTE_ACTIVATE(kn);
835 splx(s);
836
837 } else if (kev->flags & EV_DELETE) { /* delete knote */
838 kn->kn_fop->f_detach(kn);
839 knote_drop(kn, p, fdp);
840 goto done;
841 }
842
843 /* disable knote */
844 if ((kev->flags & EV_DISABLE) &&
845 ((kn->kn_status & KN_DISABLED) == 0)) {
846 s = splhigh();
847 kn->kn_status |= KN_DISABLED;
848 splx(s);
849 }
850
851 /* enable knote */
852 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
853 s = splhigh();
854 kn->kn_status &= ~KN_DISABLED;
855 if ((kn->kn_status & KN_ACTIVE) &&
856 ((kn->kn_status & KN_QUEUED) == 0))
857 knote_enqueue(kn);
858 splx(s);
859 }
860
861 done:
862 if (fp != NULL)
863 FILE_UNUSE(fp, p);
864 return (error);
865 }
866
867 /*
868 * Scan through the list of events on fp (for a maximum of maxevents),
869 * returning the results in to ulistp. Timeout is determined by tsp; if
870 * NULL, wait indefinitely, if 0 valued, perform a poll, otherwise wait
871 * as appropriate.
872 */
873 static int
874 kqueue_scan(struct file *fp, size_t maxevents, struct kevent *ulistp,
875 const struct timespec *tsp, struct proc *p, register_t *retval)
876 {
877 struct kqueue *kq;
878 struct kevent *kevp;
879 struct timeval atv;
880 struct knote *kn, marker;
881 size_t count, nkev;
882 int s, timeout, error;
883
884 kq = (struct kqueue *)fp->f_data;
885 count = maxevents;
886 nkev = error = 0;
887 if (count == 0)
888 goto done;
889
890 if (tsp) { /* timeout supplied */
891 TIMESPEC_TO_TIMEVAL(&atv, tsp);
892 if (itimerfix(&atv)) {
893 error = EINVAL;
894 goto done;
895 }
896 s = splclock();
897 timeradd(&atv, &time, &atv); /* calc. time to wait until */
898 splx(s);
899 timeout = hzto(&atv);
900 if (timeout <= 0)
901 timeout = -1; /* do poll */
902 } else {
903 /* no timeout, wait forever */
904 timeout = 0;
905 }
906 goto start;
907
908 retry:
909 if (tsp) {
910 /*
911 * We have to recalculate the timeout on every retry.
912 */
913 timeout = hzto(&atv);
914 if (timeout <= 0)
915 goto done;
916 }
917
918 start:
919 kevp = kq->kq_kev;
920 s = splhigh();
921 if (kq->kq_count == 0) {
922 if (timeout < 0) {
923 error = EWOULDBLOCK;
924 } else {
925 kq->kq_state |= KQ_SLEEP;
926 error = tsleep(kq, PSOCK | PCATCH, "kqread", timeout);
927 }
928 splx(s);
929 if (error == 0)
930 goto retry;
931 /* don't restart after signals... */
932 if (error == ERESTART)
933 error = EINTR;
934 else if (error == EWOULDBLOCK)
935 error = 0;
936 goto done;
937 }
938
939 /* mark end of knote list */
940 TAILQ_INSERT_TAIL(&kq->kq_head, &marker, kn_tqe);
941
942 while (count) { /* while user wants data ... */
943 kn = TAILQ_FIRST(&kq->kq_head); /* get next knote */
944 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
945 if (kn == &marker) { /* if it's our marker, stop */
946 splx(s);
947 if (count == maxevents)
948 goto retry;
949 goto done;
950 }
951 if (kn->kn_status & KN_DISABLED) {
952 /* don't want disabled events */
953 kn->kn_status &= ~KN_QUEUED;
954 kq->kq_count--;
955 continue;
956 }
957 if ((kn->kn_flags & EV_ONESHOT) == 0 &&
958 kn->kn_fop->f_event(kn, 0) == 0) {
959 /*
960 * non-ONESHOT event that hasn't
961 * triggered again, so de-queue.
962 */
963 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
964 kq->kq_count--;
965 continue;
966 }
967 *kevp = kn->kn_kevent;
968 kevp++;
969 nkev++;
970 if (kn->kn_flags & EV_ONESHOT) {
971 /* delete ONESHOT events after retrieval */
972 kn->kn_status &= ~KN_QUEUED;
973 kq->kq_count--;
974 splx(s);
975 kn->kn_fop->f_detach(kn);
976 knote_drop(kn, p, p->p_fd);
977 s = splhigh();
978 } else if (kn->kn_flags & EV_CLEAR) {
979 /* clear state after retrieval */
980 kn->kn_data = 0;
981 kn->kn_fflags = 0;
982 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
983 kq->kq_count--;
984 } else {
985 /* add event back on list */
986 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
987 }
988 count--;
989 if (nkev == KQ_NEVENTS) {
990 /* do copyouts in KQ_NEVENTS chunks */
991 splx(s);
992 error = copyout((caddr_t)&kq->kq_kev, (caddr_t)ulistp,
993 sizeof(struct kevent) * nkev);
994 ulistp += nkev;
995 nkev = 0;
996 kevp = kq->kq_kev;
997 s = splhigh();
998 if (error)
999 break;
1000 }
1001 }
1002
1003 /* remove marker */
1004 TAILQ_REMOVE(&kq->kq_head, &marker, kn_tqe);
1005 splx(s);
1006 done:
1007 if (nkev != 0) {
1008 /* copyout remaining events */
1009 error = copyout((caddr_t)&kq->kq_kev, (caddr_t)ulistp,
1010 sizeof(struct kevent) * nkev);
1011 }
1012 *retval = maxevents - count;
1013
1014 return (error);
1015 }
1016
1017 /*
1018 * struct fileops read method for a kqueue descriptor.
1019 * Not implemented.
1020 * XXX: This could be expanded to call kqueue_scan, if desired.
1021 */
1022 /*ARGSUSED*/
1023 static int
1024 kqueue_read(struct file *fp, off_t *offset, struct uio *uio,
1025 struct ucred *cred, int flags)
1026 {
1027
1028 return (ENXIO);
1029 }
1030
1031 /*
1032 * struct fileops write method for a kqueue descriptor.
1033 * Not implemented.
1034 */
1035 /*ARGSUSED*/
1036 static int
1037 kqueue_write(struct file *fp, off_t *offset, struct uio *uio,
1038 struct ucred *cred, int flags)
1039 {
1040
1041 return (ENXIO);
1042 }
1043
1044 /*
1045 * struct fileops ioctl method for a kqueue descriptor.
1046 *
1047 * Two ioctls are currently supported. They both use struct kfilter_mapping:
1048 * KFILTER_BYNAME find name for filter, and return result in
1049 * name, which is of size len.
1050 * KFILTER_BYFILTER find filter for name. len is ignored.
1051 */
1052 /*ARGSUSED*/
1053 static int
1054 kqueue_ioctl(struct file *fp, u_long com, caddr_t data, struct proc *p)
1055 {
1056 struct kfilter_mapping *km;
1057 const struct kfilter *kfilter;
1058 char *name;
1059 int error;
1060
1061 km = (struct kfilter_mapping *)data;
1062 error = 0;
1063
1064 switch (com) {
1065 case KFILTER_BYFILTER: /* convert filter -> name */
1066 kfilter = kfilter_byfilter(km->filter);
1067 if (kfilter != NULL)
1068 error = copyoutstr(kfilter->name, km->name, km->len,
1069 NULL);
1070 else
1071 error = ENOENT;
1072 break;
1073
1074 case KFILTER_BYNAME: /* convert name -> filter */
1075 MALLOC(name, char *, KFILTER_MAXNAME, M_KEVENT, M_WAITOK);
1076 error = copyinstr(km->name, name, KFILTER_MAXNAME, NULL);
1077 if (error) {
1078 FREE(name, M_KEVENT);
1079 break;
1080 }
1081 kfilter = kfilter_byname(name);
1082 if (kfilter != NULL)
1083 km->filter = kfilter->filter;
1084 else
1085 error = ENOENT;
1086 FREE(name, M_KEVENT);
1087 break;
1088
1089 default:
1090 error = ENOTTY;
1091
1092 }
1093 return (error);
1094 }
1095
1096 /*
1097 * struct fileops fcntl method for a kqueue descriptor.
1098 * Not implemented.
1099 */
1100 /*ARGSUSED*/
1101 static int
1102 kqueue_fcntl(struct file *fp, u_int com, caddr_t data, struct proc *p)
1103 {
1104
1105 return (ENOTTY);
1106 }
1107
1108 /*
1109 * struct fileops poll method for a kqueue descriptor.
1110 * Determine if kqueue has events pending.
1111 */
1112 static int
1113 kqueue_poll(struct file *fp, int events, struct proc *p)
1114 {
1115 struct kqueue *kq;
1116 int revents;
1117
1118 kq = (struct kqueue *)fp->f_data;
1119 revents = 0;
1120 if (events & (POLLIN | POLLRDNORM)) {
1121 if (kq->kq_count) {
1122 revents |= events & (POLLIN | POLLRDNORM);
1123 } else {
1124 selrecord(p, &kq->kq_sel);
1125 }
1126 }
1127 return (revents);
1128 }
1129
1130 /*
1131 * struct fileops stat method for a kqueue descriptor.
1132 * Returns dummy info, with st_size being number of events pending.
1133 */
1134 static int
1135 kqueue_stat(struct file *fp, struct stat *st, struct proc *p)
1136 {
1137 struct kqueue *kq;
1138
1139 kq = (struct kqueue *)fp->f_data;
1140 memset((void *)st, 0, sizeof(*st));
1141 st->st_size = kq->kq_count;
1142 st->st_blksize = sizeof(struct kevent);
1143 st->st_mode = S_IFIFO;
1144 return (0);
1145 }
1146
1147 /*
1148 * struct fileops close method for a kqueue descriptor.
1149 * Cleans up kqueue.
1150 */
1151 static int
1152 kqueue_close(struct file *fp, struct proc *p)
1153 {
1154 struct kqueue *kq;
1155 struct filedesc *fdp;
1156 struct knote **knp, *kn, *kn0;
1157 int i;
1158
1159 kq = (struct kqueue *)fp->f_data;
1160 fdp = p->p_fd;
1161 for (i = 0; i < fdp->fd_knlistsize; i++) {
1162 knp = &SLIST_FIRST(&fdp->fd_knlist[i]);
1163 kn = *knp;
1164 while (kn != NULL) {
1165 kn0 = SLIST_NEXT(kn, kn_link);
1166 if (kq == kn->kn_kq) {
1167 kn->kn_fop->f_detach(kn);
1168 FILE_UNUSE(kn->kn_fp, p);
1169 pool_put(&knote_pool, kn);
1170 *knp = kn0;
1171 } else {
1172 knp = &SLIST_NEXT(kn, kn_link);
1173 }
1174 kn = kn0;
1175 }
1176 }
1177 if (fdp->fd_knhashmask != 0) {
1178 for (i = 0; i < fdp->fd_knhashmask + 1; i++) {
1179 knp = &SLIST_FIRST(&fdp->fd_knhash[i]);
1180 kn = *knp;
1181 while (kn != NULL) {
1182 kn0 = SLIST_NEXT(kn, kn_link);
1183 if (kq == kn->kn_kq) {
1184 kn->kn_fop->f_detach(kn);
1185 /* XXX non-fd release of kn->kn_ptr */
1186 pool_put(&knote_pool, kn);
1187 *knp = kn0;
1188 } else {
1189 knp = &SLIST_NEXT(kn, kn_link);
1190 }
1191 kn = kn0;
1192 }
1193 }
1194 }
1195 pool_put(&kqueue_pool, kq);
1196 fp->f_data = NULL;
1197
1198 return (0);
1199 }
1200
1201 /*
1202 * wakeup a kqueue
1203 */
1204 static void
1205 kqueue_wakeup(struct kqueue *kq)
1206 {
1207
1208 if (kq->kq_state & KQ_SLEEP) { /* if currently sleeping ... */
1209 kq->kq_state &= ~KQ_SLEEP;
1210 wakeup(kq); /* ... wakeup */
1211 }
1212
1213 /* Notify select/poll and kevent. */
1214 selnotify(&kq->kq_sel, 0);
1215 }
1216
1217 /*
1218 * struct fileops kqfilter method for a kqueue descriptor.
1219 * Event triggered when monitored kqueue changes.
1220 */
1221 /*ARGSUSED*/
1222 static int
1223 kqueue_kqfilter(struct file *fp, struct knote *kn)
1224 {
1225 struct kqueue *kq;
1226
1227 KASSERT(fp == kn->kn_fp);
1228 kq = (struct kqueue *)kn->kn_fp->f_data;
1229 if (kn->kn_filter != EVFILT_READ)
1230 return (1);
1231 kn->kn_fop = &kqread_filtops;
1232 SLIST_INSERT_HEAD(&kq->kq_sel.sel_klist, kn, kn_selnext);
1233 return (0);
1234 }
1235
1236
1237 /*
1238 * Walk down a list of knotes, activating them if their event has triggered.
1239 */
1240 void
1241 knote(struct klist *list, long hint)
1242 {
1243 struct knote *kn;
1244
1245 SLIST_FOREACH(kn, list, kn_selnext)
1246 if (kn->kn_fop->f_event(kn, hint))
1247 KNOTE_ACTIVATE(kn);
1248 }
1249
1250 /*
1251 * Remove all knotes from a specified klist
1252 */
1253 void
1254 knote_remove(struct proc *p, struct klist *list)
1255 {
1256 struct knote *kn;
1257
1258 while ((kn = SLIST_FIRST(list)) != NULL) {
1259 kn->kn_fop->f_detach(kn);
1260 knote_drop(kn, p, p->p_fd);
1261 }
1262 }
1263
1264 /*
1265 * Remove all knotes referencing a specified fd
1266 */
1267 void
1268 knote_fdclose(struct proc *p, int fd)
1269 {
1270 struct filedesc *fdp;
1271 struct klist *list;
1272
1273 fdp = p->p_fd;
1274 list = &fdp->fd_knlist[fd];
1275 knote_remove(p, list);
1276 }
1277
1278 /*
1279 * Attach a new knote to a file descriptor
1280 */
1281 static void
1282 knote_attach(struct knote *kn, struct filedesc *fdp)
1283 {
1284 struct klist *list;
1285 int size;
1286
1287 if (! kn->kn_fop->f_isfd) {
1288 /* if knote is not on an fd, store on internal hash table */
1289 if (fdp->fd_knhashmask == 0)
1290 fdp->fd_knhash = hashinit(KN_HASHSIZE, HASH_LIST,
1291 M_KEVENT, M_WAITOK, &fdp->fd_knhashmask);
1292 list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
1293 goto done;
1294 }
1295
1296 /*
1297 * otherwise, knote is on an fd.
1298 * knotes are stored in fd_knlist indexed by kn->kn_id.
1299 */
1300 if (fdp->fd_knlistsize <= kn->kn_id) {
1301 /* expand list, it's too small */
1302 size = fdp->fd_knlistsize;
1303 while (size <= kn->kn_id) {
1304 /* grow in KQ_EXTENT chunks */
1305 size += KQ_EXTENT;
1306 }
1307 list = malloc(size * sizeof(struct klist *), M_KEVENT,M_WAITOK);
1308 if (fdp->fd_knlist) {
1309 /* copy existing knlist */
1310 memcpy((caddr_t)list, (caddr_t)fdp->fd_knlist,
1311 fdp->fd_knlistsize * sizeof(struct klist *));
1312 }
1313 /*
1314 * Zero new memory. Stylistically, SLIST_INIT() should be
1315 * used here, but that does same thing as the memset() anyway.
1316 */
1317 memset(&list[fdp->fd_knlistsize], 0,
1318 (size - fdp->fd_knlistsize) * sizeof(struct klist *));
1319
1320 /* switch to new knlist */
1321 if (fdp->fd_knlist != NULL)
1322 free(fdp->fd_knlist, M_KEVENT);
1323 fdp->fd_knlistsize = size;
1324 fdp->fd_knlist = list;
1325 }
1326
1327 /* get list head for this fd */
1328 list = &fdp->fd_knlist[kn->kn_id];
1329 done:
1330 /* add new knote */
1331 SLIST_INSERT_HEAD(list, kn, kn_link);
1332 kn->kn_status = 0;
1333 }
1334
1335 /*
1336 * Drop knote.
1337 * Should be called at spl == 0, since we don't want to hold spl
1338 * while calling FILE_UNUSE and free.
1339 */
1340 static void
1341 knote_drop(struct knote *kn, struct proc *p, struct filedesc *fdp)
1342 {
1343 struct klist *list;
1344
1345 if (kn->kn_fop->f_isfd)
1346 list = &fdp->fd_knlist[kn->kn_id];
1347 else
1348 list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
1349
1350 SLIST_REMOVE(list, kn, knote, kn_link);
1351 if (kn->kn_status & KN_QUEUED)
1352 knote_dequeue(kn);
1353 if (kn->kn_fop->f_isfd)
1354 FILE_UNUSE(kn->kn_fp, p);
1355 pool_put(&knote_pool, kn);
1356 }
1357
1358
1359 /*
1360 * Queue new event for knote.
1361 */
1362 static void
1363 knote_enqueue(struct knote *kn)
1364 {
1365 struct kqueue *kq;
1366 int s;
1367
1368 kq = kn->kn_kq;
1369 s = splhigh();
1370 KASSERT((kn->kn_status & KN_QUEUED) == 0);
1371
1372 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1373 kn->kn_status |= KN_QUEUED;
1374 kq->kq_count++;
1375 splx(s);
1376 kqueue_wakeup(kq);
1377 }
1378
1379 /*
1380 * Dequeue event for knote.
1381 */
1382 static void
1383 knote_dequeue(struct knote *kn)
1384 {
1385 struct kqueue *kq;
1386 int s;
1387
1388 kq = kn->kn_kq;
1389 s = splhigh();
1390 KASSERT(kn->kn_status & KN_QUEUED);
1391
1392 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1393 kn->kn_status &= ~KN_QUEUED;
1394 kq->kq_count--;
1395 splx(s);
1396 }
1397