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