Debian Codegraph @

src/sys/event.rs

raw
1 //! Kernel event notification mechanism
2 //!
3 //! # See Also
4 //! [kqueue(2)](https://www.freebsd.org/cgi/man.cgi?query=kqueue)
5
6 use crate::{Errno, Result};
7 #[cfg(not(target_os = "netbsd"))]
8 use libc::{c_int, c_long, intptr_t, time_t, timespec, uintptr_t};
9 #[cfg(target_os = "netbsd")]
10 use libc::{c_long, intptr_t, size_t, time_t, timespec, uintptr_t};
11 use std::convert::TryInto;
12 use std::mem;
13 use std::os::fd::{AsFd, BorrowedFd};
14 use std::os::unix::io::{AsRawFd, FromRawFd, OwnedFd};
15 use std::ptr;
16
17 /// A kernel event queue. Used to notify a process of various asynchronous
18 /// events.
19 #[repr(C)]
20 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
21 pub struct KEvent {
22 kevent: libc::kevent,
23 }
24
25 /// A kernel event queue.
26 ///
27 /// Used by the kernel to notify the process of various types of asynchronous
28 /// events.
29 #[repr(transparent)]
30 #[derive(Debug)]
31 pub struct Kqueue(OwnedFd);
32
33 impl AsFd for Kqueue {
34 fn as_fd(&self) -> BorrowedFd<'_> {
35 self.0.as_fd()
36 }
37 }
38
39 impl From<Kqueue> for OwnedFd {
40 fn from(value: Kqueue) -> Self {
41 value.0
42 }
43 }
44
45 impl Kqueue {
46 /// Create a new kernel event queue.
47 pub fn new() -> Result<Self> {
48 let res = unsafe { libc::kqueue() };
49
50 Errno::result(res).map(|fd| unsafe { Self(OwnedFd::from_raw_fd(fd)) })
51 }
52
53 /// Register new events with the kqueue, and return any pending events to
54 /// the user.
55 ///
56 /// This method will block until either the timeout expires, or a registered
57 /// event triggers a notification.
58 ///
59 /// # Arguments
60 /// - `changelist` - Any new kevents to register for notifications.
61 /// - `eventlist` - Storage space for the kernel to return notifications.
62 /// - `timeout` - An optional timeout.
63 ///
64 /// # Returns
65 /// Returns the number of events placed in the `eventlist`. If an error
66 /// occurs while processing an element of the `changelist` and there is
67 /// enough room in the `eventlist`, then the event will be placed in the
68 /// `eventlist` with `EV_ERROR` set in `flags` and the system error in
69 /// `data`.
70 pub fn kevent(
71 &self,
72 changelist: &[KEvent],
73 eventlist: &mut [KEvent],
74 timeout_opt: Option<timespec>,
75 ) -> Result<usize> {
76 let res = unsafe {
77 libc::kevent(
78 self.0.as_raw_fd(),
79 changelist.as_ptr().cast(),
80 changelist.len() as type_of_nchanges,
81 eventlist.as_mut_ptr().cast(),
82 eventlist.len() as type_of_nchanges,
83 if let Some(ref timeout) = timeout_opt {
84 timeout as *const timespec
85 } else {
86 ptr::null()
87 },
88 )
89 };
90 Errno::result(res).map(|r| r as usize)
91 }
92 }
93
94 #[cfg(any(freebsdlike, apple_targets, target_os = "openbsd"))]
95 type type_of_udata = *mut libc::c_void;
96 #[cfg(target_os = "netbsd")]
97 type type_of_udata = intptr_t;
98
99 #[cfg(target_os = "netbsd")]
100 type type_of_event_filter = u32;
101 #[cfg(not(target_os = "netbsd"))]
102 type type_of_event_filter = i16;
103 libc_enum! {
104 #[cfg_attr(target_os = "netbsd", repr(u32))]
105 #[cfg_attr(not(target_os = "netbsd"), repr(i16))]
106 #[non_exhaustive]
107 /// Kqueue filter types. These are all the different types of event that a
108 /// kqueue can notify for.
109 pub enum EventFilter {
110 /// Notifies on the completion of a POSIX AIO operation.
111 EVFILT_AIO,
112 #[cfg(target_os = "freebsd")]
113 /// Returns whenever there is no remaining data in the write buffer
114 EVFILT_EMPTY,
115 #[cfg(target_os = "dragonfly")]
116 /// Takes a descriptor as the identifier, and returns whenever one of
117 /// the specified exceptional conditions has occurred on the descriptor.
118 EVFILT_EXCEPT,
119 #[cfg(any(freebsdlike, apple_targets))]
120 /// Establishes a file system monitor.
121 EVFILT_FS,
122 #[cfg(target_os = "freebsd")]
123 /// Notify for completion of a list of POSIX AIO operations.
124 /// # See Also
125 /// [lio_listio(2)](https://www.freebsd.org/cgi/man.cgi?query=lio_listio)
126 EVFILT_LIO,
127 #[cfg(apple_targets)]
128 /// Mach portsets
129 EVFILT_MACHPORT,
130 /// Notifies when a process performs one or more of the requested
131 /// events.
132 EVFILT_PROC,
133 /// Returns events associated with the process referenced by a given
134 /// process descriptor, created by `pdfork()`. The events to monitor are:
135 ///
136 /// - NOTE_EXIT: the process has exited. The exit status will be stored in data.
137 #[cfg(target_os = "freebsd")]
138 EVFILT_PROCDESC,
139 /// Takes a file descriptor as the identifier, and notifies whenever
140 /// there is data available to read.
141 EVFILT_READ,
142 #[cfg(target_os = "freebsd")]
143 #[doc(hidden)]
144 #[deprecated(since = "0.27.0", note = "Never fully implemented by the OS")]
145 EVFILT_SENDFILE,
146 /// Takes a signal number to monitor as the identifier and notifies when
147 /// the given signal is delivered to the process.
148 EVFILT_SIGNAL,
149 /// Establishes a timer and notifies when the timer expires.
150 EVFILT_TIMER,
151 #[cfg(any(freebsdlike, apple_targets))]
152 /// Notifies only when explicitly requested by the user.
153 EVFILT_USER,
154 #[cfg(apple_targets)]
155 /// Virtual memory events
156 EVFILT_VM,
157 /// Notifies when a requested event happens on a specified file.
158 EVFILT_VNODE,
159 /// Takes a file descriptor as the identifier, and notifies whenever
160 /// it is possible to write to the file without blocking.
161 EVFILT_WRITE,
162 }
163 impl TryFrom<type_of_event_filter>
164 }
165
166 #[cfg(any(freebsdlike, apple_targets, target_os = "openbsd"))]
167 #[doc(hidden)]
168 pub type type_of_event_flag = u16;
169 #[cfg(target_os = "netbsd")]
170 #[doc(hidden)]
171 pub type type_of_event_flag = u32;
172 libc_bitflags! {
173 /// Event flags. See the man page for details.
174 // There's no useful documentation we can write for the individual flags
175 // that wouldn't simply be repeating the man page.
176 pub struct EvFlags: type_of_event_flag {
177 #[allow(missing_docs)]
178 EV_ADD;
179 #[allow(missing_docs)]
180 EV_CLEAR;
181 #[allow(missing_docs)]
182 EV_DELETE;
183 #[allow(missing_docs)]
184 EV_DISABLE;
185 #[cfg(bsd)]
186 #[allow(missing_docs)]
187 EV_DISPATCH;
188 #[cfg(target_os = "freebsd")]
189 #[allow(missing_docs)]
190 EV_DROP;
191 #[allow(missing_docs)]
192 EV_ENABLE;
193 #[allow(missing_docs)]
194 EV_EOF;
195 #[allow(missing_docs)]
196 EV_ERROR;
197 #[cfg(apple_targets)]
198 #[allow(missing_docs)]
199 EV_FLAG0;
200 #[allow(missing_docs)]
201 EV_FLAG1;
202 #[cfg(target_os = "dragonfly")]
203 #[allow(missing_docs)]
204 EV_NODATA;
205 #[allow(missing_docs)]
206 EV_ONESHOT;
207 #[cfg(apple_targets)]
208 #[allow(missing_docs)]
209 EV_OOBAND;
210 #[cfg(apple_targets)]
211 #[allow(missing_docs)]
212 EV_POLL;
213 #[cfg(bsd)]
214 #[allow(missing_docs)]
215 EV_RECEIPT;
216 }
217 }
218
219 #[deprecated(since = "0.30.0", note = "Use `EvFlags instead`")]
220 /// The deprecated EventFlag type alias
221 pub type EventFlag = EvFlags;
222
223 libc_bitflags!(
224 /// Filter-specific flags. See the man page for details.
225 // There's no useful documentation we can write for the individual flags
226 // that wouldn't simply be repeating the man page.
227 #[allow(missing_docs)]
228 pub struct FilterFlag: u32 {
229 #[cfg(apple_targets)]
230 #[allow(missing_docs)]
231 NOTE_ABSOLUTE;
232 #[allow(missing_docs)]
233 NOTE_ATTRIB;
234 #[allow(missing_docs)]
235 NOTE_CHILD;
236 #[allow(missing_docs)]
237 NOTE_DELETE;
238 #[cfg(target_os = "openbsd")]
239 #[allow(missing_docs)]
240 NOTE_EOF;
241 #[allow(missing_docs)]
242 NOTE_EXEC;
243 #[allow(missing_docs)]
244 NOTE_EXIT;
245 #[cfg(apple_targets)]
246 #[allow(missing_docs)]
247 NOTE_EXITSTATUS;
248 #[allow(missing_docs)]
249 NOTE_EXTEND;
250 #[cfg(any(apple_targets, freebsdlike))]
251 #[allow(missing_docs)]
252 NOTE_FFAND;
253 #[cfg(any(apple_targets, freebsdlike))]
254 #[allow(missing_docs)]
255 NOTE_FFCOPY;
256 #[cfg(any(apple_targets, freebsdlike))]
257 #[allow(missing_docs)]
258 NOTE_FFCTRLMASK;
259 #[cfg(any(apple_targets, freebsdlike))]
260 #[allow(missing_docs)]
261 NOTE_FFLAGSMASK;
262 #[cfg(any(apple_targets, freebsdlike))]
263 #[allow(missing_docs)]
264 NOTE_FFNOP;
265 #[cfg(any(apple_targets, freebsdlike))]
266 #[allow(missing_docs)]
267 NOTE_FFOR;
268 #[allow(missing_docs)]
269 NOTE_FORK;
270 #[allow(missing_docs)]
271 NOTE_LINK;
272 #[allow(missing_docs)]
273 NOTE_LOWAT;
274 #[cfg(target_os = "freebsd")]
275 #[allow(missing_docs)]
276 NOTE_MSECONDS;
277 #[cfg(apple_targets)]
278 #[allow(missing_docs)]
279 NOTE_NONE;
280 #[cfg(any(
281 apple_targets,
282 target_os = "freebsd"))]
283 #[allow(missing_docs)]
284 NOTE_NSECONDS;
285 #[cfg(target_os = "dragonfly")]
286 #[allow(missing_docs)]
287 NOTE_OOB;
288 #[allow(missing_docs)]
289 NOTE_PCTRLMASK;
290 #[allow(missing_docs)]
291 NOTE_PDATAMASK;
292 #[allow(missing_docs)]
293 NOTE_RENAME;
294 #[allow(missing_docs)]
295 NOTE_REVOKE;
296 #[cfg(any(
297 apple_targets,
298 target_os = "freebsd"))]
299 #[allow(missing_docs)]
300 NOTE_SECONDS;
301 #[cfg(apple_targets)]
302 #[allow(missing_docs)]
303 NOTE_SIGNAL;
304 #[allow(missing_docs)]
305 NOTE_TRACK;
306 #[allow(missing_docs)]
307 NOTE_TRACKERR;
308 #[cfg(any(apple_targets, freebsdlike))]
309 #[allow(missing_docs)]
310 NOTE_TRIGGER;
311 #[cfg(target_os = "openbsd")]
312 #[allow(missing_docs)]
313 NOTE_TRUNCATE;
314 #[cfg(any(
315 apple_targets,
316 target_os = "freebsd"))]
317 #[allow(missing_docs)]
318 NOTE_USECONDS;
319 #[cfg(apple_targets)]
320 #[allow(missing_docs)]
321 NOTE_VM_ERROR;
322 #[cfg(apple_targets)]
323 #[allow(missing_docs)]
324 NOTE_VM_PRESSURE;
325 #[cfg(apple_targets)]
326 #[allow(missing_docs)]
327 NOTE_VM_PRESSURE_SUDDEN_TERMINATE;
328 #[cfg(apple_targets)]
329 #[allow(missing_docs)]
330 NOTE_VM_PRESSURE_TERMINATE;
331 #[allow(missing_docs)]
332 NOTE_WRITE;
333 }
334 );
335
336 #[allow(missing_docs)]
337 #[deprecated(since = "0.27.0", note = "Use KEvent::new instead")]
338 pub fn kqueue() -> Result<Kqueue> {
339 Kqueue::new()
340 }
341
342 // KEvent can't derive Send because on some operating systems, udata is defined
343 // as a void*. However, KEvent's public API always treats udata as an intptr_t,
344 // which is safe to Send.
345 unsafe impl Send for KEvent {}
346
347 impl KEvent {
348 #[allow(clippy::needless_update)] // Not needless on all platforms.
349 /// Construct a new `KEvent` suitable for submission to the kernel via the
350 /// `changelist` argument of [`Kqueue::kevent`].
351 pub fn new(
352 ident: uintptr_t,
353 filter: EventFilter,
354 flags: EvFlags,
355 fflags: FilterFlag,
356 data: intptr_t,
357 udata: intptr_t,
358 ) -> KEvent {
359 KEvent {
360 kevent: libc::kevent {
361 ident,
362 filter: filter as type_of_event_filter,
363 flags: flags.bits(),
364 fflags: fflags.bits(),
365 // data can be either i64 or intptr_t, depending on platform
366 data: data as _,
367 udata: udata as type_of_udata,
368 ..unsafe { mem::zeroed() }
369 },
370 }
371 }
372
373 /// Value used to identify this event. The exact interpretation is
374 /// determined by the attached filter, but often is a raw file descriptor.
375 pub fn ident(&self) -> uintptr_t {
376 self.kevent.ident
377 }
378
379 /// Identifies the kernel filter used to process this event.
380 ///
381 /// Will only return an error if the kernel reports an event via a filter
382 /// that is unknown to Nix.
383 pub fn filter(&self) -> Result<EventFilter> {
384 self.kevent.filter.try_into()
385 }
386
387 /// Flags control what the kernel will do when this event is added with
388 /// [`Kqueue::kevent`].
389 pub fn flags(&self) -> EvFlags {
390 EvFlags::from_bits(self.kevent.flags).unwrap()
391 }
392
393 /// Filter-specific flags.
394 pub fn fflags(&self) -> FilterFlag {
395 FilterFlag::from_bits(self.kevent.fflags).unwrap()
396 }
397
398 /// Filter-specific data value.
399 pub fn data(&self) -> intptr_t {
400 self.kevent.data as intptr_t
401 }
402
403 /// Opaque user-defined value passed through the kernel unchanged.
404 pub fn udata(&self) -> intptr_t {
405 self.kevent.udata as intptr_t
406 }
407 }
408
409 #[allow(missing_docs)]
410 #[deprecated(since = "0.27.0", note = "Use Kqueue::kevent instead")]
411 pub fn kevent(
412 kq: &Kqueue,
413 changelist: &[KEvent],
414 eventlist: &mut [KEvent],
415 timeout_ms: usize,
416 ) -> Result<usize> {
417 // Convert ms to timespec
418 let timeout = timespec {
419 tv_sec: (timeout_ms / 1000) as time_t,
420 tv_nsec: ((timeout_ms % 1000) * 1_000_000) as c_long,
421 };
422
423 kq.kevent(changelist, eventlist, Some(timeout))
424 }
425
426 #[cfg(any(apple_targets, freebsdlike, target_os = "openbsd"))]
427 type type_of_nchanges = c_int;
428 #[cfg(target_os = "netbsd")]
429 type type_of_nchanges = size_t;
430
431 #[allow(missing_docs)]
432 #[deprecated(since = "0.27.0", note = "Use Kqueue::kevent instead")]
433 pub fn kevent_ts(
434 kq: &Kqueue,
435 changelist: &[KEvent],
436 eventlist: &mut [KEvent],
437 timeout_opt: Option<timespec>,
438 ) -> Result<usize> {
439 kq.kevent(changelist, eventlist, timeout_opt)
440 }
441
442 /// Modify an existing [`KEvent`].
443 // Probably should deprecate. Would anybody ever use it over `KEvent::new`?
444 #[deprecated(since = "0.27.0", note = "Use Kqueue::kevent instead")]
445 #[inline]
446 pub fn ev_set(
447 ev: &mut KEvent,
448 ident: usize,
449 filter: EventFilter,
450 flags: EvFlags,
451 fflags: FilterFlag,
452 udata: intptr_t,
453 ) {
454 ev.kevent.ident = ident as uintptr_t;
455 ev.kevent.filter = filter as type_of_event_filter;
456 ev.kevent.flags = flags.bits();
457 ev.kevent.fflags = fflags.bits();
458 ev.kevent.data = 0;
459 ev.kevent.udata = udata as type_of_udata;
460 }