1 /*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
5 * Copyright 2004 John-Mark Gurney <jmg@FreeBSD.org>
6 * Copyright (c) 2009 Apple, Inc.
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * SUCH DAMAGE.
29 */
30
31 #include <sys/cdefs.h>
32 #include "opt_ktrace.h"
33 #include "opt_kqueue.h"
34
35 #ifdef COMPAT_FREEBSD11
36 #define _WANT_FREEBSD11_KEVENT
37 #endif
38
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/capsicum.h>
42 #include <sys/kernel.h>
43 #include <sys/limits.h>
44 #include <sys/lock.h>
45 #include <sys/mutex.h>
46 #include <sys/rwlock.h>
47 #include <sys/proc.h>
48 #include <sys/malloc.h>
49 #include <sys/unistd.h>
50 #include <sys/file.h>
51 #include <sys/filedesc.h>
52 #include <sys/filio.h>
53 #include <sys/fcntl.h>
54 #include <sys/kthread.h>
55 #include <sys/selinfo.h>
56 #include <sys/queue.h>
57 #include <sys/event.h>
58 #include <sys/eventvar.h>
59 #include <sys/poll.h>
60 #include <sys/protosw.h>
61 #include <sys/resourcevar.h>
62 #include <sys/sigio.h>
63 #include <sys/signalvar.h>
64 #include <sys/socket.h>
65 #include <sys/socketvar.h>
66 #include <sys/stat.h>
67 #include <sys/sysctl.h>
68 #include <sys/sysproto.h>
69 #include <sys/syscallsubr.h>
70 #include <sys/taskqueue.h>
71 #include <sys/uio.h>
72 #include <sys/user.h>
73 #ifdef KTRACE
74 #include <sys/ktrace.h>
75 #endif
76 #include <machine/atomic.h>
77
78 #include <vm/uma.h>
79
80 static MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
81
82 /*
83 * This lock is used if multiple kq locks are required. This possibly
84 * should be made into a per proc lock.
85 */
86 static struct mtx kq_global;
87 MTX_SYSINIT(kq_global, &kq_global, "kqueue order", MTX_DEF);
88 #define KQ_GLOBAL_LOCK(lck, haslck) do { \
89 if (!haslck) \
90 mtx_lock(lck); \
91 haslck = 1; \
92 } while (0)
93 #define KQ_GLOBAL_UNLOCK(lck, haslck) do { \
94 if (haslck) \
95 mtx_unlock(lck); \
96 haslck = 0; \
97 } while (0)
98
99 TASKQUEUE_DEFINE_THREAD(kqueue_ctx);
100
101 static int kevent_copyout(void *arg, struct kevent *kevp, int count);
102 static int kevent_copyin(void *arg, struct kevent *kevp, int count);
103 static int kqueue_register(struct kqueue *kq, struct kevent *kev,
104 struct thread *td, int mflag);
105 static int kqueue_acquire(struct file *fp, struct kqueue **kqp);
106 static void kqueue_release(struct kqueue *kq, int locked);
107 static void kqueue_destroy(struct kqueue *kq);
108 static void kqueue_drain(struct kqueue *kq, struct thread *td);
109 static int kqueue_expand(struct kqueue *kq, const struct filterops *fops,
110 uintptr_t ident, int mflag);
111 static void kqueue_task(void *arg, int pending);
112 static int kqueue_scan(struct kqueue *kq, int maxevents,
113 struct kevent_copyops *k_ops,
114 const struct timespec *timeout,
115 struct kevent *keva, struct thread *td);
116 static void kqueue_wakeup(struct kqueue *kq);
117 static const struct filterops *kqueue_fo_find(int filt);
118 static void kqueue_fo_release(int filt);
119 struct g_kevent_args;
120 static int kern_kevent_generic(struct thread *td,
121 struct g_kevent_args *uap,
122 struct kevent_copyops *k_ops, const char *struct_name);
123
124 static fo_ioctl_t kqueue_ioctl;
125 static fo_poll_t kqueue_poll;
126 static fo_kqfilter_t kqueue_kqfilter;
127 static fo_stat_t kqueue_stat;
128 static fo_close_t kqueue_close;
129 static fo_fill_kinfo_t kqueue_fill_kinfo;
130
131 static struct fileops kqueueops = {
132 .fo_read = invfo_rdwr,
133 .fo_write = invfo_rdwr,
134 .fo_truncate = invfo_truncate,
135 .fo_ioctl = kqueue_ioctl,
136 .fo_poll = kqueue_poll,
137 .fo_kqfilter = kqueue_kqfilter,
138 .fo_stat = kqueue_stat,
139 .fo_close = kqueue_close,
140 .fo_chmod = invfo_chmod,
141 .fo_chown = invfo_chown,
142 .fo_sendfile = invfo_sendfile,
143 .fo_cmp = file_kcmp_generic,
144 .fo_fill_kinfo = kqueue_fill_kinfo,
145 };
146
147 static int knote_attach(struct knote *kn, struct kqueue *kq);
148 static void knote_drop(struct knote *kn, struct thread *td);
149 static void knote_drop_detached(struct knote *kn, struct thread *td);
150 static void knote_enqueue(struct knote *kn);
151 static void knote_dequeue(struct knote *kn);
152 static void knote_init(void);
153 static struct knote *knote_alloc(int mflag);
154 static void knote_free(struct knote *kn);
155
156 static void filt_kqdetach(struct knote *kn);
157 static int filt_kqueue(struct knote *kn, long hint);
158 static int filt_procattach(struct knote *kn);
159 static void filt_procdetach(struct knote *kn);
160 static int filt_proc(struct knote *kn, long hint);
161 static int filt_fileattach(struct knote *kn);
162 static void filt_timerexpire(void *knx);
163 static void filt_timerexpire_l(struct knote *kn, bool proc_locked);
164 static int filt_timerattach(struct knote *kn);
165 static void filt_timerdetach(struct knote *kn);
166 static void filt_timerstart(struct knote *kn, sbintime_t to);
167 static void filt_timertouch(struct knote *kn, struct kevent *kev,
168 u_long type);
169 static int filt_timervalidate(struct knote *kn, sbintime_t *to);
170 static int filt_timer(struct knote *kn, long hint);
171 static int filt_userattach(struct knote *kn);
172 static void filt_userdetach(struct knote *kn);
173 static int filt_user(struct knote *kn, long hint);
174 static void filt_usertouch(struct knote *kn, struct kevent *kev,
175 u_long type);
176
177 static struct filterops file_filtops = {
178 .f_isfd = 1,
179 .f_attach = filt_fileattach,
180 };
181 static struct filterops kqread_filtops = {
182 .f_isfd = 1,
183 .f_detach = filt_kqdetach,
184 .f_event = filt_kqueue,
185 };
186 /* XXX - move to kern_proc.c? */
187 static struct filterops proc_filtops = {
188 .f_isfd = 0,
189 .f_attach = filt_procattach,
190 .f_detach = filt_procdetach,
191 .f_event = filt_proc,
192 };
193 static struct filterops timer_filtops = {
194 .f_isfd = 0,
195 .f_attach = filt_timerattach,
196 .f_detach = filt_timerdetach,
197 .f_event = filt_timer,
198 .f_touch = filt_timertouch,
199 };
200 static struct filterops user_filtops = {
201 .f_attach = filt_userattach,
202 .f_detach = filt_userdetach,
203 .f_event = filt_user,
204 .f_touch = filt_usertouch,
205 };
206
207 static uma_zone_t knote_zone;
208 static unsigned int __exclusive_cache_line kq_ncallouts;
209 static unsigned int kq_calloutmax = 4 * 1024;
210 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
211 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
212
213 /* XXX - ensure not influx ? */
214 #define KNOTE_ACTIVATE(kn, islock) do { \
215 if ((islock)) \
216 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED); \
217 else \
218 KQ_LOCK((kn)->kn_kq); \
219 (kn)->kn_status |= KN_ACTIVE; \
220 if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
221 knote_enqueue((kn)); \
222 if (!(islock)) \
223 KQ_UNLOCK((kn)->kn_kq); \
224 } while(0)
225 #define KQ_LOCK(kq) do { \
226 mtx_lock(&(kq)->kq_lock); \
227 } while (0)
228 #define KQ_FLUX_WAKEUP(kq) do { \
229 if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) { \
230 (kq)->kq_state &= ~KQ_FLUXWAIT; \
231 wakeup((kq)); \
232 } \
233 } while (0)
234 #define KQ_UNLOCK_FLUX(kq) do { \
235 KQ_FLUX_WAKEUP(kq); \
236 mtx_unlock(&(kq)->kq_lock); \
237 } while (0)
238 #define KQ_UNLOCK(kq) do { \
239 mtx_unlock(&(kq)->kq_lock); \
240 } while (0)
241 #define KQ_OWNED(kq) do { \
242 mtx_assert(&(kq)->kq_lock, MA_OWNED); \
243 } while (0)
244 #define KQ_NOTOWNED(kq) do { \
245 mtx_assert(&(kq)->kq_lock, MA_NOTOWNED); \
246 } while (0)
247
248 static struct knlist *
kn_list_lock(struct knote * kn)249 kn_list_lock(struct knote *kn)
250 {
251 struct knlist *knl;
252
253 knl = kn->kn_knlist;
254 if (knl != NULL)
255 knl->kl_lock(knl->kl_lockarg);
256 return (knl);
257 }
258
259 static void
kn_list_unlock(struct knlist * knl)260 kn_list_unlock(struct knlist *knl)
261 {
262 bool do_free;
263
264 if (knl == NULL)
265 return;
266 do_free = knl->kl_autodestroy && knlist_empty(knl);
267 knl->kl_unlock(knl->kl_lockarg);
268 if (do_free) {
269 knlist_destroy(knl);
270 free(knl, M_KQUEUE);
271 }
272 }
273
274 static bool
kn_in_flux(struct knote * kn)275 kn_in_flux(struct knote *kn)
276 {
277
278 return (kn->kn_influx > 0);
279 }
280
281 static void
kn_enter_flux(struct knote * kn)282 kn_enter_flux(struct knote *kn)
283 {
284
285 KQ_OWNED(kn->kn_kq);
286 MPASS(kn->kn_influx < INT_MAX);
287 kn->kn_influx++;
288 }
289
290 static bool
kn_leave_flux(struct knote * kn)291 kn_leave_flux(struct knote *kn)
292 {
293
294 KQ_OWNED(kn->kn_kq);
295 MPASS(kn->kn_influx > 0);
296 kn->kn_influx--;
297 return (kn->kn_influx == 0);
298 }
299
300 #define KNL_ASSERT_LOCK(knl, islocked) do { \
301 if (islocked) \
302 KNL_ASSERT_LOCKED(knl); \
303 else \
304 KNL_ASSERT_UNLOCKED(knl); \
305 } while (0)
306 #ifdef INVARIANTS
307 #define KNL_ASSERT_LOCKED(knl) do { \
308 knl->kl_assert_lock((knl)->kl_lockarg, LA_LOCKED); \
309 } while (0)
310 #define KNL_ASSERT_UNLOCKED(knl) do { \
311 knl->kl_assert_lock((knl)->kl_lockarg, LA_UNLOCKED); \
312 } while (0)
313 #else /* !INVARIANTS */
314 #define KNL_ASSERT_LOCKED(knl) do {} while(0)
315 #define KNL_ASSERT_UNLOCKED(knl) do {} while (0)
316 #endif /* INVARIANTS */
317
318 #ifndef KN_HASHSIZE
319 #define KN_HASHSIZE 64 /* XXX should be tunable */
320 #endif
321
322 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
323
324 static int
filt_nullattach(struct knote * kn)325 filt_nullattach(struct knote *kn)
326 {
327
328 return (ENXIO);
329 };
330
331 struct filterops null_filtops = {
332 .f_isfd = 0,
333 .f_attach = filt_nullattach,
334 };
335
336 /* XXX - make SYSINIT to add these, and move into respective modules. */
337 extern struct filterops sig_filtops;
338 extern struct filterops fs_filtops;
339
340 /*
341 * Table for all system-defined filters.
342 */
343 static struct mtx filterops_lock;
344 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops", MTX_DEF);
345 static struct {
346 const struct filterops *for_fop;
347 int for_nolock;
348 int for_refcnt;
349 } sysfilt_ops[EVFILT_SYSCOUNT] = {
350 { &file_filtops, 1 }, /* EVFILT_READ */
351 { &file_filtops, 1 }, /* EVFILT_WRITE */
352 { &null_filtops }, /* EVFILT_AIO */
353 { &file_filtops, 1 }, /* EVFILT_VNODE */
354 { &proc_filtops, 1 }, /* EVFILT_PROC */
355 { &sig_filtops, 1 }, /* EVFILT_SIGNAL */
356 { &timer_filtops, 1 }, /* EVFILT_TIMER */
357 { &file_filtops, 1 }, /* EVFILT_PROCDESC */
358 { &fs_filtops, 1 }, /* EVFILT_FS */
359 { &null_filtops }, /* EVFILT_LIO */
360 { &user_filtops, 1 }, /* EVFILT_USER */
361 { &null_filtops }, /* EVFILT_SENDFILE */
362 { &file_filtops, 1 }, /* EVFILT_EMPTY */
363 };
364
365 /*
366 * Simple redirection for all cdevsw style objects to call their fo_kqfilter
367 * method.
368 */
369 static int
filt_fileattach(struct knote * kn)370 filt_fileattach(struct knote *kn)
371 {
372
373 return (fo_kqfilter(kn->kn_fp, kn));
374 }
375
376 /*ARGSUSED*/
377 static int
kqueue_kqfilter(struct file * fp,struct knote * kn)378 kqueue_kqfilter(struct file *fp, struct knote *kn)
379 {
380 struct kqueue *kq = kn->kn_fp->f_data;
381
382 if (kn->kn_filter != EVFILT_READ)
383 return (EINVAL);
384
385 kn->kn_status |= KN_KQUEUE;
386 kn->kn_fop = &kqread_filtops;
387 knlist_add(&kq->kq_sel.si_note, kn, 0);
388
389 return (0);
390 }
391
392 static void
filt_kqdetach(struct knote * kn)393 filt_kqdetach(struct knote *kn)
394 {
395 struct kqueue *kq = kn->kn_fp->f_data;
396
397 knlist_remove(&kq->kq_sel.si_note, kn, 0);
398 }
399
400 /*ARGSUSED*/
401 static int
filt_kqueue(struct knote * kn,long hint)402 filt_kqueue(struct knote *kn, long hint)
403 {
404 struct kqueue *kq = kn->kn_fp->f_data;
405
406 kn->kn_data = kq->kq_count;
407 return (kn->kn_data > 0);
408 }
409
410 /* XXX - move to kern_proc.c? */
411 static int
filt_procattach(struct knote * kn)412 filt_procattach(struct knote *kn)
413 {
414 struct proc *p;
415 int error;
416 bool exiting, immediate;
417
418 exiting = immediate = false;
419 if (kn->kn_sfflags & NOTE_EXIT)
420 p = pfind_any(kn->kn_id);
421 else
422 p = pfind(kn->kn_id);
423 if (p == NULL)
424 return (ESRCH);
425 if (p->p_flag & P_WEXIT)
426 exiting = true;
427
428 if ((error = p_cansee(curthread, p))) {
429 PROC_UNLOCK(p);
430 return (error);
431 }
432
433 kn->kn_ptr.p_proc = p;
434 kn->kn_flags |= EV_CLEAR; /* automatically set */
435
436 /*
437 * Internal flag indicating registration done by kernel for the
438 * purposes of getting a NOTE_CHILD notification.
439 */
440 if (kn->kn_flags & EV_FLAG2) {
441 kn->kn_flags &= ~EV_FLAG2;
442 kn->kn_data = kn->kn_sdata; /* ppid */
443 kn->kn_fflags = NOTE_CHILD;
444 kn->kn_sfflags &= ~(NOTE_EXIT | NOTE_EXEC | NOTE_FORK);
445 immediate = true; /* Force immediate activation of child note. */
446 }
447 /*
448 * Internal flag indicating registration done by kernel (for other than
449 * NOTE_CHILD).
450 */
451 if (kn->kn_flags & EV_FLAG1) {
452 kn->kn_flags &= ~EV_FLAG1;
453 }
454
455 knlist_add(p->p_klist, kn, 1);
456
457 /*
458 * Immediately activate any child notes or, in the case of a zombie
459 * target process, exit notes. The latter is necessary to handle the
460 * case where the target process, e.g. a child, dies before the kevent
461 * is registered.
462 */
463 if (immediate || (exiting && filt_proc(kn, NOTE_EXIT)))
464 KNOTE_ACTIVATE(kn, 0);
465
466 PROC_UNLOCK(p);
467
468 return (0);
469 }
470
471 /*
472 * The knote may be attached to a different process, which may exit,
473 * leaving nothing for the knote to be attached to. So when the process
474 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
475 * it will be deleted when read out. However, as part of the knote deletion,
476 * this routine is called, so a check is needed to avoid actually performing
477 * a detach, because the original process does not exist any more.
478 */
479 /* XXX - move to kern_proc.c? */
480 static void
filt_procdetach(struct knote * kn)481 filt_procdetach(struct knote *kn)
482 {
483
484 knlist_remove(kn->kn_knlist, kn, 0);
485 kn->kn_ptr.p_proc = NULL;
486 }
487
488 /* XXX - move to kern_proc.c? */
489 static int
filt_proc(struct knote * kn,long hint)490 filt_proc(struct knote *kn, long hint)
491 {
492 struct proc *p;
493 u_int event;
494
495 p = kn->kn_ptr.p_proc;
496 if (p == NULL) /* already activated, from attach filter */
497 return (0);
498
499 /* Mask off extra data. */
500 event = (u_int)hint & NOTE_PCTRLMASK;
501
502 /* If the user is interested in this event, record it. */
503 if (kn->kn_sfflags & event)
504 kn->kn_fflags |= event;
505
506 /* Process is gone, so flag the event as finished. */
507 if (event == NOTE_EXIT) {
508 kn->kn_flags |= EV_EOF | EV_ONESHOT;
509 kn->kn_ptr.p_proc = NULL;
510 if (kn->kn_fflags & NOTE_EXIT)
511 kn->kn_data = KW_EXITCODE(p->p_xexit, p->p_xsig);
512 if (kn->kn_fflags == 0)
513 kn->kn_flags |= EV_DROP;
514 return (1);
515 }
516
517 return (kn->kn_fflags != 0);
518 }
519
520 /*
521 * Called when the process forked. It mostly does the same as the
522 * knote(), activating all knotes registered to be activated when the
523 * process forked. Additionally, for each knote attached to the
524 * parent, check whether user wants to track the new process. If so
525 * attach a new knote to it, and immediately report an event with the
526 * child's pid.
527 */
528 void
knote_fork(struct knlist * list,int pid)529 knote_fork(struct knlist *list, int pid)
530 {
531 struct kqueue *kq;
532 struct knote *kn;
533 struct kevent kev;
534 int error;
535
536 MPASS(list != NULL);
537 KNL_ASSERT_LOCKED(list);
538 if (SLIST_EMPTY(&list->kl_list))
539 return;
540
541 memset(&kev, 0, sizeof(kev));
542 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
543 kq = kn->kn_kq;
544 KQ_LOCK(kq);
545 if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
546 KQ_UNLOCK(kq);
547 continue;
548 }
549
550 /*
551 * The same as knote(), activate the event.
552 */
553 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
554 if (kn->kn_fop->f_event(kn, NOTE_FORK))
555 KNOTE_ACTIVATE(kn, 1);
556 KQ_UNLOCK(kq);
557 continue;
558 }
559
560 /*
561 * The NOTE_TRACK case. In addition to the activation
562 * of the event, we need to register new events to
563 * track the child. Drop the locks in preparation for
564 * the call to kqueue_register().
565 */
566 kn_enter_flux(kn);
567 KQ_UNLOCK(kq);
568 list->kl_unlock(list->kl_lockarg);
569
570 /*
571 * Activate existing knote and register tracking knotes with
572 * new process.
573 *
574 * First register a knote to get just the child notice. This
575 * must be a separate note from a potential NOTE_EXIT
576 * notification since both NOTE_CHILD and NOTE_EXIT are defined
577 * to use the data field (in conflicting ways).
578 */
579 kev.ident = pid;
580 kev.filter = kn->kn_filter;
581 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_ONESHOT |
582 EV_FLAG2;
583 kev.fflags = kn->kn_sfflags;
584 kev.data = kn->kn_id; /* parent */
585 kev.udata = kn->kn_kevent.udata;/* preserve udata */
586 error = kqueue_register(kq, &kev, NULL, M_NOWAIT);
587 if (error)
588 kn->kn_fflags |= NOTE_TRACKERR;
589
590 /*
591 * Then register another knote to track other potential events
592 * from the new process.
593 */
594 kev.ident = pid;
595 kev.filter = kn->kn_filter;
596 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
597 kev.fflags = kn->kn_sfflags;
598 kev.data = kn->kn_id; /* parent */
599 kev.udata = kn->kn_kevent.udata;/* preserve udata */
600 error = kqueue_register(kq, &kev, NULL, M_NOWAIT);
601 if (error)
602 kn->kn_fflags |= NOTE_TRACKERR;
603 if (kn->kn_fop->f_event(kn, NOTE_FORK))
604 KNOTE_ACTIVATE(kn, 0);
605 list->kl_lock(list->kl_lockarg);
606 KQ_LOCK(kq);
607 kn_leave_flux(kn);
608 KQ_UNLOCK_FLUX(kq);
609 }
610 }
611
612 /*
613 * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
614 * interval timer support code.
615 */
616
617 #define NOTE_TIMER_PRECMASK \
618 (NOTE_SECONDS | NOTE_MSECONDS | NOTE_USECONDS | NOTE_NSECONDS)
619
620 static sbintime_t
timer2sbintime(int64_t data,int flags)621 timer2sbintime(int64_t data, int flags)
622 {
623 int64_t secs;
624
625 /*
626 * Macros for converting to the fractional second portion of an
627 * sbintime_t using 64bit multiplication to improve precision.
628 */
629 #define NS_TO_SBT(ns) (((ns) * (((uint64_t)1 << 63) / 500000000)) >> 32)
630 #define US_TO_SBT(us) (((us) * (((uint64_t)1 << 63) / 500000)) >> 32)
631 #define MS_TO_SBT(ms) (((ms) * (((uint64_t)1 << 63) / 500)) >> 32)
632 switch (flags & NOTE_TIMER_PRECMASK) {
633 case NOTE_SECONDS:
634 #ifdef __LP64__
635 if (data > (SBT_MAX / SBT_1S))
636 return (SBT_MAX);
637 #endif
638 return ((sbintime_t)data << 32);
639 case NOTE_MSECONDS: /* FALLTHROUGH */
640 case 0:
641 if (data >= 1000) {
642 secs = data / 1000;
643 #ifdef __LP64__
644 if (secs > (SBT_MAX / SBT_1S))
645 return (SBT_MAX);
646 #endif
647 return (secs << 32 | MS_TO_SBT(data % 1000));
648 }
649 return (MS_TO_SBT(data));
650 case NOTE_USECONDS:
651 if (data >= 1000000) {
652 secs = data / 1000000;
653 #ifdef __LP64__
654 if (secs > (SBT_MAX / SBT_1S))
655 return (SBT_MAX);
656 #endif
657 return (secs << 32 | US_TO_SBT(data % 1000000));
658 }
659 return (US_TO_SBT(data));
660 case NOTE_NSECONDS:
661 if (data >= 1000000000) {
662 secs = data / 1000000000;
663 #ifdef __LP64__
664 if (secs > (SBT_MAX / SBT_1S))
665 return (SBT_MAX);
666 #endif
667 return (secs << 32 | NS_TO_SBT(data % 1000000000));
668 }
669 return (NS_TO_SBT(data));
670 default:
671 break;
672 }
673 return (-1);
674 }
675
676 struct kq_timer_cb_data {
677 struct callout c;
678 struct proc *p;
679 struct knote *kn;
680 int cpuid;
681 int flags;
682 TAILQ_ENTRY(kq_timer_cb_data) link;
683 sbintime_t next; /* next timer event fires at */
684 sbintime_t to; /* precalculated timer period, 0 for abs */
685 };
686
687 #define KQ_TIMER_CB_ENQUEUED 0x01
688
689 static void
kqtimer_sched_callout(struct kq_timer_cb_data * kc)690 kqtimer_sched_callout(struct kq_timer_cb_data *kc)
691 {
692 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kc->kn,
693 kc->cpuid, C_ABSOLUTE);
694 }
695
696 void
kqtimer_proc_continue(struct proc * p)697 kqtimer_proc_continue(struct proc *p)
698 {
699 struct kq_timer_cb_data *kc, *kc1;
700 struct bintime bt;
701 sbintime_t now;
702
703 PROC_LOCK_ASSERT(p, MA_OWNED);
704
705 getboottimebin(&bt);
706 now = bttosbt(bt);
707
708 TAILQ_FOREACH_SAFE(kc, &p->p_kqtim_stop, link, kc1) {
709 TAILQ_REMOVE(&p->p_kqtim_stop, kc, link);
710 kc->flags &= ~KQ_TIMER_CB_ENQUEUED;
711 if (kc->next <= now)
712 filt_timerexpire_l(kc->kn, true);
713 else
714 kqtimer_sched_callout(kc);
715 }
716 }
717
718 static void
filt_timerexpire_l(struct knote * kn,bool proc_locked)719 filt_timerexpire_l(struct knote *kn, bool proc_locked)
720 {
721 struct kq_timer_cb_data *kc;
722 struct proc *p;
723 uint64_t delta;
724 sbintime_t now;
725
726 kc = kn->kn_ptr.p_v;
727
728 if ((kn->kn_flags & EV_ONESHOT) != 0 || kc->to == 0) {
729 kn->kn_data++;
730 KNOTE_ACTIVATE(kn, 0);
731 return;
732 }
733
734 now = sbinuptime();
735 if (now >= kc->next) {
736 delta = (now - kc->next) / kc->to;
737 if (delta == 0)
738 delta = 1;
739 kn->kn_data += delta;
740 kc->next += delta * kc->to;
741 if (now >= kc->next) /* overflow */
742 kc->next = now + kc->to;
743 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
744 }
745
746 /*
747 * Initial check for stopped kc->p is racy. It is fine to
748 * miss the set of the stop flags, at worst we would schedule
749 * one more callout. On the other hand, it is not fine to not
750 * schedule when we we missed clearing of the flags, we
751 * recheck them under the lock and observe consistent state.
752 */
753 p = kc->p;
754 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
755 if (!proc_locked)
756 PROC_LOCK(p);
757 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
758 if ((kc->flags & KQ_TIMER_CB_ENQUEUED) == 0) {
759 kc->flags |= KQ_TIMER_CB_ENQUEUED;
760 TAILQ_INSERT_TAIL(&p->p_kqtim_stop, kc, link);
761 }
762 if (!proc_locked)
763 PROC_UNLOCK(p);
764 return;
765 }
766 if (!proc_locked)
767 PROC_UNLOCK(p);
768 }
769 kqtimer_sched_callout(kc);
770 }
771
772 static void
filt_timerexpire(void * knx)773 filt_timerexpire(void *knx)
774 {
775 filt_timerexpire_l(knx, false);
776 }
777
778 /*
779 * data contains amount of time to sleep
780 */
781 static int
filt_timervalidate(struct knote * kn,sbintime_t * to)782 filt_timervalidate(struct knote *kn, sbintime_t *to)
783 {
784 struct bintime bt;
785 sbintime_t sbt;
786
787 if (kn->kn_sdata < 0)
788 return (EINVAL);
789 if (kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
790 kn->kn_sdata = 1;
791 /*
792 * The only fflags values supported are the timer unit
793 * (precision) and the absolute time indicator.
794 */
795 if ((kn->kn_sfflags & ~(NOTE_TIMER_PRECMASK | NOTE_ABSTIME)) != 0)
796 return (EINVAL);
797
798 *to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
799 if (*to < 0)
800 return (EINVAL);
801 if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
802 getboottimebin(&bt);
803 sbt = bttosbt(bt);
804 *to = MAX(0, *to - sbt);
805 }
806 return (0);
807 }
808
809 static int
filt_timerattach(struct knote * kn)810 filt_timerattach(struct knote *kn)
811 {
812 struct kq_timer_cb_data *kc;
813 sbintime_t to;
814 int error;
815
816 to = -1;
817 error = filt_timervalidate(kn, &to);
818 if (error != 0)
819 return (error);
820 KASSERT(to > 0 || (kn->kn_flags & EV_ONESHOT) != 0 ||
821 (kn->kn_sfflags & NOTE_ABSTIME) != 0,
822 ("%s: periodic timer has a calculated zero timeout", __func__));
823 KASSERT(to >= 0,
824 ("%s: timer has a calculated negative timeout", __func__));
825
826 if (atomic_fetchadd_int(&kq_ncallouts, 1) + 1 > kq_calloutmax) {
827 atomic_subtract_int(&kq_ncallouts, 1);
828 return (ENOMEM);
829 }
830
831 if ((kn->kn_sfflags & NOTE_ABSTIME) == 0)
832 kn->kn_flags |= EV_CLEAR; /* automatically set */
833 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
834 kn->kn_ptr.p_v = kc = malloc(sizeof(*kc), M_KQUEUE, M_WAITOK);
835 kc->kn = kn;
836 kc->p = curproc;
837 kc->cpuid = PCPU_GET(cpuid);
838 kc->flags = 0;
839 callout_init(&kc->c, 1);
840 filt_timerstart(kn, to);
841
842 return (0);
843 }
844
845 static void
filt_timerstart(struct knote * kn,sbintime_t to)846 filt_timerstart(struct knote *kn, sbintime_t to)
847 {
848 struct kq_timer_cb_data *kc;
849
850 kc = kn->kn_ptr.p_v;
851 if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
852 kc->next = to;
853 kc->to = 0;
854 } else {
855 kc->next = to + sbinuptime();
856 kc->to = to;
857 }
858 kqtimer_sched_callout(kc);
859 }
860
861 static void
filt_timerdetach(struct knote * kn)862 filt_timerdetach(struct knote *kn)
863 {
864 struct kq_timer_cb_data *kc;
865 unsigned int old __unused;
866 bool pending;
867
868 kc = kn->kn_ptr.p_v;
869 do {
870 callout_drain(&kc->c);
871
872 /*
873 * kqtimer_proc_continue() might have rescheduled this callout.
874 * Double-check, using the process mutex as an interlock.
875 */
876 PROC_LOCK(kc->p);
877 if ((kc->flags & KQ_TIMER_CB_ENQUEUED) != 0) {
878 kc->flags &= ~KQ_TIMER_CB_ENQUEUED;
879 TAILQ_REMOVE(&kc->p->p_kqtim_stop, kc, link);
880 }
881 pending = callout_pending(&kc->c);
882 PROC_UNLOCK(kc->p);
883 } while (pending);
884 free(kc, M_KQUEUE);
885 old = atomic_fetchadd_int(&kq_ncallouts, -1);
886 KASSERT(old > 0, ("Number of callouts cannot become negative"));
887 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
888 }
889
890 static void
filt_timertouch(struct knote * kn,struct kevent * kev,u_long type)891 filt_timertouch(struct knote *kn, struct kevent *kev, u_long type)
892 {
893 struct kq_timer_cb_data *kc;
894 struct kqueue *kq;
895 sbintime_t to;
896 int error;
897
898 switch (type) {
899 case EVENT_REGISTER:
900 /* Handle re-added timers that update data/fflags */
901 if (kev->flags & EV_ADD) {
902 kc = kn->kn_ptr.p_v;
903
904 /* Drain any existing callout. */
905 callout_drain(&kc->c);
906
907 /* Throw away any existing undelivered record
908 * of the timer expiration. This is done under
909 * the presumption that if a process is
910 * re-adding this timer with new parameters,
911 * it is no longer interested in what may have
912 * happened under the old parameters. If it is
913 * interested, it can wait for the expiration,
914 * delete the old timer definition, and then
915 * add the new one.
916 *
917 * This has to be done while the kq is locked:
918 * - if enqueued, dequeue
919 * - make it no longer active
920 * - clear the count of expiration events
921 */
922 kq = kn->kn_kq;
923 KQ_LOCK(kq);
924 if (kn->kn_status & KN_QUEUED)
925 knote_dequeue(kn);
926
927 kn->kn_status &= ~KN_ACTIVE;
928 kn->kn_data = 0;
929 KQ_UNLOCK(kq);
930
931 /* Reschedule timer based on new data/fflags */
932 kn->kn_sfflags = kev->fflags;
933 kn->kn_sdata = kev->data;
934 error = filt_timervalidate(kn, &to);
935 if (error != 0) {
936 kn->kn_flags |= EV_ERROR;
937 kn->kn_data = error;
938 } else
939 filt_timerstart(kn, to);
940 }
941 break;
942
943 case EVENT_PROCESS:
944 *kev = kn->kn_kevent;
945 if (kn->kn_flags & EV_CLEAR) {
946 kn->kn_data = 0;
947 kn->kn_fflags = 0;
948 }
949 break;
950
951 default:
952 panic("filt_timertouch() - invalid type (%ld)", type);
953 break;
954 }
955 }
956
957 static int
filt_timer(struct knote * kn,long hint)958 filt_timer(struct knote *kn, long hint)
959 {
960
961 return (kn->kn_data != 0);
962 }
963
964 static int
filt_userattach(struct knote * kn)965 filt_userattach(struct knote *kn)
966 {
967
968 /*
969 * EVFILT_USER knotes are not attached to anything in the kernel.
970 */
971 kn->kn_hook = NULL;
972 if (kn->kn_fflags & NOTE_TRIGGER)
973 kn->kn_hookid = 1;
974 else
975 kn->kn_hookid = 0;
976 return (0);
977 }
978
979 static void
filt_userdetach(__unused struct knote * kn)980 filt_userdetach(__unused struct knote *kn)
981 {
982
983 /*
984 * EVFILT_USER knotes are not attached to anything in the kernel.
985 */
986 }
987
988 static int
filt_user(struct knote * kn,__unused long hint)989 filt_user(struct knote *kn, __unused long hint)
990 {
991
992 return (kn->kn_hookid);
993 }
994
995 static void
filt_usertouch(struct knote * kn,struct kevent * kev,u_long type)996 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
997 {
998 u_int ffctrl;
999
1000 switch (type) {
1001 case EVENT_REGISTER:
1002 if (kev->fflags & NOTE_TRIGGER)
1003 kn->kn_hookid = 1;
1004
1005 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
1006 kev->fflags &= NOTE_FFLAGSMASK;
1007 switch (ffctrl) {
1008 case NOTE_FFNOP:
1009 break;
1010
1011 case NOTE_FFAND:
1012 kn->kn_sfflags &= kev->fflags;
1013 break;
1014
1015 case NOTE_FFOR:
1016 kn->kn_sfflags |= kev->fflags;
1017 break;
1018
1019 case NOTE_FFCOPY:
1020 kn->kn_sfflags = kev->fflags;
1021 break;
1022
1023 default:
1024 /* XXX Return error? */
1025 break;
1026 }
1027 kn->kn_sdata = kev->data;
1028 if (kev->flags & EV_CLEAR) {
1029 kn->kn_hookid = 0;
1030 kn->kn_data = 0;
1031 kn->kn_fflags = 0;
1032 }
1033 break;
1034
1035 case EVENT_PROCESS:
1036 *kev = kn->kn_kevent;
1037 kev->fflags = kn->kn_sfflags;
1038 kev->data = kn->kn_sdata;
1039 if (kn->kn_flags & EV_CLEAR) {
1040 kn->kn_hookid = 0;
1041 kn->kn_data = 0;
1042 kn->kn_fflags = 0;
1043 }
1044 break;
1045
1046 default:
1047 panic("filt_usertouch() - invalid type (%ld)", type);
1048 break;
1049 }
1050 }
1051
1052 int
sys_kqueue(struct thread * td,struct kqueue_args * uap)1053 sys_kqueue(struct thread *td, struct kqueue_args *uap)
1054 {
1055
1056 return (kern_kqueue(td, 0, NULL));
1057 }
1058
1059 int
sys_kqueuex(struct thread * td,struct kqueuex_args * uap)1060 sys_kqueuex(struct thread *td, struct kqueuex_args *uap)
1061 {
1062 int flags;
1063
1064 if ((uap->flags & ~(KQUEUE_CLOEXEC)) != 0)
1065 return (EINVAL);
1066 flags = 0;
1067 if ((uap->flags & KQUEUE_CLOEXEC) != 0)
1068 flags |= O_CLOEXEC;
1069 return (kern_kqueue(td, flags, NULL));
1070 }
1071
1072 static void
kqueue_init(struct kqueue * kq)1073 kqueue_init(struct kqueue *kq)
1074 {
1075
1076 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF | MTX_DUPOK);
1077 TAILQ_INIT(&kq->kq_head);
1078 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
1079 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
1080 }
1081
1082 int
kern_kqueue(struct thread * td,int flags,struct filecaps * fcaps)1083 kern_kqueue(struct thread *td, int flags, struct filecaps *fcaps)
1084 {
1085 struct filedesc *fdp;
1086 struct kqueue *kq;
1087 struct file *fp;
1088 struct ucred *cred;
1089 int fd, error;
1090
1091 fdp = td->td_proc->p_fd;
1092 cred = td->td_ucred;
1093 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_KQUEUES)))
1094 return (ENOMEM);
1095
1096 error = falloc_caps(td, &fp, &fd, flags, fcaps);
1097 if (error != 0) {
1098 chgkqcnt(cred->cr_ruidinfo, -1, 0);
1099 return (error);
1100 }
1101
1102 /* An extra reference on `fp' has been held for us by falloc(). */
1103 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
1104 kqueue_init(kq);
1105 kq->kq_fdp = fdp;
1106 kq->kq_cred = crhold(cred);
1107
1108 FILEDESC_XLOCK(fdp);
1109 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
1110 FILEDESC_XUNLOCK(fdp);
1111
1112 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
1113 fdrop(fp, td);
1114
1115 td->td_retval[0] = fd;
1116 return (0);
1117 }
1118
1119 struct g_kevent_args {
1120 int fd;
1121 void *changelist;
1122 int nchanges;
1123 void *eventlist;
1124 int nevents;
1125 const struct timespec *timeout;
1126 };
1127
1128 int
sys_kevent(struct thread * td,struct kevent_args * uap)1129 sys_kevent(struct thread *td, struct kevent_args *uap)
1130 {
1131 struct kevent_copyops k_ops = {
1132 .arg = uap,
1133 .k_copyout = kevent_copyout,
1134 .k_copyin = kevent_copyin,
1135 .kevent_size = sizeof(struct kevent),
1136 };
1137 struct g_kevent_args gk_args = {
1138 .fd = uap->fd,
1139 .changelist = uap->changelist,
1140 .nchanges = uap->nchanges,
1141 .eventlist = uap->eventlist,
1142 .nevents = uap->nevents,
1143 .timeout = uap->timeout,
1144 };
1145
1146 return (kern_kevent_generic(td, &gk_args, &k_ops, "kevent"));
1147 }
1148
1149 static int
kern_kevent_generic(struct thread * td,struct g_kevent_args * uap,struct kevent_copyops * k_ops,const char * struct_name)1150 kern_kevent_generic(struct thread *td, struct g_kevent_args *uap,
1151 struct kevent_copyops *k_ops, const char *struct_name)
1152 {
1153 struct timespec ts, *tsp;
1154 #ifdef KTRACE
1155 struct kevent *eventlist = uap->eventlist;
1156 #endif
1157 int error;
1158
1159 if (uap->timeout != NULL) {
1160 error = copyin(uap->timeout, &ts, sizeof(ts));
1161 if (error)
1162 return (error);
1163 tsp = &ts;
1164 } else
1165 tsp = NULL;
1166
1167 #ifdef KTRACE
1168 if (KTRPOINT(td, KTR_STRUCT_ARRAY))
1169 ktrstructarray(struct_name, UIO_USERSPACE, uap->changelist,
1170 uap->nchanges, k_ops->kevent_size);
1171 #endif
1172
1173 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
1174 k_ops, tsp);
1175
1176 #ifdef KTRACE
1177 if (error == 0 && KTRPOINT(td, KTR_STRUCT_ARRAY))
1178 ktrstructarray(struct_name, UIO_USERSPACE, eventlist,
1179 td->td_retval[0], k_ops->kevent_size);
1180 #endif
1181
1182 return (error);
1183 }
1184
1185 /*
1186 * Copy 'count' items into the destination list pointed to by uap->eventlist.
1187 */
1188 static int
kevent_copyout(void * arg,struct kevent * kevp,int count)1189 kevent_copyout(void *arg, struct kevent *kevp, int count)
1190 {
1191 struct kevent_args *uap;
1192 int error;
1193
1194 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1195 uap = (struct kevent_args *)arg;
1196
1197 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
1198 if (error == 0)
1199 uap->eventlist += count;
1200 return (error);
1201 }
1202
1203 /*
1204 * Copy 'count' items from the list pointed to by uap->changelist.
1205 */
1206 static int
kevent_copyin(void * arg,struct kevent * kevp,int count)1207 kevent_copyin(void *arg, struct kevent *kevp, int count)
1208 {
1209 struct kevent_args *uap;
1210 int error;
1211
1212 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1213 uap = (struct kevent_args *)arg;
1214
1215 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
1216 if (error == 0)
1217 uap->changelist += count;
1218 return (error);
1219 }
1220
1221 #ifdef COMPAT_FREEBSD11
1222 static int
kevent11_copyout(void * arg,struct kevent * kevp,int count)1223 kevent11_copyout(void *arg, struct kevent *kevp, int count)
1224 {
1225 struct freebsd11_kevent_args *uap;
1226 struct kevent_freebsd11 kev11;
1227 int error, i;
1228
1229 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1230 uap = (struct freebsd11_kevent_args *)arg;
1231
1232 for (i = 0; i < count; i++) {
1233 kev11.ident = kevp->ident;
1234 kev11.filter = kevp->filter;
1235 kev11.flags = kevp->flags;
1236 kev11.fflags = kevp->fflags;
1237 kev11.data = kevp->data;
1238 kev11.udata = kevp->udata;
1239 error = copyout(&kev11, uap->eventlist, sizeof(kev11));
1240 if (error != 0)
1241 break;
1242 uap->eventlist++;
1243 kevp++;
1244 }
1245 return (error);
1246 }
1247
1248 /*
1249 * Copy 'count' items from the list pointed to by uap->changelist.
1250 */
1251 static int
kevent11_copyin(void * arg,struct kevent * kevp,int count)1252 kevent11_copyin(void *arg, struct kevent *kevp, int count)
1253 {
1254 struct freebsd11_kevent_args *uap;
1255 struct kevent_freebsd11 kev11;
1256 int error, i;
1257
1258 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1259 uap = (struct freebsd11_kevent_args *)arg;
1260
1261 for (i = 0; i < count; i++) {
1262 error = copyin(uap->changelist, &kev11, sizeof(kev11));
1263 if (error != 0)
1264 break;
1265 kevp->ident = kev11.ident;
1266 kevp->filter = kev11.filter;
1267 kevp->flags = kev11.flags;
1268 kevp->fflags = kev11.fflags;
1269 kevp->data = (uintptr_t)kev11.data;
1270 kevp->udata = kev11.udata;
1271 bzero(&kevp->ext, sizeof(kevp->ext));
1272 uap->changelist++;
1273 kevp++;
1274 }
1275 return (error);
1276 }
1277
1278 int
freebsd11_kevent(struct thread * td,struct freebsd11_kevent_args * uap)1279 freebsd11_kevent(struct thread *td, struct freebsd11_kevent_args *uap)
1280 {
1281 struct kevent_copyops k_ops = {
1282 .arg = uap,
1283 .k_copyout = kevent11_copyout,
1284 .k_copyin = kevent11_copyin,
1285 .kevent_size = sizeof(struct kevent_freebsd11),
1286 };
1287 struct g_kevent_args gk_args = {
1288 .fd = uap->fd,
1289 .changelist = uap->changelist,
1290 .nchanges = uap->nchanges,
1291 .eventlist = uap->eventlist,
1292 .nevents = uap->nevents,
1293 .timeout = uap->timeout,
1294 };
1295
1296 return (kern_kevent_generic(td, &gk_args, &k_ops, "kevent_freebsd11"));
1297 }
1298 #endif
1299
1300 int
kern_kevent(struct thread * td,int fd,int nchanges,int nevents,struct kevent_copyops * k_ops,const struct timespec * timeout)1301 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
1302 struct kevent_copyops *k_ops, const struct timespec *timeout)
1303 {
1304 cap_rights_t rights;
1305 struct file *fp;
1306 int error;
1307
1308 cap_rights_init_zero(&rights);
1309 if (nchanges > 0)
1310 cap_rights_set_one(&rights, CAP_KQUEUE_CHANGE);
1311 if (nevents > 0)
1312 cap_rights_set_one(&rights, CAP_KQUEUE_EVENT);
1313 error = fget(td, fd, &rights, &fp);
1314 if (error != 0)
1315 return (error);
1316
1317 error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
1318 fdrop(fp, td);
1319
1320 return (error);
1321 }
1322
1323 static int
kqueue_kevent(struct kqueue * kq,struct thread * td,int nchanges,int nevents,struct kevent_copyops * k_ops,const struct timespec * timeout)1324 kqueue_kevent(struct kqueue *kq, struct thread *td, int nchanges, int nevents,
1325 struct kevent_copyops *k_ops, const struct timespec *timeout)
1326 {
1327 struct kevent keva[KQ_NEVENTS];
1328 struct kevent *kevp, *changes;
1329 int i, n, nerrors, error;
1330
1331 if (nchanges < 0)
1332 return (EINVAL);
1333
1334 nerrors = 0;
1335 while (nchanges > 0) {
1336 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
1337 error = k_ops->k_copyin(k_ops->arg, keva, n);
1338 if (error)
1339 return (error);
1340 changes = keva;
1341 for (i = 0; i < n; i++) {
1342 kevp = &changes[i];
1343 if (!kevp->filter)
1344 continue;
1345 kevp->flags &= ~EV_SYSFLAGS;
1346 error = kqueue_register(kq, kevp, td, M_WAITOK);
1347 if (error || (kevp->flags & EV_RECEIPT)) {
1348 if (nevents == 0)
1349 return (error);
1350 kevp->flags = EV_ERROR;
1351 kevp->data = error;
1352 (void)k_ops->k_copyout(k_ops->arg, kevp, 1);
1353 nevents--;
1354 nerrors++;
1355 }
1356 }
1357 nchanges -= n;
1358 }
1359 if (nerrors) {
1360 td->td_retval[0] = nerrors;
1361 return (0);
1362 }
1363
1364 return (kqueue_scan(kq, nevents, k_ops, timeout, keva, td));
1365 }
1366
1367 int
kern_kevent_fp(struct thread * td,struct file * fp,int nchanges,int nevents,struct kevent_copyops * k_ops,const struct timespec * timeout)1368 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
1369 struct kevent_copyops *k_ops, const struct timespec *timeout)
1370 {
1371 struct kqueue *kq;
1372 int error;
1373
1374 error = kqueue_acquire(fp, &kq);
1375 if (error != 0)
1376 return (error);
1377 error = kqueue_kevent(kq, td, nchanges, nevents, k_ops, timeout);
1378 kqueue_release(kq, 0);
1379 return (error);
1380 }
1381
1382 /*
1383 * Performs a kevent() call on a temporarily created kqueue. This can be
1384 * used to perform one-shot polling, similar to poll() and select().
1385 */
1386 int
kern_kevent_anonymous(struct thread * td,int nevents,struct kevent_copyops * k_ops)1387 kern_kevent_anonymous(struct thread *td, int nevents,
1388 struct kevent_copyops *k_ops)
1389 {
1390 struct kqueue kq = {};
1391 int error;
1392
1393 kqueue_init(&kq);
1394 kq.kq_refcnt = 1;
1395 error = kqueue_kevent(&kq, td, nevents, nevents, k_ops, NULL);
1396 kqueue_drain(&kq, td);
1397 kqueue_destroy(&kq);
1398 return (error);
1399 }
1400
1401 int
kqueue_add_filteropts(int filt,const struct filterops * filtops)1402 kqueue_add_filteropts(int filt, const struct filterops *filtops)
1403 {
1404 int error;
1405
1406 error = 0;
1407 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1408 printf(
1409 "trying to add a filterop that is out of range: %d is beyond %d\n",
1410 ~filt, EVFILT_SYSCOUNT);
1411 return EINVAL;
1412 }
1413 mtx_lock(&filterops_lock);
1414 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1415 sysfilt_ops[~filt].for_fop != NULL)
1416 error = EEXIST;
1417 else {
1418 sysfilt_ops[~filt].for_fop = filtops;
1419 sysfilt_ops[~filt].for_refcnt = 0;
1420 }
1421 mtx_unlock(&filterops_lock);
1422
1423 return (error);
1424 }
1425
1426 int
kqueue_del_filteropts(int filt)1427 kqueue_del_filteropts(int filt)
1428 {
1429 int error;
1430
1431 error = 0;
1432 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1433 return EINVAL;
1434
1435 mtx_lock(&filterops_lock);
1436 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1437 sysfilt_ops[~filt].for_fop == NULL)
1438 error = EINVAL;
1439 else if (sysfilt_ops[~filt].for_refcnt != 0)
1440 error = EBUSY;
1441 else {
1442 sysfilt_ops[~filt].for_fop = &null_filtops;
1443 sysfilt_ops[~filt].for_refcnt = 0;
1444 }
1445 mtx_unlock(&filterops_lock);
1446
1447 return error;
1448 }
1449
1450 static const struct filterops *
kqueue_fo_find(int filt)1451 kqueue_fo_find(int filt)
1452 {
1453
1454 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1455 return NULL;
1456
1457 if (sysfilt_ops[~filt].for_nolock)
1458 return sysfilt_ops[~filt].for_fop;
1459
1460 mtx_lock(&filterops_lock);
1461 sysfilt_ops[~filt].for_refcnt++;
1462 if (sysfilt_ops[~filt].for_fop == NULL)
1463 sysfilt_ops[~filt].for_fop = &null_filtops;
1464 mtx_unlock(&filterops_lock);
1465
1466 return sysfilt_ops[~filt].for_fop;
1467 }
1468
1469 static void
kqueue_fo_release(int filt)1470 kqueue_fo_release(int filt)
1471 {
1472
1473 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1474 return;
1475
1476 if (sysfilt_ops[~filt].for_nolock)
1477 return;
1478
1479 mtx_lock(&filterops_lock);
1480 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1481 ("filter object refcount not valid on release"));
1482 sysfilt_ops[~filt].for_refcnt--;
1483 mtx_unlock(&filterops_lock);
1484 }
1485
1486 /*
1487 * A ref to kq (obtained via kqueue_acquire) must be held.
1488 */
1489 static int
kqueue_register(struct kqueue * kq,struct kevent * kev,struct thread * td,int mflag)1490 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td,
1491 int mflag)
1492 {
1493 const struct filterops *fops;
1494 struct file *fp;
1495 struct knote *kn, *tkn;
1496 struct knlist *knl;
1497 int error, filt, event;
1498 int haskqglobal, filedesc_unlock;
1499
1500 if ((kev->flags & (EV_ENABLE | EV_DISABLE)) == (EV_ENABLE | EV_DISABLE))
1501 return (EINVAL);
1502
1503 fp = NULL;
1504 kn = NULL;
1505 knl = NULL;
1506 error = 0;
1507 haskqglobal = 0;
1508 filedesc_unlock = 0;
1509
1510 filt = kev->filter;
1511 fops = kqueue_fo_find(filt);
1512 if (fops == NULL)
1513 return EINVAL;
1514
1515 if (kev->flags & EV_ADD) {
1516 /*
1517 * Prevent waiting with locks. Non-sleepable
1518 * allocation failures are handled in the loop, only
1519 * if the spare knote appears to be actually required.
1520 */
1521 tkn = knote_alloc(mflag);
1522 } else {
1523 tkn = NULL;
1524 }
1525
1526 findkn:
1527 if (fops->f_isfd) {
1528 KASSERT(td != NULL, ("td is NULL"));
1529 if (kev->ident > INT_MAX)
1530 error = EBADF;
1531 else
1532 error = fget(td, kev->ident, &cap_event_rights, &fp);
1533 if (error)
1534 goto done;
1535
1536 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1537 kev->ident, M_NOWAIT) != 0) {
1538 /* try again */
1539 fdrop(fp, td);
1540 fp = NULL;
1541 error = kqueue_expand(kq, fops, kev->ident, mflag);
1542 if (error)
1543 goto done;
1544 goto findkn;
1545 }
1546
1547 if (fp->f_type == DTYPE_KQUEUE) {
1548 /*
1549 * If we add some intelligence about what we are doing,
1550 * we should be able to support events on ourselves.
1551 * We need to know when we are doing this to prevent
1552 * getting both the knlist lock and the kq lock since
1553 * they are the same thing.
1554 */
1555 if (fp->f_data == kq) {
1556 error = EINVAL;
1557 goto done;
1558 }
1559
1560 /*
1561 * Pre-lock the filedesc before the global
1562 * lock mutex, see the comment in
1563 * kqueue_close().
1564 */
1565 FILEDESC_XLOCK(td->td_proc->p_fd);
1566 filedesc_unlock = 1;
1567 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1568 }
1569
1570 KQ_LOCK(kq);
1571 if (kev->ident < kq->kq_knlistsize) {
1572 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1573 if (kev->filter == kn->kn_filter)
1574 break;
1575 }
1576 } else {
1577 if ((kev->flags & EV_ADD) == EV_ADD) {
1578 error = kqueue_expand(kq, fops, kev->ident, mflag);
1579 if (error != 0)
1580 goto done;
1581 }
1582
1583 KQ_LOCK(kq);
1584
1585 /*
1586 * If possible, find an existing knote to use for this kevent.
1587 */
1588 if (kev->filter == EVFILT_PROC &&
1589 (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1590 /* This is an internal creation of a process tracking
1591 * note. Don't attempt to coalesce this with an
1592 * existing note.
1593 */
1594 ;
1595 } else if (kq->kq_knhashmask != 0) {
1596 struct klist *list;
1597
1598 list = &kq->kq_knhash[
1599 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1600 SLIST_FOREACH(kn, list, kn_link)
1601 if (kev->ident == kn->kn_id &&
1602 kev->filter == kn->kn_filter)
1603 break;
1604 }
1605 }
1606
1607 /* knote is in the process of changing, wait for it to stabilize. */
1608 if (kn != NULL && kn_in_flux(kn)) {
1609 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1610 if (filedesc_unlock) {
1611 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1612 filedesc_unlock = 0;
1613 }
1614 kq->kq_state |= KQ_FLUXWAIT;
1615 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1616 if (fp != NULL) {
1617 fdrop(fp, td);
1618 fp = NULL;
1619 }
1620 goto findkn;
1621 }
1622
1623 /*
1624 * kn now contains the matching knote, or NULL if no match
1625 */
1626 if (kn == NULL) {
1627 if (kev->flags & EV_ADD) {
1628 kn = tkn;
1629 tkn = NULL;
1630 if (kn == NULL) {
1631 KQ_UNLOCK(kq);
1632 error = ENOMEM;
1633 goto done;
1634 }
1635 kn->kn_fp = fp;
1636 kn->kn_kq = kq;
1637 kn->kn_fop = fops;
1638 /*
1639 * apply reference counts to knote structure, and
1640 * do not release it at the end of this routine.
1641 */
1642 fops = NULL;
1643 fp = NULL;
1644
1645 kn->kn_sfflags = kev->fflags;
1646 kn->kn_sdata = kev->data;
1647 kev->fflags = 0;
1648 kev->data = 0;
1649 kn->kn_kevent = *kev;
1650 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1651 EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1652 kn->kn_status = KN_DETACHED;
1653 if ((kev->flags & EV_DISABLE) != 0)
1654 kn->kn_status |= KN_DISABLED;
1655 kn_enter_flux(kn);
1656
1657 error = knote_attach(kn, kq);
1658 KQ_UNLOCK(kq);
1659 if (error != 0) {
1660 tkn = kn;
1661 goto done;
1662 }
1663
1664 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1665 knote_drop_detached(kn, td);
1666 goto done;
1667 }
1668 knl = kn_list_lock(kn);
1669 goto done_ev_add;
1670 } else {
1671 /* No matching knote and the EV_ADD flag is not set. */
1672 KQ_UNLOCK(kq);
1673 error = ENOENT;
1674 goto done;
1675 }
1676 }
1677
1678 if (kev->flags & EV_DELETE) {
1679 kn_enter_flux(kn);
1680 KQ_UNLOCK(kq);
1681 knote_drop(kn, td);
1682 goto done;
1683 }
1684
1685 if (kev->flags & EV_FORCEONESHOT) {
1686 kn->kn_flags |= EV_ONESHOT;
1687 KNOTE_ACTIVATE(kn, 1);
1688 }
1689
1690 if ((kev->flags & EV_ENABLE) != 0)
1691 kn->kn_status &= ~KN_DISABLED;
1692 else if ((kev->flags & EV_DISABLE) != 0)
1693 kn->kn_status |= KN_DISABLED;
1694
1695 /*
1696 * The user may change some filter values after the initial EV_ADD,
1697 * but doing so will not reset any filter which has already been
1698 * triggered.
1699 */
1700 kn->kn_status |= KN_SCAN;
1701 kn_enter_flux(kn);
1702 KQ_UNLOCK(kq);
1703 knl = kn_list_lock(kn);
1704 kn->kn_kevent.udata = kev->udata;
1705 if (!fops->f_isfd && fops->f_touch != NULL) {
1706 fops->f_touch(kn, kev, EVENT_REGISTER);
1707 } else {
1708 kn->kn_sfflags = kev->fflags;
1709 kn->kn_sdata = kev->data;
1710 }
1711
1712 done_ev_add:
1713 /*
1714 * We can get here with kn->kn_knlist == NULL. This can happen when
1715 * the initial attach event decides that the event is "completed"
1716 * already, e.g., filt_procattach() is called on a zombie process. It
1717 * will call filt_proc() which will remove it from the list, and NULL
1718 * kn_knlist.
1719 *
1720 * KN_DISABLED will be stable while the knote is in flux, so the
1721 * unlocked read will not race with an update.
1722 */
1723 if ((kn->kn_status & KN_DISABLED) == 0)
1724 event = kn->kn_fop->f_event(kn, 0);
1725 else
1726 event = 0;
1727
1728 KQ_LOCK(kq);
1729 if (event)
1730 kn->kn_status |= KN_ACTIVE;
1731 if ((kn->kn_status & (KN_ACTIVE | KN_DISABLED | KN_QUEUED)) ==
1732 KN_ACTIVE)
1733 knote_enqueue(kn);
1734 kn->kn_status &= ~KN_SCAN;
1735 kn_leave_flux(kn);
1736 kn_list_unlock(knl);
1737 KQ_UNLOCK_FLUX(kq);
1738
1739 done:
1740 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1741 if (filedesc_unlock)
1742 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1743 if (fp != NULL)
1744 fdrop(fp, td);
1745 knote_free(tkn);
1746 if (fops != NULL)
1747 kqueue_fo_release(filt);
1748 return (error);
1749 }
1750
1751 static int
kqueue_acquire(struct file * fp,struct kqueue ** kqp)1752 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1753 {
1754 int error;
1755 struct kqueue *kq;
1756
1757 error = 0;
1758
1759 kq = fp->f_data;
1760 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1761 return (EBADF);
1762 *kqp = kq;
1763 KQ_LOCK(kq);
1764 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1765 KQ_UNLOCK(kq);
1766 return (EBADF);
1767 }
1768 kq->kq_refcnt++;
1769 KQ_UNLOCK(kq);
1770
1771 return error;
1772 }
1773
1774 static void
kqueue_release(struct kqueue * kq,int locked)1775 kqueue_release(struct kqueue *kq, int locked)
1776 {
1777 if (locked)
1778 KQ_OWNED(kq);
1779 else
1780 KQ_LOCK(kq);
1781 kq->kq_refcnt--;
1782 if (kq->kq_refcnt == 1)
1783 wakeup(&kq->kq_refcnt);
1784 if (!locked)
1785 KQ_UNLOCK(kq);
1786 }
1787
1788 void
kqueue_drain_schedtask(void)1789 kqueue_drain_schedtask(void)
1790 {
1791 taskqueue_quiesce(taskqueue_kqueue_ctx);
1792 }
1793
1794 static void
kqueue_schedtask(struct kqueue * kq)1795 kqueue_schedtask(struct kqueue *kq)
1796 {
1797 struct thread *td;
1798
1799 KQ_OWNED(kq);
1800 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1801 ("scheduling kqueue task while draining"));
1802
1803 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1804 taskqueue_enqueue(taskqueue_kqueue_ctx, &kq->kq_task);
1805 kq->kq_state |= KQ_TASKSCHED;
1806 td = curthread;
1807 thread_lock(td);
1808 td->td_flags |= TDF_ASTPENDING | TDF_KQTICKLED;
1809 thread_unlock(td);
1810 }
1811 }
1812
1813 /*
1814 * Expand the kq to make sure we have storage for fops/ident pair.
1815 *
1816 * Return 0 on success (or no work necessary), return errno on failure.
1817 */
1818 static int
kqueue_expand(struct kqueue * kq,const struct filterops * fops,uintptr_t ident,int mflag)1819 kqueue_expand(struct kqueue *kq, const struct filterops *fops, uintptr_t ident,
1820 int mflag)
1821 {
1822 struct klist *list, *tmp_knhash, *to_free;
1823 u_long tmp_knhashmask;
1824 int error, fd, size;
1825
1826 KQ_NOTOWNED(kq);
1827
1828 error = 0;
1829 to_free = NULL;
1830 if (fops->f_isfd) {
1831 fd = ident;
1832 if (kq->kq_knlistsize <= fd) {
1833 size = kq->kq_knlistsize;
1834 while (size <= fd)
1835 size += KQEXTENT;
1836 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1837 if (list == NULL)
1838 return ENOMEM;
1839 KQ_LOCK(kq);
1840 if ((kq->kq_state & KQ_CLOSING) != 0) {
1841 to_free = list;
1842 error = EBADF;
1843 } else if (kq->kq_knlistsize > fd) {
1844 to_free = list;
1845 } else {
1846 if (kq->kq_knlist != NULL) {
1847 bcopy(kq->kq_knlist, list,
1848 kq->kq_knlistsize * sizeof(*list));
1849 to_free = kq->kq_knlist;
1850 kq->kq_knlist = NULL;
1851 }
1852 bzero((caddr_t)list +
1853 kq->kq_knlistsize * sizeof(*list),
1854 (size - kq->kq_knlistsize) * sizeof(*list));
1855 kq->kq_knlistsize = size;
1856 kq->kq_knlist = list;
1857 }
1858 KQ_UNLOCK(kq);
1859 }
1860 } else {
1861 if (kq->kq_knhashmask == 0) {
1862 tmp_knhash = hashinit_flags(KN_HASHSIZE, M_KQUEUE,
1863 &tmp_knhashmask, (mflag & M_WAITOK) != 0 ?
1864 HASH_WAITOK : HASH_NOWAIT);
1865 if (tmp_knhash == NULL)
1866 return (ENOMEM);
1867 KQ_LOCK(kq);
1868 if ((kq->kq_state & KQ_CLOSING) != 0) {
1869 to_free = tmp_knhash;
1870 error = EBADF;
1871 } else if (kq->kq_knhashmask == 0) {
1872 kq->kq_knhash = tmp_knhash;
1873 kq->kq_knhashmask = tmp_knhashmask;
1874 } else {
1875 to_free = tmp_knhash;
1876 }
1877 KQ_UNLOCK(kq);
1878 }
1879 }
1880 free(to_free, M_KQUEUE);
1881
1882 KQ_NOTOWNED(kq);
1883 return (error);
1884 }
1885
1886 static void
kqueue_task(void * arg,int pending)1887 kqueue_task(void *arg, int pending)
1888 {
1889 struct kqueue *kq;
1890 int haskqglobal;
1891
1892 haskqglobal = 0;
1893 kq = arg;
1894
1895 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1896 KQ_LOCK(kq);
1897
1898 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1899
1900 kq->kq_state &= ~KQ_TASKSCHED;
1901 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1902 wakeup(&kq->kq_state);
1903 }
1904 KQ_UNLOCK(kq);
1905 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1906 }
1907
1908 /*
1909 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1910 * We treat KN_MARKER knotes as if they are in flux.
1911 */
1912 static int
kqueue_scan(struct kqueue * kq,int maxevents,struct kevent_copyops * k_ops,const struct timespec * tsp,struct kevent * keva,struct thread * td)1913 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1914 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1915 {
1916 struct kevent *kevp;
1917 struct knote *kn, *marker;
1918 struct knlist *knl;
1919 sbintime_t asbt, rsbt;
1920 int count, error, haskqglobal, influx, nkev, touch;
1921
1922 count = maxevents;
1923 nkev = 0;
1924 error = 0;
1925 haskqglobal = 0;
1926
1927 if (maxevents == 0)
1928 goto done_nl;
1929 if (maxevents < 0) {
1930 error = EINVAL;
1931 goto done_nl;
1932 }
1933
1934 rsbt = 0;
1935 if (tsp != NULL) {
1936 if (!timespecvalid_interval(tsp)) {
1937 error = EINVAL;
1938 goto done_nl;
1939 }
1940 if (timespecisset(tsp)) {
1941 if (tsp->tv_sec <= INT32_MAX) {
1942 rsbt = tstosbt(*tsp);
1943 if (TIMESEL(&asbt, rsbt))
1944 asbt += tc_tick_sbt;
1945 if (asbt <= SBT_MAX - rsbt)
1946 asbt += rsbt;
1947 else
1948 asbt = 0;
1949 rsbt >>= tc_precexp;
1950 } else
1951 asbt = 0;
1952 } else
1953 asbt = -1;
1954 } else
1955 asbt = 0;
1956 marker = knote_alloc(M_WAITOK);
1957 marker->kn_status = KN_MARKER;
1958 KQ_LOCK(kq);
1959
1960 retry:
1961 kevp = keva;
1962 if (kq->kq_count == 0) {
1963 if (asbt == -1) {
1964 error = EWOULDBLOCK;
1965 } else {
1966 kq->kq_state |= KQ_SLEEP;
1967 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1968 "kqread", asbt, rsbt, C_ABSOLUTE);
1969 }
1970 if (error == 0)
1971 goto retry;
1972 /* don't restart after signals... */
1973 if (error == ERESTART)
1974 error = EINTR;
1975 else if (error == EWOULDBLOCK)
1976 error = 0;
1977 goto done;
1978 }
1979
1980 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1981 influx = 0;
1982 while (count) {
1983 KQ_OWNED(kq);
1984 kn = TAILQ_FIRST(&kq->kq_head);
1985
1986 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1987 kn_in_flux(kn)) {
1988 if (influx) {
1989 influx = 0;
1990 KQ_FLUX_WAKEUP(kq);
1991 }
1992 kq->kq_state |= KQ_FLUXWAIT;
1993 error = msleep(kq, &kq->kq_lock, PSOCK,
1994 "kqflxwt", 0);
1995 continue;
1996 }
1997
1998 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1999 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
2000 kn->kn_status &= ~KN_QUEUED;
2001 kq->kq_count--;
2002 continue;
2003 }
2004 if (kn == marker) {
2005 KQ_FLUX_WAKEUP(kq);
2006 if (count == maxevents)
2007 goto retry;
2008 goto done;
2009 }
2010 KASSERT(!kn_in_flux(kn),
2011 ("knote %p is unexpectedly in flux", kn));
2012
2013 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
2014 kn->kn_status &= ~KN_QUEUED;
2015 kn_enter_flux(kn);
2016 kq->kq_count--;
2017 KQ_UNLOCK(kq);
2018 /*
2019 * We don't need to lock the list since we've
2020 * marked it as in flux.
2021 */
2022 knote_drop(kn, td);
2023 KQ_LOCK(kq);
2024 continue;
2025 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
2026 kn->kn_status &= ~KN_QUEUED;
2027 kn_enter_flux(kn);
2028 kq->kq_count--;
2029 KQ_UNLOCK(kq);
2030 /*
2031 * We don't need to lock the list since we've
2032 * marked the knote as being in flux.
2033 */
2034 *kevp = kn->kn_kevent;
2035 knote_drop(kn, td);
2036 KQ_LOCK(kq);
2037 kn = NULL;
2038 } else {
2039 kn->kn_status |= KN_SCAN;
2040 kn_enter_flux(kn);
2041 KQ_UNLOCK(kq);
2042 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
2043 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
2044 knl = kn_list_lock(kn);
2045 if (kn->kn_fop->f_event(kn, 0) == 0) {
2046 KQ_LOCK(kq);
2047 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
2048 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE |
2049 KN_SCAN);
2050 kn_leave_flux(kn);
2051 kq->kq_count--;
2052 kn_list_unlock(knl);
2053 influx = 1;
2054 continue;
2055 }
2056 touch = (!kn->kn_fop->f_isfd &&
2057 kn->kn_fop->f_touch != NULL);
2058 if (touch)
2059 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
2060 else
2061 *kevp = kn->kn_kevent;
2062 KQ_LOCK(kq);
2063 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
2064 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
2065 /*
2066 * Manually clear knotes who weren't
2067 * 'touch'ed.
2068 */
2069 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
2070 kn->kn_data = 0;
2071 kn->kn_fflags = 0;
2072 }
2073 if (kn->kn_flags & EV_DISPATCH)
2074 kn->kn_status |= KN_DISABLED;
2075 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
2076 kq->kq_count--;
2077 } else
2078 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2079
2080 kn->kn_status &= ~KN_SCAN;
2081 kn_leave_flux(kn);
2082 kn_list_unlock(knl);
2083 influx = 1;
2084 }
2085
2086 /* we are returning a copy to the user */
2087 kevp++;
2088 nkev++;
2089 count--;
2090
2091 if (nkev == KQ_NEVENTS) {
2092 influx = 0;
2093 KQ_UNLOCK_FLUX(kq);
2094 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
2095 nkev = 0;
2096 kevp = keva;
2097 KQ_LOCK(kq);
2098 if (error)
2099 break;
2100 }
2101 }
2102 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
2103 done:
2104 KQ_OWNED(kq);
2105 KQ_UNLOCK_FLUX(kq);
2106 knote_free(marker);
2107 done_nl:
2108 KQ_NOTOWNED(kq);
2109 if (nkev != 0)
2110 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
2111 td->td_retval[0] = maxevents - count;
2112 return (error);
2113 }
2114
2115 /*ARGSUSED*/
2116 static int
kqueue_ioctl(struct file * fp,u_long cmd,void * data,struct ucred * active_cred,struct thread * td)2117 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
2118 struct ucred *active_cred, struct thread *td)
2119 {
2120 /*
2121 * Enabling sigio causes two major problems:
2122 * 1) infinite recursion:
2123 * Synopsys: kevent is being used to track signals and have FIOASYNC
2124 * set. On receipt of a signal this will cause a kqueue to recurse
2125 * into itself over and over. Sending the sigio causes the kqueue
2126 * to become ready, which in turn posts sigio again, forever.
2127 * Solution: this can be solved by setting a flag in the kqueue that
2128 * we have a SIGIO in progress.
2129 * 2) locking problems:
2130 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
2131 * us above the proc and pgrp locks.
2132 * Solution: Post a signal using an async mechanism, being sure to
2133 * record a generation count in the delivery so that we do not deliver
2134 * a signal to the wrong process.
2135 *
2136 * Note, these two mechanisms are somewhat mutually exclusive!
2137 */
2138 #if 0
2139 struct kqueue *kq;
2140
2141 kq = fp->f_data;
2142 switch (cmd) {
2143 case FIOASYNC:
2144 if (*(int *)data) {
2145 kq->kq_state |= KQ_ASYNC;
2146 } else {
2147 kq->kq_state &= ~KQ_ASYNC;
2148 }
2149 return (0);
2150
2151 case FIOSETOWN:
2152 return (fsetown(*(int *)data, &kq->kq_sigio));
2153
2154 case FIOGETOWN:
2155 *(int *)data = fgetown(&kq->kq_sigio);
2156 return (0);
2157 }
2158 #endif
2159
2160 return (ENOTTY);
2161 }
2162
2163 /*ARGSUSED*/
2164 static int
kqueue_poll(struct file * fp,int events,struct ucred * active_cred,struct thread * td)2165 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
2166 struct thread *td)
2167 {
2168 struct kqueue *kq;
2169 int revents = 0;
2170 int error;
2171
2172 if ((error = kqueue_acquire(fp, &kq)))
2173 return POLLERR;
2174
2175 KQ_LOCK(kq);
2176 if (events & (POLLIN | POLLRDNORM)) {
2177 if (kq->kq_count) {
2178 revents |= events & (POLLIN | POLLRDNORM);
2179 } else {
2180 selrecord(td, &kq->kq_sel);
2181 if (SEL_WAITING(&kq->kq_sel))
2182 kq->kq_state |= KQ_SEL;
2183 }
2184 }
2185 kqueue_release(kq, 1);
2186 KQ_UNLOCK(kq);
2187 return (revents);
2188 }
2189
2190 /*ARGSUSED*/
2191 static int
kqueue_stat(struct file * fp,struct stat * st,struct ucred * active_cred,struct thread * td)2192 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
2193 struct thread *td)
2194 {
2195
2196 bzero((void *)st, sizeof *st);
2197 /*
2198 * We no longer return kq_count because the unlocked value is useless.
2199 * If you spent all this time getting the count, why not spend your
2200 * syscall better by calling kevent?
2201 *
2202 * XXX - This is needed for libc_r.
2203 */
2204 st->st_mode = S_IFIFO;
2205 return (0);
2206 }
2207
2208 static void
kqueue_drain(struct kqueue * kq,struct thread * td)2209 kqueue_drain(struct kqueue *kq, struct thread *td)
2210 {
2211 struct knote *kn;
2212 int i;
2213
2214 KQ_LOCK(kq);
2215
2216 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
2217 ("kqueue already closing"));
2218 kq->kq_state |= KQ_CLOSING;
2219 if (kq->kq_refcnt > 1)
2220 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
2221
2222 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
2223
2224 KASSERT(knlist_empty(&kq->kq_sel.si_note),
2225 ("kqueue's knlist not empty"));
2226
2227 for (i = 0; i < kq->kq_knlistsize; i++) {
2228 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
2229 if (kn_in_flux(kn)) {
2230 kq->kq_state |= KQ_FLUXWAIT;
2231 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
2232 continue;
2233 }
2234 kn_enter_flux(kn);
2235 KQ_UNLOCK(kq);
2236 knote_drop(kn, td);
2237 KQ_LOCK(kq);
2238 }
2239 }
2240 if (kq->kq_knhashmask != 0) {
2241 for (i = 0; i <= kq->kq_knhashmask; i++) {
2242 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
2243 if (kn_in_flux(kn)) {
2244 kq->kq_state |= KQ_FLUXWAIT;
2245 msleep(kq, &kq->kq_lock, PSOCK,
2246 "kqclo2", 0);
2247 continue;
2248 }
2249 kn_enter_flux(kn);
2250 KQ_UNLOCK(kq);
2251 knote_drop(kn, td);
2252 KQ_LOCK(kq);
2253 }
2254 }
2255 }
2256
2257 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
2258 kq->kq_state |= KQ_TASKDRAIN;
2259 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
2260 }
2261
2262 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2263 selwakeuppri(&kq->kq_sel, PSOCK);
2264 if (!SEL_WAITING(&kq->kq_sel))
2265 kq->kq_state &= ~KQ_SEL;
2266 }
2267
2268 KQ_UNLOCK(kq);
2269 }
2270
2271 static void
kqueue_destroy(struct kqueue * kq)2272 kqueue_destroy(struct kqueue *kq)
2273 {
2274
2275 KASSERT(kq->kq_fdp == NULL,
2276 ("kqueue still attached to a file descriptor"));
2277 seldrain(&kq->kq_sel);
2278 knlist_destroy(&kq->kq_sel.si_note);
2279 mtx_destroy(&kq->kq_lock);
2280
2281 if (kq->kq_knhash != NULL)
2282 free(kq->kq_knhash, M_KQUEUE);
2283 if (kq->kq_knlist != NULL)
2284 free(kq->kq_knlist, M_KQUEUE);
2285
2286 funsetown(&kq->kq_sigio);
2287 }
2288
2289 /*ARGSUSED*/
2290 static int
kqueue_close(struct file * fp,struct thread * td)2291 kqueue_close(struct file *fp, struct thread *td)
2292 {
2293 struct kqueue *kq = fp->f_data;
2294 struct filedesc *fdp;
2295 int error;
2296 int filedesc_unlock;
2297
2298 if ((error = kqueue_acquire(fp, &kq)))
2299 return error;
2300 kqueue_drain(kq, td);
2301
2302 /*
2303 * We could be called due to the knote_drop() doing fdrop(),
2304 * called from kqueue_register(). In this case the global
2305 * lock is owned, and filedesc sx is locked before, to not
2306 * take the sleepable lock after non-sleepable.
2307 */
2308 fdp = kq->kq_fdp;
2309 kq->kq_fdp = NULL;
2310 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
2311 FILEDESC_XLOCK(fdp);
2312 filedesc_unlock = 1;
2313 } else
2314 filedesc_unlock = 0;
2315 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
2316 if (filedesc_unlock)
2317 FILEDESC_XUNLOCK(fdp);
2318
2319 kqueue_destroy(kq);
2320 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
2321 crfree(kq->kq_cred);
2322 free(kq, M_KQUEUE);
2323 fp->f_data = NULL;
2324
2325 return (0);
2326 }
2327
2328 static int
kqueue_fill_kinfo(struct file * fp,struct kinfo_file * kif,struct filedesc * fdp)2329 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2330 {
2331 struct kqueue *kq = fp->f_data;
2332
2333 kif->kf_type = KF_TYPE_KQUEUE;
2334 kif->kf_un.kf_kqueue.kf_kqueue_addr = (uintptr_t)kq;
2335 kif->kf_un.kf_kqueue.kf_kqueue_count = kq->kq_count;
2336 kif->kf_un.kf_kqueue.kf_kqueue_state = kq->kq_state;
2337 return (0);
2338 }
2339
2340 static void
kqueue_wakeup(struct kqueue * kq)2341 kqueue_wakeup(struct kqueue *kq)
2342 {
2343 KQ_OWNED(kq);
2344
2345 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
2346 kq->kq_state &= ~KQ_SLEEP;
2347 wakeup(kq);
2348 }
2349 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2350 selwakeuppri(&kq->kq_sel, PSOCK);
2351 if (!SEL_WAITING(&kq->kq_sel))
2352 kq->kq_state &= ~KQ_SEL;
2353 }
2354 if (!knlist_empty(&kq->kq_sel.si_note))
2355 kqueue_schedtask(kq);
2356 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
2357 pgsigio(&kq->kq_sigio, SIGIO, 0);
2358 }
2359 }
2360
2361 /*
2362 * Walk down a list of knotes, activating them if their event has triggered.
2363 *
2364 * There is a possibility to optimize in the case of one kq watching another.
2365 * Instead of scheduling a task to wake it up, you could pass enough state
2366 * down the chain to make up the parent kqueue. Make this code functional
2367 * first.
2368 */
2369 void
knote(struct knlist * list,long hint,int lockflags)2370 knote(struct knlist *list, long hint, int lockflags)
2371 {
2372 struct kqueue *kq;
2373 struct knote *kn, *tkn;
2374 int error;
2375
2376 if (list == NULL)
2377 return;
2378
2379 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
2380
2381 if ((lockflags & KNF_LISTLOCKED) == 0)
2382 list->kl_lock(list->kl_lockarg);
2383
2384 /*
2385 * If we unlock the list lock (and enter influx), we can
2386 * eliminate the kqueue scheduling, but this will introduce
2387 * four lock/unlock's for each knote to test. Also, marker
2388 * would be needed to keep iteration position, since filters
2389 * or other threads could remove events.
2390 */
2391 SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
2392 kq = kn->kn_kq;
2393 KQ_LOCK(kq);
2394 if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
2395 /*
2396 * Do not process the influx notes, except for
2397 * the influx coming from the kq unlock in the
2398 * kqueue_scan(). In the later case, we do
2399 * not interfere with the scan, since the code
2400 * fragment in kqueue_scan() locks the knlist,
2401 * and cannot proceed until we finished.
2402 */
2403 KQ_UNLOCK(kq);
2404 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
2405 kn_enter_flux(kn);
2406 KQ_UNLOCK(kq);
2407 error = kn->kn_fop->f_event(kn, hint);
2408 KQ_LOCK(kq);
2409 kn_leave_flux(kn);
2410 if (error)
2411 KNOTE_ACTIVATE(kn, 1);
2412 KQ_UNLOCK_FLUX(kq);
2413 } else {
2414 if (kn->kn_fop->f_event(kn, hint))
2415 KNOTE_ACTIVATE(kn, 1);
2416 KQ_UNLOCK(kq);
2417 }
2418 }
2419 if ((lockflags & KNF_LISTLOCKED) == 0)
2420 list->kl_unlock(list->kl_lockarg);
2421 }
2422
2423 /*
2424 * add a knote to a knlist
2425 */
2426 void
knlist_add(struct knlist * knl,struct knote * kn,int islocked)2427 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
2428 {
2429
2430 KNL_ASSERT_LOCK(knl, islocked);
2431 KQ_NOTOWNED(kn->kn_kq);
2432 KASSERT(kn_in_flux(kn), ("knote %p not in flux", kn));
2433 KASSERT((kn->kn_status & KN_DETACHED) != 0,
2434 ("knote %p was not detached", kn));
2435 if (!islocked)
2436 knl->kl_lock(knl->kl_lockarg);
2437 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2438 if (!islocked)
2439 knl->kl_unlock(knl->kl_lockarg);
2440 KQ_LOCK(kn->kn_kq);
2441 kn->kn_knlist = knl;
2442 kn->kn_status &= ~KN_DETACHED;
2443 KQ_UNLOCK(kn->kn_kq);
2444 }
2445
2446 static void
knlist_remove_kq(struct knlist * knl,struct knote * kn,int knlislocked,int kqislocked)2447 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked,
2448 int kqislocked)
2449 {
2450
2451 KASSERT(!kqislocked || knlislocked, ("kq locked w/o knl locked"));
2452 KNL_ASSERT_LOCK(knl, knlislocked);
2453 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2454 KASSERT(kqislocked || kn_in_flux(kn), ("knote %p not in flux", kn));
2455 KASSERT((kn->kn_status & KN_DETACHED) == 0,
2456 ("knote %p was already detached", kn));
2457 if (!knlislocked)
2458 knl->kl_lock(knl->kl_lockarg);
2459 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2460 kn->kn_knlist = NULL;
2461 if (!knlislocked)
2462 kn_list_unlock(knl);
2463 if (!kqislocked)
2464 KQ_LOCK(kn->kn_kq);
2465 kn->kn_status |= KN_DETACHED;
2466 if (!kqislocked)
2467 KQ_UNLOCK(kn->kn_kq);
2468 }
2469
2470 /*
2471 * remove knote from the specified knlist
2472 */
2473 void
knlist_remove(struct knlist * knl,struct knote * kn,int islocked)2474 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2475 {
2476
2477 knlist_remove_kq(knl, kn, islocked, 0);
2478 }
2479
2480 int
knlist_empty(struct knlist * knl)2481 knlist_empty(struct knlist *knl)
2482 {
2483
2484 KNL_ASSERT_LOCKED(knl);
2485 return (SLIST_EMPTY(&knl->kl_list));
2486 }
2487
2488 static struct mtx knlist_lock;
2489 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2490 MTX_DEF);
2491 static void knlist_mtx_lock(void *arg);
2492 static void knlist_mtx_unlock(void *arg);
2493
2494 static void
knlist_mtx_lock(void * arg)2495 knlist_mtx_lock(void *arg)
2496 {
2497
2498 mtx_lock((struct mtx *)arg);
2499 }
2500
2501 static void
knlist_mtx_unlock(void * arg)2502 knlist_mtx_unlock(void *arg)
2503 {
2504
2505 mtx_unlock((struct mtx *)arg);
2506 }
2507
2508 static void
knlist_mtx_assert_lock(void * arg,int what)2509 knlist_mtx_assert_lock(void *arg, int what)
2510 {
2511
2512 if (what == LA_LOCKED)
2513 mtx_assert((struct mtx *)arg, MA_OWNED);
2514 else
2515 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2516 }
2517
2518 static void
knlist_rw_rlock(void * arg)2519 knlist_rw_rlock(void *arg)
2520 {
2521
2522 rw_rlock((struct rwlock *)arg);
2523 }
2524
2525 static void
knlist_rw_runlock(void * arg)2526 knlist_rw_runlock(void *arg)
2527 {
2528
2529 rw_runlock((struct rwlock *)arg);
2530 }
2531
2532 static void
knlist_rw_assert_lock(void * arg,int what)2533 knlist_rw_assert_lock(void *arg, int what)
2534 {
2535
2536 if (what == LA_LOCKED)
2537 rw_assert((struct rwlock *)arg, RA_LOCKED);
2538 else
2539 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2540 }
2541
2542 void
knlist_init(struct knlist * knl,void * lock,void (* kl_lock)(void *),void (* kl_unlock)(void *),void (* kl_assert_lock)(void *,int))2543 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2544 void (*kl_unlock)(void *),
2545 void (*kl_assert_lock)(void *, int))
2546 {
2547
2548 if (lock == NULL)
2549 knl->kl_lockarg = &knlist_lock;
2550 else
2551 knl->kl_lockarg = lock;
2552
2553 if (kl_lock == NULL)
2554 knl->kl_lock = knlist_mtx_lock;
2555 else
2556 knl->kl_lock = kl_lock;
2557 if (kl_unlock == NULL)
2558 knl->kl_unlock = knlist_mtx_unlock;
2559 else
2560 knl->kl_unlock = kl_unlock;
2561 if (kl_assert_lock == NULL)
2562 knl->kl_assert_lock = knlist_mtx_assert_lock;
2563 else
2564 knl->kl_assert_lock = kl_assert_lock;
2565
2566 knl->kl_autodestroy = 0;
2567 SLIST_INIT(&knl->kl_list);
2568 }
2569
2570 void
knlist_init_mtx(struct knlist * knl,struct mtx * lock)2571 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2572 {
2573
2574 knlist_init(knl, lock, NULL, NULL, NULL);
2575 }
2576
2577 struct knlist *
knlist_alloc(struct mtx * lock)2578 knlist_alloc(struct mtx *lock)
2579 {
2580 struct knlist *knl;
2581
2582 knl = malloc(sizeof(struct knlist), M_KQUEUE, M_WAITOK);
2583 knlist_init_mtx(knl, lock);
2584 return (knl);
2585 }
2586
2587 void
knlist_init_rw_reader(struct knlist * knl,struct rwlock * lock)2588 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2589 {
2590
2591 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2592 knlist_rw_assert_lock);
2593 }
2594
2595 void
knlist_destroy(struct knlist * knl)2596 knlist_destroy(struct knlist *knl)
2597 {
2598
2599 KASSERT(KNLIST_EMPTY(knl),
2600 ("destroying knlist %p with knotes on it", knl));
2601 }
2602
2603 void
knlist_detach(struct knlist * knl)2604 knlist_detach(struct knlist *knl)
2605 {
2606
2607 KNL_ASSERT_LOCKED(knl);
2608 knl->kl_autodestroy = 1;
2609 if (knlist_empty(knl)) {
2610 knlist_destroy(knl);
2611 free(knl, M_KQUEUE);
2612 }
2613 }
2614
2615 /*
2616 * Even if we are locked, we may need to drop the lock to allow any influx
2617 * knotes time to "settle".
2618 */
2619 void
knlist_cleardel(struct knlist * knl,struct thread * td,int islocked,int killkn)2620 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2621 {
2622 struct knote *kn, *kn2;
2623 struct kqueue *kq;
2624
2625 KASSERT(!knl->kl_autodestroy, ("cleardel for autodestroy %p", knl));
2626 if (islocked)
2627 KNL_ASSERT_LOCKED(knl);
2628 else {
2629 KNL_ASSERT_UNLOCKED(knl);
2630 again: /* need to reacquire lock since we have dropped it */
2631 knl->kl_lock(knl->kl_lockarg);
2632 }
2633
2634 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2635 kq = kn->kn_kq;
2636 KQ_LOCK(kq);
2637 if (kn_in_flux(kn)) {
2638 KQ_UNLOCK(kq);
2639 continue;
2640 }
2641 knlist_remove_kq(knl, kn, 1, 1);
2642 if (killkn) {
2643 kn_enter_flux(kn);
2644 KQ_UNLOCK(kq);
2645 knote_drop_detached(kn, td);
2646 } else {
2647 /* Make sure cleared knotes disappear soon */
2648 kn->kn_flags |= EV_EOF | EV_ONESHOT;
2649 KQ_UNLOCK(kq);
2650 }
2651 kq = NULL;
2652 }
2653
2654 if (!SLIST_EMPTY(&knl->kl_list)) {
2655 /* there are still in flux knotes remaining */
2656 kn = SLIST_FIRST(&knl->kl_list);
2657 kq = kn->kn_kq;
2658 KQ_LOCK(kq);
2659 KASSERT(kn_in_flux(kn), ("knote removed w/o list lock"));
2660 knl->kl_unlock(knl->kl_lockarg);
2661 kq->kq_state |= KQ_FLUXWAIT;
2662 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2663 kq = NULL;
2664 goto again;
2665 }
2666
2667 if (islocked)
2668 KNL_ASSERT_LOCKED(knl);
2669 else {
2670 knl->kl_unlock(knl->kl_lockarg);
2671 KNL_ASSERT_UNLOCKED(knl);
2672 }
2673 }
2674
2675 /*
2676 * Remove all knotes referencing a specified fd must be called with FILEDESC
2677 * lock. This prevents a race where a new fd comes along and occupies the
2678 * entry and we attach a knote to the fd.
2679 */
2680 void
knote_fdclose(struct thread * td,int fd)2681 knote_fdclose(struct thread *td, int fd)
2682 {
2683 struct filedesc *fdp = td->td_proc->p_fd;
2684 struct kqueue *kq;
2685 struct knote *kn;
2686 int influx;
2687
2688 FILEDESC_XLOCK_ASSERT(fdp);
2689
2690 /*
2691 * We shouldn't have to worry about new kevents appearing on fd
2692 * since filedesc is locked.
2693 */
2694 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2695 KQ_LOCK(kq);
2696
2697 again:
2698 influx = 0;
2699 while (kq->kq_knlistsize > fd &&
2700 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2701 if (kn_in_flux(kn)) {
2702 /* someone else might be waiting on our knote */
2703 if (influx)
2704 wakeup(kq);
2705 kq->kq_state |= KQ_FLUXWAIT;
2706 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2707 goto again;
2708 }
2709 kn_enter_flux(kn);
2710 KQ_UNLOCK(kq);
2711 influx = 1;
2712 knote_drop(kn, td);
2713 KQ_LOCK(kq);
2714 }
2715 KQ_UNLOCK_FLUX(kq);
2716 }
2717 }
2718
2719 static int
knote_attach(struct knote * kn,struct kqueue * kq)2720 knote_attach(struct knote *kn, struct kqueue *kq)
2721 {
2722 struct klist *list;
2723
2724 KASSERT(kn_in_flux(kn), ("knote %p not marked influx", kn));
2725 KQ_OWNED(kq);
2726
2727 if ((kq->kq_state & KQ_CLOSING) != 0)
2728 return (EBADF);
2729 if (kn->kn_fop->f_isfd) {
2730 if (kn->kn_id >= kq->kq_knlistsize)
2731 return (ENOMEM);
2732 list = &kq->kq_knlist[kn->kn_id];
2733 } else {
2734 if (kq->kq_knhash == NULL)
2735 return (ENOMEM);
2736 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2737 }
2738 SLIST_INSERT_HEAD(list, kn, kn_link);
2739 return (0);
2740 }
2741
2742 static void
knote_drop(struct knote * kn,struct thread * td)2743 knote_drop(struct knote *kn, struct thread *td)
2744 {
2745
2746 if ((kn->kn_status & KN_DETACHED) == 0)
2747 kn->kn_fop->f_detach(kn);
2748 knote_drop_detached(kn, td);
2749 }
2750
2751 static void
knote_drop_detached(struct knote * kn,struct thread * td)2752 knote_drop_detached(struct knote *kn, struct thread *td)
2753 {
2754 struct kqueue *kq;
2755 struct klist *list;
2756
2757 kq = kn->kn_kq;
2758
2759 KASSERT((kn->kn_status & KN_DETACHED) != 0,
2760 ("knote %p still attached", kn));
2761 KQ_NOTOWNED(kq);
2762
2763 KQ_LOCK(kq);
2764 KASSERT(kn->kn_influx == 1,
2765 ("knote_drop called on %p with influx %d", kn, kn->kn_influx));
2766
2767 if (kn->kn_fop->f_isfd)
2768 list = &kq->kq_knlist[kn->kn_id];
2769 else
2770 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2771
2772 if (!SLIST_EMPTY(list))
2773 SLIST_REMOVE(list, kn, knote, kn_link);
2774 if (kn->kn_status & KN_QUEUED)
2775 knote_dequeue(kn);
2776 KQ_UNLOCK_FLUX(kq);
2777
2778 if (kn->kn_fop->f_isfd) {
2779 fdrop(kn->kn_fp, td);
2780 kn->kn_fp = NULL;
2781 }
2782 kqueue_fo_release(kn->kn_kevent.filter);
2783 kn->kn_fop = NULL;
2784 knote_free(kn);
2785 }
2786
2787 static void
knote_enqueue(struct knote * kn)2788 knote_enqueue(struct knote *kn)
2789 {
2790 struct kqueue *kq = kn->kn_kq;
2791
2792 KQ_OWNED(kn->kn_kq);
2793 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2794
2795 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2796 kn->kn_status |= KN_QUEUED;
2797 kq->kq_count++;
2798 kqueue_wakeup(kq);
2799 }
2800
2801 static void
knote_dequeue(struct knote * kn)2802 knote_dequeue(struct knote *kn)
2803 {
2804 struct kqueue *kq = kn->kn_kq;
2805
2806 KQ_OWNED(kn->kn_kq);
2807 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2808
2809 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2810 kn->kn_status &= ~KN_QUEUED;
2811 kq->kq_count--;
2812 }
2813
2814 static void
knote_init(void)2815 knote_init(void)
2816 {
2817
2818 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2819 NULL, NULL, UMA_ALIGN_PTR, 0);
2820 }
2821 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2822
2823 static struct knote *
knote_alloc(int mflag)2824 knote_alloc(int mflag)
2825 {
2826
2827 return (uma_zalloc(knote_zone, mflag | M_ZERO));
2828 }
2829
2830 static void
knote_free(struct knote * kn)2831 knote_free(struct knote *kn)
2832 {
2833
2834 uma_zfree(knote_zone, kn);
2835 }
2836
2837 /*
2838 * Register the kev w/ the kq specified by fd.
2839 */
2840 int
kqfd_register(int fd,struct kevent * kev,struct thread * td,int mflag)2841 kqfd_register(int fd, struct kevent *kev, struct thread *td, int mflag)
2842 {
2843 struct kqueue *kq;
2844 struct file *fp;
2845 cap_rights_t rights;
2846 int error;
2847
2848 error = fget(td, fd, cap_rights_init_one(&rights, CAP_KQUEUE_CHANGE),
2849 &fp);
2850 if (error != 0)
2851 return (error);
2852 if ((error = kqueue_acquire(fp, &kq)) != 0)
2853 goto noacquire;
2854
2855 error = kqueue_register(kq, kev, td, mflag);
2856 kqueue_release(kq, 0);
2857
2858 noacquire:
2859 fdrop(fp, td);
2860 return (error);
2861 }
2862