summaryrefslogtreecommitdiffstats
path: root/rsnix/src/ahci.rs
blob: ea1a886154802384e5ffe202097707cdd2433608 (plain) (blame)
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
// ---------------------------------------------------------------------------
// AHCI — SATA host-controller driver (polling, DMA, no interrupts).
//
// Finds the chipset's AHCI controller (class 1 / subclass 6 / prog-if 1,
// e.g. the ICH9 on q35) on PCI bus 0, maps its ABAR (BAR5), starts every
// implemented port that has a device and exposes sector-level reads/writes
// for the FAT32 filesystem.  Multiple disks are supported; the filesystem
// selects one via `select()` and tries each in turn until one mounts.
//
// Commands are issued through command-slot 0 with one 4 KiB DMA buffer per
// port; completion is polled via PxCI (no ISR, no MSI).  Everything is
// identity-mapped, so "physical" DMA addresses are plain kernel pointers.
// The display is never involved, so this is a straightforward polling
// loop like the rest of the single-threaded kernel.
// ---------------------------------------------------------------------------

use crate::pci;

const SECTOR: usize = 512;
const MAX_DISKS: usize = 8;

// ABAR (HBA memory space) offsets.
const CAP: usize = 0x00;
const GHC: usize = 0x04;
const PI: usize = 0x0C;
const PORT_BASE: usize = 0x100;
const PORT_STRIDE: usize = 0x80;

// Port register offsets (relative to the port's base).
const P_CLB: usize = 0x00;
const P_CLBU: usize = 0x04;
const P_FB: usize = 0x08;
const P_FBU: usize = 0x0C;
const P_IS: usize = 0x10;
const P_CMD: usize = 0x18;
const P_TFD: usize = 0x20;
const P_SSTS: usize = 0x28;
const P_SCTL: usize = 0x2C;
const P_CI: usize = 0x38;

const CMD_ST: u32 = 1 << 0; // start
const CMD_SUD: u32 = 1 << 1; // spin-up device
const CMD_FRE: u32 = 1 << 4; // FIS receive enable
const CMD_DMAE: u32 = 1 << 23; // DMA enable (QEMU/ICH9) — required or DMA commands silently transfer nothing
const CMD_FR: u32 = 1 << 14; // FIS receive running
const CMD_CR: u32 = 1 << 15; // command list running

const ATA_IDENTIFY: u8 = 0xEC;
const ATA_READ_DMA_EXT: u8 = 0x25;
const ATA_WRITE_DMA_EXT: u8 = 0x35;

/// One attached disk: register map + DMA structures.
#[derive(Clone, Copy)]
struct Disk {
    port: usize,  // port register base = ABAR + 0x100
    clb: usize,   // command list, 1024 B (32 × 32 B), 256 B aligned
    fis: usize,   // FIS receive area, 256 B aligned
    ct: usize,    // command table, 256 B, 128 B aligned
    buf: usize,   // 4 KiB DMA data buffer (page aligned)
    sectors: u64, // total sectors (LBA48 from IDENTIFY)
}

static mut DISKS: [Option<Disk>; MAX_DISKS] = [None; MAX_DISKS];
static mut DISK_COUNT: usize = 0;
static mut ACTIVE: usize = 0;

fn reg(a: usize) -> u32 {
    unsafe { core::ptr::read_volatile(a as *const u32) }
}

fn wreg(a: usize, v: u32) {
    unsafe { core::ptr::write_volatile(a as *mut u32, v) }
}

/// Scan bus 0 for the AHCI controller (SATA, AHCI prog-if).
fn find_ahci() -> Option<(u8, u8)> {
    for dev in 0..32u8 {
        for func in 0..8u8 {
            let id = pci::config_read(0, dev, func, 0);
            if id == 0xFFFF_FFFF {
                if func == 0 {
                    break;
                }
                continue;
            }
            let cc = pci::config_read(0, dev, func, 0x08);
            let class = (cc >> 24) as u8;
            let subclass = (cc >> 16) as u8;
            let prog_if = (cc >> 8) as u8;
            if class == 0x01 && subclass == 0x06 && prog_if == 0x01 {
                return Some((dev, func));
            }
        }
    }
    None
}

/// Bring up one port: stop any firmware state, wire up its DMA structures,
/// wait for the link, start the command engine and run IDENTIFY.  Returns
/// the disk if a usable device answered.
fn start_port(abar: usize, port_idx: u32) -> Option<Disk> {
    let port = abar + PORT_BASE + port_idx as usize * PORT_STRIDE;

    // DMA structures: one 8 KiB allocation → page 0 = cmd list + FIS + cmd
    // table, page 1 = data buffer.
    let mem = crate::memory::alloc_pages(2)?;
    let clb = mem;
    let fis = mem + 1024;
    let ct = mem + 1280;
    let buf = mem + 4096;

    // Stop the port if firmware left it running.
    let mut cmd = reg(port + P_CMD);
    if cmd & CMD_ST != 0 {
        wreg(port + P_CMD, cmd & !CMD_ST);
        let mut i = 0;
        while reg(port + P_CMD) & CMD_CR != 0 && i < 1_000_000 {
            i += 1;
        }
        cmd = reg(port + P_CMD);
    }
    if cmd & CMD_FRE != 0 {
        wreg(port + P_CMD, cmd & !CMD_FRE);
        let mut i = 0;
        while reg(port + P_CMD) & CMD_FR != 0 && i < 1_000_000 {
            i += 1;
        }
    }
    unsafe {
        core::ptr::write_bytes(clb as *mut u8, 0, 1024);
        core::ptr::write_bytes(fis as *mut u8, 0, 256);
        core::ptr::write_bytes(ct as *mut u8, 0, 256);
    }

    wreg(port + P_CLB, clb as u32);
    wreg(port + P_CLBU, 0);
    wreg(port + P_FB, fis as u32);
    wreg(port + P_FBU, 0);

    // Allow device detection (clear PxSCTL.DET/IPM), then wait for the
    // link to come up (PxSSTS.DET == 3, communication established).
    // A port with no device settles at DET == 0 quickly — give up early.
    wreg(port + P_SCTL, 0);
    let mut link_ok = false;
    for i in 0..10_000_000u32 {
        let det = reg(port + P_SSTS) & 0xF;
        if det == 3 {
            link_ok = true;
            break;
        }
        if det == 0 && i > 100_000 {
            break; // settled with no device
        }
    }
    if !link_ok {
        crate::serial_println!(
            "ahci: no device on port {} (ssts={:#x})",
            port_idx,
            reg(port + P_SSTS)
        );
        return None;
    }

    // Start the command engine (DMAE required for DMA commands).
    wreg(port + P_CMD, CMD_FRE | CMD_SUD | CMD_DMAE);
    wreg(port + P_CMD, CMD_ST | CMD_FRE | CMD_SUD | CMD_DMAE);

    let mut d = Disk {
        port,
        clb,
        fis,
        ct,
        buf,
        sectors: 0,
    };
    // IDENTIFY DEVICE as a sanity check + to learn the capacity.
    if issue(&d, ATA_IDENTIFY, 0, 1, false).is_err() {
        crate::serial_println!("ahci: IDENTIFY failed on port {}", port_idx);
        return None;
    }
    let id = unsafe { core::slice::from_raw_parts(d.buf as *const u16, 256) };
    d.sectors = (id[100] as u64)
        | ((id[101] as u64) << 16)
        | ((id[102] as u64) << 32)
        | ((id[103] as u64) << 48);
    if d.sectors == 0 {
        d.sectors = id[60] as u64; // LBA28 fallback
    }
    let mut model = [0u8; 40];
    for i in 0..20 {
        model[i * 2] = (id[27 + i] >> 8) as u8;
        model[i * 2 + 1] = id[27 + i] as u8;
    }
    let model = core::str::from_utf8(&model).unwrap_or("?").trim();
    crate::serial_println!(
        "ahci: port {} up — {} sectors (~{} MB) \"{}\"",
        port_idx,
        d.sectors,
        d.sectors / 2048,
        model
    );
    Some(d)
}

/// Probe, map and start every implemented port that has a device.  Returns
/// true if at least one disk is ready for sector I/O.  Called once at boot
/// before the filesystem init; the filesystem then calls `select()` to pick
/// which disk to read.
pub fn init() -> bool {
    let Some((dev, func)) = find_ahci() else {
        return false;
    };
    // Enable memory space + bus mastering so MMIO and DMA work.
    let cmd_reg = pci::config_read(0, dev, func, 0x04);
    pci::config_write(0, dev, func, 0x04, cmd_reg | 0x7);

    let Some(abar) = pci::bar64(0, dev, func, 5) else {
        return false;
    };
    crate::serial_println!(
        "ahci: controller at {:02x}:{:02x}.{} abar={:#x}",
        0,
        dev,
        func,
        abar
    );

    // AHCI enable (GHC.AE) before touching port registers.
    wreg(abar as usize + GHC, reg(abar as usize + GHC) | (1 << 31));

    // Scan implemented ports (CAP.NP + 1 of them, filtered by PI).
    let cap = reg(abar as usize + CAP);
    let np = ((cap & 0x1F) + 1).min(32);
    let pi = reg(abar as usize + PI);
    for port_idx in 0..np {
        if (pi >> port_idx) & 1 == 0 {
            continue;
        }
        if let Some(d) = start_port(abar as usize, port_idx) {
            unsafe {
                DISKS[DISK_COUNT] = Some(d);
                DISK_COUNT += 1;
            }
        }
    }
    unsafe {
        ACTIVE = 0;
    }
    unsafe { DISK_COUNT > 0 }
}

/// Number of disks found at boot.
pub fn disk_count() -> usize {
    unsafe { DISK_COUNT }
}

/// Make `idx` the disk the sector API reads/writes.  Returns false if the
/// index is out of range.
pub fn select(idx: usize) -> bool {
    unsafe {
        if idx < DISK_COUNT {
            ACTIVE = idx;
            true
        } else {
            false
        }
    }
}

/// Issue one command through slot 0 and poll for completion.
/// `count` is sectors (1-8); data flows through the disk's DMA buffer.
fn issue(d: &Disk, cmd: u8, lba: u64, count: u32, write: bool) -> Result<(), ()> {
    if count == 0 || count > 8 {
        return Err(());
    }
    // Wait for slot 0 to be free.
    let mut i = 0;
    while reg(d.port + P_CI) & 1 != 0 && i < 10_000_000 {
        i += 1;
    }
    if reg(d.port + P_CI) & 1 != 0 {
        return Err(());
    }

    unsafe {
        core::ptr::write_bytes(d.ct as *mut u8, 0, 256);
    }

    // Host-to-device FIS (20 bytes) at the command table start.
    // Layout (SATA spec, cross-checked against QEMU + Linux libahci):
    //   0 type 0x27, 1 flags, 2 command, 3 features low,
    //   4-6 LBA[23:0], 7 device|LBA[27:24], 8-10 LBA[31:48],
    //   11 features high, 12-13 sector count, 14 ICC, 15 control.
    // Flags byte: only the C bit (0x80).  QEMU rejects H2D FISes with
    // bits 6:4 set (reserved); the transfer direction is signalled by
    // the command-header W bit instead, which issue() sets below.
    let fis = d.ct as *mut u8;
    unsafe {
        *fis = 0x27; // FIS type H2D
        *(fis.add(1)) = 0x80; // C only — QEMU rejects flags bits 6:4
        *(fis.add(2)) = cmd;
        *(fis.add(4)) = lba as u8;
        *(fis.add(5)) = (lba >> 8) as u8;
        *(fis.add(6)) = (lba >> 16) as u8;
        *(fis.add(7)) = 0x40 | (((lba >> 24) & 0x0F) as u8);
        *(fis.add(8)) = (lba >> 24) as u8;
        *(fis.add(9)) = (lba >> 32) as u8;
        *(fis.add(10)) = (lba >> 40) as u8;
        *(fis.add(11)) = 0; // features high
        *(fis.add(12)) = count as u8;
        *(fis.add(13)) = (count >> 8) as u8;
        *(fis.add(14)) = 0; // ICC
        *(fis.add(15)) = 0; // control
    }

    // PRD entry at the command table +0x80.
    let prd = (d.ct + 0x80) as *mut u32;
    unsafe {
        *prd = d.buf as u32;
        *prd.add(1) = 0;
        *prd.add(2) = 0;
        *prd.add(3) = (count * SECTOR as u32) - 1; // DBC, no I bit
    }

    // Command header 0. Layout per Linux libahci / QEMU AHCICmdHdr:
    //   DW0 bits 4:0 = CFL (FIS length in dwords), bit 6 = W,
    //   bits 31:16 = PRDTL; DW1 status; DW2/3 = command table address.
    let hdr = d.clb as *mut u32;
    unsafe {
        *hdr = 5 | (1 << 16) | if write { 1 << 6 } else { 0 };
        *hdr.add(1) = 0;
        *hdr.add(2) = d.ct as u32;
        *hdr.add(3) = 0;
    }

    // Issue and poll.
    wreg(d.port + P_CI, 1);
    let mut i = 0;
    while reg(d.port + P_CI) & 1 != 0 && i < 100_000_000 {
        i += 1;
    }
    if reg(d.port + P_CI) & 1 != 0 {
        crate::serial_println!(
            "ahci: command {:#x} lba={} cnt={} timed out (tfd={:#x} ci={:#x} cmd={:#x} prdbc={:#x})",
            cmd,
            lba,
            count,
            reg(d.port + P_TFD),
            reg(d.port + P_CI),
            reg(d.port + P_CMD),
            unsafe { *(d.clb as *const u32).add(1) }
        );
        return Err(());
    }
    // Error?  Clear any port error bits either way.
    if reg(d.port + P_TFD) & 1 != 0 {
        wreg(d.port + 0x30, 0xFFFF_FFFF); // PxSERR: clear
        crate::serial_println!(
            "ahci: command {:#x} error (tfd={:#x})",
            cmd,
            reg(d.port + P_TFD)
        );
        return Err(());
    }
    let is = reg(d.port + P_IS);
    if is != 0 {
        wreg(d.port + P_IS, is); // write-1-to-clear
    }
    Ok(())
}

fn active() -> Option<&'static Disk> {
    unsafe { DISKS.get(ACTIVE).and_then(|d| d.as_ref()) }
}

/// DMA `count` sectors starting at `lba` into the selected disk's buffer.
pub fn read_sectors(lba: u64, count: u32) -> Result<(), ()> {
    let d = active().ok_or(())?;
    if lba + count as u64 > d.sectors {
        return Err(());
    }
    issue(d, ATA_READ_DMA_EXT, lba, count, false)
}

/// DMA `count` sectors starting at `lba` out of the selected disk's buffer.
pub fn write_sectors(lba: u64, count: u32) -> Result<(), ()> {
    let d = active().ok_or(())?;
    if lba + count as u64 > d.sectors {
        return Err(());
    }
    issue(d, ATA_WRITE_DMA_EXT, lba, count, true)
}

/// Pointer to the selected disk's 4 KiB DMA buffer.
pub fn buf() -> *mut u8 {
    active()
        .map(|d| d.buf as *mut u8)
        .unwrap_or(core::ptr::null_mut())
}

/// Total sector count of the selected disk.
pub fn sector_count() -> u64 {
    active().map(|d| d.sectors).unwrap_or(0)
}