block.rs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. use crate::{
  2. bindings::root::{fs::block_device_read, EINVAL, EIO},
  3. KResult,
  4. };
  5. use super::vfs::DevId;
  6. pub fn make_device(major: u32, minor: u32) -> DevId {
  7. (major << 8) & 0xff00u32 | minor & 0xffu32
  8. }
  9. pub struct BlockDevice {
  10. device: DevId,
  11. }
  12. // pub struct BlockDeviceRequest<'lt> {
  13. // pub sector: u64, // Sector to read from, in 512-byte blocks
  14. // pub count: u64, // Number of sectors to read
  15. // pub buffer: &'lt [Page],
  16. // }
  17. pub struct BlockDeviceRequest<'lt> {
  18. pub sector: u64, // Sector to read from, in 512-byte blocks
  19. pub count: u64, // Number of sectors to read
  20. pub buffer: &'lt mut [u8],
  21. }
  22. impl BlockDevice {
  23. pub fn new(device: DevId) -> Self {
  24. BlockDevice { device }
  25. }
  26. pub fn devid(&self) -> DevId {
  27. self.device
  28. }
  29. pub fn read(&self, req: &mut BlockDeviceRequest) -> KResult<()> {
  30. // // Verify that the buffer is big enough
  31. // let buffer_size = req.buffer.iter().fold(0, |acc, e| acc + e.len());
  32. // if buffer_size / 512 < req.count as usize {
  33. // return Err(EINVAL);
  34. // }
  35. // Verify that the buffer is big enough
  36. if req.buffer.len() < req.count as usize * 512 {
  37. return Err(EINVAL);
  38. }
  39. let buffer = req.buffer.as_mut_ptr();
  40. let nread = unsafe {
  41. block_device_read(
  42. self.device as u32,
  43. buffer as *mut _,
  44. req.buffer.len(),
  45. req.sector as usize * 512,
  46. req.count as usize * 512,
  47. )
  48. };
  49. match nread {
  50. i if i < 0 => return Err(i as u32),
  51. i if i as u64 == req.count * 512 => Ok(()),
  52. _ => Err(EIO),
  53. }
  54. }
  55. }