kern_event.c revision 1.1.1.1.2.13 1 /* $NetBSD: kern_event.c,v 1.1.1.1.2.13 2002/04/09 06:23:47 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, int 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(int) nchanges;
529 syscallarg(struct kevent *) eventlist;
530 syscallarg(int) 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 int i, n, nerrors, error;
538
539 /* check that we're dealing with a kq */
540 fp = fd_getfile(p->p_fd, SCARG(uap, fd));
541 if (!fp || fp->f_type != DTYPE_KQUEUE)
542 return (EBADF);
543
544 FILE_USE(fp);
545
546 if (SCARG(uap, timeout) != NULL) {
547 error = copyin(SCARG(uap, timeout), &ts, sizeof(ts));
548 if (error)
549 goto done;
550 SCARG(uap, timeout) = &ts;
551 }
552
553 kq = (struct kqueue *)fp->f_data;
554 nerrors = 0;
555
556 /* traverse list of events to register */
557 while (SCARG(uap, nchanges) > 0) {
558 /* copyin a maximum of KQ_EVENTS at each pass */
559 n = MIN(SCARG(uap, nchanges), KQ_NEVENTS);
560 error = copyin(SCARG(uap, changelist), kq->kq_kev,
561 n * sizeof(struct kevent));
562 if (error)
563 goto done;
564 for (i = 0; i < n; i++) {
565 kevp = &kq->kq_kev[i];
566 kevp->flags &= ~EV_SYSFLAGS;
567 /* register each knote */
568 error = kqueue_register(kq, kevp, p);
569 if (error) {
570 if (SCARG(uap, nevents) != 0) {
571 kevp->flags = EV_ERROR;
572 kevp->data = error;
573 error = copyout((caddr_t)kevp,
574 (caddr_t)SCARG(uap, eventlist),
575 sizeof(*kevp));
576 if (error)
577 goto done;
578 SCARG(uap, eventlist)++;
579 SCARG(uap, nevents)--;
580 nerrors++;
581 } else {
582 goto done;
583 }
584 }
585 }
586 SCARG(uap, nchanges) -= n; /* update the results */
587 SCARG(uap, changelist) += n;
588 }
589 if (nerrors) {
590 *retval = nerrors;
591 error = 0;
592 goto done;
593 }
594
595 /* actually scan through the events */
596 error = kqueue_scan(fp, SCARG(uap, nevents), SCARG(uap, eventlist),
597 SCARG(uap, timeout), p, retval);
598 done:
599 FILE_UNUSE(fp, p);
600 return (error);
601 }
602
603 /*
604 * Register a given kevent kev onto the kqueue
605 */
606 int
607 kqueue_register(struct kqueue *kq, struct kevent *kev, struct proc *p)
608 {
609 const struct kfilter *kfilter;
610 struct filedesc *fdp;
611 struct file *fp;
612 struct knote *kn;
613 int s, error;
614
615 fdp = kq->kq_fdp;
616 fp = NULL;
617 kn = NULL;
618 error = 0;
619 kfilter = kfilter_byfilter(kev->filter);
620 if (kfilter == NULL || kfilter->filtops == NULL) {
621 /* filter not found nor implemented */
622 return (EINVAL);
623 }
624
625 /* search if knote already exists */
626 if (kfilter->filtops->f_isfd) {
627 /* monitoring a file descriptor */
628 if ((fp = fd_getfile(fdp, kev->ident)) == NULL)
629 return (EBADF); /* validate descriptor */
630 FILE_USE(fp);
631
632 if (kev->ident < fdp->fd_knlistsize) {
633 SLIST_FOREACH(kn, &fdp->fd_knlist[kev->ident], kn_link)
634 if (kq == kn->kn_kq &&
635 kev->filter == kn->kn_filter)
636 break;
637 }
638 } else {
639 /*
640 * not monitoring a file descriptor, so
641 * lookup knotes in internal hash table
642 */
643 if (fdp->fd_knhashmask != 0) {
644 struct klist *list;
645
646 list = &fdp->fd_knhash[
647 KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
648 SLIST_FOREACH(kn, list, kn_link)
649 if (kev->ident == kn->kn_id &&
650 kq == kn->kn_kq &&
651 kev->filter == kn->kn_filter)
652 break;
653 }
654 }
655
656 if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
657 error = ENOENT; /* filter not found */
658 goto done;
659 }
660
661 /*
662 * kn now contains the matching knote, or NULL if no match
663 */
664 if (kev->flags & EV_ADD) {
665 /* add knote */
666
667 if (kn == NULL) {
668 /* create new knote */
669 kn = pool_get(&knote_pool, PR_WAITOK);
670 if (kn == NULL) {
671 error = ENOMEM;
672 goto done;
673 }
674 kn->kn_fp = fp;
675 kn->kn_kq = kq;
676 kn->kn_fop = kfilter->filtops;
677
678 /*
679 * apply reference count to knote structure, and
680 * do not release it at the end of this routine.
681 */
682 fp = NULL;
683
684 kn->kn_sfflags = kev->fflags;
685 kn->kn_sdata = kev->data;
686 kev->fflags = 0;
687 kev->data = 0;
688 kn->kn_kevent = *kev;
689
690 knote_attach(kn, fdp);
691 if ((error = kfilter->filtops->f_attach(kn)) != 0) {
692 knote_drop(kn, p);
693 goto done;
694 }
695 } else {
696 /* modify existing knote */
697
698 /*
699 * The user may change some filter values after the
700 * initial EV_ADD, but doing so will not reset any
701 * filter which have already been triggered.
702 */
703 kn->kn_sfflags = kev->fflags;
704 kn->kn_sdata = kev->data;
705 kn->kn_kevent.udata = kev->udata;
706 }
707
708 s = splhigh();
709 if (kn->kn_fop->f_event(kn, 0))
710 KNOTE_ACTIVATE(kn);
711 splx(s);
712
713 } else if (kev->flags & EV_DELETE) { /* delete knote */
714 kn->kn_fop->f_detach(kn);
715 knote_drop(kn, p);
716 goto done;
717 }
718
719 /* disable knote */
720 if ((kev->flags & EV_DISABLE) &&
721 ((kn->kn_status & KN_DISABLED) == 0)) {
722 s = splhigh();
723 kn->kn_status |= KN_DISABLED;
724 splx(s);
725 }
726
727 /* enable knote */
728 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
729 s = splhigh();
730 kn->kn_status &= ~KN_DISABLED;
731 if ((kn->kn_status & KN_ACTIVE) &&
732 ((kn->kn_status & KN_QUEUED) == 0))
733 knote_enqueue(kn);
734 splx(s);
735 }
736
737 done:
738 if (fp != NULL)
739 FILE_UNUSE(fp, p);
740 return (error);
741 }
742
743 /*
744 * Scan through the list of events on fp (for a maximum of maxevents),
745 * returning the results in to ulistp. Timeout is determined by tsp; if
746 * NULL, wait indefinitely, if 0 valued, perform a poll, otherwise wait
747 * as appropriate.
748 */
749 static int
750 kqueue_scan(struct file *fp, int maxevents, struct kevent *ulistp,
751 const struct timespec *tsp, struct proc *p, register_t *retval)
752 {
753 struct kqueue *kq;
754 struct kevent *kevp;
755 struct timeval atv;
756 struct knote *kn, marker;
757 int s, count, timeout, nkev, error;
758
759 kq = (struct kqueue *)fp->f_data;
760 count = maxevents;
761 nkev = error = 0;
762 if (count == 0)
763 goto done;
764
765 if (tsp != NULL) { /* timeout supplied */
766 TIMESPEC_TO_TIMEVAL(&atv, tsp);
767 if (itimerfix(&atv)) {
768 error = EINVAL;
769 goto done;
770 }
771 s = splclock();
772 timeradd(&atv, &time, &atv); /* calc. time to wait until */
773 splx(s);
774 if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
775 timeout = -1; /* perform a poll */
776 else
777 timeout = hzto(&atv); /* calculate hz till timeout */
778 } else {
779 atv.tv_sec = 0; /* no timeout, wait forever */
780 atv.tv_usec = 0;
781 timeout = 0;
782 }
783 goto start;
784
785 retry:
786 if (atv.tv_sec || atv.tv_usec) { /* timeout requested */
787 s = splclock();
788 if (timercmp(&time, &atv, >=)) {
789 splx(s);
790 goto done; /* timeout reached */
791 }
792 splx(s);
793 timeout = hzto(&atv); /* recalc. timeout remaining */
794 }
795
796 start:
797 kevp = kq->kq_kev;
798 s = splhigh();
799 if (kq->kq_count == 0) {
800 if (timeout < 0) {
801 error = EWOULDBLOCK;
802 } else {
803 kq->kq_state |= KQ_SLEEP;
804 error = tsleep(kq, PSOCK | PCATCH, "kqread", timeout);
805 }
806 splx(s);
807 if (error == 0)
808 goto retry;
809 /* don't restart after signals... */
810 if (error == ERESTART)
811 error = EINTR;
812 else if (error == EWOULDBLOCK)
813 error = 0;
814 goto done;
815 }
816
817 /* mark end of knote list */
818 TAILQ_INSERT_TAIL(&kq->kq_head, &marker, kn_tqe);
819
820 while (count) { /* while user wants data ... */
821 kn = TAILQ_FIRST(&kq->kq_head); /* get next knote */
822 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
823 if (kn == &marker) { /* if it's our marker, stop */
824 splx(s);
825 if (count == maxevents)
826 goto retry;
827 goto done;
828 }
829 if (kn->kn_status & KN_DISABLED) {
830 /* don't want disabled events */
831 kn->kn_status &= ~KN_QUEUED;
832 kq->kq_count--;
833 continue;
834 }
835 if ((kn->kn_flags & EV_ONESHOT) == 0 &&
836 kn->kn_fop->f_event(kn, 0) == 0) {
837 /*
838 * non-ONESHOT event that hasn't
839 * triggered again, so de-queue.
840 */
841 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
842 kq->kq_count--;
843 continue;
844 }
845 *kevp = kn->kn_kevent;
846 kevp++;
847 nkev++;
848 if (kn->kn_flags & EV_ONESHOT) {
849 /* delete ONESHOT events after retrieval */
850 kn->kn_status &= ~KN_QUEUED;
851 kq->kq_count--;
852 splx(s);
853 kn->kn_fop->f_detach(kn);
854 knote_drop(kn, p);
855 s = splhigh();
856 } else if (kn->kn_flags & EV_CLEAR) {
857 /* clear state after retrieval */
858 kn->kn_data = 0;
859 kn->kn_fflags = 0;
860 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
861 kq->kq_count--;
862 } else {
863 /* add event back on list */
864 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
865 }
866 count--;
867 if (nkev == KQ_NEVENTS) {
868 /* do copyouts in KQ_NEVENTS chunks */
869 splx(s);
870 error = copyout((caddr_t)&kq->kq_kev, (caddr_t)ulistp,
871 sizeof(struct kevent) * nkev);
872 ulistp += nkev;
873 nkev = 0;
874 kevp = kq->kq_kev;
875 s = splhigh();
876 if (error)
877 break;
878 }
879 }
880
881 /* remove marker */
882 TAILQ_REMOVE(&kq->kq_head, &marker, kn_tqe);
883 splx(s);
884 done:
885 if (nkev != 0) {
886 /* copyout remaining events */
887 error = copyout((caddr_t)&kq->kq_kev, (caddr_t)ulistp,
888 sizeof(struct kevent) * nkev);
889 }
890 *retval = maxevents - count;
891
892 return (error);
893 }
894
895 /*
896 * struct fileops read method for a kqueue descriptor.
897 * Not implemented.
898 * XXX: This could be expanded to call kqueue_scan, if desired.
899 */
900 /*ARGSUSED*/
901 static int
902 kqueue_read(struct file *fp, off_t *offset, struct uio *uio,
903 struct ucred *cred, int flags)
904 {
905
906 return (ENXIO);
907 }
908
909 /*
910 * struct fileops write method for a kqueue descriptor.
911 * Not implemented.
912 */
913 /*ARGSUSED*/
914 static int
915 kqueue_write(struct file *fp, off_t *offset, struct uio *uio,
916 struct ucred *cred, int flags)
917 {
918
919 return (ENXIO);
920 }
921
922 /*
923 * struct fileops ioctl method for a kqueue descriptor.
924 *
925 * Two ioctls are currently supported. They both use struct kfilter_mapping:
926 * KFILTER_BYNAME find name for filter, and return result in
927 * name, which is of size len.
928 * KFILTER_BYFILTER find filter for name. len is ignored.
929 */
930 /*ARGSUSED*/
931 static int
932 kqueue_ioctl(struct file *fp, u_long com, caddr_t data, struct proc *p)
933 {
934 struct kfilter_mapping *km;
935 const struct kfilter *kfilter;
936 char *name;
937 int error;
938
939 km = (struct kfilter_mapping *)data;
940 error = 0;
941
942 switch (com) {
943 case KFILTER_BYFILTER: /* convert filter -> name */
944 kfilter = kfilter_byfilter(km->filter);
945 if (kfilter != NULL)
946 error = copyoutstr(kfilter->name, km->name, km->len,
947 NULL);
948 else
949 error = ENOENT;
950 break;
951
952 case KFILTER_BYNAME: /* convert name -> filter */
953 MALLOC(name, char *, KFILTER_MAXNAME, M_KEVENT, M_WAITOK);
954 error = copyinstr(km->name, name, KFILTER_MAXNAME, NULL);
955 if (error) {
956 FREE(name, M_KEVENT);
957 break;
958 }
959 kfilter = kfilter_byname(name);
960 if (kfilter != NULL)
961 km->filter = kfilter->filter;
962 else
963 error = ENOENT;
964 FREE(name, M_KEVENT);
965 break;
966
967 default:
968 error = ENOTTY;
969
970 }
971 return (error);
972 }
973
974 /*
975 * struct fileops fcntl method for a kqueue descriptor.
976 * Not implemented.
977 */
978 /*ARGSUSED*/
979 static int
980 kqueue_fcntl(struct file *fp, u_int com, caddr_t data, struct proc *p)
981 {
982
983 return (ENOTTY);
984 }
985
986 /*
987 * struct fileops poll method for a kqueue descriptor.
988 * Determine if kqueue has events pending.
989 */
990 static int
991 kqueue_poll(struct file *fp, int events, struct proc *p)
992 {
993 struct kqueue *kq;
994 int revents;
995
996 kq = (struct kqueue *)fp->f_data;
997 revents = 0;
998 if (events & (POLLIN | POLLRDNORM)) {
999 if (kq->kq_count) {
1000 revents |= events & (POLLIN | POLLRDNORM);
1001 } else {
1002 selrecord(p, &kq->kq_sel);
1003 }
1004 }
1005 return (revents);
1006 }
1007
1008 /*
1009 * struct fileops stat method for a kqueue descriptor.
1010 * Returns dummy info, with st_size being number of events pending.
1011 */
1012 static int
1013 kqueue_stat(struct file *fp, struct stat *st, struct proc *p)
1014 {
1015 struct kqueue *kq;
1016
1017 kq = (struct kqueue *)fp->f_data;
1018 memset((void *)st, 0, sizeof(*st));
1019 st->st_size = kq->kq_count;
1020 st->st_blksize = sizeof(struct kevent);
1021 st->st_mode = S_IFIFO;
1022 return (0);
1023 }
1024
1025 /*
1026 * struct fileops close method for a kqueue descriptor.
1027 * Cleans up kqueue.
1028 */
1029 static int
1030 kqueue_close(struct file *fp, struct proc *p)
1031 {
1032 struct kqueue *kq;
1033 struct filedesc *fdp;
1034 struct knote **knp, *kn, *kn0;
1035 int i;
1036
1037 kq = (struct kqueue *)fp->f_data;
1038 fdp = p->p_fd;
1039 for (i = 0; i < fdp->fd_knlistsize; i++) {
1040 knp = &SLIST_FIRST(&fdp->fd_knlist[i]);
1041 kn = *knp;
1042 while (kn != NULL) {
1043 kn0 = SLIST_NEXT(kn, kn_link);
1044 if (kq == kn->kn_kq) {
1045 kn->kn_fop->f_detach(kn);
1046 FILE_UNUSE(kn->kn_fp, p);
1047 pool_put(&knote_pool, kn);
1048 *knp = kn0;
1049 } else {
1050 knp = &SLIST_NEXT(kn, kn_link);
1051 }
1052 kn = kn0;
1053 }
1054 }
1055 if (fdp->fd_knhashmask != 0) {
1056 for (i = 0; i < fdp->fd_knhashmask + 1; i++) {
1057 knp = &SLIST_FIRST(&fdp->fd_knhash[i]);
1058 kn = *knp;
1059 while (kn != NULL) {
1060 kn0 = SLIST_NEXT(kn, kn_link);
1061 if (kq == kn->kn_kq) {
1062 kn->kn_fop->f_detach(kn);
1063 /* XXX non-fd release of kn->kn_ptr */
1064 pool_put(&knote_pool, kn);
1065 *knp = kn0;
1066 } else {
1067 knp = &SLIST_NEXT(kn, kn_link);
1068 }
1069 kn = kn0;
1070 }
1071 }
1072 }
1073 pool_put(&kqueue_pool, kq);
1074 fp->f_data = NULL;
1075
1076 return (0);
1077 }
1078
1079 /*
1080 * wakeup a kqueue
1081 */
1082 static void
1083 kqueue_wakeup(struct kqueue *kq)
1084 {
1085
1086 if (kq->kq_state & KQ_SLEEP) { /* if currently sleeping ... */
1087 kq->kq_state &= ~KQ_SLEEP;
1088 wakeup(kq); /* ... wakeup */
1089 }
1090
1091 /* Notify select/poll and kevent. */
1092 selnotify(&kq->kq_sel, 0);
1093 }
1094
1095 /*
1096 * struct fileops kqfilter method for a kqueue descriptor.
1097 * Event triggered when monitored kqueue changes.
1098 */
1099 /*ARGSUSED*/
1100 static int
1101 kqueue_kqfilter(struct file *fp, struct knote *kn)
1102 {
1103 struct kqueue *kq;
1104
1105 KASSERT(fp == kn->kn_fp);
1106 kq = (struct kqueue *)kn->kn_fp->f_data;
1107 if (kn->kn_filter != EVFILT_READ)
1108 return (1);
1109 kn->kn_fop = &kqread_filtops;
1110 SLIST_INSERT_HEAD(&kq->kq_sel.si_klist, kn, kn_selnext);
1111 return (0);
1112 }
1113
1114
1115 /*
1116 * Walk down a list of knotes, activating them if their event has triggered.
1117 */
1118 void
1119 knote(struct klist *list, long hint)
1120 {
1121 struct knote *kn;
1122
1123 SLIST_FOREACH(kn, list, kn_selnext)
1124 if (kn->kn_fop->f_event(kn, hint))
1125 KNOTE_ACTIVATE(kn);
1126 }
1127
1128 /*
1129 * Remove all knotes from a specified klist
1130 */
1131 void
1132 knote_remove(struct proc *p, struct klist *list)
1133 {
1134 struct knote *kn;
1135
1136 while ((kn = SLIST_FIRST(list)) != NULL) {
1137 kn->kn_fop->f_detach(kn);
1138 knote_drop(kn, p);
1139 }
1140 }
1141
1142 /*
1143 * Remove all knotes referencing a specified fd
1144 */
1145 void
1146 knote_fdclose(struct proc *p, int fd)
1147 {
1148 struct filedesc *fdp;
1149 struct klist *list;
1150
1151 fdp = p->p_fd;
1152 list = &fdp->fd_knlist[fd];
1153 knote_remove(p, list);
1154 }
1155
1156 /*
1157 * Attach a new knote to a file descriptor
1158 */
1159 static void
1160 knote_attach(struct knote *kn, struct filedesc *fdp)
1161 {
1162 struct klist *list;
1163 int size;
1164
1165 if (! kn->kn_fop->f_isfd) {
1166 /* if knote is not on an fd, store on internal hash table */
1167 if (fdp->fd_knhashmask == 0)
1168 fdp->fd_knhash = hashinit(KN_HASHSIZE, HASH_LIST,
1169 M_KEVENT, M_WAITOK, &fdp->fd_knhashmask);
1170 list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
1171 goto done;
1172 }
1173
1174 /*
1175 * otherwise, knote is on an fd.
1176 * knotes are stored in fd_knlist indexed by kn->kn_id.
1177 */
1178 if (fdp->fd_knlistsize <= kn->kn_id) {
1179 /* expand list, it's too small */
1180 size = fdp->fd_knlistsize;
1181 while (size <= kn->kn_id) {
1182 /* grow in KQ_EXTENT chunks */
1183 size += KQ_EXTENT;
1184 }
1185 list = malloc(size * sizeof(struct klist *), M_KEVENT,M_WAITOK);
1186 if (fdp->fd_knlist) {
1187 /* copy existing knlist */
1188 memcpy((caddr_t)list, (caddr_t)fdp->fd_knlist,
1189 fdp->fd_knlistsize * sizeof(struct klist *));
1190 }
1191 /*
1192 * Zero new memory. Stylistically, SLIST_INIT() should be
1193 * used here, but that does same thing as the memset() anyway.
1194 */
1195 memset(&list[fdp->fd_knlistsize], 0,
1196 (size - fdp->fd_knlistsize) * sizeof(struct klist *));
1197
1198 /* switch to new knlist */
1199 if (fdp->fd_knlist != NULL)
1200 free(fdp->fd_knlist, M_KEVENT);
1201 fdp->fd_knlistsize = size;
1202 fdp->fd_knlist = list;
1203 }
1204
1205 /* get list head for this fd */
1206 list = &fdp->fd_knlist[kn->kn_id];
1207 done:
1208 /* add new knote */
1209 SLIST_INSERT_HEAD(list, kn, kn_link);
1210 kn->kn_status = 0;
1211 }
1212
1213 /*
1214 * Drop knote.
1215 * Should be called at spl == 0, since we don't want to hold spl
1216 * while calling FILE_UNUSE and free.
1217 */
1218 static void
1219 knote_drop(struct knote *kn, struct proc *p)
1220 {
1221 struct filedesc *fdp;
1222 struct klist *list;
1223
1224 fdp = p->p_fd;
1225 if (kn->kn_fop->f_isfd)
1226 list = &fdp->fd_knlist[kn->kn_id];
1227 else
1228 list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
1229
1230 SLIST_REMOVE(list, kn, knote, kn_link);
1231 if (kn->kn_status & KN_QUEUED)
1232 knote_dequeue(kn);
1233 if (kn->kn_fop->f_isfd)
1234 FILE_UNUSE(kn->kn_fp, p);
1235 pool_put(&knote_pool, kn);
1236 }
1237
1238
1239 /*
1240 * Queue new event for knote.
1241 */
1242 static void
1243 knote_enqueue(struct knote *kn)
1244 {
1245 struct kqueue *kq;
1246 int s;
1247
1248 kq = kn->kn_kq;
1249 s = splhigh();
1250 KASSERT((kn->kn_status & KN_QUEUED) == 0);
1251
1252 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1253 kn->kn_status |= KN_QUEUED;
1254 kq->kq_count++;
1255 splx(s);
1256 kqueue_wakeup(kq);
1257 }
1258
1259 /*
1260 * Dequeue event for knote.
1261 */
1262 static void
1263 knote_dequeue(struct knote *kn)
1264 {
1265 struct kqueue *kq;
1266 int s;
1267
1268 kq = kn->kn_kq;
1269 s = splhigh();
1270 KASSERT(kn->kn_status & KN_QUEUED);
1271
1272 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1273 kn->kn_status &= ~KN_QUEUED;
1274 kq->kq_count--;
1275 splx(s);
1276 }
1277