BIO bi_sector submit_bio make_request_fn

本文主要探讨Linux中bio结构里bi_sector字段的含义。在读写block device时,该字段表示设备地址,以512字节扇区为单位。对于硬盘和分区,在make_request_fn中,它代表真实的物理扇区位置。同时提到submit_bio时,操作分区时该字段可能会改变,还给出了相关源代码分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

BIO结构中有一个很重要的字段叫做bi_sector,在高版本中这个字段已经叫bi_iter.bi_sector了,这个不是重点,重点是下面要说的。

当读写一个block device的时候,会提交一个bio数据结构给make_request_fn,那么这个bio结构中的bi_sector到底表示什么意思呢?

在bio.h中有这么一行注释

sector_t        bi_sector;    /* device address in 512 byte  sectors */

大意是说bi_sector是设备的地址,什么地址?以sector(512字节)为单位,也就是说以这个sector为起始地址,去block设备请求数据。

一般硬盘都是以扇区(sector)为单位的,而且一般也只有硬盘有扇区,Linux中的分区比如/dev/sda1是建立在硬盘/dev/sda的基础上的,对于每一个分区来讲,我们通过fdisk来查看分区的细节信息,如下:

Device     Boot   Start      End  Sectors  Size Id Type
/dev/sda1  *       2048   999423   997376  487M 83 Linux
/dev/sda2       1001470 41940991 40939522 19.5G  5 Extended

硬盘sda有两个分区,分别是/dev/sda1和/dev/sda2,值得注意的是,分区/dev/sda1的起始扇区是2048,/dev/sda2的起始分区是1001470,这个起始扇区在本文中非常重要

对于硬盘来讲,在make_request_fn中,bio的bi_sector代表什么呢?

代表的就是硬盘的扇区,比如bi_sector为0,则表示从0扇区开始读取或者写入数据。

对于分区来讲,在make_request_fn中,bio的bi_sector又代表什么呢?

同样,比如bio的bi_sector为0,还是表示从0扇区开始读取或者写入数据。只是,make_request_fn中很难收到这样的请求了,除非这个分区的起始扇区为0。为什么呢?这就是起始扇区的原因,对于分区来讲,收到的bio请求中,这个bi_sector总是大于等于起始扇区的,比如对于/dev/sda2来讲,收到的请求中的bi_sector总是大于等于1001470的。

总结一下,无论是硬盘还是分区,在make_request_fn中,收到的bio请求中的bi_sector已经是真实对应硬盘的物理扇区位置了。

再说一下submit_bio,

我们可以自己构建一个bio,然后调用submit_bio去直接对block设备读取或者写入数据,特别要注意的是,通过submit_bio出去的bio中的bi_sector是有可能会被改变的,如果操作的是分区,在真正提交到make_request_fn之前,会被加上该分区对应的起始扇区的,特别需要注意。

看看源代码,以2.6为例,注意黑体部分

void submit_bio(int rw, struct bio *bio)
{
    int count = bio_sectors(bio);

    bio->bi_rw |= rw;

    /*
     * If it's a regular read/write or a barrier with data attached,
     * go through the normal accounting stuff before submission.
     */
    if (bio_has_data(bio)) {
        if (rw & WRITE) {
            count_vm_events(PGPGOUT, count);
        } else {
            task_io_account_read(bio->bi_size);
            count_vm_events(PGPGIN, count);
        }

        if (unlikely(block_dump)) {
            char b[BDEVNAME_SIZE];
            printk(KERN_DEBUG "%s(%d): %s block %Lu on %s\n",
            current->comm, task_pid_nr(current),
                (rw & WRITE) ? "WRITE" : "READ",
                (unsigned long long)bio->bi_sector,
                bdevname(bio->bi_bdev, b));
        }
    }

    generic_make_request(bio);
}

void generic_make_request(struct bio *bio)
{
    if (current->bio_tail) {
        /* make_request is active */
        *(current->bio_tail) = bio;
        bio->bi_next = NULL;
        current->bio_tail = &bio->bi_next;
        return;
    }
    /* following loop may be a bit non-obvious, and so deserves some
     * explanation.
     * Before entering the loop, bio->bi_next is NULL (as all callers
     * ensure that) so we have a list with a single bio.
     * We pretend that we have just taken it off a longer list, so
     * we assign bio_list to the next (which is NULL) and bio_tail
     * to &bio_list, thus initialising the bio_list of new bios to be
     * added.  __generic_make_request may indeed add some more bios
     * through a recursive call to generic_make_request.  If it
     * did, we find a non-NULL value in bio_list and re-enter the loop
     * from the top.  In this case we really did just take the bio
     * of the top of the list (no pretending) and so fixup bio_list and
     * bio_tail or bi_next, and call into __generic_make_request again.
     *
     * The loop was structured like this to make only one call to
     * __generic_make_request (which is important as it is large and
     * inlined) and to keep the structure simple.
     */
    BUG_ON(bio->bi_next);
    do {
        current->bio_list = bio->bi_next;
        if (bio->bi_next == NULL)
            current->bio_tail = &current->bio_list;
        else
            bio->bi_next = NULL;
        __generic_make_request(bio);
        bio = current->bio_list;
    } while (bio);
    current->bio_tail = NULL; /* deactivate */
}

static inline void __generic_make_request(struct bio *bio)
{
    struct request_queue *q;
    sector_t old_sector;
    int ret, nr_sectors = bio_sectors(bio);
    dev_t old_dev;
    int err = -EIO;

    might_sleep();

    if (bio_check_eod(bio, nr_sectors))
        goto end_io;

    /*
     * Resolve the mapping until finished. (drivers are
     * still free to implement/resolve their own stacking
     * by explicitly returning 0)
     *
     * NOTE: we don't repeat the blk_size check for each new device.
     * Stacking drivers are expected to know what they are doing.
     */
    old_sector = -1;
    old_dev = 0;
    do {
        char b[BDEVNAME_SIZE];

        q = bdev_get_queue(bio->bi_bdev);
        if (unlikely(!q)) {
            printk(KERN_ERR
                   "generic_make_request: Trying to access "
                "nonexistent block-device %s (%Lu)\n",
                bdevname(bio->bi_bdev, b),
                (long long) bio->bi_sector);
            goto end_io;
        }

        if (unlikely(!bio_rw_flagged(bio, BIO_RW_DISCARD) &&
                 nr_sectors > queue_max_hw_sectors(q))) {
            printk(KERN_ERR "bio too big device %s (%u > %u)\n",
                   bdevname(bio->bi_bdev, b),
                   bio_sectors(bio),
                   queue_max_hw_sectors(q));
            goto end_io;
        }

        if (unlikely(test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)))
            goto end_io;

        if (should_fail_request(bio))
            goto end_io;

        /*
         * If this device has partitions, remap block n
         * of partition p to block n+start(p) of the disk.
         */
        blk_partition_remap(bio);

        if (bio_integrity_enabled(bio) && bio_integrity_prep(bio))
            goto end_io;

        if (old_sector != -1)
            trace_block_remap(q, bio, old_dev, old_sector);

        old_sector = bio->bi_sector;
        old_dev = bio->bi_bdev->bd_dev;

        if (bio_check_eod(bio, nr_sectors))
            goto end_io;

        if (bio_rw_flagged(bio, BIO_RW_DISCARD) &&
            !blk_queue_discard(q)) {
            err = -EOPNOTSUPP;
            goto end_io;
        }

        trace_block_bio_queue(q, bio);

        ret = q->make_request_fn(q, bio);
    } while (ret);

    return;

end_io:
    bio_endio(bio, err);
}

 

*
 * If bio->bi_dev is a partition, remap the location
 */
static inline void blk_partition_remap(struct bio *bio)
{
    struct block_device *bdev = bio->bi_bdev;

    if (bio_sectors(bio) && bdev != bdev->bd_contains) {
        struct hd_struct *p = bdev->bd_part;

        bio->bi_sector += p->start_sect;
        bio->bi_bdev = bdev->bd_contains;

        trace_block_remap(bdev_get_queue(bio->bi_bdev), bio,
                    bdev->bd_dev,
                    bio->bi_sector - p->start_sect);
    }
}
 

这是现在的代码#include <linux/module.h> #include <linux/kernel.h> #include <linux/proc_fs.h> #include <linux/fs.h> #include <linux/blkdev.h> #include <linux/bio.h> #include <linux/random.h> #include <linux/version.h> #include <linux/slab.h> #define DEV_NAME "sda1" #define START_BYTE (562 * 1024 * 1024) #define END_BYTE (818 * 1024 * 1024) static struct gendisk *target_disk; static struct block_device *target_bdev; static int trigger_enabled = 0; static unsigned long error_count = 0; static struct proc_dir_entry *trigger_proc; static unsigned int logical_block_size = 512; // 多版本API支持 #if LINUX_VERSION_CODE >= KERNEL_VERSION(5,9,0) typedef blk_qc_t (submit_bio_t)(struct bio *bio); static submit_bio_t *orig_submit_bio; #else typedef blk_qc_t (make_request_fn_t)(struct request_queue *q, struct bio *bio); static make_request_fn_t *orig_make_request_fn; #endif // 创建可修改的fops副本 static struct block_device_operations *modified_fops = NULL; // 处理/proc/trigger_io写入 static ssize_t trigger_io_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { char cmd[32]; // 检查用户空间指针有效性 if (!buf) return -EFAULT; // 从用户空间复制数据 if (copy_from_user(cmd, buf, min(count, sizeof(cmd)-1))) return -EFAULT; // 确保字符串终止 cmd[min(count, sizeof(cmd)-1)] = '\0'; // 命令解析 if (strcmp(cmd, "enable") == 0 || strcmp(cmd, "1") == 0) { trigger_enabled = 1; printk(KERN_INFO "I/O error trigger ENABLED\n"); } else if (strcmp(cmd, "disable") == 0 || strcmp(cmd, "0") == 0) { trigger_enabled = 0; printk(KERN_INFO "I/O error trigger DISABLED\n"); } else if (strcmp(cmd, "reset") == 0) { error_count = 0; printk(KERN_INFO "Error counter reset\n"); } else { printk(KERN_WARNING "Unknown command: %s\n", cmd); return -EINVAL; // 无效命令返回错误 } // 必须返回写入的字节数 return count; } // 处理/proc/trigger_io读取 static ssize_t trigger_io_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { char status[128]; int len; // 生成状态信息 len = snprintf(status, sizeof(status), "Status: %s\nError count: %lu\nTarget device: %s\nRange: %uMB-%uMB\nSector size: %u\n", trigger_enabled ? "ENABLED" : "DISABLED", error_count, DEV_NAME, START_BYTE/(1024*1024), END_BYTE/(1024*1024), logical_block_size); // 使用内核辅助函数返回数据 return simple_read_from_buffer(buf, count, ppos, status, len); } static const struct proc_ops trigger_io_fops = { .proc_read = trigger_io_read, .proc_write = trigger_io_write, }; // Linux 5.9+ 使用submit_bio API #if LINUX_VERSION_CODE >= KERNEL_VERSION(5,9,0) static void modified_submit_bio(struct bio *bio) { if (trigger_enabled && bio->bi_disk && bio->bi_disk == target_disk) { sector_t sector = bio->bi_iter.bi_sector; unsigned long byte_offset = (unsigned long)(sector * logical_block_size); if (byte_offset >= START_BYTE && byte_offset <= END_BYTE) { if (get_random_u32() % 2 == 0) { printk(KERN_INFO "Injecting I/O error at sector %llu\n", (u64)sector); bio->bi_status = BLK_STS_IOERR; bio_endio(bio); error_count++; return; } } } orig_submit_bio(bio); } // Linux <5.9 使用make_request_fn API #else static blk_qc_t modified_make_request(struct request_queue *q, struct bio *bio) { if (trigger_enabled && bio->bi_disk && bio->bi_disk == target_disk) { sector_t sector = bio->bi_iter.bi_sector; unsigned long byte_offset = (unsigned long)(sector * logical_block_size); if (byte_offset >= START_BYTE && byte_offset <= END_BYTE) { if (get_random_u32() % 2 == 0) { printk(KERN_INFO "Injecting I/O error at sector %llu\n", (u64)sector); bio->bi_status = BLK_STS_IOERR; bio_endio(bio); error_count++; return BLK_QC_T_NONE; } } } return orig_make_request_fn(q, bio); } #endif static int __init trigger_io_init(void) { int ret = 0; struct request_queue *q = NULL; // 声明提前 // 获取块设备 target_bdev = blkdev_get_by_dev(MKDEV(8, 1), FMODE_READ, NULL); if (IS_ERR(target_bdev)) { ret = PTR_ERR(target_bdev); printk(KERN_ERR "Failed to get block device for %s, error %d\n", DEV_NAME, ret); return ret; } target_disk = target_bdev->bd_disk; if (!target_disk) { printk(KERN_ERR "Failed to get gendisk for %s\n", DEV_NAME); blkdev_put(target_bdev, FMODE_READ); return -ENODEV; } q = bdev_get_queue(target_bdev); if (!q) { printk(KERN_ERR "Failed to get request queue for %s\n", DEV_NAME); blkdev_put(target_bdev, FMODE_READ); return -ENODEV; } logical_block_size = queue_logical_block_size(q); printk(KERN_INFO "Device %s logical block size: %u\n", DEV_NAME, logical_block_size); // 内核版本适配 (Linux 5.9+) #if LINUX_VERSION_CODE >= KERNEL_VERSION(5,9,0) // 创建fops的副本 modified_fops = kmemdup(target_disk->fops, sizeof(*modified_fops), GFP_KERNEL); if (!modified_fops) { printk(KERN_ERR "Failed to allocate fops copy\n"); blkdev_put(target_bdev, FMODE_READ); return -ENOMEM; } // 保存原始函数指针 orig_submit_bio = modified_fops->submit_bio; // 修改副本中的函数指针 modified_fops->submit_bio = modified_submit_bio; // 替换整个fops结构 target_disk->fops = modified_fops; #else // Linux <5.9 使用传统方法 orig_make_request_fn = q->make_request_fn; WRITE_ONCE(q->make_request_fn, modified_make_request); #endif // 创建/proc文件 trigger_proc = proc_create("trigger_io", 0644, NULL, &trigger_io_fops); if (!trigger_proc) { printk(KERN_ERR "Failed to create /proc/trigger_io\n"); #if LINUX_VERSION_CODE >= KERNEL_VERSION(5,9,0) target_disk->fops->submit_bio = orig_submit_bio; #else WRITE_ONCE(q->make_request_fn, orig_make_request_fn); #endif blkdev_put(target_bdev, FMODE_READ); return -ENOMEM; } printk(KERN_INFO "I/O trigger module loaded for %s\n", DEV_NAME); return 0; } static void __exit trigger_io_exit(void) { if (target_bdev) { #if LINUX_VERSION_CODE >= KERNEL_VERSION(5,9,0) // 恢复原始fops if (modified_fops) { target_disk->fops = modified_fops->submit_bio; kfree(modified_fops); modified_fops = NULL; } #else // 恢复传统方法 struct request_queue *q = bdev_get_queue(target_bdev); if (q && orig_make_request_fn) { WRITE_ONCE(q->make_request_fn, orig_make_request_fn); } #endif blkdev_put(target_bdev, FMODE_READ); } if (trigger_proc) { proc_remove(trigger_proc); } printk(KERN_INFO "I/O trigger module unloaded\n"); } module_init(trigger_io_init); module_exit(trigger_io_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Your Name"); MODULE_DESCRIPTION("Controlled I/O error trigger"); 编译报错/k_trigger_io.c:184:35: error: assignment to 'blk_qc_t (*)(struct bio *)' {aka 'unsigned int (*)(struct bio *)'} from incompatible pointer type 'void (*)(struct bio *)' [-Werror=incompatible-pointer-types] 184 | modified_fops->submit_bio = modified_submit_bio; | ^ /home/bba/projects/nvr/repo_reconstruct/torchlight/build_dir/linux-mstar_msr931/tp_k_trigger_io/k_trigger_io.c:199:43: error: assignment of member 'submit_bio' in read-only object 199 | target_disk->fops->submit_bio = orig_submit_bio;
最新发布
08-08
/k_trigger_io.c:107:19: error: too many arguments to function 'blkdev_get_by_dev' 107 | target_bdev = blkdev_get_by_dev(MKDEV(8, 1), FMODE_READ, NULL, NULL); | ^~~~~~~~~~~~~~~~~ In file included from /home/bba/projects/nvr/repo_reconstruct/torchlight/build_dir/linux-mstar_msr931/tp_k_trigger_io/k_trigger_io.c:5: /home/bba/projects/nvr/repo_reconstruct/sstar931/linux-5.10.61/include/linux/blkdev.h:2006:22: note: declared here 2006 | struct block_device *blkdev_get_by_dev(dev_t dev, fmode_t mode, void *holder); | ^~~~~~~~~~~~~~~~~ /home/bba/projects/nvr/repo_reconstruct/torchlight/build_dir/linux-mstar_msr931/tp_k_trigger_io/k_trigger_io.c:127:43: error: 'struct request_queue' has no member named 'make_request_fn' 127 | orig_make_request = target_disk->queue->make_request_fn; | ^~ /home/bba/projects/nvr/repo_reconstruct/torchlight/build_dir/linux-mstar_msr931/tp_k_trigger_io/k_trigger_io.c:128:23: error: 'struct request_queue' has no member named 'make_request_fn' 128 | target_disk->queue->make_request_fn = modified_make_request; | ^~ /home/bba/projects/nvr/repo_reconstruct/torchlight/build_dir/linux-mstar_msr931/tp_k_trigger_io/k_trigger_io.c:135:27: error: 'struct request_queue' has no member named 'make_request_fn' 135 | target_disk->queue->make_request_fn = orig_make_request; | ^~ /home/bba/projects/nvr/repo_reconstruct/torchlight/build_dir/linux-mstar_msr931/tp_k_trigger_io/k_trigger_io.c: In function 'trigger_io_exit': /home/bba/projects/nvr/repo_reconstruct/torchlight/build_dir/linux-mstar_msr931/tp_k_trigger_io/k_trigger_io.c:148:27: error: 'struct request_queue' has no member named 'make_request_fn' 148 | target_disk->queue->make_request_fn = orig_make_request;
08-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Simple-Soft

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值