-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathbuild.rs
385 lines (335 loc) · 11.7 KB
/
build.rs
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
extern crate bindgen;
extern crate cc;
use crate::build_helpers::{print_path_var, Error, LibraryConfig};
use bindgen::callbacks::{MacroParsingBehavior, ParseCallbacks};
use std::{
collections::HashSet,
env,
ffi::OsStr,
fs,
path::{Path, PathBuf},
sync::{Arc, RwLock},
};
mod build_helpers;
#[derive(Debug)]
struct MacroCallback {
macros: Arc<RwLock<HashSet<String>>>,
}
impl ParseCallbacks for MacroCallback {
fn will_parse_macro(&self, name: &str) -> MacroParsingBehavior {
self.macros.write().unwrap().insert(name.into());
if name == "IPPORT_RESERVED" {
return MacroParsingBehavior::Ignore;
}
MacroParsingBehavior::Default
}
}
/// Returns package's root dir.
fn get_root_dir() -> PathBuf {
PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap())
}
/// Returns output dir.
fn get_out_dir() -> PathBuf {
PathBuf::from(env::var("OUT_DIR").unwrap())
}
/// Returns target dir.
#[allow(dead_code)]
fn get_target_dir() -> PathBuf {
let mut p = get_out_dir();
p.pop();
p.pop();
assert_eq!(p.file_name(), Some(OsStr::new("build")));
p.pop();
p
}
/// Returns nightly rustfmt path, if it can be found. Returns None otherwise.
fn rust_fmt_nightly() -> Option<PathBuf> {
match env::var_os("RUST_NIGHTLY_PATH") {
Some(s) => {
let mut p = PathBuf::from(s);
p.push("bin");
p.push("rustfmt");
Some(p)
}
None => {
let mut cmd = std::process::Command::new("rustup");
cmd.args(["which", "rustfmt", "--toolchain=nightly"]);
build_helpers::run_command(&mut cmd, "rustup", None)
.ok()
.and_then(|r| r.1.first().map(PathBuf::from))
}
}
}
/// Returns absolute path for SPDK library.
fn get_spdk_path() -> Result<PathBuf, Error> {
let spdk_path = match env::var_os("SPDK_ROOT_DIR") {
Some(s) => {
println!("SPDK_ROOT_DIR variable is set to {}", s.to_str().unwrap());
PathBuf::from(s)
}
None => {
let mut spdk_path = get_root_dir();
spdk_path.push("spdk");
println!(
"SPDK_ROOT_DIR variable not set, trying {}",
spdk_path.to_str().unwrap()
);
spdk_path
}
};
match fs::canonicalize(&spdk_path) {
Ok(res) => {
println!("SPDK found at {}", res.to_str().unwrap());
Ok(res)
}
Err(e) => Err(Error::Generic(format!(
"Bad SPDK path {}: {}",
spdk_path.to_str().unwrap(),
e
))),
}
}
/// Finds and configures SPDK library.
fn configure_spdk() -> Result<LibraryConfig, Error> {
let spdk_path = get_spdk_path()?;
print_path_var("****", "PKG_CONFIG_PATH");
print_path_var("****", "PKG_CONFIG_PATH_FOR_TARGET");
let mut spdk_lib = LibraryConfig::new();
spdk_lib.add_inc(spdk_path.join("include"))?;
spdk_lib.add_inc(spdk_path.join("include/spdk_internal"))?;
spdk_lib.add_inc_alt(
spdk_path.join("include/spdk/module"),
spdk_path.join("module"),
)?;
spdk_lib.add_inc_alt(spdk_path.join("include/spdk/lib"), spdk_path.join("lib"))?;
spdk_lib.add_inc_alt(
spdk_path.join("include/spdk/lib/ftl"),
spdk_path.join("lib/ftl"),
)?;
spdk_lib.find_pkg_config_dirs(&spdk_path)?;
spdk_lib.exclude_lib("spdk_bdev_blobfs");
spdk_lib.exclude_lib("spdk_bdev_gpt");
spdk_lib.exclude_lib("spdk_bdev_passthru");
spdk_lib.exclude_lib("spdk_bdev_raid");
spdk_lib.exclude_lib("spdk_bdev_split");
spdk_lib.exclude_lib("spdk_event_nvmf");
spdk_lib.exclude_lib("spdk_sock_uring");
spdk_lib.exclude_lib("spdk_ut_mock");
spdk_lib.mark_system("aio");
spdk_lib.mark_system("bsd");
spdk_lib.mark_system("crypto");
spdk_lib.mark_system("dl");
spdk_lib.mark_system("m");
spdk_lib.mark_system("md");
spdk_lib.mark_system("numa");
spdk_lib.mark_system("pcap");
spdk_lib.mark_system("rt");
spdk_lib.mark_system("ssl");
spdk_lib.mark_system("uring");
spdk_lib.mark_system("uuid");
spdk_lib.mark_system("rdmacm");
spdk_lib.mark_system("ibverbs");
spdk_lib.set_static_search(true);
spdk_lib.find_lib("libdpdk")?;
spdk_lib.find_libs(&vec![
"spdk_accel",
"spdk_accel_ioat",
"spdk_bdev_aio",
// #[cfg(target_arch = "x86_64")]
// "spdk_bdev_crypto",
"spdk_bdev_delay",
"spdk_bdev_error",
"spdk_bdev_ftl",
"spdk_bdev_lvol",
"spdk_bdev_malloc",
"spdk_bdev_null",
"spdk_bdev_nvme",
"spdk_bdev_uring",
"spdk_bdev_virtio",
"spdk_bdev_zone_block",
"spdk_env_dpdk",
"spdk_env_dpdk_rpc",
"spdk_event",
"spdk_event_accel",
"spdk_event_bdev",
"spdk_event_iscsi",
"spdk_event_nbd",
"spdk_event_scsi",
"spdk_event_sock",
"spdk_event_vmd",
"spdk_nvmf",
"spdk_util",
])?;
spdk_lib.find_lib("spdk_syslibs")?;
spdk_lib.dump();
/*
println!("Merging SPDK static libraries into a shared library...");
let lib_name = OsStr::new("spdk-bundle");
let lib_dir = get_target_dir();
let lib_path = spdk_lib.build_shared_lib(&lib_dir, lib_name)?;
println!("cargo:rustc-link-lib=dylib={}", lib_name.to_str().unwrap());
println!("cargo:root={}", lib_dir.to_str().unwrap());
println!("cargo:lib_path={}", lib_path.to_str().unwrap());
*/
println!("Link against static SPDK...");
spdk_lib.cargo();
println!("cargo:rerun-if-env-changed=SPDK_ROOT_DIR");
println!("cargo:rerun-if-env-changed=PKG_CONFIG_PATH_FOR_TARGET");
Ok(spdk_lib)
}
/// Compiles SPDK helper sources.
fn compile_spdk_helpers<P>(inc_dirs: P) -> Result<(), Error>
where
P: IntoIterator,
P::Item: AsRef<Path>,
{
let files = vec![
"helpers/logwrapper.h",
"helpers/logwrapper.c",
"helpers/nvme_helper.h",
"helpers/nvme_helper.c",
"helpers/spdk_helper.h",
"helpers/spdk_helper.c",
];
let mut src_files = Vec::new();
for s in &files {
match fs::canonicalize(s) {
Ok(p) => {
println!("cargo:rerun-if-changed={}", p.to_str().unwrap());
if p.extension().unwrap() == "c" {
src_files.push(p);
}
}
Err(e) => return Err(Error::Generic(format!("Bad SPDK helper source {s}: {e}"))),
}
}
cc::Build::new()
.includes(inc_dirs)
.files(src_files)
.compile("helpers");
Ok(())
}
fn main() {
#![allow(unreachable_code)]
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
panic!("spdk-rs crate is only for x86_64 (Nehalem or later) and aarch64 (with crypto) ISAs.");
#[cfg(not(target_os = "linux"))]
panic!("spdk-rs crate works only on linux");
// Configure SPDK library.
println!("\nConfiguring SPDK library...");
let spdk_lib = match configure_spdk() {
Ok(c) => {
println!("Successfully configured SPDK library");
c
}
Err(e) => {
eprintln!("\nFailed to configure SPDK: {e}\n");
std::process::exit(1);
}
};
let inc_dirs = spdk_lib.get_inc_paths();
// Compile SPDK helpers.
println!("\nCompiling SPDK helpers...");
match compile_spdk_helpers(&inc_dirs) {
Ok(_) => {
println!("Successfully compiled SPDK helpers\n");
}
Err(e) => {
eprintln!("\nFailed to complie SPDK helpers: {e}\n");
std::process::exit(1);
}
}
// Generate Rust bindings for SPDK.
let clang_args: Vec<String> = inc_dirs
.iter()
.map(|p| format!("-I{}", p.to_str().unwrap()))
.collect();
let macros = Arc::new(RwLock::new(HashSet::new()));
let bindings = bindgen::Builder::default()
.clang_args(clang_args)
.header("wrapper.h")
.formatter(bindgen::Formatter::Rustfmt)
.allowlist_function(".*.aio.*")
.allowlist_function(".*.crypto_disk.*")
.allowlist_function(".*.iscsi.*")
.allowlist_function(".*.lock_lba_range")
.allowlist_function(".*.lvol.*")
.allowlist_function(".*.lvs.*")
.allowlist_function(".*.uring.*")
.allowlist_function("^iscsi.*")
.allowlist_function("^spdk.*")
.allowlist_function("^.*malloc_disk")
.allowlist_function("^bdev.*")
.allowlist_function("^nbd_.*")
.allowlist_function("^vbdev_.*")
.allowlist_function("^nvme_cmd_.*")
.allowlist_function("^nvme_status_.*")
.allowlist_function("^nvmf_subsystem_find_listener")
.allowlist_function("^nvmf_subsystem_set_ana_state")
.allowlist_function("^nvmf_subsystem_set_cntlid_range")
.allowlist_function("^nvmf_tgt_accept")
.allowlist_function("^nvme_qpair_.*")
.allowlist_function("^nvme_ctrlr_.*")
.allowlist_function("^nvme_transport_qpair_.*")
.blocklist_type("^longfunc")
.allowlist_type("^spdk_nvme_ns_flags")
.allowlist_type("^spdk_nvme_registered_ctrlr.*")
.allowlist_type("^spdk_nvme_reservation.*")
.allowlist_type("spdk_nvme_status_code_type")
.rustified_enum("spdk_nvme_status_code_type")
.allowlist_type("spdk_nvme_generic_command_status_code")
.rustified_enum("spdk_nvme_generic_command_status_code")
.allowlist_type("spdk_nvme_command_specific_status_code")
.rustified_enum("spdk_nvme_command_specific_status_code")
.allowlist_type("spdk_nvme_media_error_status_code")
.rustified_enum("spdk_nvme_media_error_status_code")
.allowlist_type("spdk_nvme_path_status_code")
.rustified_enum("spdk_nvme_path_status_code")
.allowlist_type("spdk_ftl_mode")
.rustified_enum("spdk_ftl_mode")
.allowlist_var("^NVMF.*")
.allowlist_var("^SPDK.*")
.allowlist_var("^spdk.*")
.trust_clang_mangling(false)
.opaque_type("^spdk_nvme_ctrlr_data")
.opaque_type("^spdk_nvme_feat_async_event_configuration.*")
.opaque_type("^spdk_nvmf_fabric_connect.*")
.opaque_type("^spdk_nvmf_fabric_prop.*")
.layout_tests(false)
.derive_debug(true)
.derive_copy(true)
.derive_partialeq(true)
.derive_partialord(true)
.prepend_enum_name(false)
.size_t_is_usize(false)
.generate_inline_functions(true)
.parse_callbacks(Box::new(MacroCallback { macros }));
// Use nightly rustfmt if it is possible.
let bindings = if let Some(rust_fmt) = rust_fmt_nightly() {
bindings.with_rustfmt(rust_fmt)
} else {
bindings
};
#[cfg(target_arch = "x86_64")]
let bindings = bindings.clang_arg("-march=nehalem");
let bindings = bindings
.generate()
.expect("Unable to generate SPDK bindings");
let out_path = get_out_dir();
bindings
.write_to_file(out_path.join("libspdk.rs"))
.expect("Couldn't write SPDK bindings!");
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=wrapper.h");
println!("cargo:rerun-if-changed=build_scripts/build_spdk.sh");
// When `SPDK_RS_BUILD_USE_LOGS` env var is set `yes`, rebuild if the
// contents of `build_logs` directory has been changed.
//
// This allows `spdk-rs` to recompile every time a locally-built SPDK is
// configured or compiled with `build_scripts/build_spdk.sh`.
println!("cargo:rerun-if-env-changed=SPDK_RS_BUILD_USE_LOGS");
if env::var("SPDK_RS_BUILD_USE_LOGS").unwrap_or_default() == "yes" {
fs::create_dir("build_logs").ok();
println!("cargo:rerun-if-changed=build_logs");
}
}