kernel - general cleanup and mplock removal
[dragonfly.git] / sys / kern / kern_event.c
1 /*-
2  * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/kern/kern_event.c,v 1.2.2.10 2004/04/04 07:03:14 cperciva Exp $
27  */
28
29 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/kernel.h>
32 #include <sys/proc.h>
33 #include <sys/malloc.h> 
34 #include <sys/unistd.h>
35 #include <sys/file.h>
36 #include <sys/lock.h>
37 #include <sys/fcntl.h>
38 #include <sys/queue.h>
39 #include <sys/event.h>
40 #include <sys/eventvar.h>
41 #include <sys/protosw.h>
42 #include <sys/socket.h>
43 #include <sys/socketvar.h>
44 #include <sys/stat.h>
45 #include <sys/sysctl.h>
46 #include <sys/sysproto.h>
47 #include <sys/thread.h>
48 #include <sys/uio.h>
49 #include <sys/signalvar.h>
50 #include <sys/filio.h>
51 #include <sys/ktr.h>
52
53 #include <sys/thread2.h>
54 #include <sys/file2.h>
55 #include <sys/mplock2.h>
56
57 /*
58  * Global token for kqueue subsystem
59  */
60 #if 0
61 struct lwkt_token kq_token = LWKT_TOKEN_INITIALIZER(kq_token);
62 SYSCTL_LONG(_lwkt, OID_AUTO, kq_collisions,
63     CTLFLAG_RW, &kq_token.t_collisions, 0,
64     "Collision counter of kq_token");
65 #endif
66
67 MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
68
69 struct kevent_copyin_args {
70         struct kevent_args      *ka;
71         int                     pchanges;
72 };
73
74 static int      kqueue_sleep(struct kqueue *kq, struct timespec *tsp);
75 static int      kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
76                     struct knote *marker);
77 static int      kqueue_read(struct file *fp, struct uio *uio,
78                     struct ucred *cred, int flags);
79 static int      kqueue_write(struct file *fp, struct uio *uio,
80                     struct ucred *cred, int flags);
81 static int      kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
82                     struct ucred *cred, struct sysmsg *msg);
83 static int      kqueue_kqfilter(struct file *fp, struct knote *kn);
84 static int      kqueue_stat(struct file *fp, struct stat *st,
85                     struct ucred *cred);
86 static int      kqueue_close(struct file *fp);
87 static void     kqueue_wakeup(struct kqueue *kq);
88 static int      filter_attach(struct knote *kn);
89 static int      filter_event(struct knote *kn, long hint);
90
91 /*
92  * MPSAFE
93  */
94 static struct fileops kqueueops = {
95         .fo_read = kqueue_read,
96         .fo_write = kqueue_write,
97         .fo_ioctl = kqueue_ioctl,
98         .fo_kqfilter = kqueue_kqfilter,
99         .fo_stat = kqueue_stat,
100         .fo_close = kqueue_close,
101         .fo_shutdown = nofo_shutdown
102 };
103
104 static void     knote_attach(struct knote *kn);
105 static void     knote_drop(struct knote *kn);
106 static void     knote_detach_and_drop(struct knote *kn);
107 static void     knote_enqueue(struct knote *kn);
108 static void     knote_dequeue(struct knote *kn);
109 static struct   knote *knote_alloc(void);
110 static void     knote_free(struct knote *kn);
111
112 static void     filt_kqdetach(struct knote *kn);
113 static int      filt_kqueue(struct knote *kn, long hint);
114 static int      filt_procattach(struct knote *kn);
115 static void     filt_procdetach(struct knote *kn);
116 static int      filt_proc(struct knote *kn, long hint);
117 static int      filt_fileattach(struct knote *kn);
118 static void     filt_timerexpire(void *knx);
119 static int      filt_timerattach(struct knote *kn);
120 static void     filt_timerdetach(struct knote *kn);
121 static int      filt_timer(struct knote *kn, long hint);
122
123 static struct filterops file_filtops =
124         { FILTEROP_ISFD, filt_fileattach, NULL, NULL };
125 static struct filterops kqread_filtops =
126         { FILTEROP_ISFD, NULL, filt_kqdetach, filt_kqueue };
127 static struct filterops proc_filtops =
128         { 0, filt_procattach, filt_procdetach, filt_proc };
129 static struct filterops timer_filtops =
130         { 0, filt_timerattach, filt_timerdetach, filt_timer };
131
132 static int              kq_ncallouts = 0;
133 static int              kq_calloutmax = (4 * 1024);
134 SYSCTL_INT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
135     &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
136 static int              kq_checkloop = 1000000;
137 SYSCTL_INT(_kern, OID_AUTO, kq_checkloop, CTLFLAG_RW,
138     &kq_checkloop, 0, "Maximum number of callouts allocated for kqueue");
139
140 #define KNOTE_ACTIVATE(kn) do {                                         \
141         kn->kn_status |= KN_ACTIVE;                                     \
142         if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0)           \
143                 knote_enqueue(kn);                                      \
144 } while(0)
145
146 #define KN_HASHSIZE             64              /* XXX should be tunable */
147 #define KN_HASH(val, mask)      (((val) ^ (val >> 8)) & (mask))
148
149 extern struct filterops aio_filtops;
150 extern struct filterops sig_filtops;
151
152 /*
153  * Table for for all system-defined filters.
154  */
155 static struct filterops *sysfilt_ops[] = {
156         &file_filtops,                  /* EVFILT_READ */
157         &file_filtops,                  /* EVFILT_WRITE */
158         &aio_filtops,                   /* EVFILT_AIO */
159         &file_filtops,                  /* EVFILT_VNODE */
160         &proc_filtops,                  /* EVFILT_PROC */
161         &sig_filtops,                   /* EVFILT_SIGNAL */
162         &timer_filtops,                 /* EVFILT_TIMER */
163         &file_filtops,                  /* EVFILT_EXCEPT */
164 };
165
166 static int
167 filt_fileattach(struct knote *kn)
168 {
169         return (fo_kqfilter(kn->kn_fp, kn));
170 }
171
172 /*
173  * MPSAFE
174  */
175 static int
176 kqueue_kqfilter(struct file *fp, struct knote *kn)
177 {
178         struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
179
180         if (kn->kn_filter != EVFILT_READ)
181                 return (EOPNOTSUPP);
182
183         kn->kn_fop = &kqread_filtops;
184         knote_insert(&kq->kq_kqinfo.ki_note, kn);
185         return (0);
186 }
187
188 static void
189 filt_kqdetach(struct knote *kn)
190 {
191         struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
192
193         knote_remove(&kq->kq_kqinfo.ki_note, kn);
194 }
195
196 /*ARGSUSED*/
197 static int
198 filt_kqueue(struct knote *kn, long hint)
199 {
200         struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
201
202         kn->kn_data = kq->kq_count;
203         return (kn->kn_data > 0);
204 }
205
206 static int
207 filt_procattach(struct knote *kn)
208 {
209         struct proc *p;
210         int immediate;
211
212         immediate = 0;
213         p = pfind(kn->kn_id);
214         if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
215                 p = zpfind(kn->kn_id);
216                 immediate = 1;
217         }
218         if (p == NULL) {
219                 return (ESRCH);
220         }
221         if (!PRISON_CHECK(curthread->td_ucred, p->p_ucred)) {
222                 if (p)
223                         PRELE(p);
224                 return (EACCES);
225         }
226
227         lwkt_gettoken(&p->p_token);
228         kn->kn_ptr.p_proc = p;
229         kn->kn_flags |= EV_CLEAR;               /* automatically set */
230
231         /*
232          * internal flag indicating registration done by kernel
233          */
234         if (kn->kn_flags & EV_FLAG1) {
235                 kn->kn_data = kn->kn_sdata;             /* ppid */
236                 kn->kn_fflags = NOTE_CHILD;
237                 kn->kn_flags &= ~EV_FLAG1;
238         }
239
240         knote_insert(&p->p_klist, kn);
241
242         /*
243          * Immediately activate any exit notes if the target process is a
244          * zombie.  This is necessary to handle the case where the target
245          * process, e.g. a child, dies before the kevent is negistered.
246          */
247         if (immediate && filt_proc(kn, NOTE_EXIT))
248                 KNOTE_ACTIVATE(kn);
249         lwkt_reltoken(&p->p_token);
250         PRELE(p);
251
252         return (0);
253 }
254
255 /*
256  * The knote may be attached to a different process, which may exit,
257  * leaving nothing for the knote to be attached to.  So when the process
258  * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
259  * it will be deleted when read out.  However, as part of the knote deletion,
260  * this routine is called, so a check is needed to avoid actually performing
261  * a detach, because the original process does not exist any more.
262  */
263 static void
264 filt_procdetach(struct knote *kn)
265 {
266         struct proc *p;
267
268         if (kn->kn_status & KN_DETACHED)
269                 return;
270         /* XXX locking? take proc_token here? */
271         p = kn->kn_ptr.p_proc;
272         knote_remove(&p->p_klist, kn);
273 }
274
275 static int
276 filt_proc(struct knote *kn, long hint)
277 {
278         u_int event;
279
280         /*
281          * mask off extra data
282          */
283         event = (u_int)hint & NOTE_PCTRLMASK;
284
285         /*
286          * if the user is interested in this event, record it.
287          */
288         if (kn->kn_sfflags & event)
289                 kn->kn_fflags |= event;
290
291         /*
292          * Process is gone, so flag the event as finished.  Detach the
293          * knote from the process now because the process will be poof,
294          * gone later on.
295          */
296         if (event == NOTE_EXIT) {
297                 struct proc *p = kn->kn_ptr.p_proc;
298                 if ((kn->kn_status & KN_DETACHED) == 0) {
299                         PHOLD(p);
300                         knote_remove(&p->p_klist, kn);
301                         kn->kn_status |= KN_DETACHED;
302                         kn->kn_data = p->p_xstat;
303                         kn->kn_ptr.p_proc = NULL;
304                         PRELE(p);
305                 }
306                 kn->kn_flags |= (EV_EOF | EV_NODATA | EV_ONESHOT); 
307                 return (1);
308         }
309
310         /*
311          * process forked, and user wants to track the new process,
312          * so attach a new knote to it, and immediately report an
313          * event with the parent's pid.
314          */
315         if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
316                 struct kevent kev;
317                 int error;
318
319                 /*
320                  * register knote with new process.
321                  */
322                 kev.ident = hint & NOTE_PDATAMASK;      /* pid */
323                 kev.filter = kn->kn_filter;
324                 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
325                 kev.fflags = kn->kn_sfflags;
326                 kev.data = kn->kn_id;                   /* parent */
327                 kev.udata = kn->kn_kevent.udata;        /* preserve udata */
328                 error = kqueue_register(kn->kn_kq, &kev);
329                 if (error)
330                         kn->kn_fflags |= NOTE_TRACKERR;
331         }
332
333         return (kn->kn_fflags != 0);
334 }
335
336 /*
337  * The callout interlocks with callout_terminate() but can still
338  * race a deletion so if KN_DELETING is set we just don't touch
339  * the knote.
340  */
341 static void
342 filt_timerexpire(void *knx)
343 {
344         struct lwkt_token *tok;
345         struct knote *kn = knx;
346         struct callout *calloutp;
347         struct timeval tv;
348         int tticks;
349
350         tok = lwkt_token_pool_lookup(kn->kn_kq);
351         lwkt_gettoken(tok);
352         if ((kn->kn_status & KN_DELETING) == 0) {
353                 kn->kn_data++;
354                 KNOTE_ACTIVATE(kn);
355
356                 if ((kn->kn_flags & EV_ONESHOT) == 0) {
357                         tv.tv_sec = kn->kn_sdata / 1000;
358                         tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
359                         tticks = tvtohz_high(&tv);
360                         calloutp = (struct callout *)kn->kn_hook;
361                         callout_reset(calloutp, tticks, filt_timerexpire, kn);
362                 }
363         }
364         lwkt_reltoken(tok);
365 }
366
367 /*
368  * data contains amount of time to sleep, in milliseconds
369  */ 
370 static int
371 filt_timerattach(struct knote *kn)
372 {
373         struct callout *calloutp;
374         struct timeval tv;
375         int tticks;
376
377         if (kq_ncallouts >= kq_calloutmax) {
378                 kn->kn_hook = NULL;
379                 return (ENOMEM);
380         }
381         kq_ncallouts++;
382
383         tv.tv_sec = kn->kn_sdata / 1000;
384         tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
385         tticks = tvtohz_high(&tv);
386
387         kn->kn_flags |= EV_CLEAR;               /* automatically set */
388         calloutp = kmalloc(sizeof(*calloutp), M_KQUEUE, M_WAITOK);
389         callout_init(calloutp);
390         kn->kn_hook = (caddr_t)calloutp;
391         callout_reset(calloutp, tticks, filt_timerexpire, kn);
392
393         return (0);
394 }
395
396 /*
397  * This function is called with the knote flagged locked but it is
398  * still possible to race a callout event due to the callback blocking.
399  * We must call callout_terminate() instead of callout_stop() to deal
400  * with the race.
401  */
402 static void
403 filt_timerdetach(struct knote *kn)
404 {
405         struct callout *calloutp;
406
407         calloutp = (struct callout *)kn->kn_hook;
408         callout_terminate(calloutp);
409         kfree(calloutp, M_KQUEUE);
410         kq_ncallouts--;
411 }
412
413 static int
414 filt_timer(struct knote *kn, long hint)
415 {
416
417         return (kn->kn_data != 0);
418 }
419
420 /*
421  * Acquire a knote, return non-zero on success, 0 on failure.
422  *
423  * If we cannot acquire the knote we sleep and return 0.  The knote
424  * may be stale on return in this case and the caller must restart
425  * whatever loop they are in.
426  *
427  * Related kq token must be held.
428  */
429 static __inline
430 int
431 knote_acquire(struct knote *kn)
432 {
433         if (kn->kn_status & KN_PROCESSING) {
434                 kn->kn_status |= KN_WAITING | KN_REPROCESS;
435                 tsleep(kn, 0, "kqepts", hz);
436                 /* knote may be stale now */
437                 return(0);
438         }
439         kn->kn_status |= KN_PROCESSING;
440         return(1);
441 }
442
443 /*
444  * Release an acquired knote, clearing KN_PROCESSING and handling any
445  * KN_REPROCESS events.
446  *
447  * Caller must be holding the related kq token
448  *
449  * Non-zero is returned if the knote is destroyed or detached.
450  */
451 static __inline
452 int
453 knote_release(struct knote *kn)
454 {
455         while (kn->kn_status & KN_REPROCESS) {
456                 kn->kn_status &= ~KN_REPROCESS;
457                 if (kn->kn_status & KN_WAITING) {
458                         kn->kn_status &= ~KN_WAITING;
459                         wakeup(kn);
460                 }
461                 if (kn->kn_status & KN_DELETING) {
462                         knote_detach_and_drop(kn);
463                         return(1);
464                         /* NOT REACHED */
465                 }
466                 if (filter_event(kn, 0))
467                         KNOTE_ACTIVATE(kn);
468         }
469         if (kn->kn_status & KN_DETACHED) {
470                 kn->kn_status &= ~KN_PROCESSING;
471                 return(1);
472         } else {
473                 kn->kn_status &= ~KN_PROCESSING;
474                 return(0);
475         }
476 }
477
478 /*
479  * Initialize a kqueue.
480  *
481  * NOTE: The lwp/proc code initializes a kqueue for select/poll ops.
482  *
483  * MPSAFE
484  */
485 void
486 kqueue_init(struct kqueue *kq, struct filedesc *fdp)
487 {
488         TAILQ_INIT(&kq->kq_knpend);
489         TAILQ_INIT(&kq->kq_knlist);
490         kq->kq_count = 0;
491         kq->kq_fdp = fdp;
492         SLIST_INIT(&kq->kq_kqinfo.ki_note);
493 }
494
495 /*
496  * Terminate a kqueue.  Freeing the actual kq itself is left up to the
497  * caller (it might be embedded in a lwp so we don't do it here).
498  *
499  * The kq's knlist must be completely eradicated so block on any
500  * processing races.
501  */
502 void
503 kqueue_terminate(struct kqueue *kq)
504 {
505         struct lwkt_token *tok;
506         struct knote *kn;
507
508         tok = lwkt_token_pool_lookup(kq);
509         lwkt_gettoken(tok);
510         while ((kn = TAILQ_FIRST(&kq->kq_knlist)) != NULL) {
511                 if (knote_acquire(kn))
512                         knote_detach_and_drop(kn);
513         }
514         if (kq->kq_knhash) {
515                 hashdestroy(kq->kq_knhash, M_KQUEUE, kq->kq_knhashmask);
516                 kq->kq_knhash = NULL;
517                 kq->kq_knhashmask = 0;
518         }
519         lwkt_reltoken(tok);
520 }
521
522 /*
523  * MPSAFE
524  */
525 int
526 sys_kqueue(struct kqueue_args *uap)
527 {
528         struct thread *td = curthread;
529         struct kqueue *kq;
530         struct file *fp;
531         int fd, error;
532
533         error = falloc(td->td_lwp, &fp, &fd);
534         if (error)
535                 return (error);
536         fp->f_flag = FREAD | FWRITE;
537         fp->f_type = DTYPE_KQUEUE;
538         fp->f_ops = &kqueueops;
539
540         kq = kmalloc(sizeof(struct kqueue), M_KQUEUE, M_WAITOK | M_ZERO);
541         kqueue_init(kq, td->td_proc->p_fd);
542         fp->f_data = kq;
543
544         fsetfd(kq->kq_fdp, fp, fd);
545         uap->sysmsg_result = fd;
546         fdrop(fp);
547         return (error);
548 }
549
550 /*
551  * Copy 'count' items into the destination list pointed to by uap->eventlist.
552  */
553 static int
554 kevent_copyout(void *arg, struct kevent *kevp, int count, int *res)
555 {
556         struct kevent_copyin_args *kap;
557         int error;
558
559         kap = (struct kevent_copyin_args *)arg;
560
561         error = copyout(kevp, kap->ka->eventlist, count * sizeof(*kevp));
562         if (error == 0) {
563                 kap->ka->eventlist += count;
564                 *res += count;
565         } else {
566                 *res = -1;
567         }
568
569         return (error);
570 }
571
572 /*
573  * Copy at most 'max' items from the list pointed to by kap->changelist,
574  * return number of items in 'events'.
575  */
576 static int
577 kevent_copyin(void *arg, struct kevent *kevp, int max, int *events)
578 {
579         struct kevent_copyin_args *kap;
580         int error, count;
581
582         kap = (struct kevent_copyin_args *)arg;
583
584         count = min(kap->ka->nchanges - kap->pchanges, max);
585         error = copyin(kap->ka->changelist, kevp, count * sizeof *kevp);
586         if (error == 0) {
587                 kap->ka->changelist += count;
588                 kap->pchanges += count;
589                 *events = count;
590         }
591
592         return (error);
593 }
594
595 /*
596  * MPSAFE
597  */
598 int
599 kern_kevent(struct kqueue *kq, int nevents, int *res, void *uap,
600             k_copyin_fn kevent_copyinfn, k_copyout_fn kevent_copyoutfn,
601             struct timespec *tsp_in)
602 {
603         struct kevent *kevp;
604         struct timespec *tsp;
605         int i, n, total, error, nerrors = 0;
606         int lres;
607         int limit = kq_checkloop;
608         struct kevent kev[KQ_NEVENTS];
609         struct knote marker;
610         struct lwkt_token *tok;
611
612         if (tsp_in == NULL || tsp_in->tv_sec || tsp_in->tv_nsec)
613                 atomic_set_int(&curthread->td_mpflags, TDF_MP_BATCH_DEMARC);
614
615
616         tsp = tsp_in;
617         *res = 0;
618
619         tok = lwkt_token_pool_lookup(kq);
620         lwkt_gettoken(tok);
621         for ( ;; ) {
622                 n = 0;
623                 error = kevent_copyinfn(uap, kev, KQ_NEVENTS, &n);
624                 if (error)
625                         goto done;
626                 if (n == 0)
627                         break;
628                 for (i = 0; i < n; i++) {
629                         kevp = &kev[i];
630                         kevp->flags &= ~EV_SYSFLAGS;
631                         error = kqueue_register(kq, kevp);
632
633                         /*
634                          * If a registration returns an error we
635                          * immediately post the error.  The kevent()
636                          * call itself will fail with the error if
637                          * no space is available for posting.
638                          *
639                          * Such errors normally bypass the timeout/blocking
640                          * code.  However, if the copyoutfn function refuses
641                          * to post the error (see sys_poll()), then we
642                          * ignore it too.
643                          */
644                         if (error) {
645                                 kevp->flags = EV_ERROR;
646                                 kevp->data = error;
647                                 lres = *res;
648                                 kevent_copyoutfn(uap, kevp, 1, res);
649                                 if (*res < 0) {
650                                         goto done;
651                                 } else if (lres != *res) {
652                                         nevents--;
653                                         nerrors++;
654                                 }
655                         }
656                 }
657         }
658         if (nerrors) {
659                 error = 0;
660                 goto done;
661         }
662
663         /*
664          * Acquire/wait for events - setup timeout
665          */
666         if (tsp != NULL) {
667                 struct timespec ats;
668
669                 if (tsp->tv_sec || tsp->tv_nsec) {
670                         getnanouptime(&ats);
671                         timespecadd(tsp, &ats);         /* tsp = target time */
672                 }
673         }
674
675         /*
676          * Loop as required.
677          *
678          * Collect as many events as we can. Sleeping on successive
679          * loops is disabled if copyoutfn has incremented (*res).
680          *
681          * The loop stops if an error occurs, all events have been
682          * scanned (the marker has been reached), or fewer than the
683          * maximum number of events is found.
684          *
685          * The copyoutfn function does not have to increment (*res) in
686          * order for the loop to continue.
687          *
688          * NOTE: doselect() usually passes 0x7FFFFFFF for nevents.
689          */
690         total = 0;
691         error = 0;
692         marker.kn_filter = EVFILT_MARKER;
693         marker.kn_status = KN_PROCESSING;
694         TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
695         while ((n = nevents - total) > 0) {
696                 if (n > KQ_NEVENTS)
697                         n = KQ_NEVENTS;
698
699                 /*
700                  * If no events are pending sleep until timeout (if any)
701                  * or an event occurs.
702                  *
703                  * After the sleep completes the marker is moved to the
704                  * end of the list, making any received events available
705                  * to our scan.
706                  */
707                 if (kq->kq_count == 0 && *res == 0) {
708                         error = kqueue_sleep(kq, tsp);
709                         if (error)
710                                 break;
711
712                         TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
713                         TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
714                 }
715
716                 /*
717                  * Process all received events
718                  * Account for all non-spurious events in our total
719                  */
720                 i = kqueue_scan(kq, kev, n, &marker);
721                 if (i) {
722                         lres = *res;
723                         error = kevent_copyoutfn(uap, kev, i, res);
724                         total += *res - lres;
725                         if (error)
726                                 break;
727                 }
728                 if (limit && --limit == 0)
729                         panic("kqueue: checkloop failed i=%d", i);
730
731                 /*
732                  * Normally when fewer events are returned than requested
733                  * we can stop.  However, if only spurious events were
734                  * collected the copyout will not bump (*res) and we have
735                  * to continue.
736                  */
737                 if (i < n && *res)
738                         break;
739
740                 /*
741                  * Deal with an edge case where spurious events can cause
742                  * a loop to occur without moving the marker.  This can
743                  * prevent kqueue_scan() from picking up new events which
744                  * race us.  We must be sure to move the marker for this
745                  * case.
746                  *
747                  * NOTE: We do not want to move the marker if events
748                  *       were scanned because normal kqueue operations
749                  *       may reactivate events.  Moving the marker in
750                  *       that case could result in duplicates for the
751                  *       same event.
752                  */
753                 if (i == 0) {
754                         TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
755                         TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
756                 }
757         }
758         TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
759
760         /* Timeouts do not return EWOULDBLOCK. */
761         if (error == EWOULDBLOCK)
762                 error = 0;
763
764 done:
765         lwkt_reltoken(tok);
766         return (error);
767 }
768
769 /*
770  * MPALMOSTSAFE
771  */
772 int
773 sys_kevent(struct kevent_args *uap)
774 {
775         struct thread *td = curthread;
776         struct proc *p = td->td_proc;
777         struct timespec ts, *tsp;
778         struct kqueue *kq;
779         struct file *fp = NULL;
780         struct kevent_copyin_args *kap, ka;
781         int error;
782
783         if (uap->timeout) {
784                 error = copyin(uap->timeout, &ts, sizeof(ts));
785                 if (error)
786                         return (error);
787                 tsp = &ts;
788         } else {
789                 tsp = NULL;
790         }
791         fp = holdfp(p->p_fd, uap->fd, -1);
792         if (fp == NULL)
793                 return (EBADF);
794         if (fp->f_type != DTYPE_KQUEUE) {
795                 fdrop(fp);
796                 return (EBADF);
797         }
798
799         kq = (struct kqueue *)fp->f_data;
800
801         kap = &ka;
802         kap->ka = uap;
803         kap->pchanges = 0;
804
805         error = kern_kevent(kq, uap->nevents, &uap->sysmsg_result, kap,
806                             kevent_copyin, kevent_copyout, tsp);
807
808         fdrop(fp);
809
810         return (error);
811 }
812
813 /*
814  * Caller must be holding the kq token
815  */
816 int
817 kqueue_register(struct kqueue *kq, struct kevent *kev)
818 {
819         struct lwkt_token *tok;
820         struct filedesc *fdp = kq->kq_fdp;
821         struct filterops *fops;
822         struct file *fp = NULL;
823         struct knote *kn = NULL;
824         int error = 0;
825
826         if (kev->filter < 0) {
827                 if (kev->filter + EVFILT_SYSCOUNT < 0)
828                         return (EINVAL);
829                 fops = sysfilt_ops[~kev->filter];       /* to 0-base index */
830         } else {
831                 /*
832                  * XXX
833                  * filter attach routine is responsible for insuring that
834                  * the identifier can be attached to it.
835                  */
836                 kprintf("unknown filter: %d\n", kev->filter);
837                 return (EINVAL);
838         }
839
840         tok = lwkt_token_pool_lookup(kq);
841         lwkt_gettoken(tok);
842         if (fops->f_flags & FILTEROP_ISFD) {
843                 /* validate descriptor */
844                 fp = holdfp(fdp, kev->ident, -1);
845                 if (fp == NULL) {
846                         lwkt_reltoken(tok);
847                         return (EBADF);
848                 }
849                 lwkt_getpooltoken(&fp->f_klist);
850 again1:
851                 SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
852                         if (kn->kn_kq == kq &&
853                             kn->kn_filter == kev->filter &&
854                             kn->kn_id == kev->ident) {
855                                 if (knote_acquire(kn) == 0)
856                                         goto again1;
857                                 break;
858                         }
859                 }
860                 lwkt_relpooltoken(&fp->f_klist);
861         } else {
862                 if (kq->kq_knhashmask) {
863                         struct klist *list;
864                         
865                         list = &kq->kq_knhash[
866                             KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
867                         lwkt_getpooltoken(list);
868 again2:
869                         SLIST_FOREACH(kn, list, kn_link) {
870                                 if (kn->kn_id == kev->ident &&
871                                     kn->kn_filter == kev->filter) {
872                                         if (knote_acquire(kn) == 0)
873                                                 goto again2;
874                                         break;
875                                 }
876                         }
877                         lwkt_relpooltoken(list);
878                 }
879         }
880
881         /*
882          * NOTE: At this point if kn is non-NULL we will have acquired
883          *       it and set KN_PROCESSING.
884          */
885         if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
886                 error = ENOENT;
887                 goto done;
888         }
889
890         /*
891          * kn now contains the matching knote, or NULL if no match
892          */
893         if (kev->flags & EV_ADD) {
894                 if (kn == NULL) {
895                         kn = knote_alloc();
896                         if (kn == NULL) {
897                                 error = ENOMEM;
898                                 goto done;
899                         }
900                         kn->kn_fp = fp;
901                         kn->kn_kq = kq;
902                         kn->kn_fop = fops;
903
904                         /*
905                          * apply reference count to knote structure, and
906                          * do not release it at the end of this routine.
907                          */
908                         fp = NULL;
909
910                         kn->kn_sfflags = kev->fflags;
911                         kn->kn_sdata = kev->data;
912                         kev->fflags = 0;
913                         kev->data = 0;
914                         kn->kn_kevent = *kev;
915
916                         /*
917                          * KN_PROCESSING prevents the knote from getting
918                          * ripped out from under us while we are trying
919                          * to attach it, in case the attach blocks.
920                          */
921                         kn->kn_status = KN_PROCESSING;
922                         knote_attach(kn);
923                         if ((error = filter_attach(kn)) != 0) {
924                                 kn->kn_status |= KN_DELETING | KN_REPROCESS;
925                                 knote_drop(kn);
926                                 goto done;
927                         }
928
929                         /*
930                          * Interlock against close races which either tried
931                          * to remove our knote while we were blocked or missed
932                          * it entirely prior to our attachment.  We do not
933                          * want to end up with a knote on a closed descriptor.
934                          */
935                         if ((fops->f_flags & FILTEROP_ISFD) &&
936                             checkfdclosed(fdp, kev->ident, kn->kn_fp)) {
937                                 kn->kn_status |= KN_DELETING | KN_REPROCESS;
938                         }
939                 } else {
940                         /*
941                          * The user may change some filter values after the
942                          * initial EV_ADD, but doing so will not reset any 
943                          * filter which have already been triggered.
944                          */
945                         KKASSERT(kn->kn_status & KN_PROCESSING);
946                         kn->kn_sfflags = kev->fflags;
947                         kn->kn_sdata = kev->data;
948                         kn->kn_kevent.udata = kev->udata;
949                 }
950
951                 /*
952                  * Execute the filter event to immediately activate the
953                  * knote if necessary.  If reprocessing events are pending
954                  * due to blocking above we do not run the filter here
955                  * but instead let knote_release() do it.  Otherwise we
956                  * might run the filter on a deleted event.
957                  */
958                 if ((kn->kn_status & KN_REPROCESS) == 0) {
959                         if (filter_event(kn, 0))
960                                 KNOTE_ACTIVATE(kn);
961                 }
962         } else if (kev->flags & EV_DELETE) {
963                 /*
964                  * Delete the existing knote
965                  */
966                 knote_detach_and_drop(kn);
967                 goto done;
968         }
969
970         /*
971          * Disablement does not deactivate a knote here.
972          */
973         if ((kev->flags & EV_DISABLE) &&
974             ((kn->kn_status & KN_DISABLED) == 0)) {
975                 kn->kn_status |= KN_DISABLED;
976         }
977
978         /*
979          * Re-enablement may have to immediately enqueue an active knote.
980          */
981         if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
982                 kn->kn_status &= ~KN_DISABLED;
983                 if ((kn->kn_status & KN_ACTIVE) &&
984                     ((kn->kn_status & KN_QUEUED) == 0)) {
985                         knote_enqueue(kn);
986                 }
987         }
988
989         /*
990          * Handle any required reprocessing
991          */
992         knote_release(kn);
993         /* kn may be invalid now */
994
995 done:
996         lwkt_reltoken(tok);
997         if (fp != NULL)
998                 fdrop(fp);
999         return (error);
1000 }
1001
1002 /*
1003  * Block as necessary until the target time is reached.
1004  * If tsp is NULL we block indefinitely.  If tsp->ts_secs/nsecs are both
1005  * 0 we do not block at all.
1006  *
1007  * Caller must be holding the kq token.
1008  */
1009 static int
1010 kqueue_sleep(struct kqueue *kq, struct timespec *tsp)
1011 {
1012         int error = 0;
1013
1014         if (tsp == NULL) {
1015                 kq->kq_state |= KQ_SLEEP;
1016                 error = tsleep(kq, PCATCH, "kqread", 0);
1017         } else if (tsp->tv_sec == 0 && tsp->tv_nsec == 0) {
1018                 error = EWOULDBLOCK;
1019         } else {
1020                 struct timespec ats;
1021                 struct timespec atx = *tsp;
1022                 int timeout;
1023
1024                 getnanouptime(&ats);
1025                 timespecsub(&atx, &ats);
1026                 if (ats.tv_sec < 0) {
1027                         error = EWOULDBLOCK;
1028                 } else {
1029                         timeout = atx.tv_sec > 24 * 60 * 60 ?
1030                                 24 * 60 * 60 * hz : tstohz_high(&atx);
1031                         kq->kq_state |= KQ_SLEEP;
1032                         error = tsleep(kq, PCATCH, "kqread", timeout);
1033                 }
1034         }
1035
1036         /* don't restart after signals... */
1037         if (error == ERESTART)
1038                 return (EINTR);
1039
1040         return (error);
1041 }
1042
1043 /*
1044  * Scan the kqueue, return the number of active events placed in kevp up
1045  * to count.
1046  *
1047  * Continuous mode events may get recycled, do not continue scanning past
1048  * marker unless no events have been collected.
1049  *
1050  * Caller must be holding the kq token
1051  */
1052 static int
1053 kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
1054             struct knote *marker)
1055 {
1056         struct knote *kn, local_marker;
1057         int total;
1058
1059         total = 0;
1060         local_marker.kn_filter = EVFILT_MARKER;
1061         local_marker.kn_status = KN_PROCESSING;
1062
1063         /*
1064          * Collect events.
1065          */
1066         TAILQ_INSERT_HEAD(&kq->kq_knpend, &local_marker, kn_tqe);
1067         while (count) {
1068                 kn = TAILQ_NEXT(&local_marker, kn_tqe);
1069                 if (kn->kn_filter == EVFILT_MARKER) {
1070                         /* Marker reached, we are done */
1071                         if (kn == marker)
1072                                 break;
1073
1074                         /* Move local marker past some other threads marker */
1075                         kn = TAILQ_NEXT(kn, kn_tqe);
1076                         TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1077                         TAILQ_INSERT_BEFORE(kn, &local_marker, kn_tqe);
1078                         continue;
1079                 }
1080
1081                 /*
1082                  * We can't skip a knote undergoing processing, otherwise
1083                  * we risk not returning it when the user process expects
1084                  * it should be returned.  Sleep and retry.
1085                  */
1086                 if (knote_acquire(kn) == 0)
1087                         continue;
1088
1089                 /*
1090                  * Remove the event for processing.
1091                  *
1092                  * WARNING!  We must leave KN_QUEUED set to prevent the
1093                  *           event from being KNOTE_ACTIVATE()d while
1094                  *           the queue state is in limbo, in case we
1095                  *           block.
1096                  *
1097                  * WARNING!  We must set KN_PROCESSING to avoid races
1098                  *           against deletion or another thread's
1099                  *           processing.
1100                  */
1101                 TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1102                 kq->kq_count--;
1103
1104                 /*
1105                  * We have to deal with an extremely important race against
1106                  * file descriptor close()s here.  The file descriptor can
1107                  * disappear MPSAFE, and there is a small window of
1108                  * opportunity between that and the call to knote_fdclose().
1109                  *
1110                  * If we hit that window here while doselect or dopoll is
1111                  * trying to delete a spurious event they will not be able
1112                  * to match up the event against a knote and will go haywire.
1113                  */
1114                 if ((kn->kn_fop->f_flags & FILTEROP_ISFD) &&
1115                     checkfdclosed(kq->kq_fdp, kn->kn_kevent.ident, kn->kn_fp)) {
1116                         kn->kn_status |= KN_DELETING | KN_REPROCESS;
1117                 }
1118
1119                 if (kn->kn_status & KN_DISABLED) {
1120                         /*
1121                          * If disabled we ensure the event is not queued
1122                          * but leave its active bit set.  On re-enablement
1123                          * the event may be immediately triggered.
1124                          */
1125                         kn->kn_status &= ~KN_QUEUED;
1126                 } else if ((kn->kn_flags & EV_ONESHOT) == 0 &&
1127                            (kn->kn_status & KN_DELETING) == 0 &&
1128                            filter_event(kn, 0) == 0) {
1129                         /*
1130                          * If not running in one-shot mode and the event
1131                          * is no longer present we ensure it is removed
1132                          * from the queue and ignore it.
1133                          */
1134                         kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1135                 } else {
1136                         /*
1137                          * Post the event
1138                          */
1139                         *kevp++ = kn->kn_kevent;
1140                         ++total;
1141                         --count;
1142
1143                         if (kn->kn_flags & EV_ONESHOT) {
1144                                 kn->kn_status &= ~KN_QUEUED;
1145                                 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1146                         } else if (kn->kn_flags & EV_CLEAR) {
1147                                 kn->kn_data = 0;
1148                                 kn->kn_fflags = 0;
1149                                 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1150                         } else {
1151                                 TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1152                                 kq->kq_count++;
1153                         }
1154                 }
1155
1156                 /*
1157                  * Handle any post-processing states
1158                  */
1159                 knote_release(kn);
1160         }
1161         TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1162
1163         return (total);
1164 }
1165
1166 /*
1167  * XXX
1168  * This could be expanded to call kqueue_scan, if desired.
1169  *
1170  * MPSAFE
1171  */
1172 static int
1173 kqueue_read(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1174 {
1175         return (ENXIO);
1176 }
1177
1178 /*
1179  * MPSAFE
1180  */
1181 static int
1182 kqueue_write(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1183 {
1184         return (ENXIO);
1185 }
1186
1187 /*
1188  * MPALMOSTSAFE
1189  */
1190 static int
1191 kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
1192              struct ucred *cred, struct sysmsg *msg)
1193 {
1194         struct lwkt_token *tok;
1195         struct kqueue *kq;
1196         int error;
1197
1198         kq = (struct kqueue *)fp->f_data;
1199         tok = lwkt_token_pool_lookup(kq);
1200         lwkt_gettoken(tok);
1201
1202         switch(com) {
1203         case FIOASYNC:
1204                 if (*(int *)data)
1205                         kq->kq_state |= KQ_ASYNC;
1206                 else
1207                         kq->kq_state &= ~KQ_ASYNC;
1208                 error = 0;
1209                 break;
1210         case FIOSETOWN:
1211                 error = fsetown(*(int *)data, &kq->kq_sigio);
1212                 break;
1213         default:
1214                 error = ENOTTY;
1215                 break;
1216         }
1217         lwkt_reltoken(tok);
1218         return (error);
1219 }
1220
1221 /*
1222  * MPSAFE
1223  */
1224 static int
1225 kqueue_stat(struct file *fp, struct stat *st, struct ucred *cred)
1226 {
1227         struct kqueue *kq = (struct kqueue *)fp->f_data;
1228
1229         bzero((void *)st, sizeof(*st));
1230         st->st_size = kq->kq_count;
1231         st->st_blksize = sizeof(struct kevent);
1232         st->st_mode = S_IFIFO;
1233         return (0);
1234 }
1235
1236 /*
1237  * MPSAFE
1238  */
1239 static int
1240 kqueue_close(struct file *fp)
1241 {
1242         struct kqueue *kq = (struct kqueue *)fp->f_data;
1243
1244         kqueue_terminate(kq);
1245
1246         fp->f_data = NULL;
1247         funsetown(&kq->kq_sigio);
1248
1249         kfree(kq, M_KQUEUE);
1250         return (0);
1251 }
1252
1253 static void
1254 kqueue_wakeup(struct kqueue *kq)
1255 {
1256         if (kq->kq_state & KQ_SLEEP) {
1257                 kq->kq_state &= ~KQ_SLEEP;
1258                 wakeup(kq);
1259         }
1260         KNOTE(&kq->kq_kqinfo.ki_note, 0);
1261 }
1262
1263 /*
1264  * Calls filterops f_attach function, acquiring mplock if filter is not
1265  * marked as FILTEROP_MPSAFE.
1266  *
1267  * Caller must be holding the related kq token
1268  */
1269 static int
1270 filter_attach(struct knote *kn)
1271 {
1272         int ret;
1273
1274         if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1275                 ret = kn->kn_fop->f_attach(kn);
1276         } else {
1277                 get_mplock();
1278                 ret = kn->kn_fop->f_attach(kn);
1279                 rel_mplock();
1280         }
1281         return (ret);
1282 }
1283
1284 /*
1285  * Detach the knote and drop it, destroying the knote.
1286  *
1287  * Calls filterops f_detach function, acquiring mplock if filter is not
1288  * marked as FILTEROP_MPSAFE.
1289  *
1290  * Caller must be holding the related kq token
1291  */
1292 static void
1293 knote_detach_and_drop(struct knote *kn)
1294 {
1295         kn->kn_status |= KN_DELETING | KN_REPROCESS;
1296         if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1297                 kn->kn_fop->f_detach(kn);
1298         } else {
1299                 get_mplock();
1300                 kn->kn_fop->f_detach(kn);
1301                 rel_mplock();
1302         }
1303         knote_drop(kn);
1304 }
1305
1306 /*
1307  * Calls filterops f_event function, acquiring mplock if filter is not
1308  * marked as FILTEROP_MPSAFE.
1309  *
1310  * If the knote is in the middle of being created or deleted we cannot
1311  * safely call the filter op.
1312  *
1313  * Caller must be holding the related kq token
1314  */
1315 static int
1316 filter_event(struct knote *kn, long hint)
1317 {
1318         int ret;
1319
1320         if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1321                 ret = kn->kn_fop->f_event(kn, hint);
1322         } else {
1323                 get_mplock();
1324                 ret = kn->kn_fop->f_event(kn, hint);
1325                 rel_mplock();
1326         }
1327         return (ret);
1328 }
1329
1330 /*
1331  * Walk down a list of knotes, activating them if their event has triggered.
1332  *
1333  * If we encounter any knotes which are undergoing processing we just mark
1334  * them for reprocessing and do not try to [re]activate the knote.  However,
1335  * if a hint is being passed we have to wait and that makes things a bit
1336  * sticky.
1337  */
1338 void
1339 knote(struct klist *list, long hint)
1340 {
1341         struct kqueue *kq;
1342         struct knote *kn;
1343         struct knote *kntmp;
1344
1345         lwkt_getpooltoken(list);
1346 restart:
1347         SLIST_FOREACH(kn, list, kn_next) {
1348                 kq = kn->kn_kq;
1349                 lwkt_getpooltoken(kq);
1350
1351                 /* temporary verification hack */
1352                 SLIST_FOREACH(kntmp, list, kn_next) {
1353                         if (kn == kntmp)
1354                                 break;
1355                 }
1356                 if (kn != kntmp || kn->kn_kq != kq) {
1357                         lwkt_relpooltoken(kq);
1358                         goto restart;
1359                 }
1360
1361                 if (kn->kn_status & KN_PROCESSING) {
1362                         /*
1363                          * Someone else is processing the knote, ask the
1364                          * other thread to reprocess it and don't mess
1365                          * with it otherwise.
1366                          */
1367                         if (hint == 0) {
1368                                 kn->kn_status |= KN_REPROCESS;
1369                                 lwkt_relpooltoken(kq);
1370                                 continue;
1371                         }
1372
1373                         /*
1374                          * If the hint is non-zero we have to wait or risk
1375                          * losing the state the caller is trying to update.
1376                          *
1377                          * XXX This is a real problem, certain process
1378                          *     and signal filters will bump kn_data for
1379                          *     already-processed notes more than once if
1380                          *     we restart the list scan.  FIXME.
1381                          */
1382                         kn->kn_status |= KN_WAITING | KN_REPROCESS;
1383                         tsleep(kn, 0, "knotec", hz);
1384                         lwkt_relpooltoken(kq);
1385                         goto restart;
1386                 }
1387
1388                 /*
1389                  * Become the reprocessing master ourselves.
1390                  *
1391                  * If hint is non-zer running the event is mandatory
1392                  * when not deleting so do it whether reprocessing is
1393                  * set or not.
1394                  */
1395                 kn->kn_status |= KN_PROCESSING;
1396                 if ((kn->kn_status & KN_DELETING) == 0) {
1397                         if (filter_event(kn, hint))
1398                                 KNOTE_ACTIVATE(kn);
1399                 }
1400                 if (knote_release(kn)) {
1401                         lwkt_relpooltoken(kq);
1402                         goto restart;
1403                 }
1404                 lwkt_relpooltoken(kq);
1405         }
1406         lwkt_relpooltoken(list);
1407 }
1408
1409 /*
1410  * Insert knote at head of klist.
1411  *
1412  * This function may only be called via a filter function and thus
1413  * kq_token should already be held and marked for processing.
1414  */
1415 void
1416 knote_insert(struct klist *klist, struct knote *kn)
1417 {
1418         lwkt_getpooltoken(klist);
1419         KKASSERT(kn->kn_status & KN_PROCESSING);
1420         SLIST_INSERT_HEAD(klist, kn, kn_next);
1421         lwkt_relpooltoken(klist);
1422 }
1423
1424 /*
1425  * Remove knote from a klist
1426  *
1427  * This function may only be called via a filter function and thus
1428  * kq_token should already be held and marked for processing.
1429  */
1430 void
1431 knote_remove(struct klist *klist, struct knote *kn)
1432 {
1433         lwkt_getpooltoken(klist);
1434         KKASSERT(kn->kn_status & KN_PROCESSING);
1435         SLIST_REMOVE(klist, kn, knote, kn_next);
1436         lwkt_relpooltoken(klist);
1437 }
1438
1439 #if 0
1440 /*
1441  * Remove all knotes from a specified klist
1442  *
1443  * Only called from aio.
1444  */
1445 void
1446 knote_empty(struct klist *list)
1447 {
1448         struct knote *kn;
1449
1450         lwkt_gettoken(&kq_token);
1451         while ((kn = SLIST_FIRST(list)) != NULL) {
1452                 if (knote_acquire(kn))
1453                         knote_detach_and_drop(kn);
1454         }
1455         lwkt_reltoken(&kq_token);
1456 }
1457 #endif
1458
1459 void
1460 knote_assume_knotes(struct kqinfo *src, struct kqinfo *dst,
1461                     struct filterops *ops, void *hook)
1462 {
1463         struct kqueue *kq;
1464         struct knote *kn;
1465
1466         lwkt_getpooltoken(&src->ki_note);
1467         lwkt_getpooltoken(&dst->ki_note);
1468         while ((kn = SLIST_FIRST(&src->ki_note)) != NULL) {
1469                 kq = kn->kn_kq;
1470                 lwkt_getpooltoken(kq);
1471                 if (SLIST_FIRST(&src->ki_note) != kn || kn->kn_kq != kq) {
1472                         lwkt_relpooltoken(kq);
1473                         continue;
1474                 }
1475                 if (knote_acquire(kn)) {
1476                         knote_remove(&src->ki_note, kn);
1477                         kn->kn_fop = ops;
1478                         kn->kn_hook = hook;
1479                         knote_insert(&dst->ki_note, kn);
1480                         knote_release(kn);
1481                         /* kn may be invalid now */
1482                 }
1483                 lwkt_relpooltoken(kq);
1484         }
1485         lwkt_relpooltoken(&dst->ki_note);
1486         lwkt_relpooltoken(&src->ki_note);
1487 }
1488
1489 /*
1490  * Remove all knotes referencing a specified fd
1491  */
1492 void
1493 knote_fdclose(struct file *fp, struct filedesc *fdp, int fd)
1494 {
1495         struct kqueue *kq;
1496         struct knote *kn;
1497         struct knote *kntmp;
1498
1499         lwkt_getpooltoken(&fp->f_klist);
1500 restart:
1501         SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
1502                 if (kn->kn_kq->kq_fdp == fdp && kn->kn_id == fd) {
1503                         kq = kn->kn_kq;
1504                         lwkt_getpooltoken(kq);
1505
1506                         /* temporary verification hack */
1507                         SLIST_FOREACH(kntmp, &fp->f_klist, kn_link) {
1508                                 if (kn == kntmp)
1509                                         break;
1510                         }
1511                         if (kn != kntmp || kn->kn_kq->kq_fdp != fdp ||
1512                             kn->kn_id != fd || kn->kn_kq != kq) {
1513                                 lwkt_relpooltoken(kq);
1514                                 goto restart;
1515                         }
1516                         if (knote_acquire(kn))
1517                                 knote_detach_and_drop(kn);
1518                         lwkt_relpooltoken(kq);
1519                         goto restart;
1520                 }
1521         }
1522         lwkt_relpooltoken(&fp->f_klist);
1523 }
1524
1525 /*
1526  * Low level attach function.
1527  *
1528  * The knote should already be marked for processing.
1529  * Caller must hold the related kq token.
1530  */
1531 static void
1532 knote_attach(struct knote *kn)
1533 {
1534         struct klist *list;
1535         struct kqueue *kq = kn->kn_kq;
1536
1537         if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1538                 KKASSERT(kn->kn_fp);
1539                 list = &kn->kn_fp->f_klist;
1540         } else {
1541                 if (kq->kq_knhashmask == 0)
1542                         kq->kq_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1543                                                  &kq->kq_knhashmask);
1544                 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1545         }
1546         lwkt_getpooltoken(list);
1547         SLIST_INSERT_HEAD(list, kn, kn_link);
1548         TAILQ_INSERT_HEAD(&kq->kq_knlist, kn, kn_kqlink);
1549         lwkt_relpooltoken(list);
1550 }
1551
1552 /*
1553  * Low level drop function.
1554  *
1555  * The knote should already be marked for processing.
1556  * Caller must hold the related kq token.
1557  */
1558 static void
1559 knote_drop(struct knote *kn)
1560 {
1561         struct kqueue *kq;
1562         struct klist *list;
1563
1564         kq = kn->kn_kq;
1565
1566         if (kn->kn_fop->f_flags & FILTEROP_ISFD)
1567                 list = &kn->kn_fp->f_klist;
1568         else
1569                 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1570
1571         lwkt_getpooltoken(list);
1572         SLIST_REMOVE(list, kn, knote, kn_link);
1573         TAILQ_REMOVE(&kq->kq_knlist, kn, kn_kqlink);
1574         if (kn->kn_status & KN_QUEUED)
1575                 knote_dequeue(kn);
1576         if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1577                 fdrop(kn->kn_fp);
1578                 kn->kn_fp = NULL;
1579         }
1580         knote_free(kn);
1581         lwkt_relpooltoken(list);
1582 }
1583
1584 /*
1585  * Low level enqueue function.
1586  *
1587  * The knote should already be marked for processing.
1588  * Caller must be holding the kq token
1589  */
1590 static void
1591 knote_enqueue(struct knote *kn)
1592 {
1593         struct kqueue *kq = kn->kn_kq;
1594
1595         KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
1596         TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1597         kn->kn_status |= KN_QUEUED;
1598         ++kq->kq_count;
1599
1600         /*
1601          * Send SIGIO on request (typically set up as a mailbox signal)
1602          */
1603         if (kq->kq_sigio && (kq->kq_state & KQ_ASYNC) && kq->kq_count == 1)
1604                 pgsigio(kq->kq_sigio, SIGIO, 0);
1605
1606         kqueue_wakeup(kq);
1607 }
1608
1609 /*
1610  * Low level dequeue function.
1611  *
1612  * The knote should already be marked for processing.
1613  * Caller must be holding the kq token
1614  */
1615 static void
1616 knote_dequeue(struct knote *kn)
1617 {
1618         struct kqueue *kq = kn->kn_kq;
1619
1620         KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
1621         TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1622         kn->kn_status &= ~KN_QUEUED;
1623         kq->kq_count--;
1624 }
1625
1626 static struct knote *
1627 knote_alloc(void)
1628 {
1629         return kmalloc(sizeof(struct knote), M_KQUEUE, M_WAITOK);
1630 }
1631
1632 static void
1633 knote_free(struct knote *kn)
1634 {
1635         kfree(kn, M_KQUEUE);
1636 }