1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
use crate::error::{Error, Result};
use crate::raw;
use crate::{IoctlFlags, Uffd};
use bitflags::bitflags;
use nix::errno::Errno;
cfg_if::cfg_if! {
if #[cfg(any(feature = "linux5_7", feature = "linux4_14"))] {
bitflags! {
pub struct FeatureFlags: u64 {
const PAGEFAULT_FLAG_WP = raw::UFFD_FEATURE_PAGEFAULT_FLAG_WP;
const EVENT_FORK = raw::UFFD_FEATURE_EVENT_FORK;
const EVENT_REMAP = raw::UFFD_FEATURE_EVENT_REMAP;
const EVENT_REMOVE = raw::UFFD_FEATURE_EVENT_REMOVE;
const MISSING_HUGETLBFS = raw::UFFD_FEATURE_MISSING_HUGETLBFS;
const MISSING_SHMEM = raw::UFFD_FEATURE_MISSING_SHMEM;
const EVENT_UNMAP = raw::UFFD_FEATURE_EVENT_UNMAP;
const SIGBUS = raw::UFFD_FEATURE_SIGBUS;
const THREAD_ID = raw::UFFD_FEATURE_THREAD_ID;
}
}
} else {
bitflags! {
pub struct FeatureFlags: u64 {
const PAGEFAULT_FLAG_WP = raw::UFFD_FEATURE_PAGEFAULT_FLAG_WP;
const EVENT_FORK = raw::UFFD_FEATURE_EVENT_FORK;
const EVENT_REMAP = raw::UFFD_FEATURE_EVENT_REMAP;
const EVENT_REMOVE = raw::UFFD_FEATURE_EVENT_REMOVE;
const MISSING_HUGETLBFS = raw::UFFD_FEATURE_MISSING_HUGETLBFS;
const MISSING_SHMEM = raw::UFFD_FEATURE_MISSING_SHMEM;
const EVENT_UNMAP = raw::UFFD_FEATURE_EVENT_UNMAP;
}
}
}
}
pub struct UffdBuilder {
close_on_exec: bool,
non_blocking: bool,
req_features: FeatureFlags,
req_ioctls: IoctlFlags,
}
impl UffdBuilder {
pub fn new() -> UffdBuilder {
UffdBuilder {
close_on_exec: false,
non_blocking: false,
req_features: FeatureFlags::empty(),
req_ioctls: IoctlFlags::empty(),
}
}
pub fn close_on_exec(&mut self, close_on_exec: bool) -> &mut Self {
self.close_on_exec = close_on_exec;
self
}
pub fn non_blocking(&mut self, non_blocking: bool) -> &mut Self {
self.non_blocking = non_blocking;
self
}
pub fn require_features(&mut self, feature: FeatureFlags) -> &mut Self {
self.req_features |= feature;
self
}
pub fn require_ioctls(&mut self, ioctls: IoctlFlags) -> &mut Self {
self.req_ioctls |= ioctls;
self
}
pub fn create(&self) -> Result<Uffd> {
let mut flags = 0;
if self.close_on_exec {
flags |= libc::O_CLOEXEC;
}
if self.non_blocking {
flags |= libc::O_NONBLOCK;
}
let fd = Errno::result(unsafe { raw::userfaultfd(flags) })?;
let mut api = raw::uffdio_api {
api: raw::UFFD_API,
features: self.req_features.bits(),
ioctls: 0,
};
unsafe {
raw::api(fd, &mut api as *mut raw::uffdio_api)?;
}
let supported =
IoctlFlags::from_bits(api.ioctls).ok_or(Error::UnrecognizedIoctls(api.ioctls))?;
if !supported.contains(self.req_ioctls) {
Err(Error::UnsupportedIoctls(supported))
} else {
Ok(Uffd { fd })
}
}
}