Compare commits

..
4 Commits
Author SHA1 Message Date
Alexander Wolf e340fdfe81 Tiny fixes 2025-10-18 02:54:31 -04:00
Alexander Wolf 63a428301c Got reading from a disk to work properly 2025-10-12 14:42:20 -04:00
Alexander Wolf b0d7010534 Got the driver working with all slots populated 2025-10-12 12:23:15 -04:00
Alexander Wolf 33aaf7a002 Updated the target file 2025-09-07 22:49:10 -04:00
11 changed files with 624 additions and 131 deletions

No files matched your search

+1 -1
View File
@@ -6,4 +6,4 @@ panic-abort-tests = true
[build]
#target = "x86_64-unknown-none"
#target = "../build-targets/x84_64.json"
target = "./x86_64-target.json"
target = "./targets/x86_64.json"
Generated
+52 -2
View File
@@ -4,10 +4,11 @@ version = 4
[[package]]
name = "ata-driver"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"conquer-once",
"crossbeam-queue",
"serial-driver",
"x86_64",
]
@@ -17,6 +18,12 @@ version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc827186963e592360843fb5ba4b973e145841266c1357f7180c43526f2e5b61"
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitflags"
version = "2.6.0"
@@ -53,12 +60,55 @@ version = "0.8.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
[[package]]
name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
dependencies = [
"spin 0.9.8",
]
[[package]]
name = "rustversion"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7c45b9784283f1b2e7fb61b42047c2fd678ef0960d4f6f1eba131594cc369d4"
[[package]]
name = "serial-driver"
version = "0.1.0"
source = "git+https://gitea.puppylab.net/PupTech/serial-driver.git#0f3cc25a5095367c5158de6bdcd4d9006aba33a6"
dependencies = [
"lazy_static",
"spin 0.5.2",
"uart_16550",
"x86_64",
]
[[package]]
name = "spin"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"
[[package]]
name = "spin"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
[[package]]
name = "uart_16550"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "614ff2a87880d4bd4374722268598a970bbad05ced8bf630439417347254ab2e"
dependencies = [
"bitflags 1.3.2",
"rustversion",
"x86_64",
]
[[package]]
name = "volatile"
version = "0.4.6"
@@ -72,7 +122,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c101112411baafbb4bf8d33e4c4a80ab5b02d74d2612331c61e8192fc9710491"
dependencies = [
"bit_field",
"bitflags",
"bitflags 2.6.0",
"rustversion",
"volatile",
]
+7 -1
View File
@@ -1,10 +1,16 @@
[package]
name = "ata-driver"
version = "0.1.0"
version = "0.1.2"
edition = "2024"
[features]
default = []
debug = ["serial"]
serial = ["dep:serial-driver"]
[dependencies]
x86_64 = "0.14.2"
serial-driver = { git = "https://gitea.puppylab.net/PupTech/serial-driver.git", optional = true }
[dependencies.crossbeam-queue]
version = "0.3.11"
+3 -2
View File
@@ -21,7 +21,8 @@ extern crate alloc;
pub mod commands;
pub mod pio;
pub mod wrapper;
fn dummy_sleep(cycles: usize) {
for n in 0..cycles {}
pub(crate) fn dummy_sleep(cycles: usize) {
for _ in 0..cycles {}
}
+8 -8
View File
@@ -2,14 +2,14 @@ use super::ATAPIODriver;
#[derive(Debug, Clone, Copy)]
pub struct ATAPIODeviceErrorStatus {
address_mark_not_found: bool,
track_zero_not_found: bool,
aborted_command: bool,
media_change_request: bool,
id_not_found: bool,
media_changed: bool,
uncorrectable_data_error: bool,
bad_block_detected: bool
pub address_mark_not_found: bool,
pub track_zero_not_found: bool,
pub aborted_command: bool,
pub media_change_request: bool,
pub id_not_found: bool,
pub media_changed: bool,
pub uncorrectable_data_error: bool,
pub bad_block_detected: bool
}
impl From<u8> for ATAPIODeviceErrorStatus {
+20 -21
View File
@@ -36,21 +36,21 @@ impl fmt::Display for ATAPIODeviceIdentity {
.collect::<Vec<_>>()
.join("");
writeln!(f, "[Device Identity]");
writeln!(f, " [G0] {}", self.g0);
writeln!(f, " [Cylinders] {}", self.cylinders);
writeln!(f, " [Heads] {}", self.heads);
writeln!(f, " [Sectors/Track] {}", self.sectors_per_track);
writeln!(f, " [Serial] {}", serial);
writeln!(f, " [Firmware Rev] {}", firmware_rev);
writeln!(f, " [Model #] {}", model_num);
writeln!(f, " [Max Sectors/Int] {}", self.max_sectors_per_interupt);
writeln!(f, " [Capabilities] {}", self.capabilities);
writeln!(f, " [Sectors] (LBA28:{}),(LBA48:{})", self.lba28_sectors, self.lba48_sectors);
writeln!(f, " [Major Ver] {}", self.ata_major_ver);
writeln!(f, " [CCS] {}", self.command_set_supported);
writeln!(f, " [CCSext] {}", self.command_set_supported_ext);
writeln!(f, " [Checksum] {}", self.checksum);
writeln!(f, "[[Device Identity]]")?;
writeln!(f, " [G0] {}", self.g0)?;
writeln!(f, " [Cylinders] {}", self.cylinders)?;
writeln!(f, " [Heads] {}", self.heads)?;
writeln!(f, " [Sectors/Track] {}", self.sectors_per_track)?;
writeln!(f, " [Serial] {}", serial)?;
writeln!(f, " [Firmware Rev] {}", firmware_rev)?;
writeln!(f, " [Model #] {}", model_num)?;
writeln!(f, " [Max Sectors/Int] {}", self.max_sectors_per_interupt)?;
writeln!(f, " [Capabilities] {}", self.capabilities)?;
writeln!(f, " [Sectors] (LBA28:{}),(LBA48:{})", self.lba28_sectors, self.lba48_sectors)?;
writeln!(f, " [Major Ver] {}", self.ata_major_ver)?;
writeln!(f, " [CCS] {}", self.command_set_supported)?;
writeln!(f, " [CCSext] {}", self.command_set_supported_ext)?;
writeln!(f, " [Checksum] {}", self.checksum)?;
writeln!(f, "")
}
}
@@ -104,12 +104,11 @@ impl From<&[u16; 256]> for ATAPIODeviceIdentity {
buffer[46],
], &mut model_number);
let lba28_sectors: u32 = ((buffer[60] as u32) & 0xFFFF) << 16 | ((buffer[61] as u32) & 0xFFFF);
let lba48_sectors: u64 =
((buffer[100] as u64) & 0xFFFF) << 16 |
((buffer[101] as u64) & 0xFFFF) << 16 |
((buffer[102] as u64) & 0xFFFF) << 16 |
((buffer[103] as u64) & 0xFFFF) << 16;
let lba28_sectors = ((buffer[61] as u32) << 16) | (buffer[60] as u32);
let lba48_sectors = ((buffer[103] as u64) << 48)
| ((buffer[102] as u64) << 32)
| ((buffer[101] as u64) << 16)
| (buffer[100] as u64);
Self {
g0: buffer[0],
+9 -9
View File
@@ -37,15 +37,15 @@ impl From<&ATAPIODriver> for ATAPIODeviceStatus {
impl fmt::Display for ATAPIODeviceStatus {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "[Device Status]");
writeln!(f, " [Error] {}", self.err);
writeln!(f, " [Index] {}", self.index);
writeln!(f, " [CorrectedData] {}", self.corrected_data);
writeln!(f, " [DataReady] {}", self.data_ready);
writeln!(f, " [OMSR] {}", self.overlapped_mode_service_request);
writeln!(f, " [Fault] {}", self.drive_fault_error);
writeln!(f, " [Ready] {}", self.ready);
writeln!(f, " [Busy] {}", self.busy);
writeln!(f, "[Device Status]")?;
writeln!(f, " [Error] {}", self.err)?;
writeln!(f, " [Index] {}", self.index)?;
writeln!(f, " [CorrectedData] {}", self.corrected_data)?;
writeln!(f, " [DataReady] {}", self.data_ready)?;
writeln!(f, " [OMSR] {}", self.overlapped_mode_service_request)?;
writeln!(f, " [Fault] {}", self.drive_fault_error)?;
writeln!(f, " [Ready] {}", self.ready)?;
writeln!(f, " [Busy] {}", self.busy)?;
writeln!(f, "")
}
}
+35 -8
View File
@@ -1,31 +1,58 @@
use alloc::boxed::Box;
use core::fmt;
use crate::pio::deverrors::ATAPIODeviceError;
#[derive(Debug, Clone)]
pub enum ATAPIODriverExceptions {
DeviceNotATAPIO(),
ErrorQueryingDevice(),
UnknownException,
DeviceNotATAPIO,
ErrorQueryingDevice(Option<ATAPIODeviceError>),
DriverInitFailure(Option<Box<ATAPIODriverExceptions>>),
AddressSpaceExceeded,
InvalidDataSize,
Timeout,
DeviceNotReady
}
impl fmt::Display for ATAPIODriverExceptions {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "Exception raised in ATAPIODriver!");
writeln!(f, "Exception raised in ATAPIODriver!")?;
match self {
Self::DeviceNotATAPIO() => {
Self::DeviceNotATAPIO => {
writeln!(f, "")
},
Self::DriverInitFailure(suberror) => {
writeln!(f, "Failed to initialize driver!");
writeln!(f, "Failed to initialize driver!")?;
if let Some(suberror_cell) = suberror {
writeln!(f, "Suberror:\n{}", suberror_cell)
} else {
writeln!(f, "No suberror.")
}
},
Self::ErrorQueryingDevice() => {
writeln!(f, "Failed to query device!")
Self::ErrorQueryingDevice(suberror) => {
writeln!(f, "Failed to query device!")?;
if let Some(suberror_cell) = suberror {
writeln!(f, "Suberror:\n{}", suberror_cell)
} else {
writeln!(f, "No suberror.")
}
},
Self::AddressSpaceExceeded => {
writeln!(f, "The given address has exceeded the possible address space!")
},
Self::InvalidDataSize => {
writeln!(f, "The given value was of an incorrect data size!")
},
Self::Timeout => {
writeln!(f, "The task timed-out!")
},
Self::DeviceNotReady => {
writeln!(f, "The device is not ready!")
},
Self::UnknownException => {
writeln!(f, "Unknown exception occurred!")
}
}
}
}
}
+486 -77
View File
@@ -1,9 +1,32 @@
use core::{fmt, num::NonZeroU64};
use alloc::{boxed::Box, rc::Rc, vec::Vec};
use conquer_once::spin::{OnceCell};
use alloc::{boxed::Box, vec::Vec};
use x86_64::instructions::port::{Port, PortGeneric, ReadWriteAccess};
const BUFFER_LIM: usize = 256;
#[cfg(feature="serial")]
use serial_driver::{serial_println, serial_print};
#[macro_export]
macro_rules! ata_log {
($($arg:tt)*) => ({
#[cfg(feature="serial")]
{
serial_print!("[ATA-DRIVER] ");
serial_println!($($arg)*);
}
})
}
#[macro_export]
macro_rules! ata_log_inline {
($($arg:tt)*) => ({
#[cfg(feature="serial")] {
serial_print!("[ATA-DRIVER] ");
serial_print!($($arg)*);
}
})
}
pub mod exceptions;
pub mod devstatus;
pub mod devidentity;
@@ -20,36 +43,47 @@ use deverrors::ATAPIODeviceError;
use crate::dummy_sleep;
// Constants
#[derive(Debug, Clone, Copy)]
pub enum DeviceSelect {
Master,
Slave,
}
#[derive(Debug, Clone, Copy)]
pub struct DeviceMapping {
io_port: u16,
control_port: u16,
irq: Option<u16>
irq: Option<u16>,
devsel: DeviceSelect
}
pub static PRIMARY_MASTER_DEVICE: DeviceMapping = DeviceMapping {
pub static PRIMARY_CHANNEL: DeviceMapping = DeviceMapping {
io_port: 0x1F0,
control_port: 0x3F6,
irq: Some(14)
irq: Some(14),
devsel: DeviceSelect::Master
};
pub static PRIMARY_SLAVE_DEVICE: DeviceMapping = DeviceMapping {
pub static SECONDARY_CHANNEL: DeviceMapping = DeviceMapping {
io_port: 0x170,
control_port: 0x376,
irq: Some(15)
irq: Some(15),
devsel: DeviceSelect::Master
};
pub static SECONDARY_MASTER_DEVICE: DeviceMapping = DeviceMapping {
io_port: 0x1E8,
control_port: 0x3E6,
irq: None
};
pub fn get_primary_master() -> ATAPIODriver { ATAPIODriver::new(PRIMARY_CHANNEL) }
pub fn get_primary_slave() -> ATAPIODriver {
let mut map = PRIMARY_CHANNEL;
map.devsel = DeviceSelect::Slave;
ATAPIODriver::new(map)
}
pub static SECONDARY_SLAVE_DEVICE: DeviceMapping = DeviceMapping {
io_port: 0x168,
control_port: 0x366,
irq: None
};
pub fn get_secondary_master() -> ATAPIODriver { ATAPIODriver::new(SECONDARY_CHANNEL) }
pub fn get_secondary_slave() -> ATAPIODriver {
let mut map = SECONDARY_CHANNEL;
map.devsel = DeviceSelect::Slave;
ATAPIODriver::new(map)
}
// Global init
pub fn init() {
@@ -58,6 +92,7 @@ pub fn init() {
/// Called by the keyboard interrupt handler
/// Must not block or allocate.
#[allow(dead_code)]
pub(crate) fn irq_event_responder() {
}
@@ -81,6 +116,9 @@ pub struct ATAPIODriver {
// Constructors
impl ATAPIODriver {
pub fn new(mapping: DeviceMapping) -> Self {
#[cfg(feature = "debug")]
ata_log!("New driver created!");
Self {
mapping: mapping,
devswap_last: 0,
@@ -89,19 +127,27 @@ impl ATAPIODriver {
}
pub fn get_device_1() -> Self {
Self::new(PRIMARY_MASTER_DEVICE)
#[cfg(feature = "debug")]
ata_log!("Selecting PRIMARY_MASTER");
get_primary_master()
}
pub fn get_device_2() -> Self {
Self::new(PRIMARY_SLAVE_DEVICE)
#[cfg(feature = "debug")]
ata_log!("Selecting PRIMARY_SLAVE");
get_primary_slave()
}
pub fn get_device_3() -> Self {
Self::new(SECONDARY_MASTER_DEVICE)
#[cfg(feature = "debug")]
ata_log!("Selecting SECONDARY_MASTER");
get_secondary_master()
}
pub fn get_device_4() -> Self {
Self::new(SECONDARY_SLAVE_DEVICE)
#[cfg(feature = "debug")]
ata_log!("Selecting SECONDARY_SLAVE");
get_secondary_slave()
}
}
@@ -119,32 +165,49 @@ impl ATAPIODriver {
// Wrapper methods to do work
impl ATAPIODriver {
pub fn init_device(&mut self, force: bool) -> Result<(), ATAPIODriverExceptions> {
#[cfg(feature = "debug")]
ata_log!("Starting driver init...");
if !force && let Some(_) = &self.identity {
// Device has already been setup
#[cfg(feature = "debug")]
ata_log!("Init already ran!");
return Ok(());
} else {
#[cfg(feature = "debug")]
ata_log!("Attempting to identify device...");
// Query the device, so we can get all the configuration data for the disk
match self.query_device(true) {
Ok(query) => {
self.identity = Some(query);
#[cfg(feature = "debug")]
ata_log!("Device identified! Serial({:?})", query.serial);
return Ok(());
},
Err(exception) => return Err(
ATAPIODriverExceptions::DriverInitFailure(Some(Box::new(exception)))
),
Err(exception) => {
#[cfg(feature = "debug")]
ata_log!("There was an exception identifying the device!");
return Err(
ATAPIODriverExceptions::DriverInitFailure(Some(Box::new(exception)))
)
},
}
}
}
fn delay400ns(&self) -> u8 {
#[cfg(feature = "debug")]
ata_log!("Waiting...");
let mut status: u8 = 0;
for n in 0..15 {
for _ in 0..15 {
status = self.read_reg_status();
}
status
}
pub fn read_errors(&mut self, use_lba48: bool) -> ATAPIODeviceError {
#[cfg(feature = "debug")]
ata_log!("Reading errors...");
let error_value = {
if use_lba48 {
self.read_reg_error_lba48() as u8
@@ -153,79 +216,196 @@ impl ATAPIODriver {
}
};
ATAPIODeviceError::from(error_value)
let err = ATAPIODeviceError::from(error_value);
#[cfg(feature = "debug")]
ata_log!("Error read: {}", err);
err
}
pub fn raw_send_command(&mut self, command: u8) {
#[cfg(feature = "debug")]
ata_log!("Preparing to send raw command (COMMAND={:x})...", command);
// Check if BSY or DRQ bits are set before trying to send a command
// Device may still be switching, so read the status port 15 times,
// only care about last read
let cdrive = self.read_reg_drive();
if cdrive != self.devswap_last {
#[cfg(feature = "debug")]
ata_log!("CDRIVE != DEVSWAP_LAST");
let _ = self.delay400ns();
let mut status = self.get_status();
#[cfg(feature = "debug")]
ata_log!("Device status: [{}]", status);
let mut busy = status.busy || status.data_ready;
#[cfg(feature = "debug")]
ata_log!("Device busy: [{}]", busy);
if busy {
#[cfg(feature = "debug")]
ata_log!("Waiting for device to be free...");
}
while busy {
status = self.get_status();
busy = status.busy || status.data_ready;
dummy_sleep(1000);
}
#[cfg(feature = "debug")]
ata_log!("Device available!");
self.devswap_last = cdrive;
}
#[cfg(feature = "debug")]
ata_log!("Writing COMMAND({:x})", command);
self.write_reg_command(command);
}
fn poll_device(&self) -> Result<ATAPIODeviceStatus, ATAPIODriverExceptions> {
let mut ds1 = self.read_reg_status();
fn poll_device(&mut self) -> Result<ATAPIODeviceStatus, ATAPIODriverExceptions> {
self.poll_device_with_timeout(None)
}
fn poll_device_with_timeout(&mut self, timeout: Option<usize>) -> Result<ATAPIODeviceStatus, ATAPIODriverExceptions> {
let mut cycles: usize = 0;
#[cfg(feature = "debug")]
ata_log!("<poll_device>");
#[cfg(feature = "debug")]
ata_log!("Polling device...");
let ds1 = self.read_reg_status();
#[cfg(feature = "debug")]
ata_log!("POLL_REG_STATUS({})", ds1);
if ds1 == 0 {
return Err(ATAPIODriverExceptions::DeviceNotATAPIO());
#[cfg(feature = "debug")]
ata_log!("Unable to continue! This device is not ATAPIO!");
return Err(ATAPIODriverExceptions::DeviceNotATAPIO);
}
let mut status = self.get_status();
loop {
if !status.busy { break; }
#[cfg(feature = "debug")]
ata_log!("DeviceStatus({})", status);
if status.busy {
#[cfg(feature = "debug")]
ata_log!("Waiting for device to be available...");
}
while status.busy && timeout_compare(cycles, timeout) {
cycles = cycles + 1;
status = self.get_status();
}
if !timeout_compare(cycles, timeout) {
return Err(ATAPIODriverExceptions::Timeout);
}
cycles = 0;
#[cfg(feature = "debug")]
ata_log!("Device available!");
#[cfg(feature = "debug")]
ata_log!("Waiting for data...");
loop {
if status.err {
return Err(ATAPIODriverExceptions::ErrorQueryingDevice());
let error = self.read_errors(false);
#[cfg(feature = "debug")]
ata_log!("There was an exception!");
ata_log!("ATAPIODeviceError: {}", error);
return Err(ATAPIODriverExceptions::ErrorQueryingDevice(Some(error)));
} else if status.data_ready {
#[cfg(feature = "debug")]
ata_log!("Data ready!");
break;
} else {
}
if timeout_compare(cycles, timeout) {
status = self.get_status();
cycles = cycles + 1;
} else {
return Err(ATAPIODriverExceptions::Timeout);
}
}
#[cfg(feature = "debug")]
ata_log!("</poll_device>");
Ok(status)
}
pub fn raw_read_data_block(&mut self) -> [u16; 256] {
let mut buffer: [u16; 256] = [0;256];
#[cfg(feature = "debug")]
ata_log!("Preparing to read raw data block...");
let mut buffer: [u16; 256] = [0; BUFFER_LIM];
#[cfg(feature = "debug")]
ata_log!("Attempting to read {} bytes into the buffer...", buffer_lim);
#[cfg(feature = "debug")]
serial_print!("[ATA-DRIVER] Reading");
for n in 0..256 {
buffer[n] = self.read_reg_data();
#[cfg(feature = "debug")]
serial_print!(".");
}
#[cfg(feature = "debug")]
serial_print!("\n");
#[cfg(feature = "debug")]
ata_log!("Returning buffer!");
buffer
}
pub fn query_device(&mut self, master: bool) -> Result<ATAPIODeviceIdentity, ATAPIODriverExceptions> {
#[cfg(feature = "debug")]
ata_log!("Querying device...");
// Select the drive
if master {
#[cfg(feature = "debug")]
ata_log!("Selecting MASTER by WRITE_REG_DRIVE(0xA0)");
self.write_reg_drive(0xA0);
} else {
#[cfg(feature = "debug")]
ata_log!("Selecting SLAVE by WRITE_REG_DRIVE(0xB0)");
self.write_reg_drive(0xB0);
}
self.write_reg_sector_count_lba28(0);
self.write_reg_cyl_low_lba28(0);
self.write_reg_cyl_mid_lba28(0);
self.write_reg_cyl_high_lba28(0);
self.set_count_cyl(0, 0, 0, 0);
#[cfg(feature = "debug")]
ata_log!("Sending command 0xEC...");
self.raw_send_command(0xEC);
#[cfg(feature = "debug")]
ata_log!("Sleeping for 1000cycles...");
dummy_sleep(1000);
#[cfg(feature = "debug")]
ata_log!("Polling device...");
let _ = self.poll_device();
#[cfg(feature = "debug")]
ata_log!("Reading raw data block...");
let buffer = self.raw_read_data_block();
#[cfg(feature = "debug")]
ata_log!("Parsing identity...");
let identity = ATAPIODeviceIdentity::from(&buffer);
return Ok(identity);
@@ -233,49 +413,174 @@ impl ATAPIODriver {
}
impl ATAPIODriver {
pub fn read_bytes_lba28(&mut self, slave: bool, address: u32, count: usize) -> Vec<u8> {
let aligned_count = count + (count % 16);
let cell_count = aligned_count * 2;
let mut data_buffer: Vec<u8> = alloc::vec![0; cell_count];
fn set_count_cyl(&mut self, sec_count: u8, cyl_low: u8, cyl_mid: u8, cyl_high: u8) {
#[cfg(feature = "debug")]
ata_log!(
"Setting registers: SECTOR_COUNT_LBA28({}), CYL_LOW_LBA28({}), CYL_MID_LBA28({}), CYL_HIGH_LBA28({})",
sec_count,
cyl_low,
cyl_mid,
cyl_high
);
let mut keep_reading = true;
self.write_reg_sector_count_lba28(sec_count);
self.write_reg_cyl_low_lba28(cyl_low);
self.write_reg_cyl_mid_lba28(cyl_mid);
self.write_reg_cyl_high_lba28(cyl_high);
}
let slave_bit: u32 = match slave {
true => 1,
false => 0
};
/// Reads `sector_count` sectors starting at `lba28_address`.
/// Each sector is 512 bytes.
pub fn read_bytes_lba28(
&mut self,
lba28_address: u32,
sector_count: usize
) -> Result<Vec<u8>, ATAPIODriverExceptions> {
#[cfg(feature = "debug")]
ata_log!("Attempting to read bytes via LBA28...");
let mut current_address = address;
let mut buffer_offset: usize = 0;
#[cfg(feature = "debug")]
ata_log!("Address:({:x}), sectors:({})", lba28_address, sector_count);
while keep_reading {
let device_value = (0xE0 | (slave_bit << 4) | ((current_address >> 24) & 0xF)) as u8;
self.write_reg_drive(device_value);
self.write_reg_sector_count_lba28(count as u8);
self.write_reg_cyl_low_lba28((current_address) as u8);
self.write_reg_cyl_mid_lba28((current_address >> 8) as u8);
self.write_reg_cyl_high_lba28((current_address >> 16) as u8);
if lba28_address >= 0x10000000 {
// LBA28 limit: 28-bit addressing
#[cfg(feature = "debug")]
ata_log!("The address of {:x} exceeded the 28-bit addressing limit!", lba28_address);
return Err(ATAPIODriverExceptions::AddressSpaceExceeded);
}
let mut remaining_sectors = sector_count;
let mut current_lba = lba28_address;
let mut data_buffer: Vec<u8> = Vec::with_capacity(sector_count * 512);
#[cfg(feature = "debug")]
ata_log!("Starting to read sectors...");
while remaining_sectors > 0 {
// ATA limits max sectors per READ SECTORS command to 255
let sectors_this_round = remaining_sectors.min(255);
remaining_sectors -= sectors_this_round;
#[cfg(feature = "debug")]
ata_log!("Reading {} sectors this round ({} remaining)...", sectors_this_round, remaining_sectors);
// Set up the drive/head register (top 4 bits of LBA in high nibble)
let drive_reg = ((current_lba >> 24) & 0x0F) as u8 | 0x40;
// LBA28 sector count & cylinder registers
let sec_count = sectors_this_round as u8;
let cyl_low = (current_lba & 0xFF) as u8;
let cyl_mid = ((current_lba >> 8) & 0xFF) as u8;
let cyl_high = ((current_lba >> 16) & 0xFF) as u8;
self.set_count_cyl(sec_count, cyl_low, cyl_mid, cyl_high);
#[cfg(feature = "debug")]
ata_log!("Setting up drive/head register...");
self.write_reg_drive(drive_reg);
#[cfg(feature = "debug")]
serial_println!(
"LBA28_READ_SECTORS: LBA={:#X}, sectors={}, DRV={:#X}",
current_lba, sectors_this_round, drive_reg
);
// Send READ SECTORS command
#[cfg(feature = "debug")]
ata_log!("Sending READ_SECTORS command...");
self.raw_send_command(0x20);
let _ = self.poll_device();
let buffer = self.raw_read_data_block();
for word in buffer {
for byte in word.to_be_bytes() {
if buffer_offset < cell_count {
data_buffer[buffer_offset] = byte;
buffer_offset += 1;
} else {
break;
}
// Poll per sector
#[cfg(feature = "debug")]
ata_log!("Polling for this sector...");
for _round in 0..sectors_this_round {
#[cfg(feature = "debug")]
ata_log!("Polling round {}", _round);
#[cfg(feature = "debug")]
ata_log!("Waiting for DRQ...");
self.poll_device()?; // wait for DRQ
#[cfg(feature = "debug")]
ata_log!("Reading words...");
let words = self.raw_read_data_block();
for word in words {
data_buffer.extend_from_slice(&word.to_be_bytes());
}
}
self.delay400ns();
#[cfg(feature = "debug")]
ata_log!("Polling finished for this block...");
let status = self.get_status();
keep_reading = status.data_ready && data_buffer.len() < cell_count;
current_lba += sectors_this_round as u32;
self.delay400ns();
}
data_buffer
#[cfg(feature = "debug")]
ata_log!("Reading complete!");
Ok(data_buffer)
}
/// Writes `data` to `sector_count` sectors starting at `lba28_address`.
/// Each sector is 512 bytes.
pub fn write_bytes_lba28(
&mut self,
lba28_address: u32,
data: &[u8],
sector_count: usize
) -> Result<(), ATAPIODriverExceptions> {
#[cfg(feature = "debug")]
ata_log!("Attempting to write bytes via LBA28...");
if lba28_address >= 0x10000000 {
return Err(ATAPIODriverExceptions::AddressSpaceExceeded);
}
if data.len() != sector_count * 512 {
return Err(ATAPIODriverExceptions::InvalidDataSize);
}
let mut remaining_sectors = sector_count;
let mut current_lba = lba28_address;
let mut data_offset = 0;
while remaining_sectors > 0 {
let sectors_this_round = remaining_sectors.min(255);
remaining_sectors -= sectors_this_round;
// Set up registers for write command
let drive_reg = ((current_lba >> 24) & 0x0F) as u8 | 0x40;
let sec_count = sectors_this_round as u8;
let cyl_low = (current_lba & 0xFF) as u8;
let cyl_mid = ((current_lba >> 8) & 0xFF) as u8;
let cyl_high = ((current_lba >> 16) & 0xFF) as u8;
self.set_count_cyl(sec_count, cyl_low, cyl_mid, cyl_high);
self.write_reg_drive(drive_reg);
// Send WRITE SECTORS command
self.raw_send_command(0x30);
// Write data for each sector
for _ in 0..sectors_this_round {
self.poll_device()?; // Wait for DRQ
// Write 256 words (512 bytes) per sector
for word_idx in 0..256 {
let byte_offset = data_offset + (word_idx * 2);
let word = u16::from_le_bytes([
data[byte_offset],
data[byte_offset + 1]
]);
self.write_reg_data(word);
}
data_offset += 512;
}
current_lba += sectors_this_round as u32;
self.delay400ns();
}
Ok(())
}
}
@@ -283,17 +588,37 @@ impl ATAPIODriver {
impl ATAPIODriver {
pub fn write_reg_data(&self, value: u16) {
let mut port: PortGeneric<u16, ReadWriteAccess> = Port::new(self.mapping.io_port + 0);
#[cfg(feature = "debug")]
ata_log!("WRITE<REG_DATA>({:x}) @ {:x}", value, self.mapping.io_port + 0);
unsafe { port.write(value) }
}
pub fn read_reg_data(&self) -> u16 {
let mut port: PortGeneric<u16, ReadWriteAccess> = Port::new(self.mapping.io_port + 0);
unsafe { port.read() }
let value = unsafe { port.read() };
// #[cfg(feature = "debug")]
// ata_log!("READ<REG_DATA>({}) @ {:x}", value, self.mapping.io_port + 0);
value
}
pub fn write_reg_drive(&self, v: u8) {
/// Write the Drive/Head register, automatically including master/slave selection
pub fn write_reg_drive(&self, value: u8) {
let dev_bit = match self.mapping.devsel {
DeviceSelect::Master => 0xA0, // Correct master select bit
DeviceSelect::Slave => 0xB0, // Correct slave select bit
};
let final_value = (value & 0x0F) | dev_bit | 0x40; // Lower nibble from value, upper from dev_bit
let mut port: PortGeneric<u8, ReadWriteAccess> = Port::new(self.mapping.io_port + 6);
unsafe { port.write(v) }
#[cfg(feature = "debug")]
ata_log!("WRITE<REG_DRIVE(DEV_BIT={:x})>(VALUE={:x}) @ {:x}", dev_bit, final_value, self.mapping.io_port + 6);
unsafe { port.write(final_value) }
}
/// Read the Drive/Head register (devsel bit is part of return value)
pub fn read_reg_drive(&self) -> u8 {
let mut port: PortGeneric<u8, ReadWriteAccess> = Port::new(self.mapping.io_port + 6);
unsafe { port.read() }
@@ -304,15 +629,22 @@ impl ATAPIODriver {
unsafe { port.read() }
}
pub fn write_reg_command(&self, v: u8) {
pub fn write_reg_command(&self, value: u8) {
let mut port: PortGeneric<u8, ReadWriteAccess> = Port::new(self.mapping.io_port + 7);
unsafe { port.write(v) }
#[cfg(feature = "debug")]
ata_log!("WRITE<REG_COMMAND>({:x}) @ {:x}", value, self.mapping.io_port + 7);
unsafe { port.write(value) }
}
}
// Control port stuff
impl ATAPIODriver {
pub fn disable_device_interrupts(&self) {
#[cfg(feature = "debug")]
ata_log!("!! Disabling interrupts !!");
let cs = self.read_reg_alt_status();
let cs_mod = cs & !(0b1 << 1);
self.write_reg_dev_ctl(cs_mod);
@@ -322,9 +654,15 @@ impl ATAPIODriver {
let cs = self.read_reg_alt_status();
let cs_mod = cs | (0b1 << 1);
self.write_reg_dev_ctl(cs_mod);
#[cfg(feature = "debug")]
ata_log!("!! Enabled interrupts !!");
}
pub fn soft_reset(&self) {
#[cfg(feature = "debug")]
ata_log!("Running soft reset...");
let cs = self.read_reg_alt_status();
let cs_mod = cs | (0b1 << 2);
self.write_reg_dev_ctl(cs_mod);
@@ -333,12 +671,18 @@ impl ATAPIODriver {
}
pub fn enable_high_order_byte(&self) {
#[cfg(feature = "debug")]
ata_log!("Enabling high_order_byte");
let cs = self.read_reg_alt_status();
let cs_mod = cs | (0b1 << 7);
self.write_reg_dev_ctl(cs_mod);
}
pub fn disable_high_order_byte(&self) {
#[cfg(feature = "debug")]
ata_log!("Disabling high_order_byte");
let cs = self.read_reg_alt_status();
let cs_mod = cs & !(0b1 << 7);
self.write_reg_dev_ctl(cs_mod);
@@ -352,6 +696,10 @@ impl ATAPIODriver {
}
pub fn write_reg_dev_ctl(&self, v: u8) {
let mut port: PortGeneric<u8, ReadWriteAccess> = Port::new(self.mapping.control_port + 0);
#[cfg(feature = "debug")]
ata_log!("WRITE<REG_COMMAND>({:x}) @ {:x}", v, self.mapping.control_port + 0);
#[cfg(feature = "debug")]
ata_log!("");
unsafe { port.write(v) }
}
@@ -370,11 +718,15 @@ impl ATAPIODriver {
pub fn write_reg_features_lba28(&self, value: u8) {
let mut port: PortGeneric<u8, ReadWriteAccess> = Port::new(self.mapping.io_port + 1);
#[cfg(feature = "debug")]
ata_log!("WRITE<REG_FEATURES_LBA28>({:x}) @ {:x}", value, self.mapping.io_port + 1);
unsafe { port.write(value) }
}
pub fn write_reg_sector_count_lba28(&self, v: u8) {
let mut port: PortGeneric<u8, ReadWriteAccess> = Port::new(self.mapping.io_port + 2);
#[cfg(feature = "debug")]
ata_log!("WRITE<REG_SECTOR_COUNT_LBA28>({:x}) @ {:x}", v, self.mapping.io_port + 2);
unsafe { port.write(v) }
}
pub fn read_reg_sector_count_lba28(&self) -> u8 {
@@ -384,6 +736,8 @@ impl ATAPIODriver {
pub fn write_reg_cyl_low_lba28(&self, v: u8) {
let mut port: PortGeneric<u8, ReadWriteAccess> = Port::new(self.mapping.io_port + 3);
#[cfg(feature = "debug")]
ata_log!("WRITE<REG_CYL_LOW_LBA28>({:x}) @ {:x}", v, self.mapping.io_port + 3);
unsafe { port.write(v) }
}
pub fn read_reg_cyl_low_lba28(&self) -> u8 {
@@ -393,6 +747,8 @@ impl ATAPIODriver {
pub fn write_reg_cyl_mid_lba28(&self, v: u8) {
let mut port: PortGeneric<u8, ReadWriteAccess> = Port::new(self.mapping.io_port + 4);
#[cfg(feature = "debug")]
ata_log!("WRITE<REG_CYL_MID_LBA28>({:x}) @ {:x}", v, self.mapping.io_port + 4);
unsafe { port.write(v) }
}
pub fn read_reg_cyl_mid_lba28(&self) -> u8 {
@@ -402,6 +758,8 @@ impl ATAPIODriver {
pub fn write_reg_cyl_high_lba28(&self, v: u8) {
let mut port: PortGeneric<u8, ReadWriteAccess> = Port::new(self.mapping.io_port + 5);
#[cfg(feature = "debug")]
ata_log!("WRITE<REG_CYL_HIGHLBA28>({:x}) @ {:x}", v, self.mapping.io_port + 5);
unsafe { port.write(v) }
}
pub fn read_reg_cyl_high_lba28(&self) -> u8 {
@@ -420,11 +778,15 @@ impl ATAPIODriver {
pub fn write_reg_features_lba48(&self, value: u16) {
let mut port: PortGeneric<u16, ReadWriteAccess> = Port::new(self.mapping.io_port + 1);
#[cfg(feature = "debug")]
ata_log!("WRITE<REG_FEATURES_LBA48>({:x}) @ {:x}", value, self.mapping.io_port + 1);
unsafe { port.write(value) }
}
pub fn write_reg_sector_count_lba48(&self, v: u16) {
let mut port: PortGeneric<u16, ReadWriteAccess> = Port::new(self.mapping.io_port + 2);
#[cfg(feature = "debug")]
ata_log!("WRITE<REG_SECTOR_COUNT_LBA48>({:x}) @ {:x}", v, self.mapping.io_port + 2);
unsafe { port.write(v) }
}
pub fn read_reg_sector_count_lba48(&self) -> u16 {
@@ -434,6 +796,8 @@ impl ATAPIODriver {
pub fn write_reg_cyl_low_lba48(&self, v: u16) {
let mut port: PortGeneric<u16, ReadWriteAccess> = Port::new(self.mapping.io_port + 3);
#[cfg(feature = "debug")]
ata_log!("WRITE<REG_CYL_LOW_LBA48>({:x}) @ {:x}", v, self.mapping.io_port + 3);
unsafe { port.write(v) }
}
pub fn read_reg_cyl_low_lba48(&self) -> u16 {
@@ -443,6 +807,8 @@ impl ATAPIODriver {
pub fn write_reg_cyl_mid_lba48(&self, v: u16) {
let mut port: PortGeneric<u16, ReadWriteAccess> = Port::new(self.mapping.io_port + 4);
#[cfg(feature = "debug")]
ata_log!("WRITE<REG_CYL_MID_LBA48>({:X}) @ {:x}", v, self.mapping.io_port + 4);
unsafe { port.write(v) }
}
pub fn read_reg_cyl_mid_lba48(&self) -> u16 {
@@ -452,6 +818,8 @@ impl ATAPIODriver {
pub fn write_reg_cyl_high_lba48(&self, v: u16) {
let mut port: PortGeneric<u16, ReadWriteAccess> = Port::new(self.mapping.io_port + 5);
#[cfg(feature = "debug")]
ata_log!("WRITE<REG_CYL_HIGH_LBA48>({:x}) @ {:x}", v, self.mapping.io_port + 5);
unsafe { port.write(v) }
}
pub fn read_reg_cyl_high_lba48(&self) -> u16 {
@@ -459,4 +827,45 @@ impl ATAPIODriver {
unsafe { port.read() }
}
}
impl ATAPIODriver {
pub fn set_power_standby(&mut self) -> Result<(), ATAPIODriverExceptions> {
self.raw_send_command(0xE2); // STANDBY command
self.poll_device()?;
Ok(())
}
pub fn set_power_idle(&mut self) -> Result<(), ATAPIODriverExceptions> {
self.raw_send_command(0xE3); // IDLE command
self.poll_device()?;
Ok(())
}
pub fn set_power_sleep(&mut self) -> Result<(), ATAPIODriverExceptions> {
self.raw_send_command(0xE6); // SLEEP command
self.poll_device()?;
Ok(())
}
}
impl ATAPIODriver {
pub fn flush_cache(&mut self) -> Result<(), ATAPIODriverExceptions> {
self.raw_send_command(0xE7); // FLUSH CACHE command
self.poll_device()?;
Ok(())
}
pub fn flush_cache_ext(&mut self) -> Result<(), ATAPIODriverExceptions> {
self.raw_send_command(0xEA); // FLUSH CACHE EXT command
self.poll_device()?;
Ok(())
}
}
fn timeout_compare(tick: usize, limit: Option<usize>) -> bool {
match limit {
Some(limit) => tick < limit,
None => true
}
}
View File
Whitespace-only changes.
+3 -2
View File
@@ -4,12 +4,13 @@
"arch": "x86_64",
"target-endian": "little",
"target-pointer-width": "64",
"target-c-int-width": "32",
"target-c-int-width": 32,
"os": "none",
"executables": true,
"linker-flavor": "ld.lld",
"linker": "rust-lld",
"panic-strategy": "abort",
"disable-redzone": true,
"features": "-mmx,-sse,+soft-float"
"features": "-mmx,-sse,+soft-float",
"rustc-abi": "x86-softfloat"
}