kern_event.c revision 1.11 1 /* $NetBSD: kern_event.c,v 1.11 2003/02/23 21:44:26 pk 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 == NULL)
666 return (EBADF);
667
668 if (fp->f_type != DTYPE_KQUEUE) {
669 simple_unlock(&fp->f_slock);
670 return (EBADF);
671 }
672
673 FILE_USE(fp);
674
675 if (SCARG(uap, timeout) != NULL) {
676 error = copyin(SCARG(uap, timeout), &ts, sizeof(ts));
677 if (error)
678 goto done;
679 SCARG(uap, timeout) = &ts;
680 }
681
682 kq = (struct kqueue *)fp->f_data;
683 nerrors = 0;
684
685 /* traverse list of events to register */
686 while (SCARG(uap, nchanges) > 0) {
687 /* copyin a maximum of KQ_EVENTS at each pass */
688 n = MIN(SCARG(uap, nchanges), KQ_NEVENTS);
689 error = copyin(SCARG(uap, changelist), kq->kq_kev,
690 n * sizeof(struct kevent));
691 if (error)
692 goto done;
693 for (i = 0; i < n; i++) {
694 kevp = &kq->kq_kev[i];
695 kevp->flags &= ~EV_SYSFLAGS;
696 /* register each knote */
697 error = kqueue_register(kq, kevp, p);
698 if (error) {
699 if (SCARG(uap, nevents) != 0) {
700 kevp->flags = EV_ERROR;
701 kevp->data = error;
702 error = copyout((caddr_t)kevp,
703 (caddr_t)SCARG(uap, eventlist),
704 sizeof(*kevp));
705 if (error)
706 goto done;
707 SCARG(uap, eventlist)++;
708 SCARG(uap, nevents)--;
709 nerrors++;
710 } else {
711 goto done;
712 }
713 }
714 }
715 SCARG(uap, nchanges) -= n; /* update the results */
716 SCARG(uap, changelist) += n;
717 }
718 if (nerrors) {
719 *retval = nerrors;
720 error = 0;
721 goto done;
722 }
723
724 /* actually scan through the events */
725 error = kqueue_scan(fp, SCARG(uap, nevents), SCARG(uap, eventlist),
726 SCARG(uap, timeout), p, retval);
727 done:
728 FILE_UNUSE(fp, p);
729 return (error);
730 }
731
732 /*
733 * Register a given kevent kev onto the kqueue
734 */
735 int
736 kqueue_register(struct kqueue *kq, struct kevent *kev, struct proc *p)
737 {
738 const struct kfilter *kfilter;
739 struct filedesc *fdp;
740 struct file *fp;
741 struct knote *kn;
742 int s, error;
743
744 fdp = kq->kq_fdp;
745 fp = NULL;
746 kn = NULL;
747 error = 0;
748 kfilter = kfilter_byfilter(kev->filter);
749 if (kfilter == NULL || kfilter->filtops == NULL) {
750 /* filter not found nor implemented */
751 return (EINVAL);
752 }
753
754 /* search if knote already exists */
755 if (kfilter->filtops->f_isfd) {
756 /* monitoring a file descriptor */
757 if ((fp = fd_getfile(fdp, kev->ident)) == NULL)
758 return (EBADF); /* validate descriptor */
759 FILE_USE(fp);
760
761 if (kev->ident < fdp->fd_knlistsize) {
762 SLIST_FOREACH(kn, &fdp->fd_knlist[kev->ident], kn_link)
763 if (kq == kn->kn_kq &&
764 kev->filter == kn->kn_filter)
765 break;
766 }
767 } else {
768 /*
769 * not monitoring a file descriptor, so
770 * lookup knotes in internal hash table
771 */
772 if (fdp->fd_knhashmask != 0) {
773 struct klist *list;
774
775 list = &fdp->fd_knhash[
776 KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
777 SLIST_FOREACH(kn, list, kn_link)
778 if (kev->ident == kn->kn_id &&
779 kq == kn->kn_kq &&
780 kev->filter == kn->kn_filter)
781 break;
782 }
783 }
784
785 if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
786 error = ENOENT; /* filter not found */
787 goto done;
788 }
789
790 /*
791 * kn now contains the matching knote, or NULL if no match
792 */
793 if (kev->flags & EV_ADD) {
794 /* add knote */
795
796 if (kn == NULL) {
797 /* create new knote */
798 kn = pool_get(&knote_pool, PR_WAITOK);
799 if (kn == NULL) {
800 error = ENOMEM;
801 goto done;
802 }
803 kn->kn_fp = fp;
804 kn->kn_kq = kq;
805 kn->kn_fop = kfilter->filtops;
806
807 /*
808 * apply reference count to knote structure, and
809 * do not release it at the end of this routine.
810 */
811 fp = NULL;
812
813 kn->kn_sfflags = kev->fflags;
814 kn->kn_sdata = kev->data;
815 kev->fflags = 0;
816 kev->data = 0;
817 kn->kn_kevent = *kev;
818
819 knote_attach(kn, fdp);
820 if ((error = kfilter->filtops->f_attach(kn)) != 0) {
821 knote_drop(kn, p, fdp);
822 goto done;
823 }
824 } else {
825 /* modify existing knote */
826
827 /*
828 * The user may change some filter values after the
829 * initial EV_ADD, but doing so will not reset any
830 * filter which have already been triggered.
831 */
832 kn->kn_sfflags = kev->fflags;
833 kn->kn_sdata = kev->data;
834 kn->kn_kevent.udata = kev->udata;
835 }
836
837 s = splsched();
838 if (kn->kn_fop->f_event(kn, 0))
839 KNOTE_ACTIVATE(kn);
840 splx(s);
841
842 } else if (kev->flags & EV_DELETE) { /* delete knote */
843 kn->kn_fop->f_detach(kn);
844 knote_drop(kn, p, fdp);
845 goto done;
846 }
847
848 /* disable knote */
849 if ((kev->flags & EV_DISABLE) &&
850 ((kn->kn_status & KN_DISABLED) == 0)) {
851 s = splsched();
852 kn->kn_status |= KN_DISABLED;
853 splx(s);
854 }
855
856 /* enable knote */
857 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
858 s = splsched();
859 kn->kn_status &= ~KN_DISABLED;
860 if ((kn->kn_status & KN_ACTIVE) &&
861 ((kn->kn_status & KN_QUEUED) == 0))
862 knote_enqueue(kn);
863 splx(s);
864 }
865
866 done:
867 if (fp != NULL)
868 FILE_UNUSE(fp, p);
869 return (error);
870 }
871
872 /*
873 * Scan through the list of events on fp (for a maximum of maxevents),
874 * returning the results in to ulistp. Timeout is determined by tsp; if
875 * NULL, wait indefinitely, if 0 valued, perform a poll, otherwise wait
876 * as appropriate.
877 */
878 static int
879 kqueue_scan(struct file *fp, size_t maxevents, struct kevent *ulistp,
880 const struct timespec *tsp, struct proc *p, register_t *retval)
881 {
882 struct kqueue *kq;
883 struct kevent *kevp;
884 struct timeval atv;
885 struct knote *kn, marker;
886 size_t count, nkev;
887 int s, timeout, error;
888
889 kq = (struct kqueue *)fp->f_data;
890 count = maxevents;
891 nkev = error = 0;
892 if (count == 0)
893 goto done;
894
895 if (tsp) { /* timeout supplied */
896 TIMESPEC_TO_TIMEVAL(&atv, tsp);
897 if (itimerfix(&atv)) {
898 error = EINVAL;
899 goto done;
900 }
901 s = splclock();
902 timeradd(&atv, &time, &atv); /* calc. time to wait until */
903 splx(s);
904 timeout = hzto(&atv);
905 if (timeout <= 0)
906 timeout = -1; /* do poll */
907 } else {
908 /* no timeout, wait forever */
909 timeout = 0;
910 }
911 goto start;
912
913 retry:
914 if (tsp) {
915 /*
916 * We have to recalculate the timeout on every retry.
917 */
918 timeout = hzto(&atv);
919 if (timeout <= 0)
920 goto done;
921 }
922
923 start:
924 kevp = kq->kq_kev;
925 s = splsched();
926 if (kq->kq_count == 0) {
927 if (timeout < 0) {
928 error = EWOULDBLOCK;
929 } else {
930 kq->kq_state |= KQ_SLEEP;
931 error = tsleep(kq, PSOCK | PCATCH, "kqread", timeout);
932 }
933 splx(s);
934 if (error == 0)
935 goto retry;
936 /* don't restart after signals... */
937 if (error == ERESTART)
938 error = EINTR;
939 else if (error == EWOULDBLOCK)
940 error = 0;
941 goto done;
942 }
943
944 /* mark end of knote list */
945 TAILQ_INSERT_TAIL(&kq->kq_head, &marker, kn_tqe);
946
947 while (count) { /* while user wants data ... */
948 kn = TAILQ_FIRST(&kq->kq_head); /* get next knote */
949 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
950 if (kn == &marker) { /* if it's our marker, stop */
951 splx(s);
952 if (count == maxevents)
953 goto retry;
954 goto done;
955 }
956 if (kn->kn_status & KN_DISABLED) {
957 /* don't want disabled events */
958 kn->kn_status &= ~KN_QUEUED;
959 kq->kq_count--;
960 continue;
961 }
962 if ((kn->kn_flags & EV_ONESHOT) == 0 &&
963 kn->kn_fop->f_event(kn, 0) == 0) {
964 /*
965 * non-ONESHOT event that hasn't
966 * triggered again, so de-queue.
967 */
968 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
969 kq->kq_count--;
970 continue;
971 }
972 *kevp = kn->kn_kevent;
973 kevp++;
974 nkev++;
975 if (kn->kn_flags & EV_ONESHOT) {
976 /* delete ONESHOT events after retrieval */
977 kn->kn_status &= ~KN_QUEUED;
978 kq->kq_count--;
979 splx(s);
980 kn->kn_fop->f_detach(kn);
981 knote_drop(kn, p, p->p_fd);
982 s = splsched();
983 } else if (kn->kn_flags & EV_CLEAR) {
984 /* clear state after retrieval */
985 kn->kn_data = 0;
986 kn->kn_fflags = 0;
987 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
988 kq->kq_count--;
989 } else {
990 /* add event back on list */
991 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
992 }
993 count--;
994 if (nkev == KQ_NEVENTS) {
995 /* do copyouts in KQ_NEVENTS chunks */
996 splx(s);
997 error = copyout((caddr_t)&kq->kq_kev, (caddr_t)ulistp,
998 sizeof(struct kevent) * nkev);
999 ulistp += nkev;
1000 nkev = 0;
1001 kevp = kq->kq_kev;
1002 s = splsched();
1003 if (error)
1004 break;
1005 }
1006 }
1007
1008 /* remove marker */
1009 TAILQ_REMOVE(&kq->kq_head, &marker, kn_tqe);
1010 splx(s);
1011 done:
1012 if (nkev != 0) {
1013 /* copyout remaining events */
1014 error = copyout((caddr_t)&kq->kq_kev, (caddr_t)ulistp,
1015 sizeof(struct kevent) * nkev);
1016 }
1017 *retval = maxevents - count;
1018
1019 return (error);
1020 }
1021
1022 /*
1023 * struct fileops read method for a kqueue descriptor.
1024 * Not implemented.
1025 * XXX: This could be expanded to call kqueue_scan, if desired.
1026 */
1027 /*ARGSUSED*/
1028 static int
1029 kqueue_read(struct file *fp, off_t *offset, struct uio *uio,
1030 struct ucred *cred, int flags)
1031 {
1032
1033 return (ENXIO);
1034 }
1035
1036 /*
1037 * struct fileops write method for a kqueue descriptor.
1038 * Not implemented.
1039 */
1040 /*ARGSUSED*/
1041 static int
1042 kqueue_write(struct file *fp, off_t *offset, struct uio *uio,
1043 struct ucred *cred, int flags)
1044 {
1045
1046 return (ENXIO);
1047 }
1048
1049 /*
1050 * struct fileops ioctl method for a kqueue descriptor.
1051 *
1052 * Two ioctls are currently supported. They both use struct kfilter_mapping:
1053 * KFILTER_BYNAME find name for filter, and return result in
1054 * name, which is of size len.
1055 * KFILTER_BYFILTER find filter for name. len is ignored.
1056 */
1057 /*ARGSUSED*/
1058 static int
1059 kqueue_ioctl(struct file *fp, u_long com, caddr_t data, struct proc *p)
1060 {
1061 struct kfilter_mapping *km;
1062 const struct kfilter *kfilter;
1063 char *name;
1064 int error;
1065
1066 km = (struct kfilter_mapping *)data;
1067 error = 0;
1068
1069 switch (com) {
1070 case KFILTER_BYFILTER: /* convert filter -> name */
1071 kfilter = kfilter_byfilter(km->filter);
1072 if (kfilter != NULL)
1073 error = copyoutstr(kfilter->name, km->name, km->len,
1074 NULL);
1075 else
1076 error = ENOENT;
1077 break;
1078
1079 case KFILTER_BYNAME: /* convert name -> filter */
1080 MALLOC(name, char *, KFILTER_MAXNAME, M_KEVENT, M_WAITOK);
1081 error = copyinstr(km->name, name, KFILTER_MAXNAME, NULL);
1082 if (error) {
1083 FREE(name, M_KEVENT);
1084 break;
1085 }
1086 kfilter = kfilter_byname(name);
1087 if (kfilter != NULL)
1088 km->filter = kfilter->filter;
1089 else
1090 error = ENOENT;
1091 FREE(name, M_KEVENT);
1092 break;
1093
1094 default:
1095 error = ENOTTY;
1096
1097 }
1098 return (error);
1099 }
1100
1101 /*
1102 * struct fileops fcntl method for a kqueue descriptor.
1103 * Not implemented.
1104 */
1105 /*ARGSUSED*/
1106 static int
1107 kqueue_fcntl(struct file *fp, u_int com, caddr_t data, struct proc *p)
1108 {
1109
1110 return (ENOTTY);
1111 }
1112
1113 /*
1114 * struct fileops poll method for a kqueue descriptor.
1115 * Determine if kqueue has events pending.
1116 */
1117 static int
1118 kqueue_poll(struct file *fp, int events, struct proc *p)
1119 {
1120 struct kqueue *kq;
1121 int revents;
1122
1123 kq = (struct kqueue *)fp->f_data;
1124 revents = 0;
1125 if (events & (POLLIN | POLLRDNORM)) {
1126 if (kq->kq_count) {
1127 revents |= events & (POLLIN | POLLRDNORM);
1128 } else {
1129 selrecord(p, &kq->kq_sel);
1130 }
1131 }
1132 return (revents);
1133 }
1134
1135 /*
1136 * struct fileops stat method for a kqueue descriptor.
1137 * Returns dummy info, with st_size being number of events pending.
1138 */
1139 static int
1140 kqueue_stat(struct file *fp, struct stat *st, struct proc *p)
1141 {
1142 struct kqueue *kq;
1143
1144 kq = (struct kqueue *)fp->f_data;
1145 memset((void *)st, 0, sizeof(*st));
1146 st->st_size = kq->kq_count;
1147 st->st_blksize = sizeof(struct kevent);
1148 st->st_mode = S_IFIFO;
1149 return (0);
1150 }
1151
1152 /*
1153 * struct fileops close method for a kqueue descriptor.
1154 * Cleans up kqueue.
1155 */
1156 static int
1157 kqueue_close(struct file *fp, struct proc *p)
1158 {
1159 struct kqueue *kq;
1160 struct filedesc *fdp;
1161 struct knote **knp, *kn, *kn0;
1162 int i;
1163
1164 kq = (struct kqueue *)fp->f_data;
1165 fdp = p->p_fd;
1166 for (i = 0; i < fdp->fd_knlistsize; i++) {
1167 knp = &SLIST_FIRST(&fdp->fd_knlist[i]);
1168 kn = *knp;
1169 while (kn != NULL) {
1170 kn0 = SLIST_NEXT(kn, kn_link);
1171 if (kq == kn->kn_kq) {
1172 kn->kn_fop->f_detach(kn);
1173 FILE_UNUSE(kn->kn_fp, p);
1174 pool_put(&knote_pool, kn);
1175 *knp = kn0;
1176 } else {
1177 knp = &SLIST_NEXT(kn, kn_link);
1178 }
1179 kn = kn0;
1180 }
1181 }
1182 if (fdp->fd_knhashmask != 0) {
1183 for (i = 0; i < fdp->fd_knhashmask + 1; i++) {
1184 knp = &SLIST_FIRST(&fdp->fd_knhash[i]);
1185 kn = *knp;
1186 while (kn != NULL) {
1187 kn0 = SLIST_NEXT(kn, kn_link);
1188 if (kq == kn->kn_kq) {
1189 kn->kn_fop->f_detach(kn);
1190 /* XXX non-fd release of kn->kn_ptr */
1191 pool_put(&knote_pool, kn);
1192 *knp = kn0;
1193 } else {
1194 knp = &SLIST_NEXT(kn, kn_link);
1195 }
1196 kn = kn0;
1197 }
1198 }
1199 }
1200 pool_put(&kqueue_pool, kq);
1201 fp->f_data = NULL;
1202
1203 return (0);
1204 }
1205
1206 /*
1207 * wakeup a kqueue
1208 */
1209 static void
1210 kqueue_wakeup(struct kqueue *kq)
1211 {
1212
1213 if (kq->kq_state & KQ_SLEEP) { /* if currently sleeping ... */
1214 kq->kq_state &= ~KQ_SLEEP;
1215 wakeup(kq); /* ... wakeup */
1216 }
1217
1218 /* Notify select/poll and kevent. */
1219 selnotify(&kq->kq_sel, 0);
1220 }
1221
1222 /*
1223 * struct fileops kqfilter method for a kqueue descriptor.
1224 * Event triggered when monitored kqueue changes.
1225 */
1226 /*ARGSUSED*/
1227 static int
1228 kqueue_kqfilter(struct file *fp, struct knote *kn)
1229 {
1230 struct kqueue *kq;
1231
1232 KASSERT(fp == kn->kn_fp);
1233 kq = (struct kqueue *)kn->kn_fp->f_data;
1234 if (kn->kn_filter != EVFILT_READ)
1235 return (1);
1236 kn->kn_fop = &kqread_filtops;
1237 SLIST_INSERT_HEAD(&kq->kq_sel.sel_klist, kn, kn_selnext);
1238 return (0);
1239 }
1240
1241
1242 /*
1243 * Walk down a list of knotes, activating them if their event has triggered.
1244 */
1245 void
1246 knote(struct klist *list, long hint)
1247 {
1248 struct knote *kn;
1249
1250 SLIST_FOREACH(kn, list, kn_selnext)
1251 if (kn->kn_fop->f_event(kn, hint))
1252 KNOTE_ACTIVATE(kn);
1253 }
1254
1255 /*
1256 * Remove all knotes from a specified klist
1257 */
1258 void
1259 knote_remove(struct proc *p, struct klist *list)
1260 {
1261 struct knote *kn;
1262
1263 while ((kn = SLIST_FIRST(list)) != NULL) {
1264 kn->kn_fop->f_detach(kn);
1265 knote_drop(kn, p, p->p_fd);
1266 }
1267 }
1268
1269 /*
1270 * Remove all knotes referencing a specified fd
1271 */
1272 void
1273 knote_fdclose(struct proc *p, int fd)
1274 {
1275 struct filedesc *fdp;
1276 struct klist *list;
1277
1278 fdp = p->p_fd;
1279 list = &fdp->fd_knlist[fd];
1280 knote_remove(p, list);
1281 }
1282
1283 /*
1284 * Attach a new knote to a file descriptor
1285 */
1286 static void
1287 knote_attach(struct knote *kn, struct filedesc *fdp)
1288 {
1289 struct klist *list;
1290 int size;
1291
1292 if (! kn->kn_fop->f_isfd) {
1293 /* if knote is not on an fd, store on internal hash table */
1294 if (fdp->fd_knhashmask == 0)
1295 fdp->fd_knhash = hashinit(KN_HASHSIZE, HASH_LIST,
1296 M_KEVENT, M_WAITOK, &fdp->fd_knhashmask);
1297 list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
1298 goto done;
1299 }
1300
1301 /*
1302 * otherwise, knote is on an fd.
1303 * knotes are stored in fd_knlist indexed by kn->kn_id.
1304 */
1305 if (fdp->fd_knlistsize <= kn->kn_id) {
1306 /* expand list, it's too small */
1307 size = fdp->fd_knlistsize;
1308 while (size <= kn->kn_id) {
1309 /* grow in KQ_EXTENT chunks */
1310 size += KQ_EXTENT;
1311 }
1312 list = malloc(size * sizeof(struct klist *), M_KEVENT,M_WAITOK);
1313 if (fdp->fd_knlist) {
1314 /* copy existing knlist */
1315 memcpy((caddr_t)list, (caddr_t)fdp->fd_knlist,
1316 fdp->fd_knlistsize * sizeof(struct klist *));
1317 }
1318 /*
1319 * Zero new memory. Stylistically, SLIST_INIT() should be
1320 * used here, but that does same thing as the memset() anyway.
1321 */
1322 memset(&list[fdp->fd_knlistsize], 0,
1323 (size - fdp->fd_knlistsize) * sizeof(struct klist *));
1324
1325 /* switch to new knlist */
1326 if (fdp->fd_knlist != NULL)
1327 free(fdp->fd_knlist, M_KEVENT);
1328 fdp->fd_knlistsize = size;
1329 fdp->fd_knlist = list;
1330 }
1331
1332 /* get list head for this fd */
1333 list = &fdp->fd_knlist[kn->kn_id];
1334 done:
1335 /* add new knote */
1336 SLIST_INSERT_HEAD(list, kn, kn_link);
1337 kn->kn_status = 0;
1338 }
1339
1340 /*
1341 * Drop knote.
1342 * Should be called at spl == 0, since we don't want to hold spl
1343 * while calling FILE_UNUSE and free.
1344 */
1345 static void
1346 knote_drop(struct knote *kn, struct proc *p, struct filedesc *fdp)
1347 {
1348 struct klist *list;
1349
1350 if (kn->kn_fop->f_isfd)
1351 list = &fdp->fd_knlist[kn->kn_id];
1352 else
1353 list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
1354
1355 SLIST_REMOVE(list, kn, knote, kn_link);
1356 if (kn->kn_status & KN_QUEUED)
1357 knote_dequeue(kn);
1358 if (kn->kn_fop->f_isfd)
1359 FILE_UNUSE(kn->kn_fp, p);
1360 pool_put(&knote_pool, kn);
1361 }
1362
1363
1364 /*
1365 * Queue new event for knote.
1366 */
1367 static void
1368 knote_enqueue(struct knote *kn)
1369 {
1370 struct kqueue *kq;
1371 int s;
1372
1373 kq = kn->kn_kq;
1374 s = splsched();
1375 KASSERT((kn->kn_status & KN_QUEUED) == 0);
1376
1377 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1378 kn->kn_status |= KN_QUEUED;
1379 kq->kq_count++;
1380 splx(s);
1381 kqueue_wakeup(kq);
1382 }
1383
1384 /*
1385 * Dequeue event for knote.
1386 */
1387 static void
1388 knote_dequeue(struct knote *kn)
1389 {
1390 struct kqueue *kq;
1391 int s;
1392
1393 kq = kn->kn_kq;
1394 s = splsched();
1395 KASSERT(kn->kn_status & KN_QUEUED);
1396
1397 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1398 kn->kn_status &= ~KN_QUEUED;
1399 kq->kq_count--;
1400 splx(s);
1401 }
1402