morpheus_network/asm/drivers/
virtio.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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! VirtIO ASM bindings.
//!
//! Complete bindings for VirtIO device initialization and virtqueue operations.
//!
//! # Reference
//! NETWORK_IMPL_GUIDE.md §2.2.2, §4

use crate::types::repr_c::{RxResult, VirtqueueState};

// ═══════════════════════════════════════════════════════════════════════════
// Device Initialization Functions
// ═══════════════════════════════════════════════════════════════════════════

#[cfg(target_arch = "x86_64")]
extern "win64" {
    /// Verify VirtIO magic value (0x74726976 = "virt").
    /// Returns 1 if valid, 0 if not.
    fn asm_virtio_verify_magic(mmio_base: u64) -> u32;

    /// Get VirtIO device version (2 = modern).
    fn asm_virtio_get_version(mmio_base: u64) -> u32;

    /// Get VirtIO device ID (1 = net, 2 = block, etc.).
    fn asm_virtio_get_device_id(mmio_base: u64) -> u32;

    /// Reset VirtIO device (write 0 to status, wait for completion).
    /// Returns 0 on success, 1 on timeout.
    fn asm_virtio_reset(mmio_base: u64) -> u32;

    /// Set VirtIO device status.
    fn asm_virtio_set_status(mmio_base: u64, status: u8);

    /// Get VirtIO device status.
    fn asm_virtio_get_status(mmio_base: u64) -> u8;

    /// Read device feature bits (64-bit, handles feature_sel).
    fn asm_virtio_read_features(mmio_base: u64) -> u64;

    /// Write driver-accepted feature bits.
    fn asm_virtio_write_features(mmio_base: u64, features: u64);

    /// Read MAC address from config space.
    /// Returns 0 on success, 1 if MAC feature not negotiated.
    fn asm_virtio_read_mac(mmio_base: u64, mac_out: *mut [u8; 6]) -> u32;
}

// ═══════════════════════════════════════════════════════════════════════════
// Virtqueue Configuration Functions
// ═══════════════════════════════════════════════════════════════════════════

#[cfg(target_arch = "x86_64")]
extern "win64" {
    /// Select virtqueue by index.
    fn asm_vq_select(mmio_base: u64, queue_idx: u16);

    /// Get maximum queue size for selected queue.
    fn asm_vq_get_max_size(mmio_base: u64) -> u16;

    /// Set queue size for selected queue.
    fn asm_vq_set_size(mmio_base: u64, size: u16);

    /// Set descriptor table address.
    fn asm_vq_set_desc(mmio_base: u64, addr: u64);

    /// Set driver (available) ring address.
    fn asm_vq_set_driver(mmio_base: u64, addr: u64);

    /// Set device (used) ring address.
    fn asm_vq_set_device(mmio_base: u64, addr: u64);

    /// Enable selected queue.
    fn asm_vq_enable(mmio_base: u64);

    /// Disable selected queue.
    fn asm_vq_disable(mmio_base: u64);

    /// Check if queue is ready.
    fn asm_vq_is_ready(mmio_base: u64) -> u32;

    /// Full queue setup helper.
    fn asm_vq_setup(
        mmio_base: u64,
        queue_idx: u16,
        size: u16,
        desc_addr: u64,
        driver_addr: u64,
        device_addr: u64,
    );

    /// Initialize a single descriptor.
    fn asm_vq_init_desc(desc_table: u64, idx: u16, addr: u64, len: u32, flags: u16, next: u16);

    /// Initialize descriptor chain (for multi-descriptor buffers).
    fn asm_vq_init_desc_chain(
        desc_table: u64,
        start_idx: u16,
        addrs: *const u64,
        lens: *const u32,
        count: u16,
        write_flags: u16,
    );
}

// ═══════════════════════════════════════════════════════════════════════════
// TX/RX Operations
// ═══════════════════════════════════════════════════════════════════════════

#[cfg(target_arch = "x86_64")]
extern "win64" {
    /// Submit buffer to TX queue.
    /// Returns 0 on success, 1 if queue full.
    fn asm_vq_submit_tx(vq: *mut VirtqueueState, buffer_idx: u16, buffer_len: u16) -> u32;

    /// Poll TX completion.
    /// Returns buffer index (0-0xFFFE) or 0xFFFFFFFF if no completion.
    fn asm_vq_poll_tx_complete(vq: *mut VirtqueueState) -> u32;

    /// Get number of available TX slots.
    fn asm_vq_tx_avail_slots(vq: *mut VirtqueueState) -> u16;

    /// Submit buffer to RX queue.
    /// Returns 0 on success, 1 if queue full.
    fn asm_vq_submit_rx(vq: *mut VirtqueueState, buffer_idx: u16, capacity: u16) -> u32;

    /// Poll for received packet.
    /// Returns 0 if no packet, 1 if packet ready (result populated).
    fn asm_vq_poll_rx(vq: *mut VirtqueueState, result: *mut RxResult) -> u32;

    /// Get number of pending RX packets.
    fn asm_vq_rx_pending(vq: *mut VirtqueueState) -> u16;
}

// ═══════════════════════════════════════════════════════════════════════════
// Queue Notification
// ═══════════════════════════════════════════════════════════════════════════

#[cfg(target_arch = "x86_64")]
extern "win64" {
    /// Notify device about queue activity (uses vq.notify_addr).
    fn asm_vq_notify(vq: *mut VirtqueueState);

    /// Direct notify with explicit address.
    fn asm_vq_notify_direct(notify_addr: u64, queue_idx: u16);

    /// Check if notification is needed (event suppression).
    fn asm_vq_should_notify(vq: *mut VirtqueueState) -> u32;

    /// Set notify address in VirtqueueState.
    fn asm_vq_set_notify_addr(vq: *mut VirtqueueState, addr: u64);
}

// ═══════════════════════════════════════════════════════════════════════════
// Safe Rust Wrappers
// ═══════════════════════════════════════════════════════════════════════════

/// VirtIO device operations.
pub mod device {
    use super::*;

    /// Check if MMIO region contains valid VirtIO device.
    #[cfg(target_arch = "x86_64")]
    pub fn verify_magic(mmio_base: u64) -> bool {
        unsafe { asm_virtio_verify_magic(mmio_base) == 1 }
    }

    /// Get device version (2 = modern VirtIO 1.0+).
    #[cfg(target_arch = "x86_64")]
    pub fn get_version(mmio_base: u64) -> u32 {
        unsafe { asm_virtio_get_version(mmio_base) }
    }

    /// Get device type ID (1 = network).
    #[cfg(target_arch = "x86_64")]
    pub fn get_device_id(mmio_base: u64) -> u32 {
        unsafe { asm_virtio_get_device_id(mmio_base) }
    }

    /// Reset device. Returns true on success.
    #[cfg(target_arch = "x86_64")]
    pub fn reset(mmio_base: u64) -> bool {
        unsafe { asm_virtio_reset(mmio_base) == 0 }
    }

    /// Set device status bits.
    #[cfg(target_arch = "x86_64")]
    pub fn set_status(mmio_base: u64, status: u8) {
        unsafe { asm_virtio_set_status(mmio_base, status) }
    }

    /// Get current device status.
    #[cfg(target_arch = "x86_64")]
    pub fn get_status(mmio_base: u64) -> u8 {
        unsafe { asm_virtio_get_status(mmio_base) }
    }

    /// Read device feature bits.
    #[cfg(target_arch = "x86_64")]
    pub fn read_features(mmio_base: u64) -> u64 {
        unsafe { asm_virtio_read_features(mmio_base) }
    }

    /// Write driver-accepted feature bits.
    #[cfg(target_arch = "x86_64")]
    pub fn write_features(mmio_base: u64, features: u64) {
        unsafe { asm_virtio_write_features(mmio_base, features) }
    }

    /// Read MAC address. Returns None if not available.
    #[cfg(target_arch = "x86_64")]
    pub fn read_mac(mmio_base: u64) -> Option<[u8; 6]> {
        let mut mac = [0u8; 6];
        if unsafe { asm_virtio_read_mac(mmio_base, &mut mac) } == 0 {
            Some(mac)
        } else {
            None
        }
    }

    // Stubs for non-x86_64
    #[cfg(not(target_arch = "x86_64"))]
    pub fn verify_magic(_mmio_base: u64) -> bool {
        false
    }
    #[cfg(not(target_arch = "x86_64"))]
    pub fn get_version(_mmio_base: u64) -> u32 {
        0
    }
    #[cfg(not(target_arch = "x86_64"))]
    pub fn get_device_id(_mmio_base: u64) -> u32 {
        0
    }
    #[cfg(not(target_arch = "x86_64"))]
    pub fn reset(_mmio_base: u64) -> bool {
        false
    }
    #[cfg(not(target_arch = "x86_64"))]
    pub fn set_status(_mmio_base: u64, _status: u8) {}
    #[cfg(not(target_arch = "x86_64"))]
    pub fn get_status(_mmio_base: u64) -> u8 {
        0
    }
    #[cfg(not(target_arch = "x86_64"))]
    pub fn read_features(_mmio_base: u64) -> u64 {
        0
    }
    #[cfg(not(target_arch = "x86_64"))]
    pub fn write_features(_mmio_base: u64, _features: u64) {}
    #[cfg(not(target_arch = "x86_64"))]
    pub fn read_mac(_mmio_base: u64) -> Option<[u8; 6]> {
        None
    }
}

/// Virtqueue operations.
pub mod queue {
    use super::*;

    /// Select a virtqueue by index.
    #[cfg(target_arch = "x86_64")]
    pub fn select(mmio_base: u64, queue_idx: u16) {
        unsafe { asm_vq_select(mmio_base, queue_idx) }
    }

    /// Get max queue size for selected queue.
    #[cfg(target_arch = "x86_64")]
    pub fn get_max_size(mmio_base: u64) -> u16 {
        unsafe { asm_vq_get_max_size(mmio_base) }
    }

    /// Get queue size (alias for get_max_size for compatibility).
    #[cfg(target_arch = "x86_64")]
    pub fn get_size(mmio_base: u64) -> u16 {
        unsafe { asm_vq_get_max_size(mmio_base) }
    }

    /// Set queue size.
    #[cfg(target_arch = "x86_64")]
    pub fn set_size(mmio_base: u64, size: u16) {
        unsafe { asm_vq_set_size(mmio_base, size) }
    }

    /// Set descriptor table address.
    #[cfg(target_arch = "x86_64")]
    pub fn set_desc_addr(mmio_base: u64, addr: u64) {
        unsafe { asm_vq_set_desc(mmio_base, addr) }
    }

    /// Set driver (available) ring address.
    #[cfg(target_arch = "x86_64")]
    pub fn set_driver_addr(mmio_base: u64, addr: u64) {
        unsafe { asm_vq_set_driver(mmio_base, addr) }
    }

    /// Set device (used) ring address.
    #[cfg(target_arch = "x86_64")]
    pub fn set_device_addr(mmio_base: u64, addr: u64) {
        unsafe { asm_vq_set_device(mmio_base, addr) }
    }

    /// Enable the selected queue.
    #[cfg(target_arch = "x86_64")]
    pub fn enable(mmio_base: u64) {
        unsafe { asm_vq_enable(mmio_base) }
    }

    /// Full queue setup.
    #[cfg(target_arch = "x86_64")]
    pub fn setup(
        mmio_base: u64,
        queue_idx: u16,
        size: u16,
        desc_addr: u64,
        driver_addr: u64,
        device_addr: u64,
    ) {
        unsafe {
            asm_vq_setup(
                mmio_base,
                queue_idx,
                size,
                desc_addr,
                driver_addr,
                device_addr,
            )
        }
    }

    /// Get notify offset for queue notifications.
    /// For MMIO VirtIO, this is typically 0x50 (QueueNotify register).
    #[cfg(target_arch = "x86_64")]
    pub fn get_notify_offset(_mmio_base: u64) -> u64 {
        0x50 // VirtIO MMIO QueueNotify register offset
    }

    // Stubs for non-x86_64
    #[cfg(not(target_arch = "x86_64"))]
    pub fn select(_mmio_base: u64, _queue_idx: u16) {}
    #[cfg(not(target_arch = "x86_64"))]
    pub fn get_max_size(_mmio_base: u64) -> u16 {
        0
    }
    #[cfg(not(target_arch = "x86_64"))]
    pub fn get_size(_mmio_base: u64) -> u16 {
        0
    }
    #[cfg(not(target_arch = "x86_64"))]
    pub fn set_size(_mmio_base: u64, _size: u16) {}
    #[cfg(not(target_arch = "x86_64"))]
    pub fn set_desc_addr(_mmio_base: u64, _addr: u64) {}
    #[cfg(not(target_arch = "x86_64"))]
    pub fn set_driver_addr(_mmio_base: u64, _addr: u64) {}
    #[cfg(not(target_arch = "x86_64"))]
    pub fn set_device_addr(_mmio_base: u64, _addr: u64) {}
    #[cfg(not(target_arch = "x86_64"))]
    pub fn enable(_mmio_base: u64) {}
    #[cfg(not(target_arch = "x86_64"))]
    pub fn setup(
        _mmio_base: u64,
        _queue_idx: u16,
        _size: u16,
        _desc_addr: u64,
        _driver_addr: u64,
        _device_addr: u64,
    ) {
    }
    #[cfg(not(target_arch = "x86_64"))]
    pub fn get_notify_offset(_mmio_base: u64) -> u64 {
        0x50
    }
}

/// TX operations.
pub mod tx {
    use super::*;

    /// Submit packet for transmission. Fire-and-forget!
    /// Returns true on success, false if queue full.
    #[cfg(target_arch = "x86_64")]
    pub fn submit(vq: &mut VirtqueueState, buffer_idx: u16, len: u16) -> bool {
        unsafe { asm_vq_submit_tx(vq, buffer_idx, len) == 0 }
    }

    /// Poll for TX completion.
    /// Returns Some(buffer_idx) if a buffer completed, None otherwise.
    #[cfg(target_arch = "x86_64")]
    pub fn poll_complete(vq: &mut VirtqueueState) -> Option<u16> {
        let result = unsafe { asm_vq_poll_tx_complete(vq) };
        if result == 0xFFFFFFFF {
            None
        } else {
            Some(result as u16)
        }
    }

    /// Get number of available TX slots.
    #[cfg(target_arch = "x86_64")]
    pub fn available_slots(vq: &mut VirtqueueState) -> u16 {
        unsafe { asm_vq_tx_avail_slots(vq) }
    }

    // Stubs for non-x86_64
    #[cfg(not(target_arch = "x86_64"))]
    pub fn submit(_vq: &mut VirtqueueState, _buffer_idx: u16, _len: u16) -> bool {
        false
    }
    #[cfg(not(target_arch = "x86_64"))]
    pub fn poll_complete(_vq: &mut VirtqueueState) -> Option<u16> {
        None
    }
    #[cfg(not(target_arch = "x86_64"))]
    pub fn available_slots(_vq: &mut VirtqueueState) -> u16 {
        0
    }
}

/// RX operations.
pub mod rx {
    use super::*;

    /// Submit buffer to receive queue.
    /// Returns true on success, false if queue full.
    #[cfg(target_arch = "x86_64")]
    pub fn submit(vq: &mut VirtqueueState, buffer_idx: u16, capacity: u16) -> bool {
        unsafe { asm_vq_submit_rx(vq, buffer_idx, capacity) == 0 }
    }

    /// Poll for received packet.
    /// Returns Some(RxResult) if packet ready, None otherwise.
    #[cfg(target_arch = "x86_64")]
    pub fn poll(vq: &mut VirtqueueState) -> Option<RxResult> {
        let mut result = RxResult::default();
        if unsafe { asm_vq_poll_rx(vq, &mut result) } == 1 {
            Some(result)
        } else {
            None
        }
    }

    /// Get number of pending packets.
    #[cfg(target_arch = "x86_64")]
    pub fn pending_count(vq: &mut VirtqueueState) -> u16 {
        unsafe { asm_vq_rx_pending(vq) }
    }

    // Stubs for non-x86_64
    #[cfg(not(target_arch = "x86_64"))]
    pub fn submit(_vq: &mut VirtqueueState, _buffer_idx: u16, _capacity: u16) -> bool {
        false
    }
    #[cfg(not(target_arch = "x86_64"))]
    pub fn poll(_vq: &mut VirtqueueState) -> Option<RxResult> {
        None
    }
    #[cfg(not(target_arch = "x86_64"))]
    pub fn pending_count(_vq: &mut VirtqueueState) -> u16 {
        0
    }
}

/// Notification operations.
pub mod notify {
    use super::*;

    /// Notify device about queue activity.
    #[cfg(target_arch = "x86_64")]
    pub fn notify(vq: &mut VirtqueueState) {
        // Sanity check the notify_addr (keep minimal safety checks)
        if vq.notify_addr == 0 || vq.notify_addr < 0x1000 {
            return; // Invalid notify address, skip
        }
        unsafe { asm_vq_notify(vq) }
    }

    /// Direct notify with explicit address.
    #[cfg(target_arch = "x86_64")]
    pub fn notify_direct(notify_addr: u64, queue_idx: u16) {
        unsafe { asm_vq_notify_direct(notify_addr, queue_idx) }
    }

    /// Check if notification is needed.
    #[cfg(target_arch = "x86_64")]
    pub fn should_notify(vq: &mut VirtqueueState) -> bool {
        unsafe { asm_vq_should_notify(vq) == 1 }
    }

    // Stubs for non-x86_64
    #[cfg(not(target_arch = "x86_64"))]
    pub fn notify(_vq: &mut VirtqueueState) {}
    #[cfg(not(target_arch = "x86_64"))]
    pub fn notify_direct(_notify_addr: u64, _queue_idx: u16) {}
    #[cfg(not(target_arch = "x86_64"))]
    pub fn should_notify(_vq: &mut VirtqueueState) -> bool {
        false
    }
}