1 /*参考drivers/block/xd.c 2 *以及drivers/block/z2ram.c 3 */ 4 #include <linux/module.h> 5 #include <linux/errno.h> 6 #include <linux/interrupt.h> 7 #include <linux/mm.h> 8 #include <linux/fs.h> 9 #include <linux/kernel.h> 10 #include <linux/timer.h> 11 #include <linux/genhd.h> 12 #include <linux/hdreg.h> 13 #include <linux/ioport.h> 14 #include <linux/init.h> 15 #include <linux/wait.h> 16 #include <linux/blkdev.h> 17 #include <linux/mutex.h> 18 #include <linux/blkpg.h> 19 #include <linux/delay.h> 20 #include <linux/io.h> 21 #include <linux/gfp.h> 22 23 #include <asm/uaccess.h> 24 #include <asm/dma.h> 25 26 27 static struct gendisk *ramblock_disk; 28 static struct request_queue *ramblock_queue; 29 static DEFINE_SPINLOCK(ramblock_lock); 30 31 #define RAMBLOCKSIZE (1024*1024) 32 static int major; 33 static unsigned char *ramblock; 34 35 static int ramblock_getgeo(struct block_device *bdev, struct hd_geometry *geo) 36 { 37 38 geo->heads = 2; 39 geo->sectors = 32; 40 geo->cylinders = RAMBLOCKSIZE/2/32/512; 41 return 0; 42 } 43 44 static const struct block_device_operations ramblock_fops = { 45 .owner = THIS_MODULE, 46 .getgeo = ramblock_getgeo, 47 }; 48 49 static void do_ramblock_request (struct request_queue * q) 50 { 51 static int cnt = 0; 52 struct request *req; 53 54 printk("do_ramblock_request %d : ",++cnt); 55 req = blk_fetch_request(q); 56 while(req){ 57 unsigned long start = blk_rq_pos(req) << 9; //源 58 unsigned long len = blk_rq_cur_bytes(req); //长度 59 /*目的:req->buffer*/ 60 if (rq_data_dir(req) == READ) 61 memcpy(req->buffer, ramblock+start, len); 62 else 63 memcpy(ramblock+start, req->buffer, len); 64 65 if (!__blk_end_request_cur(req, 0)) 66 req = blk_fetch_request(q); 67 } 68 } 69 70 static int ramblock_init(void) 71 { 72 ramblock_disk = alloc_disk(16); //次设备号个数,分区数+1 73 74 ramblock_queue = blk_init_queue(do_ramblock_request, &ramblock_lock); 75 76 major = register_blkdev(0, "ramblock"); // /dev/ramblock 77 78 ramblock_disk->major = major; 79 ramblock_disk->first_minor = 0; 80 sprintf(ramblock_disk->disk_name, "ramblock"); 81 ramblock_disk->fops = &ramblock_fops; 82 ramblock_disk->queue = ramblock_queue; 83 set_capacity(ramblock_disk, RAMBLOCKSIZE/512); //设置容量,以扇区512字节为单位 84 85 ramblock = kzalloc(RAMBLOCKSIZE,GFP_KERNEL); 86 if(ramblock == NULL){ 87 printk("alloc ramblock failed! "); 88 return -1; 89 } 90 add_disk(ramblock_disk); 91 return 0; 92 } 93 94 static void ramblock_exit(void) 95 { 96 del_gendisk(ramblock_disk); 97 unregister_blkdev(major,"ramblock"); 98 blk_cleanup_queue(ramblock_queue); 99 put_disk(ramblock_disk); 100 kfree(ramblock); 101 } 102 103 module_init(ramblock_init); 104 module_exit(ramblock_exit); 105 106 MODULE_LICENSE("GPL"); 107 MODULE_AUTHOR("1653699780@qq.com");