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