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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Implements dual 8237 ISA DMA controllers.
//!
//! Tested working with Floppy, but may require additional improvements to work
//! properly with other legacy hardware (e.g: Sound Blaster)
//!
//! Rather than having the DMA controller device be some big, complicated
//! behemoth that asynchronously resolves DMA requests itself (i.e: how the DMA
//! controller works in actual hardware), our virtual DMA controller takes a
//! simpler approach.
//!
//! This device is essentially just a big bundle-of-registers, which DMA capable
//! devices can query via the specialized
//! [`vmcore::isa_dma_channel::IsaDmaChannel`] trait in order to get the info
//! they need to fulfil DMA requests themselves.

#![warn(missing_docs)]

use chipset_device::io::IoError;
use chipset_device::io::IoResult;
use chipset_device::pio::PortIoIntercept;
use chipset_device::ChipsetDevice;
use inspect::Inspect;
use inspect::InspectMut;
use open_enum::open_enum;
use std::ops::RangeInclusive;
use vmcore::device_state::ChangeDeviceState;
use vmcore::isa_dma_channel::IsaDmaBuffer;
use vmcore::isa_dma_channel::IsaDmaDirection;

// Skip registering page port 0x80 so that the PCAT BIOS can handle
// it for debugging purposes.
const DMA_PAGE_REGISTER_PORT_RANGE: u16 = 0x80;
const PAGE_PORTS: RangeInclusive<u16> =
    (DMA_PAGE_REGISTER_PORT_RANGE + 0x1)..=(DMA_PAGE_REGISTER_PORT_RANGE + 0xf);
const CONTROLLER0_PORTS: RangeInclusive<u16> = 0x00..=0x0f;
/// Only the even ports, e.g., 0xc0, 0xc2, ..., 0xde, due to the 16
/// bit channel size that the second DMA controller supports.
const CONTROLLER1_PORTS: RangeInclusive<u16> = 0xc0..=0xdf;

const CHANNELS_PER_CONTROLLER: usize = 4;

const PAGE_PORTS_FOR_CHANNEL: [usize; 8] = [0x7, 0x3, 0x1, 0x2, 0xF, 0xB, 0x9, 0xA];

open_enum! {
    // Starts at offset 8 from the register bank.
    enum ControlRegister: u16 {
        STATUS = 0,          // port 0x08 (controller 0), port 0xd0 (controller 1). Read-only
        COMMAND = 0,         // port 0x08 (controller 0), port 0xd0 (controller 1). Write-only
        REQUEST = 1,         // port 0x09 (controller 0), port 0xd2 (controller 1)
        MASK = 2,            // port 0x0a (controller 0), port 0xd4 (controller 1)
        MODE = 3,            // port 0x0b (controller 0), port 0xd6 (controller 1)
        CLEAR_FLIP_FLOP = 4, // port 0x0c (controller 0), port 0xd8 (controller 1)
        INTERMEDIATE = 5,    // port 0x0d (controller 0), port 0xda (controller 1). Read-only
        RESET = 5,           // port 0x0d (controller 0), port 0xda (controller 1). Write-only
        CLEAR_MASK = 6,      // port 0x0e (controller 0), port 0xdc (controller 1)
        WRITE_MASK = 7,      // port 0x0f (controller 0), port 0xde (controller 1)
    }
}

/// Dual 8237 DMA controllers.
#[derive(Debug, InspectMut)]
pub struct DmaController {
    // Volatile state
    state: DmaControllerState,
}

#[derive(Debug, Default, Clone, Inspect)]
struct DmaControllerState {
    #[inspect(iter_by_index)]
    page_registers: [u8; 16],
    controller0: Controller,
    controller1: Controller,
}

impl DmaController {
    /// Returns a new controller.
    pub fn new() -> Self {
        Self {
            state: DmaControllerState::default(),
        }
    }

    fn get_controller(&mut self, channel_number: usize) -> Option<&mut Controller> {
        if channel_number < CHANNELS_PER_CONTROLLER {
            Some(&mut self.state.controller0)
        } else if channel_number < CHANNELS_PER_CONTROLLER * 2 {
            Some(&mut self.state.controller1)
        } else {
            None
        }
    }

    /// Checks the value of the DMA channel's configured transfer size.
    ///
    /// Corresponds to the `check_transfer_size` function in the `IsaDmaChannel`
    /// trait.
    pub fn check_transfer_size(&mut self, channel_number: usize) -> u16 {
        let Some(controller) = self.get_controller(channel_number) else {
            tracelimit::error_ratelimited!(?channel_number, "invalid channel number");
            return 0;
        };

        controller.channels[channel_number % CHANNELS_PER_CONTROLLER].count
    }

    /// Requests an access to ISA DMA channel buffer.
    ///
    /// Corresponds to the `request` function in the `IsaDmaChannel` trait.
    pub fn request(
        &mut self,
        channel_number: usize,
        direction: IsaDmaDirection,
    ) -> Option<IsaDmaBuffer> {
        if channel_number >= CHANNELS_PER_CONTROLLER * 2 {
            tracelimit::error_ratelimited!(?channel_number, "invalid channel number");
            return None;
        }

        let page = self.state.page_registers[PAGE_PORTS_FOR_CHANNEL[channel_number]];

        let controller = self.get_controller(channel_number).unwrap();
        if controller.disabled {
            tracelimit::warn_ratelimited!(?channel_number, "channel is disabled");
            return None;
        }

        let channel_index = channel_number % CHANNELS_PER_CONTROLLER;

        let channel = &controller.channels[channel_index];
        if !channel.enabled {
            tracing::warn!(
                ?channel_number,
                ?channel_index,
                "channel currently disabled"
            );
            return None;
        }

        let transfer_type = match (channel.mode >> 2) & 0x3 {
            0 => {
                tracing::error!(?channel_number, "invalid request: mode is self-test");
                return None;
            }
            1 => IsaDmaDirection::Write,
            2 => IsaDmaDirection::Read,
            _ => {
                tracing::error!(?channel_number, "invalid request: mode is invalid");
                return None;
            }
        };

        if transfer_type != direction {
            tracing::warn!(
                ?channel_number,
                ?channel_index,
                "mismatch between programmed and requested transfer directions"
            );
            return None;
        }

        let address = channel.address as u64 | (page as u64) << 16;

        // Report the channel as being active.
        controller.status &= !(1 << channel_index);

        let buffer = IsaDmaBuffer {
            address,
            size: channel.count as usize,
        };

        Some(buffer)
    }

    /// Signals to the DMA controller that the transfer is concluded.
    ///
    /// Corresponds to the `complete` function in the `IsaDmaChannel` trait.
    pub fn complete(&mut self, channel_number: usize) {
        let Some(controller) = self.get_controller(channel_number) else {
            tracing::error!(?channel_number, "invalid channel number");
            return;
        };

        let channel_index = channel_number % CHANNELS_PER_CONTROLLER;

        if (controller.status & (1 << channel_index)) != 0 {
            tracing::warn!(?channel_number, "channel was not active");
        }

        // Report the channel as being inactive.
        controller.status |= 1 << channel_index;
    }
}

impl ChangeDeviceState for DmaController {
    fn start(&mut self) {}

    async fn stop(&mut self) {}

    async fn reset(&mut self) {
        self.state = Default::default();
    }
}

impl ChipsetDevice for DmaController {
    fn supports_pio(&mut self) -> Option<&mut dyn PortIoIntercept> {
        Some(self)
    }
}

impl PortIoIntercept for DmaController {
    fn io_read(&mut self, io_port: u16, data: &mut [u8]) -> IoResult {
        data.fill(0);
        data[0] = if PAGE_PORTS.contains(&io_port) {
            self.state.page_registers[io_port as usize & 0xf]
        } else if CONTROLLER0_PORTS.contains(&io_port) {
            match self.state.controller0.read(io_port) {
                Ok(val) => val,
                Err(e) => return IoResult::Err(e),
            }
        } else if CONTROLLER1_PORTS.contains(&io_port) {
            // The secondary controller registers are 16 bits wide (but still have only 8 bytes of data).
            match self.state.controller1.read((io_port / 2) & 0xf) {
                Ok(val) => val,
                Err(e) => return IoResult::Err(e),
            }
        } else {
            return IoResult::Err(IoError::InvalidRegister);
        };

        IoResult::Ok
    }

    fn io_write(&mut self, io_port: u16, data: &[u8]) -> IoResult {
        if PAGE_PORTS.contains(&io_port) {
            self.state.page_registers[io_port as usize & 0xf] = data[0];
            IoResult::Ok
        } else if CONTROLLER0_PORTS.contains(&io_port) {
            self.state.controller0.write(io_port, data[0])
        } else if CONTROLLER1_PORTS.contains(&io_port) {
            // The secondary controller registers are 16 bits wide (but still have only 8 bytes of data).
            self.state.controller1.write((io_port / 2) & 0xf, data[0])
        } else {
            IoResult::Err(IoError::InvalidRegister)
        }
    }

    fn get_static_regions(&mut self) -> &[(&str, RangeInclusive<u16>)] {
        &[
            ("page", PAGE_PORTS),
            ("controller0", CONTROLLER0_PORTS),
            ("controller1", CONTROLLER1_PORTS),
        ]
    }
}

/// A single DMA controller.
#[derive(Debug, Default, Clone, Inspect)]
struct Controller {
    #[inspect(iter_by_index)]
    channels: [Channel; CHANNELS_PER_CONTROLLER],
    flip_flop_high: bool,
    latched_address: u16,
    latched_count: u16,
    disabled: bool,
    status: u8,
}

#[derive(Debug, Default, Clone, Inspect)]
struct Channel {
    #[inspect(hex)]
    address: u16,
    #[inspect(hex)]
    count: u16,
    #[inspect(hex)]
    mode: u8,
    enabled: bool,
}

impl Controller {
    fn read(&mut self, reg: u16) -> Result<u8, IoError> {
        let res = if reg < 8 {
            let channel = reg as usize / 2;
            let data = if reg % 2 == 0 {
                // Address port.
                if !self.flip_flop_high {
                    self.latched_address = self.channels[channel].address;
                }
                self.latched_address
            } else {
                // Word count port.
                if !self.flip_flop_high {
                    self.latched_count = self.channels[channel].count;
                }
                self.latched_count
            };

            // Extract the high or low byte depending on the flip-flop state.
            self.flip_flop_high = !self.flip_flop_high;
            if !self.flip_flop_high {
                (data >> 8) as u8
            } else {
                data as u8
            }
        } else {
            match ControlRegister(reg - 8) {
                ControlRegister::STATUS => std::mem::take(&mut self.status),
                ControlRegister::INTERMEDIATE => 0,
                ControlRegister::WRITE_MASK => {
                    let mut data = 0xf0;
                    for (n, channel) in self.channels.iter().enumerate() {
                        if channel.enabled {
                            // should this be `!channel.enabled`?
                            data |= 1 << n;
                        }
                    }
                    data
                }
                _ => return Err(IoError::InvalidRegister),
            }
        };

        Ok(res)
    }

    fn write(&mut self, reg: u16, data: u8) -> IoResult {
        if reg < 8 {
            let channel = reg as usize / 2;
            let mem = if reg % 2 == 0 {
                // Address port.
                &mut self.channels[channel].address
            } else {
                &mut self.channels[channel].count
            };
            if self.flip_flop_high {
                *mem = (*mem & 0xff) | (data as u16) << 8
            } else {
                *mem = (*mem & 0xff00) | data as u16
            }
            self.flip_flop_high = !self.flip_flop_high;
        } else {
            match ControlRegister(reg - 8) {
                ControlRegister::COMMAND => {
                    self.disabled = data != 0;
                }
                ControlRegister::REQUEST => {
                    // Our emulation doesn't support software-initiated DMA
                    // transfers. Specify that the channel has reached its
                    // terminal count.
                    self.status |= 1 << (data & 3);
                }
                ControlRegister::MASK => {
                    self.channels[data as usize & 3].enabled = data & 4 == 0;
                }
                ControlRegister::MODE => self.channels[data as usize & 3].mode = data,
                ControlRegister::RESET => {
                    *self = Default::default();
                }
                ControlRegister::CLEAR_MASK => {
                    for channel in &mut self.channels {
                        channel.enabled = true;
                    }
                }
                ControlRegister::WRITE_MASK => {
                    for (n, channel) in self.channels.iter_mut().enumerate() {
                        channel.enabled = data & (1 << n) == 0;
                    }
                }
                ControlRegister::CLEAR_FLIP_FLOP => self.flip_flop_high = false,
                _ => return IoResult::Err(IoError::InvalidRegister),
            }
        }

        IoResult::Ok
    }
}

mod save_restore {
    use super::*;
    use vmcore::save_restore::RestoreError;
    use vmcore::save_restore::SaveError;
    use vmcore::save_restore::SaveRestore;

    mod state {
        use mesh::payload::Protobuf;
        use vmcore::save_restore::SavedStateRoot;

        #[derive(Protobuf, SavedStateRoot)]
        #[mesh(package = "chipset.dma")]
        pub struct SavedState {
            #[mesh(1)]
            pub page_registers: [u8; 16],
            #[mesh(2)]
            pub controller0: SavedController,
            #[mesh(3)]
            pub controller1: SavedController,
        }

        #[derive(Protobuf)]
        #[mesh(package = "chipset.dma")]
        pub struct SavedController {
            #[mesh(1)]
            pub channels: [SavedChannel; 4],
            #[mesh(2)]
            pub flip_flop_high: bool,
            #[mesh(3)]
            pub latched_address: u16,
            #[mesh(4)]
            pub latched_count: u16,
            #[mesh(5)]
            pub status: u8,
            #[mesh(6)]
            pub disabled: bool,
        }

        #[derive(Protobuf)]
        #[mesh(package = "chipset.dma")]
        pub struct SavedChannel {
            #[mesh(1)]
            pub address: u16,
            #[mesh(2)]
            pub count: u16,
            #[mesh(3)]
            pub mode: u8,
            #[mesh(4)]
            pub enabled: bool,
        }
    }

    impl SaveRestore for DmaController {
        type SavedState = state::SavedState;

        fn save(&mut self) -> Result<Self::SavedState, SaveError> {
            let DmaControllerState {
                page_registers,
                controller0,
                controller1,
            } = self.state.clone();

            let [controller0, controller1] = [controller0, controller1].map(|con| {
                let Controller {
                    channels,
                    flip_flop_high,
                    latched_address,
                    latched_count,
                    status,
                    disabled,
                } = con;

                state::SavedController {
                    channels: channels.map(|chan| {
                        let Channel {
                            address,
                            count,
                            mode,
                            enabled,
                        } = chan;

                        state::SavedChannel {
                            address,
                            count,
                            mode,
                            enabled,
                        }
                    }),
                    flip_flop_high,
                    latched_address,
                    latched_count,
                    status,
                    disabled,
                }
            });

            let saved_state = state::SavedState {
                page_registers,
                controller0,
                controller1,
            };

            Ok(saved_state)
        }

        fn restore(&mut self, state: Self::SavedState) -> Result<(), RestoreError> {
            let state::SavedState {
                page_registers,
                controller0,
                controller1,
            } = state;

            let [controller0, controller1] = [controller0, controller1].map(|con| {
                let state::SavedController {
                    channels,
                    flip_flop_high,
                    latched_address,
                    latched_count,
                    status,
                    disabled,
                } = con;

                Controller {
                    channels: channels.map(|chan| {
                        let state::SavedChannel {
                            address,
                            count,
                            mode,
                            enabled,
                        } = chan;

                        Channel {
                            address,
                            count,
                            mode,
                            enabled,
                        }
                    }),
                    flip_flop_high,
                    latched_address,
                    latched_count,
                    status,
                    disabled,
                }
            });

            self.state = DmaControllerState {
                page_registers,
                controller0,
                controller1,
            };

            Ok(())
        }
    }
}