virtio_blk.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. use core::{any::Any, fmt::Debug};
  2. use alloc::{
  3. collections::LinkedList,
  4. string::{String, ToString},
  5. sync::{Arc, Weak},
  6. vec::Vec,
  7. };
  8. use bitmap::traits::BitMapOps;
  9. use log::error;
  10. use system_error::SystemError;
  11. use unified_init::macros::unified_init;
  12. use virtio_drivers::device::blk::{VirtIOBlk, SECTOR_SIZE};
  13. use crate::{
  14. driver::{
  15. base::{
  16. block::{
  17. block_device::{BlockDevName, BlockDevice, BlockId, GeneralBlockRange, LBA_SIZE},
  18. disk_info::Partition,
  19. manager::{block_dev_manager, BlockDevMeta},
  20. },
  21. class::Class,
  22. device::{
  23. bus::Bus,
  24. driver::{Driver, DriverCommonData},
  25. Device, DeviceCommonData, DeviceId, DeviceType, IdTable,
  26. },
  27. kobject::{KObjType, KObject, KObjectCommonData, KObjectState, LockedKObjectState},
  28. kset::KSet,
  29. },
  30. virtio::{
  31. sysfs::{virtio_bus, virtio_device_manager, virtio_driver_manager},
  32. transport::VirtIOTransport,
  33. virtio_impl::HalImpl,
  34. VirtIODevice, VirtIODeviceIndex, VirtIODriver, VirtIODriverCommonData, VirtioDeviceId,
  35. VIRTIO_VENDOR_ID,
  36. },
  37. },
  38. exception::{irqdesc::IrqReturn, IrqNumber},
  39. filesystem::{kernfs::KernFSInode, mbr::MbrDiskPartionTable, sysfs::AttributeGroup},
  40. init::initcall::INITCALL_POSTCORE,
  41. libs::{
  42. rwlock::{RwLockReadGuard, RwLockWriteGuard},
  43. spinlock::{SpinLock, SpinLockGuard},
  44. },
  45. };
  46. const VIRTIO_BLK_BASENAME: &str = "virtio_blk";
  47. static mut VIRTIO_BLK_DRIVER: Option<Arc<VirtIOBlkDriver>> = None;
  48. #[inline(always)]
  49. #[allow(dead_code)]
  50. fn virtio_blk_driver() -> Arc<VirtIOBlkDriver> {
  51. unsafe { VIRTIO_BLK_DRIVER.as_ref().unwrap().clone() }
  52. }
  53. /// Get the first virtio block device
  54. #[allow(dead_code)]
  55. pub fn virtio_blk_0() -> Option<Arc<VirtIOBlkDevice>> {
  56. virtio_blk_driver()
  57. .devices()
  58. .first()
  59. .cloned()
  60. .map(|dev| dev.arc_any().downcast().unwrap())
  61. }
  62. pub fn virtio_blk(
  63. transport: VirtIOTransport,
  64. dev_id: Arc<DeviceId>,
  65. dev_parent: Option<Arc<dyn Device>>,
  66. ) {
  67. let device = VirtIOBlkDevice::new(transport, dev_id);
  68. if let Some(device) = device {
  69. if let Some(dev_parent) = dev_parent {
  70. device.set_dev_parent(Some(Arc::downgrade(&dev_parent)));
  71. }
  72. virtio_device_manager()
  73. .device_add(device.clone() as Arc<dyn VirtIODevice>)
  74. .expect("Add virtio blk failed");
  75. }
  76. }
  77. static mut VIRTIOBLK_MANAGER: Option<VirtIOBlkManager> = None;
  78. #[inline]
  79. fn virtioblk_manager() -> &'static VirtIOBlkManager {
  80. unsafe { VIRTIOBLK_MANAGER.as_ref().unwrap() }
  81. }
  82. #[unified_init(INITCALL_POSTCORE)]
  83. fn virtioblk_manager_init() -> Result<(), SystemError> {
  84. unsafe {
  85. VIRTIOBLK_MANAGER = Some(VirtIOBlkManager::new());
  86. }
  87. Ok(())
  88. }
  89. pub struct VirtIOBlkManager {
  90. inner: SpinLock<InnerVirtIOBlkManager>,
  91. }
  92. struct InnerVirtIOBlkManager {
  93. id_bmp: bitmap::StaticBitmap<{ VirtIOBlkManager::MAX_DEVICES }>,
  94. devname: [Option<BlockDevName>; VirtIOBlkManager::MAX_DEVICES],
  95. }
  96. impl VirtIOBlkManager {
  97. pub const MAX_DEVICES: usize = 25;
  98. pub fn new() -> Self {
  99. Self {
  100. inner: SpinLock::new(InnerVirtIOBlkManager {
  101. id_bmp: bitmap::StaticBitmap::new(),
  102. devname: [const { None }; Self::MAX_DEVICES],
  103. }),
  104. }
  105. }
  106. fn inner(&self) -> SpinLockGuard<InnerVirtIOBlkManager> {
  107. self.inner.lock()
  108. }
  109. pub fn alloc_id(&self) -> Option<BlockDevName> {
  110. let mut inner = self.inner();
  111. let idx = inner.id_bmp.first_false_index()?;
  112. inner.id_bmp.set(idx, true);
  113. let name = Self::format_name(idx);
  114. inner.devname[idx] = Some(name.clone());
  115. Some(name)
  116. }
  117. /// Generate a new block device name like 'vda', 'vdb', etc.
  118. fn format_name(id: usize) -> BlockDevName {
  119. let x = (b'a' + id as u8) as char;
  120. BlockDevName::new(format!("vd{}", x), id)
  121. }
  122. pub fn free_id(&self, id: usize) {
  123. if id >= Self::MAX_DEVICES {
  124. return;
  125. }
  126. self.inner().id_bmp.set(id, false);
  127. self.inner().devname[id] = None;
  128. }
  129. }
  130. /// virtio block device
  131. #[derive(Debug)]
  132. #[cast_to([sync] VirtIODevice)]
  133. #[cast_to([sync] Device)]
  134. pub struct VirtIOBlkDevice {
  135. blkdev_meta: BlockDevMeta,
  136. dev_id: Arc<DeviceId>,
  137. inner: SpinLock<InnerVirtIOBlkDevice>,
  138. locked_kobj_state: LockedKObjectState,
  139. self_ref: Weak<Self>,
  140. }
  141. unsafe impl Send for VirtIOBlkDevice {}
  142. unsafe impl Sync for VirtIOBlkDevice {}
  143. impl VirtIOBlkDevice {
  144. pub fn new(transport: VirtIOTransport, dev_id: Arc<DeviceId>) -> Option<Arc<Self>> {
  145. let devname = virtioblk_manager().alloc_id()?;
  146. let irq = transport.irq().map(|irq| IrqNumber::new(irq.data()));
  147. let device_inner = VirtIOBlk::<HalImpl, VirtIOTransport>::new(transport);
  148. if let Err(e) = device_inner {
  149. error!("VirtIOBlkDevice '{dev_id:?}' create failed: {:?}", e);
  150. return None;
  151. }
  152. let mut device_inner: VirtIOBlk<HalImpl, VirtIOTransport> = device_inner.unwrap();
  153. device_inner.enable_interrupts();
  154. let dev = Arc::new_cyclic(|self_ref| Self {
  155. blkdev_meta: BlockDevMeta::new(devname),
  156. self_ref: self_ref.clone(),
  157. dev_id,
  158. locked_kobj_state: LockedKObjectState::default(),
  159. inner: SpinLock::new(InnerVirtIOBlkDevice {
  160. device_inner,
  161. name: None,
  162. virtio_index: None,
  163. device_common: DeviceCommonData::default(),
  164. kobject_common: KObjectCommonData::default(),
  165. irq,
  166. }),
  167. });
  168. Some(dev)
  169. }
  170. fn inner(&self) -> SpinLockGuard<InnerVirtIOBlkDevice> {
  171. self.inner.lock()
  172. }
  173. }
  174. impl BlockDevice for VirtIOBlkDevice {
  175. fn dev_name(&self) -> &BlockDevName {
  176. &self.blkdev_meta.devname
  177. }
  178. fn blkdev_meta(&self) -> &BlockDevMeta {
  179. &self.blkdev_meta
  180. }
  181. fn disk_range(&self) -> GeneralBlockRange {
  182. let inner = self.inner();
  183. let blocks = inner.device_inner.capacity() as usize * SECTOR_SIZE / LBA_SIZE;
  184. drop(inner);
  185. log::debug!(
  186. "VirtIOBlkDevice '{:?}' disk_range: 0..{}",
  187. self.dev_name(),
  188. blocks
  189. );
  190. GeneralBlockRange::new(0, blocks).unwrap()
  191. }
  192. fn read_at_sync(
  193. &self,
  194. lba_id_start: BlockId,
  195. count: usize,
  196. buf: &mut [u8],
  197. ) -> Result<usize, SystemError> {
  198. let mut inner = self.inner();
  199. inner
  200. .device_inner
  201. .read_blocks(lba_id_start, &mut buf[..count * LBA_SIZE])
  202. .map_err(|e| {
  203. error!(
  204. "VirtIOBlkDevice '{:?}' read_at_sync failed: {:?}",
  205. self.dev_id, e
  206. );
  207. SystemError::EIO
  208. })?;
  209. Ok(count)
  210. }
  211. fn write_at_sync(
  212. &self,
  213. lba_id_start: BlockId,
  214. count: usize,
  215. buf: &[u8],
  216. ) -> Result<usize, SystemError> {
  217. self.inner()
  218. .device_inner
  219. .write_blocks(lba_id_start, &buf[..count * LBA_SIZE])
  220. .map_err(|_| SystemError::EIO)?;
  221. Ok(count)
  222. }
  223. fn sync(&self) -> Result<(), SystemError> {
  224. Ok(())
  225. }
  226. fn blk_size_log2(&self) -> u8 {
  227. 9
  228. }
  229. fn as_any_ref(&self) -> &dyn Any {
  230. self
  231. }
  232. fn device(&self) -> Arc<dyn Device> {
  233. self.self_ref.upgrade().unwrap()
  234. }
  235. fn block_size(&self) -> usize {
  236. todo!()
  237. }
  238. fn partitions(&self) -> Vec<Arc<Partition>> {
  239. let device = self.self_ref.upgrade().unwrap() as Arc<dyn BlockDevice>;
  240. let mbr_table = MbrDiskPartionTable::from_disk(device.clone())
  241. .expect("Failed to get MBR partition table");
  242. mbr_table.partitions(Arc::downgrade(&device))
  243. }
  244. }
  245. struct InnerVirtIOBlkDevice {
  246. device_inner: VirtIOBlk<HalImpl, VirtIOTransport>,
  247. name: Option<String>,
  248. virtio_index: Option<VirtIODeviceIndex>,
  249. device_common: DeviceCommonData,
  250. kobject_common: KObjectCommonData,
  251. irq: Option<IrqNumber>,
  252. }
  253. impl Debug for InnerVirtIOBlkDevice {
  254. fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
  255. f.debug_struct("InnerVirtIOBlkDevice").finish()
  256. }
  257. }
  258. impl VirtIODevice for VirtIOBlkDevice {
  259. fn irq(&self) -> Option<IrqNumber> {
  260. self.inner().irq
  261. }
  262. fn handle_irq(
  263. &self,
  264. _irq: crate::exception::IrqNumber,
  265. ) -> Result<IrqReturn, system_error::SystemError> {
  266. // todo: handle virtio blk irq
  267. Ok(crate::exception::irqdesc::IrqReturn::Handled)
  268. }
  269. fn dev_id(&self) -> &Arc<DeviceId> {
  270. &self.dev_id
  271. }
  272. fn set_device_name(&self, name: String) {
  273. self.inner().name = Some(name);
  274. }
  275. fn device_name(&self) -> String {
  276. self.inner()
  277. .name
  278. .clone()
  279. .unwrap_or_else(|| VIRTIO_BLK_BASENAME.to_string())
  280. }
  281. fn set_virtio_device_index(&self, index: VirtIODeviceIndex) {
  282. self.inner().virtio_index = Some(index);
  283. }
  284. fn virtio_device_index(&self) -> Option<VirtIODeviceIndex> {
  285. self.inner().virtio_index
  286. }
  287. fn device_type_id(&self) -> u32 {
  288. virtio_drivers::transport::DeviceType::Block as u32
  289. }
  290. fn vendor(&self) -> u32 {
  291. VIRTIO_VENDOR_ID.into()
  292. }
  293. }
  294. impl Device for VirtIOBlkDevice {
  295. fn dev_type(&self) -> DeviceType {
  296. DeviceType::Block
  297. }
  298. fn id_table(&self) -> IdTable {
  299. IdTable::new(VIRTIO_BLK_BASENAME.to_string(), None)
  300. }
  301. fn bus(&self) -> Option<Weak<dyn Bus>> {
  302. self.inner().device_common.bus.clone()
  303. }
  304. fn set_bus(&self, bus: Option<Weak<dyn Bus>>) {
  305. self.inner().device_common.bus = bus;
  306. }
  307. fn class(&self) -> Option<Arc<dyn Class>> {
  308. let mut guard = self.inner();
  309. let r = guard.device_common.class.clone()?.upgrade();
  310. if r.is_none() {
  311. guard.device_common.class = None;
  312. }
  313. return r;
  314. }
  315. fn set_class(&self, class: Option<Weak<dyn Class>>) {
  316. self.inner().device_common.class = class;
  317. }
  318. fn driver(&self) -> Option<Arc<dyn Driver>> {
  319. let r = self.inner().device_common.driver.clone()?.upgrade();
  320. if r.is_none() {
  321. self.inner().device_common.driver = None;
  322. }
  323. return r;
  324. }
  325. fn set_driver(&self, driver: Option<Weak<dyn Driver>>) {
  326. self.inner().device_common.driver = driver;
  327. }
  328. fn is_dead(&self) -> bool {
  329. false
  330. }
  331. fn can_match(&self) -> bool {
  332. self.inner().device_common.can_match
  333. }
  334. fn set_can_match(&self, can_match: bool) {
  335. self.inner().device_common.can_match = can_match;
  336. }
  337. fn state_synced(&self) -> bool {
  338. true
  339. }
  340. fn dev_parent(&self) -> Option<Weak<dyn Device>> {
  341. self.inner().device_common.get_parent_weak_or_clear()
  342. }
  343. fn set_dev_parent(&self, parent: Option<Weak<dyn Device>>) {
  344. self.inner().device_common.parent = parent;
  345. }
  346. }
  347. impl KObject for VirtIOBlkDevice {
  348. fn as_any_ref(&self) -> &dyn Any {
  349. self
  350. }
  351. fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
  352. self.inner().kobject_common.kern_inode = inode;
  353. }
  354. fn inode(&self) -> Option<Arc<KernFSInode>> {
  355. self.inner().kobject_common.kern_inode.clone()
  356. }
  357. fn parent(&self) -> Option<Weak<dyn KObject>> {
  358. self.inner().kobject_common.parent.clone()
  359. }
  360. fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
  361. self.inner().kobject_common.parent = parent;
  362. }
  363. fn kset(&self) -> Option<Arc<KSet>> {
  364. self.inner().kobject_common.kset.clone()
  365. }
  366. fn set_kset(&self, kset: Option<Arc<KSet>>) {
  367. self.inner().kobject_common.kset = kset;
  368. }
  369. fn kobj_type(&self) -> Option<&'static dyn KObjType> {
  370. self.inner().kobject_common.kobj_type
  371. }
  372. fn name(&self) -> String {
  373. self.device_name()
  374. }
  375. fn set_name(&self, _name: String) {
  376. // do nothing
  377. }
  378. fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
  379. self.locked_kobj_state.read()
  380. }
  381. fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
  382. self.locked_kobj_state.write()
  383. }
  384. fn set_kobj_state(&self, state: KObjectState) {
  385. *self.locked_kobj_state.write() = state;
  386. }
  387. fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
  388. self.inner().kobject_common.kobj_type = ktype;
  389. }
  390. }
  391. #[unified_init(INITCALL_POSTCORE)]
  392. fn virtio_blk_driver_init() -> Result<(), SystemError> {
  393. let driver = VirtIOBlkDriver::new();
  394. virtio_driver_manager()
  395. .register(driver.clone() as Arc<dyn VirtIODriver>)
  396. .expect("Add virtio block driver failed");
  397. unsafe {
  398. VIRTIO_BLK_DRIVER = Some(driver);
  399. }
  400. return Ok(());
  401. }
  402. #[derive(Debug)]
  403. #[cast_to([sync] VirtIODriver)]
  404. #[cast_to([sync] Driver)]
  405. struct VirtIOBlkDriver {
  406. inner: SpinLock<InnerVirtIOBlkDriver>,
  407. kobj_state: LockedKObjectState,
  408. }
  409. impl VirtIOBlkDriver {
  410. pub fn new() -> Arc<Self> {
  411. let inner = InnerVirtIOBlkDriver {
  412. virtio_driver_common: VirtIODriverCommonData::default(),
  413. driver_common: DriverCommonData::default(),
  414. kobj_common: KObjectCommonData::default(),
  415. };
  416. let id_table = VirtioDeviceId::new(
  417. virtio_drivers::transport::DeviceType::Block as u32,
  418. VIRTIO_VENDOR_ID.into(),
  419. );
  420. let result = VirtIOBlkDriver {
  421. inner: SpinLock::new(inner),
  422. kobj_state: LockedKObjectState::default(),
  423. };
  424. result.add_virtio_id(id_table);
  425. return Arc::new(result);
  426. }
  427. fn inner(&self) -> SpinLockGuard<InnerVirtIOBlkDriver> {
  428. return self.inner.lock();
  429. }
  430. }
  431. #[derive(Debug)]
  432. struct InnerVirtIOBlkDriver {
  433. virtio_driver_common: VirtIODriverCommonData,
  434. driver_common: DriverCommonData,
  435. kobj_common: KObjectCommonData,
  436. }
  437. impl VirtIODriver for VirtIOBlkDriver {
  438. fn probe(&self, device: &Arc<dyn VirtIODevice>) -> Result<(), SystemError> {
  439. let dev = device
  440. .clone()
  441. .arc_any()
  442. .downcast::<VirtIOBlkDevice>()
  443. .map_err(|_| {
  444. error!(
  445. "VirtIOBlkDriver::probe() failed: device is not a VirtIO block device. Device: '{:?}'",
  446. device.name()
  447. );
  448. SystemError::EINVAL
  449. })?;
  450. block_dev_manager().register(dev as Arc<dyn BlockDevice>)?;
  451. return Ok(());
  452. }
  453. fn virtio_id_table(&self) -> LinkedList<crate::driver::virtio::VirtioDeviceId> {
  454. self.inner().virtio_driver_common.id_table.clone()
  455. }
  456. fn add_virtio_id(&self, id: VirtioDeviceId) {
  457. self.inner().virtio_driver_common.id_table.push_back(id);
  458. }
  459. }
  460. impl Driver for VirtIOBlkDriver {
  461. fn id_table(&self) -> Option<IdTable> {
  462. Some(IdTable::new(VIRTIO_BLK_BASENAME.to_string(), None))
  463. }
  464. fn add_device(&self, device: Arc<dyn Device>) {
  465. let iface = device
  466. .arc_any()
  467. .downcast::<VirtIOBlkDevice>()
  468. .expect("VirtIOBlkDriver::add_device() failed: device is not a VirtIOBlkDevice");
  469. self.inner()
  470. .driver_common
  471. .devices
  472. .push(iface as Arc<dyn Device>);
  473. }
  474. fn delete_device(&self, device: &Arc<dyn Device>) {
  475. let _iface = device
  476. .clone()
  477. .arc_any()
  478. .downcast::<VirtIOBlkDevice>()
  479. .expect("VirtIOBlkDriver::delete_device() failed: device is not a VirtIOBlkDevice");
  480. let mut guard = self.inner();
  481. let index = guard
  482. .driver_common
  483. .devices
  484. .iter()
  485. .position(|dev| Arc::ptr_eq(device, dev))
  486. .expect("VirtIOBlkDriver::delete_device() failed: device not found");
  487. guard.driver_common.devices.remove(index);
  488. }
  489. fn devices(&self) -> Vec<Arc<dyn Device>> {
  490. self.inner().driver_common.devices.clone()
  491. }
  492. fn bus(&self) -> Option<Weak<dyn Bus>> {
  493. Some(Arc::downgrade(&virtio_bus()) as Weak<dyn Bus>)
  494. }
  495. fn set_bus(&self, _bus: Option<Weak<dyn Bus>>) {
  496. // do nothing
  497. }
  498. }
  499. impl KObject for VirtIOBlkDriver {
  500. fn as_any_ref(&self) -> &dyn Any {
  501. self
  502. }
  503. fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
  504. self.inner().kobj_common.kern_inode = inode;
  505. }
  506. fn inode(&self) -> Option<Arc<KernFSInode>> {
  507. self.inner().kobj_common.kern_inode.clone()
  508. }
  509. fn parent(&self) -> Option<Weak<dyn KObject>> {
  510. self.inner().kobj_common.parent.clone()
  511. }
  512. fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
  513. self.inner().kobj_common.parent = parent;
  514. }
  515. fn kset(&self) -> Option<Arc<KSet>> {
  516. self.inner().kobj_common.kset.clone()
  517. }
  518. fn set_kset(&self, kset: Option<Arc<KSet>>) {
  519. self.inner().kobj_common.kset = kset;
  520. }
  521. fn kobj_type(&self) -> Option<&'static dyn KObjType> {
  522. self.inner().kobj_common.kobj_type
  523. }
  524. fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
  525. self.inner().kobj_common.kobj_type = ktype;
  526. }
  527. fn name(&self) -> String {
  528. VIRTIO_BLK_BASENAME.to_string()
  529. }
  530. fn set_name(&self, _name: String) {
  531. // do nothing
  532. }
  533. fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
  534. self.kobj_state.read()
  535. }
  536. fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
  537. self.kobj_state.write()
  538. }
  539. fn set_kobj_state(&self, state: KObjectState) {
  540. *self.kobj_state.write() = state;
  541. }
  542. }