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