strat9_kernel/hardware/storage/
ata_legacy.rs1use alloc::{format, string::String, sync::Arc, vec::Vec};
27use core::sync::atomic::{AtomicBool, Ordering};
28use spin::Mutex;
29
30use super::virtio_block::{BlockDevice, BlockError, SECTOR_SIZE};
31
32const ATA_PRIMARY_IO: u16 = 0x1F0;
33const ATA_SECONDARY_IO: u16 = 0x170;
34
35#[allow(dead_code)]
36const ATA_REG_DATA: usize = 0;
37#[allow(dead_code)]
38const ATA_REG_ERROR: usize = 1;
39const ATA_REG_SECCOUNT: usize = 2;
40const ATA_REG_LBA_LOW: usize = 3;
41const ATA_REG_LBA_MID: usize = 4;
42const ATA_REG_LBA_HIGH: usize = 5;
43const ATA_REG_DEVICE: usize = 6;
44const ATA_REG_STATUS: usize = 7;
45const ATA_REG_COMMAND: usize = 7;
46
47const ATA_SR_BSY: u8 = 0x80;
48#[allow(dead_code)]
49const ATA_SR_DRDY: u8 = 0x40;
50const ATA_SR_DRQ: u8 = 0x08;
51const ATA_SR_ERR: u8 = 0x01;
52
53const ATA_CMD_IDENTIFY: u8 = 0xEC;
54const ATA_CMD_FLUSH_CACHE: u8 = 0xE7;
55
56const ATA_DEVICE_MASTER: u8 = 0xA0;
57const ATA_DEVICE_SLAVE: u8 = 0xB0;
58const ATA_DEVICE_LBA: u8 = 0x40;
59
60const POLL_TIMEOUT_TSC: u64 = 2_000_000;
65
66#[derive(Clone, Copy)]
67pub struct AtaChannel {
68 io_base: u16,
69 #[allow(dead_code)]
70 control_base: u16,
71 bus: u8,
72}
73
74impl AtaChannel {
75 fn new(io_base: u16, bus: u8) -> Self {
77 Self {
78 io_base,
79 control_base: io_base + 0x206,
80 bus,
81 }
82 }
83
84 fn read8(&self, offset: usize) -> u8 {
86 unsafe {
87 crate::x86_crate_shim::instructions::port::Port::new(self.io_base + offset as u16)
88 .read()
89 }
90 }
91
92 fn write8(&self, offset: usize, value: u8) {
94 unsafe {
95 crate::x86_crate_shim::instructions::port::Port::new(self.io_base + offset as u16)
96 .write(value)
97 }
98 }
99
100 fn read16(&self) -> u16 {
102 unsafe { crate::x86_crate_shim::instructions::port::Port::new(self.io_base).read() }
103 }
104
105 fn write16(&self, value: u16) {
107 unsafe { crate::x86_crate_shim::instructions::port::Port::new(self.io_base).write(value) }
108 }
109
110 fn wait_ready(&self) -> Result<(), &'static str> {
112 let deadline = self.poll_deadline();
113 loop {
114 let status = self.read8(ATA_REG_STATUS);
115 if (status & ATA_SR_BSY) == 0 {
116 return Ok(());
117 }
118 if crate::arch::rdtsc() >= deadline {
119 return Err("ATA timeout");
120 }
121 core::hint::spin_loop();
122 }
123 }
124
125 fn wait_drq(&self) -> Result<(), &'static str> {
127 let deadline = self.poll_deadline();
128 loop {
129 let status = self.read8(ATA_REG_STATUS);
130 if (status & ATA_SR_DRQ) != 0 {
131 return Ok(());
132 }
133 if (status & ATA_SR_ERR) != 0 {
134 return Err("ATA error");
135 }
136 if crate::arch::rdtsc() >= deadline {
137 return Err("ATA timeout");
138 }
139 core::hint::spin_loop();
140 }
141 }
142
143 fn poll_deadline(&self) -> u64 {
149 crate::arch::rdtsc().wrapping_add(POLL_TIMEOUT_TSC)
150 }
151
152 fn select_device(&self, _device: u8, lba: u64) {
154 let device_reg = ATA_DEVICE_MASTER | ATA_DEVICE_LBA | ((lba >> 24) & 0x0F) as u8;
155 self.write8(ATA_REG_DEVICE, device_reg);
156 self.read8(ATA_REG_STATUS);
157 for _ in 0..4 {
158 core::hint::spin_loop();
159 }
160 }
161
162 fn identify(&self, device: u8) -> Option<AtaDriveInfo> {
164 self.select_device(device, 0);
165 self.write8(ATA_REG_SECCOUNT, 0);
166 self.write8(ATA_REG_LBA_LOW, 0);
167 self.write8(ATA_REG_LBA_MID, 0);
168 self.write8(ATA_REG_LBA_HIGH, 0);
169 self.write8(ATA_REG_COMMAND, ATA_CMD_IDENTIFY);
170
171 let status = self.read8(ATA_REG_STATUS);
172 if status == 0 {
173 return None;
174 }
175
176 if let Err(_) = self.wait_ready() {
177 return None;
178 }
179
180 if let Err(_) = self.wait_drq() {
181 return None;
182 }
183
184 let mut buffer = [0u16; 256];
185 for i in 0..256 {
186 buffer[i] = self.read16();
187 }
188
189 let serial = Self::decode_identify_string(&buffer, 10, 20);
190 let model = Self::decode_identify_string(&buffer, 27, 54);
191 let capacity = (buffer[60] as u64) | ((buffer[61] as u64) << 16);
192
193 Some(AtaDriveInfo {
194 model,
195 serial,
196 capacity,
197 })
198 }
199
200 fn decode_identify_string(buffer: &[u16], start: usize, end: usize) -> String {
202 use alloc::string::String;
203 let mut s = String::new();
204 for i in start..end {
205 if i < buffer.len() {
206 let c = buffer[i];
207 let hi = (c >> 8) as u8;
208 let lo = (c & 0xFF) as u8;
209 if hi != 0 {
210 s.push(hi as char);
211 }
212 if lo != 0 {
213 s.push(lo as char);
214 }
215 }
216 }
217 s
218 }
219
220 fn read_sector_pio(&self, device: u8, lba: u64, buffer: &mut [u8]) -> Result<(), &'static str> {
222 if buffer.len() < SECTOR_SIZE {
223 return Err("Buffer too small");
224 }
225
226 self.wait_ready()?;
227 self.select_device(device, lba);
228
229 self.write8(ATA_REG_SECCOUNT, 1);
230 self.write8(ATA_REG_LBA_LOW, (lba & 0xFF) as u8);
231 self.write8(ATA_REG_LBA_MID, ((lba >> 8) & 0xFF) as u8);
232 self.write8(ATA_REG_LBA_HIGH, ((lba >> 16) & 0xFF) as u8);
233
234 self.write8(ATA_REG_COMMAND, 0x24);
235 self.wait_drq()?;
236
237 let buf_ptr = buffer.as_mut_ptr() as *mut u16;
238 for i in 0..256 {
239 unsafe {
240 core::ptr::write_volatile(buf_ptr.add(i), self.read16());
241 }
242 }
243
244 self.wait_ready()?;
245 Ok(())
246 }
247
248 fn write_sector_pio(&self, device: u8, lba: u64, buffer: &[u8]) -> Result<(), &'static str> {
250 if buffer.len() < SECTOR_SIZE {
251 return Err("Buffer too small");
252 }
253
254 self.wait_ready()?;
255 self.select_device(device, lba);
256
257 self.write8(ATA_REG_SECCOUNT, 1);
258 self.write8(ATA_REG_LBA_LOW, (lba & 0xFF) as u8);
259 self.write8(ATA_REG_LBA_MID, ((lba >> 8) & 0xFF) as u8);
260 self.write8(ATA_REG_LBA_HIGH, ((lba >> 16) & 0xFF) as u8);
261
262 self.write8(ATA_REG_COMMAND, 0x34);
263 self.wait_drq()?;
264
265 let buf_ptr = buffer.as_ptr() as *const u16;
266 for i in 0..256 {
267 unsafe {
268 self.write16(core::ptr::read_volatile(buf_ptr.add(i)));
269 }
270 }
271
272 self.wait_ready()?;
273 Ok(())
274 }
275
276 fn flush_cache(&self, device: u8) -> Result<(), &'static str> {
281 self.wait_ready()?;
282 self.select_device(device, 0);
283 self.write8(ATA_REG_COMMAND, ATA_CMD_FLUSH_CACHE);
284 self.wait_ready()?;
285 if (self.read8(ATA_REG_STATUS) & ATA_SR_ERR) != 0 {
286 return Err("ATA flush error");
287 }
288 Ok(())
289 }
290}
291
292#[derive(Clone)]
293pub struct AtaDriveInfo {
294 pub model: String,
295 pub serial: String,
296 pub capacity: u64,
297}
298
299pub struct AtaDrive {
300 channel: AtaChannel,
301 device: u8,
302 info: AtaDriveInfo,
303 #[allow(dead_code)]
304 name: String,
305}
306
307unsafe impl Send for AtaDrive {}
308unsafe impl Sync for AtaDrive {}
309
310impl AtaDrive {
311 pub fn new(channel: AtaChannel, device: u8) -> Option<Self> {
313 let info = channel.identify(device)?;
314 let name = format!(
315 "ata{}_{}",
316 channel.bus,
317 if device == ATA_DEVICE_MASTER {
318 "master"
319 } else {
320 "slave"
321 }
322 );
323 Some(Self {
324 channel,
325 device,
326 info,
327 name,
328 })
329 }
330
331 pub fn info(&self) -> &AtaDriveInfo {
333 &self.info
334 }
335}
336
337impl BlockDevice for AtaDrive {
338 fn read_sector(&self, sector: u64, buf: &mut [u8]) -> Result<(), BlockError> {
340 self.channel
341 .read_sector_pio(self.device, sector, buf)
342 .map_err(|_| BlockError::IoError)
343 }
344
345 fn write_sector(&self, sector: u64, buf: &[u8]) -> Result<(), BlockError> {
347 self.channel
348 .write_sector_pio(self.device, sector, buf)
349 .map_err(|_| BlockError::IoError)
350 }
351
352 fn sector_count(&self) -> u64 {
354 self.info.capacity
355 }
356
357 fn flush(&self) -> Result<(), BlockError> {
359 self.channel
360 .flush_cache(self.device)
361 .map_err(|_| BlockError::IoError)
362 }
363}
364
365static ATA_DRIVES: Mutex<Vec<Arc<AtaDrive>>> = Mutex::new(Vec::new());
366static ATA_INITIALIZED: AtomicBool = AtomicBool::new(false);
367
368pub fn init() {
373 if ATA_INITIALIZED.load(Ordering::Relaxed) {
374 return;
375 }
376 log::info!("[ATA] Scanning for legacy ATA/IDE devices...");
377
378 let channels = [
379 AtaChannel::new(ATA_PRIMARY_IO, 0),
380 AtaChannel::new(ATA_SECONDARY_IO, 1),
381 ];
382
383 for channel in &channels {
384 for device in [ATA_DEVICE_MASTER, ATA_DEVICE_SLAVE] {
385 if let Some(drive) = AtaDrive::new(channel.clone(), device) {
386 log::info!(
387 "ATA: Found drive on bus{} device{}: {} ({} sectors)",
388 channel.bus,
389 if device == ATA_DEVICE_MASTER {
390 "master"
391 } else {
392 "slave"
393 },
394 drive.info().model,
395 drive.info().capacity
396 );
397 ATA_DRIVES.lock().push(Arc::new(drive));
398 }
399 }
400 }
401
402 ATA_INITIALIZED.store(true, Ordering::SeqCst);
403 log::info!("[ATA] Found {} drive(s)", ATA_DRIVES.lock().len());
404}
405
406pub fn get_drive(index: usize) -> Option<Arc<AtaDrive>> {
408 ATA_DRIVES.lock().get(index).cloned()
409}
410
411pub fn get_first_drive() -> Option<Arc<AtaDrive>> {
413 ATA_DRIVES.lock().first().cloned()
414}
415
416pub fn is_available() -> bool {
418 ATA_INITIALIZED.load(Ordering::Relaxed)
419}