Skip to content
systemcoding.dev
Kernels

Allocate a blk-mq disk with blk_mq_alloc_disk

Create a block device the modern way with blk_mq_alloc_tag_set and blk_mq_alloc_disk on Linux 6.12, which takes a queue_limits pointer since 6.9.

1 min read
Summarize in AI

A block driver on current kernels is built on blk-mq: a tag set describes the hardware queues, and the disk is allocated from it. In Linux 6.9 the call gained a queue_limits argument, so code written for 6.8 and earlier does not compile.

c
static struct blk_mq_tag_set demo_set;
static struct gendisk *demo_disk;

static int demo_create(void)
{
	int ret;

	demo_set.ops = &demo_mq_ops;
	demo_set.nr_hw_queues = 1;
	demo_set.queue_depth = 64;
	demo_set.numa_node = NUMA_NO_NODE;
	ret = blk_mq_alloc_tag_set(&demo_set);
	if (ret)
		return ret;

	demo_disk = blk_mq_alloc_disk(&demo_set, NULL, NULL);
	if (IS_ERR(demo_disk)) {
		blk_mq_free_tag_set(&demo_set);
		return PTR_ERR(demo_disk);
	}
	demo_disk->fops = &demo_fops;
	snprintf(demo_disk->disk_name, DISK_NAME_LEN, "demo0");
	set_capacity(demo_disk, 2048);
	return add_disk(demo_disk);
}
Shell
cat /sys/block/demo0/size
Text
2048

The two NULL arguments are the default limits and the queuedata pointer. The function returns an error pointer, so test it with IS_ERR. The disk is not visible until add_disk succeeds, and teardown is del_gendisk, put_disk and then blk_mq_free_tag_set, in that order. See the blk-mq documentation.

Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.