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
//! Host protocol API wrappers for megakernel control/ring buffers.
mod publish;
use crate::PipelineError;
use super::protocol::{self, DebugRecord};
use super::Megakernel;
impl Megakernel {
/// Encode a control-buffer payload.
///
/// # Errors
///
/// Returns [`PipelineError::QueueFull`] when the requested observable region
/// cannot fit in process address space.
pub fn encode_control(
shutdown: bool,
tenant_count: u32,
observable_slots: u32,
) -> Result<Vec<u8>, PipelineError> {
protocol::encode_control(shutdown, tenant_count, observable_slots).map_err(protocol_error)
}
/// Fallible control-buffer encoder for callers accepting untrusted sizing.
///
/// # Errors
///
/// Returns [`PipelineError::QueueFull`] when the requested observable region
/// cannot fit in process address space.
pub fn try_encode_control(
shutdown: bool,
tenant_count: u32,
observable_slots: u32,
) -> Result<Vec<u8>, PipelineError> {
Self::encode_control(shutdown, tenant_count, observable_slots)
}
/// Fallible control-buffer encoder into caller-owned storage.
///
/// # Errors
///
/// Returns [`PipelineError::QueueFull`] when the requested observable region
/// cannot fit in process address space.
pub fn try_encode_control_into(
shutdown: bool,
tenant_count: u32,
observable_slots: u32,
dst: &mut Vec<u8>,
) -> Result<(), PipelineError> {
protocol::try_encode_control_into(shutdown, tenant_count, observable_slots, dst)
.map_err(protocol_error)
}
/// Encode an empty ring buffer with `slot_count` slots.
///
/// # Errors
///
/// Returns [`PipelineError::QueueFull`] when `slot_count * SLOT_WORDS * 4`
/// overflows.
pub fn encode_empty_ring(slot_count: u32) -> Result<Vec<u8>, PipelineError> {
protocol::encode_empty_ring(slot_count).map_err(protocol_error)
}
/// Fallible ring-buffer encoder for callers accepting untrusted slot counts.
///
/// # Errors
///
/// Returns [`PipelineError::QueueFull`] when `slot_count * SLOT_WORDS * 4`
/// overflows.
pub fn try_encode_empty_ring(slot_count: u32) -> Result<Vec<u8>, PipelineError> {
Self::encode_empty_ring(slot_count)
}
/// Fallible ring-buffer encoder into caller-owned storage.
///
/// # Errors
///
/// Returns [`PipelineError::QueueFull`] when `slot_count * SLOT_WORDS * 4`
/// overflows.
pub fn try_encode_empty_ring_into(
slot_count: u32,
dst: &mut Vec<u8>,
) -> Result<(), PipelineError> {
protocol::try_encode_empty_ring_into(slot_count, dst).map_err(protocol_error)
}
/// Encode an empty PRINTF channel buffer.
///
/// # Errors
///
/// Returns [`PipelineError::QueueFull`] when the record capacity overflows.
pub fn encode_empty_debug_log(record_capacity: u32) -> Result<Vec<u8>, PipelineError> {
protocol::encode_empty_debug_log(record_capacity).map_err(protocol_error)
}
/// Fallible debug-log encoder for callers accepting untrusted capacities.
///
/// # Errors
///
/// Returns [`PipelineError::QueueFull`] when the record capacity overflows.
pub fn try_encode_empty_debug_log(record_capacity: u32) -> Result<Vec<u8>, PipelineError> {
Self::encode_empty_debug_log(record_capacity)
}
/// Fallible debug-log encoder into caller-owned storage.
///
/// # Errors
///
/// Returns [`PipelineError::QueueFull`] when the record capacity overflows.
pub fn try_encode_empty_debug_log_into(
record_capacity: u32,
dst: &mut Vec<u8>,
) -> Result<(), PipelineError> {
protocol::try_encode_empty_debug_log_into(record_capacity, dst).map_err(protocol_error)
}
/// Decode the kernel's `done_count` from a control buffer.
#[must_use]
pub fn read_done_count(control_bytes: &[u8]) -> u32 {
protocol::read_done_count(control_bytes)
}
/// Strictly decode the kernel's `done_count` from a control buffer.
///
/// # Errors
///
/// Returns [`PipelineError`] when the control buffer is malformed or too
/// short to contain the done counter.
pub fn try_read_done_count(control_bytes: &[u8]) -> Result<u32, PipelineError> {
protocol::try_read_done_count(control_bytes).map_err(protocol_error)
}
/// Strictly count DONE slots in a ring-buffer readback.
///
/// # Errors
///
/// Returns [`PipelineError`] when the ring readback is malformed or too
/// short for `item_count` complete protocol slots.
pub fn try_count_done_ring_slots(
ring_bytes: &[u8],
item_count: usize,
) -> Result<u64, PipelineError> {
protocol::try_count_done_ring_slots(ring_bytes, item_count).map_err(protocol_error)
}
/// Decode PRINTF records out of the debug-log buffer.
#[must_use]
pub fn read_debug_log(debug_bytes: &[u8]) -> Vec<DebugRecord> {
protocol::read_debug_log(debug_bytes)
}
/// Decode PRINTF records into caller-owned storage.
pub fn read_debug_log_into(debug_bytes: &[u8], out: &mut Vec<DebugRecord>) {
protocol::read_debug_log_into(debug_bytes, out);
}
/// Strictly decode PRINTF records out of the debug-log buffer.
///
/// # Errors
///
/// Returns [`PipelineError`] when the debug-log buffer is malformed or the
/// cursor points at a partial record.
pub fn try_read_debug_log(debug_bytes: &[u8]) -> Result<Vec<DebugRecord>, PipelineError> {
protocol::try_read_debug_log(debug_bytes).map_err(protocol_error)
}
/// Strictly decode PRINTF records into caller-owned storage.
///
/// # Errors
///
/// Returns [`PipelineError`] when the debug-log buffer is malformed or the
/// cursor points at a partial record.
pub fn try_read_debug_log_into(
debug_bytes: &[u8],
out: &mut Vec<DebugRecord>,
) -> Result<(), PipelineError> {
protocol::try_read_debug_log_into(debug_bytes, out).map_err(protocol_error)
}
/// Read the epoch counter from a control buffer. The epoch
/// increments on each `BATCH_FENCE` execution - the host polls
/// this to detect batch completion without scanning the ring.
#[must_use]
pub fn read_epoch(control_bytes: &[u8]) -> u32 {
protocol::read_epoch(control_bytes)
}
/// Strictly read the epoch counter from a control buffer.
///
/// # Errors
///
/// Returns [`PipelineError`] when the control buffer is malformed or too
/// short to contain the epoch counter.
pub fn try_read_epoch(control_bytes: &[u8]) -> Result<u32, PipelineError> {
protocol::try_read_epoch(control_bytes).map_err(protocol_error)
}
/// Read an observable result word from a control buffer.
/// Opcodes like `LOAD_U32`, `COMPARE_SWAP`, and `BATCH_FENCE`
/// write results here.
#[must_use]
pub fn read_observable(control_bytes: &[u8], index: u32) -> u32 {
protocol::read_observable(control_bytes, index)
}
/// Strictly read an observable result word from a control buffer.
///
/// # Errors
///
/// Returns [`PipelineError`] when the buffer is malformed or the
/// observable index is outside the supplied readback.
pub fn try_read_observable(control_bytes: &[u8], index: u32) -> Result<u32, PipelineError> {
protocol::try_read_observable(control_bytes, index).map_err(protocol_error)
}
/// Read per-opcode metrics counters from a control buffer.
/// Returns a map of `opcode_id → execution_count` for any
/// non-zero counters.
#[must_use]
pub fn read_metrics(control_bytes: &[u8]) -> Vec<(u32, u32)> {
protocol::read_metrics(control_bytes)
}
/// Read per-opcode metrics counters into caller-owned storage.
pub fn read_metrics_into(control_bytes: &[u8], out: &mut Vec<(u32, u32)>) {
protocol::read_metrics_into(control_bytes, out);
}
/// Strictly read per-opcode metrics counters from a control buffer.
///
/// # Errors
///
/// Returns [`PipelineError`] when the buffer is malformed or too short for
/// the fixed metrics window.
pub fn try_read_metrics(control_bytes: &[u8]) -> Result<Vec<(u32, u32)>, PipelineError> {
protocol::try_read_metrics(control_bytes).map_err(protocol_error)
}
/// Strictly read per-opcode metrics counters into caller-owned storage.
///
/// # Errors
///
/// Returns [`PipelineError`] when the buffer is malformed or too short for
/// the fixed metrics window.
pub fn try_read_metrics_into(
control_bytes: &[u8],
out: &mut Vec<(u32, u32)>,
) -> Result<(), PipelineError> {
protocol::try_read_metrics_into(control_bytes, out).map_err(protocol_error)
}
}
fn protocol_error(error: protocol::ProtocolError) -> PipelineError {
match error {
protocol::ProtocolError::ByteLengthOverflow { fix, .. } => PipelineError::QueueFull {
queue: "submission",
fix,
},
other => PipelineError::Backend(other.to_string()),
}
}
pub(super) fn validate_control_bytes(control_bytes: &[u8]) -> Result<(), PipelineError> {
let min = protocol::control_byte_len(0).ok_or_else(|| {
PipelineError::Backend(
"megakernel minimum control-buffer length overflowed usize. Fix: keep CONTROL_MIN_WORDS within host address limits."
.to_string(),
)
})?;
if control_bytes.len() < min || control_bytes.len() % 4 != 0 {
return Err(PipelineError::Backend(format!(
"megakernel control buffer has {} bytes, expected at least {min} bytes and 4-byte alignment. Fix: build it with Megakernel::encode_control.",
control_bytes.len()
)));
}
Ok(())
}
pub(super) fn validate_debug_log_bytes(debug_log_bytes: &[u8]) -> Result<(), PipelineError> {
let expected = protocol::debug_log_byte_len(protocol::debug::RECORD_CAPACITY)
.ok_or(PipelineError::QueueFull {
queue: "submission",
fix: "debug-log minimum length overflowed usize; keep debug ABI constants within host limits",
})?;
if debug_log_bytes.len() != expected {
return Err(PipelineError::Backend(format!(
"megakernel debug-log buffer has {} bytes, expected exactly {expected} bytes for {} PRINTF records. Fix: build it with Megakernel::encode_empty_debug_log(protocol::debug::RECORD_CAPACITY).",
debug_log_bytes.len(),
protocol::debug::RECORD_CAPACITY
)));
}
Ok(())
}
#[cfg(test)]
mod tests;