1use std::process::ExitCode;
19
20use et_abi::ReduceArgs;
21use et_soc1::trace::TraceBuffer;
22use et_soc1::{Device, TraceConfig};
23
24const N: u32 = 1 << 18;
27const TRACE_BUFFER_SIZE: u64 = 4096 * 2048;
28
29fn main() -> ExitCode {
30 match run() {
31 Ok(()) => ExitCode::SUCCESS,
32 Err(e) => {
33 eprintln!("error: {e}");
34 ExitCode::FAILURE
35 }
36 }
37}
38
39fn run() -> et_soc1::Result<()> {
40 let kernel_path = std::env::args().nth(1).unwrap_or_else(|| {
41 eprintln!("usage: reduce <reduce-rs.elf>");
42 std::process::exit(2);
43 });
44 let elf = std::fs::read(&kernel_path).map_err(|e| et_soc1::Error::io("read kernel ELF", e))?;
45
46 let device = open_device()?;
47 let di = device.dram_info();
48 println!(
49 "Device ready: DRAM base {:#x}, size {} bytes",
50 di.base, di.size
51 );
52
53 let topo = device.topology()?;
55 let shire_mask = topo.first_shire();
56 let n_harts = topo.harts_per_shire;
57 if shire_mask != 1 {
60 return Err(et_soc1::Error::Limit(format!(
61 "reduce requires shire 0 (present mask {:#x})",
62 topo.shire_mask
63 )));
64 }
65 println!(
66 "Topology: {} shire(s) present (mask {:#x}), {} harts/shire; launching on shire mask {:#x}",
67 topo.num_shires(),
68 topo.shire_mask,
69 topo.harts_per_shire,
70 shire_mask
71 );
72
73 let kernel = device.load_kernel(&elf)?;
74
75 let host_in: Vec<u32> = (0..N).map(|i| i + 1).collect();
77
78 let input = device.upload(&host_in)?;
82 let partials = device.alloc_padded::<u64>(n_harts as usize)?;
83 device.fill(partials.region(), 0)?;
86 let trace_buf = device.alloc(TRACE_BUFFER_SIZE)?;
87
88 let args = ReduceArgs {
91 input: input.addr(),
92 out: partials.addr(),
93 n: N,
94 n_harts,
95 };
96
97 let launch = device.launch_spmd_traced(
99 &kernel,
100 shire_mask,
101 &args,
102 TraceConfig::full(trace_buf, shire_mask),
103 );
104
105 if let Ok(tb) = TraceBuffer::parse(&out_trace(&device, trace_buf)?) {
108 for (hart, s) in tb.string_entries() {
109 println!("[hart {hart}] {}", s.trim_end());
110 }
111 }
112
113 match &launch {
114 Ok(r) => println!(
115 "Kernel completed in {} cycles (waited {}).",
116 r.timing.execute_dur, r.timing.wait_dur
117 ),
118 Err(e) => println!("Launch error: {e}"),
119 }
120 launch?;
121
122 let parts = device.download_padded(&partials)?;
124 let total: u64 = parts.iter().copied().fold(0u64, u64::wrapping_add);
125 let nonzero = parts.iter().filter(|&&p| p != 0).count();
126
127 let expected = (N as u64) * (N as u64 + 1) / 2;
128 println!(
129 "\nReduction over {N} elements on {n_harts} harts ({nonzero} contributed):\n \
130 device total = {total}\n expected = {expected}"
131 );
132 if nonzero != n_harts as usize {
133 return Err(et_soc1::Error::Protocol(format!(
134 "only {nonzero} of {n_harts} harts wrote a partial"
135 )));
136 }
137 if total == expected {
138 println!("RESULT PASS");
139 Ok(())
140 } else {
141 Err(et_soc1::Error::Protocol(format!(
142 "reduction mismatch: got {total}, expected {expected}"
143 )))
144 }
145}
146
147fn out_trace<T: et_soc1::Transport>(
149 device: &Device<T>,
150 trace_buf: et_soc1::DeviceRegion,
151) -> et_soc1::Result<Vec<u8>> {
152 let mut host = vec![0u8; trace_buf.size as usize];
153 device.memcpy_d2h(trace_buf.addr, &mut host)?;
154 Ok(host)
155}
156
157#[cfg(feature = "emu")]
158fn open_device() -> et_soc1::Result<Device<et_soc1::FfiTransport>> {
159 let sdk_prefix = std::env::var("ET_SDK_PREFIX").unwrap_or_else(|_| "/opt/et".to_string());
160 let run_dir = std::env::current_dir()
161 .map_err(|e| et_soc1::Error::io("current_dir", e))?
162 .join("sysemu-run");
163 std::fs::create_dir_all(&run_dir).map_err(|e| et_soc1::Error::io("create run dir", e))?;
164 eprintln!("Booting software emulator (this can take a while)...");
165 Device::open_emulator(&sdk_prefix, &run_dir)
166}
167
168#[cfg(not(feature = "emu"))]
169fn open_device() -> et_soc1::Result<Device> {
170 Device::open(0)
171}