1 // SPDX-License-Identifier: GPL-2.0 2 3 //! This is a Rust implementation of the C null block driver. 4 5 mod configfs; 6 7 use configfs::IRQMode; 8 use kernel::{ 9 block::{ 10 self, 11 mq::{ 12 self, 13 gen_disk::{ 14 self, 15 GenDisk, // 16 }, 17 Operations, 18 TagSet, // 19 }, // 20 }, 21 prelude::*, 22 sync::{ 23 aref::ARef, 24 Arc, // 25 }, // 26 }; 27 28 module! { 29 type: NullBlkModule, 30 name: "rnull_mod", 31 authors: ["Andreas Hindborg"], 32 description: "Rust implementation of the C null block driver", 33 license: "GPL v2", 34 } 35 36 #[pin_data] 37 struct NullBlkModule { 38 #[pin] 39 configfs_subsystem: kernel::configfs::Subsystem<configfs::Config>, 40 } 41 42 impl kernel::InPlaceModule for NullBlkModule { 43 fn init(_module: &'static ThisModule) -> impl PinInit<Self, Error> { 44 pr_info!("Rust null_blk loaded\n"); 45 46 try_pin_init!(Self { 47 configfs_subsystem <- configfs::subsystem(), 48 }) 49 } 50 } 51 52 struct NullBlkDevice; 53 54 impl NullBlkDevice { 55 fn new( 56 name: &CStr, 57 block_size: u32, 58 rotational: bool, 59 capacity_mib: u64, 60 irq_mode: IRQMode, 61 ) -> Result<GenDisk<Self>> { 62 let tagset = Arc::pin_init(TagSet::new(1, 256, 1), GFP_KERNEL)?; 63 64 let queue_data = Box::new(QueueData { irq_mode }, GFP_KERNEL)?; 65 66 gen_disk::GenDiskBuilder::new() 67 .capacity_sectors(capacity_mib << (20 - block::SECTOR_SHIFT)) 68 .logical_block_size(block_size)? 69 .physical_block_size(block_size)? 70 .rotational(rotational) 71 .build(fmt!("{}", name.to_str()?), tagset, queue_data) 72 } 73 } 74 75 struct QueueData { 76 irq_mode: IRQMode, 77 } 78 79 #[vtable] 80 impl Operations for NullBlkDevice { 81 type QueueData = KBox<QueueData>; 82 83 #[inline(always)] 84 fn queue_rq(queue_data: &QueueData, rq: ARef<mq::Request<Self>>, _is_last: bool) -> Result { 85 match queue_data.irq_mode { 86 IRQMode::None => mq::Request::end_ok(rq) 87 .map_err(|_e| kernel::error::code::EIO) 88 // We take no refcounts on the request, so we expect to be able to 89 // end the request. The request reference must be unique at this 90 // point, and so `end_ok` cannot fail. 91 .expect("Fatal error - expected to be able to end request"), 92 IRQMode::Soft => mq::Request::complete(rq), 93 } 94 Ok(()) 95 } 96 97 fn commit_rqs(_queue_data: &QueueData) {} 98 99 fn complete(rq: ARef<mq::Request<Self>>) { 100 mq::Request::end_ok(rq) 101 .map_err(|_e| kernel::error::code::EIO) 102 // We take no refcounts on the request, so we expect to be able to 103 // end the request. The request reference must be unique at this 104 // point, and so `end_ok` cannot fail. 105 .expect("Fatal error - expected to be able to end request"); 106 } 107 } 108