如何从 Linux 内核模块读取磁盘的已知扇区

How can I read a known sector of a disk from Linux kernel module

在linux内核中,如果我们有一个指向磁盘“struct gendisk”的指针,那么我们如何从磁盘读取一个已知的扇区号。

这些功能对我有帮助。我使用 submit_bio 并向磁盘提交了个人简介。主要和次要应假定为 read_sector_thread_func

的输入
static struct bio * my_mpage_alloc(struct block_device *bdev,
                sector_t first_sector, int nr_vecs,
                gfp_t gfp_flags)
{
        struct bio *bio;

        bio = my_bio_alloc(gfp_flags, nr_vecs);

        if (bio == NULL && (current->flags & PF_MEMALLOC)) {
                while (!bio && (nr_vecs /= 2))
                        bio = my_bio_alloc(gfp_flags, nr_vecs);
        }

        if (bio) {
                //bio->bi_bdev = bdev;
                bio->bi_iter.bi_sector = first_sector;
        }
        return bio;
}

static void src_endio(struct bio *bio)
{
        if (bio->bi_private) {
                complete(bio->bi_private);
        }
        return;
}

static int read_sector_thread_func(void *data)
{
    struct block_device *r_bdev = NULL;
    struct bio *r_bio = NULL;
    struct page *page = NULL;
    int part = NULL;
    int len = 0;
    struct gendisk * disk = NULL;
    unsigned char * addr;
    u64 first_sector_num = 0;

    disk = get_gendisk(MKDEV(global_dev_major, global_dev_minor), &part);

    DECLARE_COMPLETION_ONSTACK(r_wait);

    page = alloc_pages(GFP_ATOMIC, 0);
    printk("%d : %s ", __LINE__, __func__);
    r_bio = my_mpage_alloc(r_bdev, first_sector_num, 1, GFP_ATOMIC);

    if(r_bio==NULL)
    {
        printk("bio is NULL");
        return;
    }

    bio_add_page(r_bio, page, 512, 0);
    r_bio->bi_private = &r_wait;
    r_bio->bi_end_io = src_endio;
    r_bio->bi_disk = disk;

    bio_associate_blkg(r_bio);
    bio_get(r_bio);
    bio_set_op_attrs(r_bio, REQ_OP_READ, 0);

    submit_bio(r_bio);

    wait_for_completion_io(&r_wait);

    bio_put(r_bio);
    return 0;
}