xref: /freebsd-14.2/lib/libc/sys/kqueue.2 (revision eb9de28f)
1.\" Copyright (c) 2000 Jonathan Lemon
2.\" All rights reserved.
3.\"
4.\" Redistribution and use in source and binary forms, with or without
5.\" modification, are permitted provided that the following conditions
6.\" are met:
7.\" 1. Redistributions of source code must retain the above copyright
8.\"    notice, this list of conditions and the following disclaimer.
9.\" 2. Redistributions in binary form must reproduce the above copyright
10.\"    notice, this list of conditions and the following disclaimer in the
11.\"    documentation and/or other materials provided with the distribution.
12.\"
13.\" THIS SOFTWARE IS PROVIDED ``AS IS'' AND
14.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23.\" SUCH DAMAGE.
24.\"
25.\" $FreeBSD$
26.\"
27.Dd September 15, 2009
28.Dt KQUEUE 2
29.Os
30.Sh NAME
31.Nm kqueue ,
32.Nm kevent
33.Nd kernel event notification mechanism
34.Sh LIBRARY
35.Lb libc
36.Sh SYNOPSIS
37.In sys/types.h
38.In sys/event.h
39.In sys/time.h
40.Ft int
41.Fn kqueue "void"
42.Ft int
43.Fn kevent "int kq" "const struct kevent *changelist" "int nchanges" "struct kevent *eventlist" "int nevents" "const struct timespec *timeout"
44.Fn EV_SET "&kev" ident filter flags fflags data udata
45.Sh DESCRIPTION
46The
47.Fn kqueue
48system call
49provides a generic method of notifying the user when an event
50happens or a condition holds, based on the results of small
51pieces of kernel code termed filters.
52A kevent is identified by the (ident, filter) pair; there may only
53be one unique kevent per kqueue.
54.Pp
55The filter is executed upon the initial registration of a kevent
56in order to detect whether a preexisting condition is present, and is also
57executed whenever an event is passed to the filter for evaluation.
58If the filter determines that the condition should be reported,
59then the kevent is placed on the kqueue for the user to retrieve.
60.Pp
61The filter is also run when the user attempts to retrieve the kevent
62from the kqueue.
63If the filter indicates that the condition that triggered
64the event no longer holds, the kevent is removed from the kqueue and
65is not returned.
66.Pp
67Multiple events which trigger the filter do not result in multiple
68kevents being placed on the kqueue; instead, the filter will aggregate
69the events into a single struct kevent.
70Calling
71.Fn close
72on a file descriptor will remove any kevents that reference the descriptor.
73.Pp
74The
75.Fn kqueue
76system call
77creates a new kernel event queue and returns a descriptor.
78The queue is not inherited by a child created with
79.Xr fork 2 .
80However, if
81.Xr rfork 2
82is called without the
83.Dv RFFDG
84flag, then the descriptor table is shared,
85which will allow sharing of the kqueue between two processes.
86.Pp
87The
88.Fn kevent
89system call
90is used to register events with the queue, and return any pending
91events to the user.
92The
93.Fa changelist
94argument
95is a pointer to an array of
96.Va kevent
97structures, as defined in
98.In sys/event.h .
99All changes contained in the
100.Fa changelist
101are applied before any pending events are read from the queue.
102The
103.Fa nchanges
104argument
105gives the size of
106.Fa changelist .
107The
108.Fa eventlist
109argument
110is a pointer to an array of kevent structures.
111The
112.Fa nevents
113argument
114determines the size of
115.Fa eventlist .
116When
117.Fa nevents
118is zero,
119.Fn kevent
120will return immediately even if there is a
121.Fa timeout
122specified unlike
123.Xr select 2 .
124If
125.Fa timeout
126is a non-NULL pointer, it specifies a maximum interval to wait
127for an event, which will be interpreted as a struct timespec.
128If
129.Fa timeout
130is a NULL pointer,
131.Fn kevent
132waits indefinitely.
133To effect a poll, the
134.Fa timeout
135argument should be non-NULL, pointing to a zero-valued
136.Va timespec
137structure.
138The same array may be used for the
139.Fa changelist
140and
141.Fa eventlist .
142.Pp
143The
144.Fn EV_SET
145macro is provided for ease of initializing a
146kevent structure.
147.Pp
148The
149.Va kevent
150structure is defined as:
151.Bd -literal
152struct kevent {
153	uintptr_t ident;	/* identifier for this event */
154	short	  filter;	/* filter for event */
155	u_short	  flags;	/* action flags for kqueue */
156	u_int	  fflags;	/* filter flag value */
157	intptr_t  data;		/* filter data value */
158	void	  *udata;	/* opaque user data identifier */
159};
160.Ed
161.Pp
162The fields of
163.Fa struct kevent
164are:
165.Bl -tag -width XXXfilter
166.It ident
167Value used to identify this event.
168The exact interpretation is determined by the attached filter,
169but often is a file descriptor.
170.It filter
171Identifies the kernel filter used to process this event.
172The pre-defined
173system filters are described below.
174.It flags
175Actions to perform on the event.
176.It fflags
177Filter-specific flags.
178.It data
179Filter-specific data value.
180.It udata
181Opaque user-defined value passed through the kernel unchanged.
182.El
183.Pp
184The
185.Va flags
186field can contain the following values:
187.Bl -tag -width XXXEV_ONESHOT
188.It EV_ADD
189Adds the event to the kqueue.
190Re-adding an existing event
191will modify the parameters of the original event, and not result
192in a duplicate entry.
193Adding an event automatically enables it,
194unless overridden by the EV_DISABLE flag.
195.It EV_ENABLE
196Permit
197.Fn kevent
198to return the event if it is triggered.
199.It EV_DISABLE
200Disable the event so
201.Fn kevent
202will not return it.
203The filter itself is not disabled.
204.It EV_DISPATCH
205Disable the event source immediately after delivery of an event.
206See
207.Dv EV_DISABLE
208above.
209.It EV_DELETE
210Removes the event from the kqueue.
211Events which are attached to
212file descriptors are automatically deleted on the last close of
213the descriptor.
214.It EV_RECEIPT
215This flag is useful for making bulk changes to a kqueue without draining
216any pending events.
217When passed as input, it forces
218.Dv EV_ERROR
219to always be returned.
220When a filter is successfully added the
221.Va data
222field will be zero.
223.It EV_ONESHOT
224Causes the event to return only the first occurrence of the filter
225being triggered.
226After the user retrieves the event from the kqueue,
227it is deleted.
228.It EV_CLEAR
229After the event is retrieved by the user, its state is reset.
230This is useful for filters which report state transitions
231instead of the current state.
232Note that some filters may automatically
233set this flag internally.
234.It EV_EOF
235Filters may set this flag to indicate filter-specific EOF condition.
236.It EV_ERROR
237See
238.Sx RETURN VALUES
239below.
240.El
241.Pp
242The predefined system filters are listed below.
243Arguments may be passed to and from the filter via the
244.Va fflags
245and
246.Va data
247fields in the kevent structure.
248.Bl -tag -width EVFILT_SIGNAL
249.It EVFILT_READ
250Takes a descriptor as the identifier, and returns whenever
251there is data available to read.
252The behavior of the filter is slightly different depending
253on the descriptor type.
254.Pp
255.Bl -tag -width 2n
256.It Sockets
257Sockets which have previously been passed to
258.Fn listen
259return when there is an incoming connection pending.
260.Va data
261contains the size of the listen backlog.
262.Pp
263Other socket descriptors return when there is data to be read,
264subject to the
265.Dv SO_RCVLOWAT
266value of the socket buffer.
267This may be overridden with a per-filter low water mark at the
268time the filter is added by setting the
269NOTE_LOWAT
270flag in
271.Va fflags ,
272and specifying the new low water mark in
273.Va data .
274On return,
275.Va data
276contains the number of bytes of protocol data available to read.
277.Pp
278If the read direction of the socket has shutdown, then the filter
279also sets EV_EOF in
280.Va flags ,
281and returns the socket error (if any) in
282.Va fflags .
283It is possible for EOF to be returned (indicating the connection is gone)
284while there is still data pending in the socket buffer.
285.It Vnodes
286Returns when the file pointer is not at the end of file.
287.Va data
288contains the offset from current position to end of file,
289and may be negative.
290.It "Fifos, Pipes"
291Returns when the there is data to read;
292.Va data
293contains the number of bytes available.
294.Pp
295When the last writer disconnects, the filter will set EV_EOF in
296.Va flags .
297This may be cleared by passing in EV_CLEAR, at which point the
298filter will resume waiting for data to become available before
299returning.
300.It "BPF devices"
301Returns when the BPF buffer is full, the BPF timeout has expired, or
302when the BPF has
303.Dq immediate mode
304enabled and there is any data to read;
305.Va data
306contains the number of bytes available.
307.El
308.It EVFILT_WRITE
309Takes a descriptor as the identifier, and returns whenever
310it is possible to write to the descriptor.
311For sockets, pipes
312and fifos,
313.Va data
314will contain the amount of space remaining in the write buffer.
315The filter will set EV_EOF when the reader disconnects, and for
316the fifo case, this may be cleared by use of EV_CLEAR.
317Note that this filter is not supported for vnodes or BPF devices.
318.Pp
319For sockets, the low water mark and socket error handling is
320identical to the EVFILT_READ case.
321.It EVFILT_AIO
322The sigevent portion of the AIO request is filled in, with
323.Va sigev_notify_kqueue
324containing the descriptor of the kqueue that the event should
325be attached to,
326.Va sigev_value
327containing the udata value, and
328.Va sigev_notify
329set to SIGEV_KEVENT.
330When the
331.Fn aio_*
332system call is made, the event will be registered
333with the specified kqueue, and the
334.Va ident
335argument set to the
336.Fa struct aiocb
337returned by the
338.Fn aio_*
339system call.
340The filter returns under the same conditions as aio_error.
341.It EVFILT_VNODE
342Takes a file descriptor as the identifier and the events to watch for in
343.Va fflags ,
344and returns when one or more of the requested events occurs on the descriptor.
345The events to monitor are:
346.Bl -tag -width XXNOTE_RENAME
347.It NOTE_DELETE
348The
349.Fn unlink
350system call
351was called on the file referenced by the descriptor.
352.It NOTE_WRITE
353A write occurred on the file referenced by the descriptor.
354.It NOTE_EXTEND
355The file referenced by the descriptor was extended.
356.It NOTE_ATTRIB
357The file referenced by the descriptor had its attributes changed.
358.It NOTE_LINK
359The link count on the file changed.
360.It NOTE_RENAME
361The file referenced by the descriptor was renamed.
362.It NOTE_REVOKE
363Access to the file was revoked via
364.Xr revoke 2
365or the underlying file system was unmounted.
366.El
367.Pp
368On return,
369.Va fflags
370contains the events which triggered the filter.
371.It EVFILT_PROC
372Takes the process ID to monitor as the identifier and the events to watch for
373in
374.Va fflags ,
375and returns when the process performs one or more of the requested events.
376If a process can normally see another process, it can attach an event to it.
377The events to monitor are:
378.Bl -tag -width XXNOTE_TRACKERR
379.It NOTE_EXIT
380The process has exited.
381The exit status will be stored in
382.Va data .
383.It NOTE_FORK
384The process has called
385.Fn fork .
386.It NOTE_EXEC
387The process has executed a new process via
388.Xr execve 2
389or similar call.
390.It NOTE_TRACK
391Follow a process across
392.Fn fork
393calls.
394The parent process will return with NOTE_TRACK set in the
395.Va fflags
396field, while the child process will return with NOTE_CHILD set in
397.Va fflags
398and the parent PID in
399.Va data .
400.It NOTE_TRACKERR
401This flag is returned if the system was unable to attach an event to
402the child process, usually due to resource limitations.
403.El
404.Pp
405On return,
406.Va fflags
407contains the events which triggered the filter.
408.It EVFILT_SIGNAL
409Takes the signal number to monitor as the identifier and returns
410when the given signal is delivered to the process.
411This coexists with the
412.Fn signal
413and
414.Fn sigaction
415facilities, and has a lower precedence.
416The filter will record
417all attempts to deliver a signal to a process, even if the signal has
418been marked as SIG_IGN.
419Event notification happens after normal
420signal delivery processing.
421.Va data
422returns the number of times the signal has occurred since the last call to
423.Fn kevent .
424This filter automatically sets the EV_CLEAR flag internally.
425.It EVFILT_TIMER
426Establishes an arbitrary timer identified by
427.Va ident .
428When adding a timer,
429.Va data
430specifies the timeout period in milliseconds.
431The timer will be periodic unless EV_ONESHOT is specified.
432On return,
433.Va data
434contains the number of times the timeout has expired since the last call to
435.Fn kevent .
436This filter automatically sets the EV_CLEAR flag internally.
437There is a system wide limit on the number of timers
438which is controlled by the
439.Va kern.kq_calloutmax
440sysctl.
441.It Dv EVFILT_NETDEV
442Takes a descriptor to a network interface as the identifier, and the events to watch for in
443.Va fflags .
444It returns, when one or more of the requested events occur on the descriptor.
445The events to monitor are:
446.Bl -tag -width XXNOTE_LINKDOWN
447.It Dv NOTE_LINKUP
448The link is up.
449.It Dv NOTE_LINKDOWN
450The link is down.
451.It Dv NOTE_LINKINV
452The link state is invalid.
453.El
454.Pp
455On return,
456.Va fflags
457contains the events which triggered the filter.
458.It Dv EVFILT_USER
459Establishes a user event identified by
460.Va ident
461which is not assosicated with any kernel mechanism but is triggered by
462user level code.
463The lower 24 bits of the
464.Va fflags
465may be used for user defined flags and manipulated using the following:
466.Bl -tag -width XXNOTE_FFLAGSMASK
467.It Dv NOTE_FFNOP
468Ignore the input
469.Va fflags .
470.It Dv NOTE_FFAND
471Bitwise AND
472.Va fflags .
473.It Dv NOTE_FFOR
474Bitwise OR
475.Va fflags .
476.It Dv NOTE_COPY
477Copy
478.Va fflags .
479.It Dv NOTE_FFCTRLMASK
480Control mask for
481.Va fflags .
482.It Dv NOTE_FFLAGSMASK
483User defined flag mask for
484.Va fflags .
485.El
486.Pp
487A user event is triggered for output with the following:
488.Bl -tag -width XXNOTE_FFLAGSMASK
489.It Dv NOTE_TRIGGER
490Cause the event to be triggered.
491.El
492.Pp
493On return,
494.Va fflags
495contains the users defined flags in the lower 24 bits.
496.El
497.Sh RETURN VALUES
498The
499.Fn kqueue
500system call
501creates a new kernel event queue and returns a file descriptor.
502If there was an error creating the kernel event queue, a value of -1 is
503returned and errno set.
504.Pp
505The
506.Fn kevent
507system call
508returns the number of events placed in the
509.Fa eventlist ,
510up to the value given by
511.Fa nevents .
512If an error occurs while processing an element of the
513.Fa changelist
514and there is enough room in the
515.Fa eventlist ,
516then the event will be placed in the
517.Fa eventlist
518with
519.Dv EV_ERROR
520set in
521.Va flags
522and the system error in
523.Va data .
524Otherwise,
525.Dv -1
526will be returned, and
527.Dv errno
528will be set to indicate the error condition.
529If the time limit expires, then
530.Fn kevent
531returns 0.
532.Sh ERRORS
533The
534.Fn kqueue
535system call fails if:
536.Bl -tag -width Er
537.It Bq Er ENOMEM
538The kernel failed to allocate enough memory for the kernel queue.
539.It Bq Er EMFILE
540The per-process descriptor table is full.
541.It Bq Er ENFILE
542The system file table is full.
543.El
544.Pp
545The
546.Fn kevent
547system call fails if:
548.Bl -tag -width Er
549.It Bq Er EACCES
550The process does not have permission to register a filter.
551.It Bq Er EFAULT
552There was an error reading or writing the
553.Va kevent
554structure.
555.It Bq Er EBADF
556The specified descriptor is invalid.
557.It Bq Er EINTR
558A signal was delivered before the timeout expired and before any
559events were placed on the kqueue for return.
560.It Bq Er EINVAL
561The specified time limit or filter is invalid.
562.It Bq Er ENOENT
563The event could not be found to be modified or deleted.
564.It Bq Er ENOMEM
565No memory was available to register the event
566or, in the special case of a timer, the maximum number of
567timers has been exceeded.
568This maximum is configurable via the
569.Va kern.kq_calloutmax
570sysctl.
571.It Bq Er ESRCH
572The specified process to attach to does not exist.
573.El
574.Sh SEE ALSO
575.Xr aio_error 2 ,
576.Xr aio_read 2 ,
577.Xr aio_return 2 ,
578.Xr poll 2 ,
579.Xr read 2 ,
580.Xr select 2 ,
581.Xr sigaction 2 ,
582.Xr write 2 ,
583.Xr signal 3
584.Sh HISTORY
585The
586.Fn kqueue
587and
588.Fn kevent
589system calls first appeared in
590.Fx 4.1 .
591.Sh AUTHORS
592The
593.Fn kqueue
594system and this manual page were written by
595.An Jonathan Lemon Aq [email protected] .
596.Sh BUGS
597The
598.Dv EVFILT_NETDEV
599filter is currently only implemented for devices that use the
600.Xr miibus 4
601driver for LINKUP and LINKDOWN operations.
602Therefore, it will not work with many non-ethernet devices.
603.Pp
604The
605.Fa timeout
606value is limited to 24 hours; longer timeouts will be silently
607reinterpreted as 24 hours.
608