Skip to contentSkip to conversation

ublk: add io_uring based userspace block driver

PATCH Superseded Ming Lei 4 participants 18 messages Jun 28, 2022 – Jul 7, 2022

Subsystems (4)

v3 of 5 Superseded Latest is v5 →

lore
Share & tools
lore

Ming Lei

author
#0 lore raw

v3 cover ublk: add io_uring based userspace block driver

Hello Guys,

ublk driver is one kernel driver for implementing generic userspace block device/driver, which delivers io request from ublk block device(/dev/ublkbN) into ublk server[1] which is the userspace part of ublk for communicating with ublk driver and handling specific io logic by its target module.

Another thing ublk driver handles is to copy data between user space buffer and request/bio's pages, or take zero copy if mm is ready for support it in future. ublk driver doesn't handle any IO logic of the specific driver, so it is small/simple, and all io logics are done by the target code in ublkserver.

The above two are main jobs done by ublk driver.

ublk driver can help to move IO logic into userspace, in which the development work is easier/more effective than doing in kernel, such as, ublk-loop takes < 200 lines of loop specific code to get basically same function with kernel loop block driver, meantime the performance is is even better than kernel loop with same setting. ublksrv[1] provide built-in test for comparing both by running "make test T=loop", for example, see the test result running on VM which is over my lattop(root disk is nvme/device mapper/xfs):

	[root@ktest-36 ubdsrv]#make -s -C /root/git/ubdsrv/tests run T=loop/001 R=10
	running loop/001
		fio (ublk/loop(/root/git/ubdsrv/tests/tmp/ublk_loop_VqbMA), libaio, bs 4k, dio, hw queues:1)...
		randwrite: jobs 1, iops 32572
		randread: jobs 1, iops 143052
		rw: jobs 1, iops read 29919 write 29964
	
	[root@ktest-36 ubdsrv]# make test T=loop/003
	make -s -C /root/git/ubdsrv/tests run T=loop/003 R=10
	running loop/003
		fio (kernel_loop/kloop(/root/git/ubdsrv/tests/tmp/ublk_loop_ZIVnG), libaio, bs 4k, dio, hw queues:1)...
		randwrite: jobs 1, iops 27436
		randread: jobs 1, iops 95273
		rw: jobs 1, iops read 22542 write 22543 

Another example is high performance qcow2 support[2], which could be built with ublk framework more easily than doing it inside kernel.

Also there are more people who express interests on userspace block driver[3], Gabriel Krisman Bertazi proposes this topic in lsf/mm/ebpf 2022 and mentioned requirement from Google. Ziyang Zhang from Alibaba said they "plan to replace TCMU by UBD as a new choice" because UBD can get better throughput than TCMU even with single queue[4], meantime UBD is simple. Also there is userspace storage service for providing storage to containers.

It is io_uring based: io request is delivered to userspace via new added io_uring command which has been proved as very efficient for making nvme passthrough IO to get better IOPS than io_uring(READ/WRITE). Meantime one shared/mmap buffer is used for sharing io descriptor to userspace, the buffer is readonly for userspace, each IO just takes 24bytes so far. It is suggested to use io_uring in userspace(target part of ublk server) to handle IO request too. And it is still easy for ublkserver to support io handling by non-io_uring, and this work isn't done yet, but can be supported easily with help o eventfd.

This way is efficient since no extra io command copy is required, no sleep is needed in transferring io command to userspace. Meantime the communication protocol is simple and efficient, one single command of UBD_IO_COMMIT_AND_FETCH_REQ can handle both fetching io request desc and commit command result in one trip. IO handling is often batched after single io_uring_enter() returns, both IO requests from ublk server target and IO commands could be handled as a whole batch.

And the patch by patch change can be found in the following tree:

https://github.com/ming1/linux/tree/my_for-5.20-ubd-devel_v3

ublk server repo:

https://github.com/ming1/ubdsrv

Any comments are welcome!

Since V2:
- fix one big performance problem:

	https://github.com/ming1/linux/commit/3c9fd476951759858cc548dee4cedc074194d0b0

- rename as ublk, as suggested by Gabriel Krisman Bertazi
- lots of cleanup & code improvement & bugfix, see details in git hisotry

Since V1:

Remove RFC now because ublk driver codes gets lots of cleanup, enhancement and bug fixes since V1:

- cleanup uapi: remove ublk specific error code, switch to linux error code, remove one command op, remove one field from cmd_desc

- add monitor mechanism to handle ubq_daemon being killed, ublksrv[1] includes builtin tests for covering heavy IO with deleting ublk / killing ubq_daemon at the same time, and V2 pass all the two tests(make test T=generic), and the abort/stop mechanism is simple

- fix MQ command buffer mmap bug, and now 'xfstetests -g auto' works well on MQ ublk-loop devices(test/scratch)

- improve batching submission as suggested by Jens

- improve handling for starting device, replace random wait/poll with completion

- all kinds of cleanup, bug fix,..

Ming Lei (1):
ublk: add io_uring based userspace block driver

 drivers/block/Kconfig         |    6 +
 drivers/block/Makefile        |    2 +
 drivers/block/ublk_drv.c      | 1603 +++++++++++++++++++++++++++++++++
 include/uapi/linux/ublk_cmd.h |  158 ++++
 4 files changed, 1769 insertions(+)
 create mode 100644 drivers/block/ublk_drv.c
 create mode 100644 include/uapi/linux/ublk_cmd.h
Signature · 1 line
2.31.1
author
#1 lore raw

PATCH v3 1/1 ublk: add io_uring based userspace block driver

This is the driver part of userspace block driver(ublk driver), the other part is userspace daemon part(ublksrv)[1].

The two parts communicate by io_uring's IORING_OP_URING_CMD with one shared cmd buffer for storing io command, and the buffer is read only for ublksrv, each io command is indexed by io request tag directly, and is written by ublk driver.

For example, when one READ io request is submitted to ublk block driver, ublk driver stores the io command into cmd buffer first, then completes one IORING_OP_URING_CMD for notifying ublksrv, and the URING_CMD is issued to ublk driver beforehand by ublksrv for getting notification of any new io request, and each URING_CMD is associated with one io request by tag.

After ublksrv gets the io command, it translates and handles the ublk io request, such as, for the ublk-loop target, ublksrv translates the request into same request on another file or disk, like the kernel loop block driver. In ublksrv's implementation, the io is still handled by io_uring, and share same ring with IORING_OP_URING_CMD command. When the target io request is done, the same IORING_OP_URING_CMD is issued to ublk driver for both committing io request result and getting future notification of new io request.

Another thing done by ublk driver is to copy data between kernel io request and ublksrv's io buffer:

1) before ubsrv handles WRITE request, copy the request's data into ublksrv's userspace io buffer, so that ublksrv can handle the write request

2) after ubsrv handles READ request, copy ublksrv's userspace io buffer into this READ request, then ublk driver can complete the READ request

Zero copy may be switched if mm is ready to support it.

ublk driver doesn't handle any logic of the specific user space driver, so it should be small/simple enough.

[1] ublksrv

https://github.com/ming1/ubdsrv

---
 drivers/block/Kconfig         |    6 +
 drivers/block/Makefile        |    2 +
 drivers/block/ublk_drv.c      | 1603 +++++++++++++++++++++++++++++++++
 include/uapi/linux/ublk_cmd.h |  158 ++++
 4 files changed, 1769 insertions(+)
 create mode 100644 drivers/block/ublk_drv.c
 create mode 100644 include/uapi/linux/ublk_cmd.h
drivers/block/Kconfig +6 -0
index fdb81f2794cd..d218089cdbec 100644
@@ -408,6 +408,12 @@ config BLK_DEV_RBD
 
 	  If unsure, say N.
 
+config BLK_DEV_UBLK
+	bool "Userspace block driver"
+	select IO_URING
+	help
+          io uring based userspace block driver.
+
 source "drivers/block/rnbd/Kconfig"
 
 endif # BLK_DEV
drivers/block/Makefile +2 -0
index 934a9c7c3a7c..be631352567e 100644
@@ -39,4 +39,6 @@ obj-$(CONFIG_BLK_DEV_RNBD)	+= rnbd/
 
 obj-$(CONFIG_BLK_DEV_NULL_BLK)	+= null_blk/
 
+obj-$(CONFIG_BLK_DEV_UBLK)			+= ublk_drv.o
+
 swim_mod-y	:= swim.o swim_asm.o
drivers/block/ublk_drv.c new file +1603 -0

1,603 lines not on this page · raw message

include/uapi/linux/ublk_cmd.h new file +158 -0

158 lines not on this page · raw message

Signature · 1 line
2.31.1
#2 lore raw

On 2022/6/29 00:08, Ming Lei wrote:

[...]

Quoted 117 lines
drivers/block/ublk_drv.c new file +116 -0
+#define UBLK_MAX_PIN_PAGES	32
+
+static inline void ublk_release_pages(struct ublk_queue *ubq, struct page **pages,
+		int nr_pages)
+{
+	int i;
+
+	for (i = 0; i < nr_pages; i++)
+		put_page(pages[i]);
+}
+
+static inline int ublk_pin_user_pages(struct ublk_queue *ubq, u64 start_vm,
+		unsigned int nr_pages, unsigned int gup_flags,
+		struct page **pages)
+{
+	return get_user_pages_fast(start_vm, nr_pages, gup_flags, pages);
+}
 
+
+static inline unsigned ublk_copy_bv(struct bio_vec *bv, void **bv_addr,
+		void *pg_addr, unsigned int *pg_off,
+		unsigned int *pg_len, bool to_bv)
+{
+	unsigned len = min_t(unsigned, bv->bv_len, *pg_len);
+
+	if (*bv_addr == NULL)
+		*bv_addr = kmap_local_page(bv->bv_page);
+
+	if (to_bv)
+		memcpy(*bv_addr + bv->bv_offset, pg_addr + *pg_off, len);
+	else
+		memcpy(pg_addr + *pg_off, *bv_addr + bv->bv_offset, len);
+
+	bv->bv_offset += len;
+	bv->bv_len -= len;
+	*pg_off += len;
+	*pg_len -= len;
+
+	if (!bv->bv_len) {
+		kunmap_local(*bv_addr);
+		*bv_addr = NULL;
+	}
+
+	return len;
+}
+
+/* copy rq pages to ublksrv vm address pointed by io->addr */
+static int ublk_copy_pages(struct ublk_queue *ubq, struct request *rq, bool to_rq,
+		unsigned int max_bytes)
+{
+	unsigned int gup_flags = to_rq ? 0 : FOLL_WRITE;
+	struct ublk_io *io = &ubq->ios[rq->tag];
+	struct page *pgs[UBLK_MAX_PIN_PAGES];
+	struct req_iterator req_iter;
+	struct bio_vec bv;
+	const unsigned int rq_bytes = min(blk_rq_bytes(rq), max_bytes);
+	unsigned long start = io->addr, left = rq_bytes;
+	unsigned int idx = 0, pg_len = 0, pg_off = 0;
+	int nr_pin = 0;
+	void *pg_addr = NULL;
+	struct page *curr = NULL;
+
+	rq_for_each_segment(bv, rq, req_iter) {
+		unsigned len, bv_off = bv.bv_offset, bv_len = bv.bv_len;
+		void *bv_addr = NULL;
+
+refill:
+		if (pg_len == 0) {
+			unsigned int off = 0;
+
+			if (pg_addr) {
+				kunmap_local(pg_addr);
+				if (!to_rq)
+					set_page_dirty_lock(curr);
+				pg_addr = NULL;
+			}
+
+			/* refill pages */
+			if (idx >= nr_pin) {
+				unsigned int max_pages;
+
+				ublk_release_pages(ubq, pgs, nr_pin);
+
+				off = start & (PAGE_SIZE - 1);
+				max_pages = min_t(unsigned, (off + left +
+						PAGE_SIZE - 1) >> PAGE_SHIFT,
+						UBLK_MAX_PIN_PAGES);
+				nr_pin = ublk_pin_user_pages(ubq, start,
+						max_pages, gup_flags, pgs);
+				if (nr_pin < 0)
+					goto exit;
+				idx = 0;
+			}
+			pg_off = off;
+			pg_len = min(PAGE_SIZE - off, left);
+			off = 0;
+			curr = pgs[idx++];
+			pg_addr = kmap_local_page(curr);
+		}
+
+		len = ublk_copy_bv(&bv, &bv_addr, pg_addr, &pg_off, &pg_len,
+				to_rq);
+		/* either one of the two has been consumed */
+		WARN_ON_ONCE(bv.bv_len && pg_len);
+		start += len;
+		left -= len;
+
+		/* overflow */
+		WARN_ON_ONCE(left > rq_bytes);
+		WARN_ON_ONCE(bv.bv_len > bv_len);
+		if (bv.bv_len)
+			goto refill;
+
+		bv.bv_len = bv_len;
+		bv.bv_offset = bv_off;
+	}
+	if (pg_addr) {

drivers/block/ublk_drv.c line 319

Quoted 10 lines
drivers/block/ublk_drv.c new file +10 -0
+		kunmap_local(pg_addr);
+		if (!to_rq)
+			set_page_dirty_lock(curr);
+	}
+	ublk_release_pages(ubq, pgs, nr_pin);
+
+exit:
+	return rq_bytes - left;
+}
+

Hi Ming,

I note that you pin the user buffer's pages, memcpy() and release them immediately.

1) I think maybe copy_page_from_iter() is another choice for copying user buffer to biovecs since copy_page_from_iter() do not pin pages(But it may raise page fault).

2) Or will you design some mechanism such as LRU to manage these pinned pages? For example pin those pages frequently required for a long time and release those pages not used for a long time.
I remember you have talked about this LRU on pinned pages?

Which one do you think is better? copy_page_from_iter() or pin pages with LRU? Maybe it depends on the user's workload?

Regards,
Zhang

author
#3 lore raw
Quoted 134 lines · Ziyang Zhang

On 2022/6/29 00:08, Ming Lei wrote:

[...]

Quoted 117 lines
drivers/block/ublk_drv.c new file +116 -0
+#define UBLK_MAX_PIN_PAGES	32
+
+static inline void ublk_release_pages(struct ublk_queue *ubq, struct page **pages,
+		int nr_pages)
+{
+	int i;
+
+	for (i = 0; i < nr_pages; i++)
+		put_page(pages[i]);
+}
+
+static inline int ublk_pin_user_pages(struct ublk_queue *ubq, u64 start_vm,
+		unsigned int nr_pages, unsigned int gup_flags,
+		struct page **pages)
+{
+	return get_user_pages_fast(start_vm, nr_pages, gup_flags, pages);
+}
 
+
+static inline unsigned ublk_copy_bv(struct bio_vec *bv, void **bv_addr,
+		void *pg_addr, unsigned int *pg_off,
+		unsigned int *pg_len, bool to_bv)
+{
+	unsigned len = min_t(unsigned, bv->bv_len, *pg_len);
+
+	if (*bv_addr == NULL)
+		*bv_addr = kmap_local_page(bv->bv_page);
+
+	if (to_bv)
+		memcpy(*bv_addr + bv->bv_offset, pg_addr + *pg_off, len);
+	else
+		memcpy(pg_addr + *pg_off, *bv_addr + bv->bv_offset, len);
+
+	bv->bv_offset += len;
+	bv->bv_len -= len;
+	*pg_off += len;
+	*pg_len -= len;
+
+	if (!bv->bv_len) {
+		kunmap_local(*bv_addr);
+		*bv_addr = NULL;
+	}
+
+	return len;
+}
+
+/* copy rq pages to ublksrv vm address pointed by io->addr */
+static int ublk_copy_pages(struct ublk_queue *ubq, struct request *rq, bool to_rq,
+		unsigned int max_bytes)
+{
+	unsigned int gup_flags = to_rq ? 0 : FOLL_WRITE;
+	struct ublk_io *io = &ubq->ios[rq->tag];
+	struct page *pgs[UBLK_MAX_PIN_PAGES];
+	struct req_iterator req_iter;
+	struct bio_vec bv;
+	const unsigned int rq_bytes = min(blk_rq_bytes(rq), max_bytes);
+	unsigned long start = io->addr, left = rq_bytes;
+	unsigned int idx = 0, pg_len = 0, pg_off = 0;
+	int nr_pin = 0;
+	void *pg_addr = NULL;
+	struct page *curr = NULL;
+
+	rq_for_each_segment(bv, rq, req_iter) {
+		unsigned len, bv_off = bv.bv_offset, bv_len = bv.bv_len;
+		void *bv_addr = NULL;
+
+refill:
+		if (pg_len == 0) {
+			unsigned int off = 0;
+
+			if (pg_addr) {
+				kunmap_local(pg_addr);
+				if (!to_rq)
+					set_page_dirty_lock(curr);
+				pg_addr = NULL;
+			}
+
+			/* refill pages */
+			if (idx >= nr_pin) {
+				unsigned int max_pages;
+
+				ublk_release_pages(ubq, pgs, nr_pin);
+
+				off = start & (PAGE_SIZE - 1);
+				max_pages = min_t(unsigned, (off + left +
+						PAGE_SIZE - 1) >> PAGE_SHIFT,
+						UBLK_MAX_PIN_PAGES);
+				nr_pin = ublk_pin_user_pages(ubq, start,
+						max_pages, gup_flags, pgs);
+				if (nr_pin < 0)
+					goto exit;
+				idx = 0;
+			}
+			pg_off = off;
+			pg_len = min(PAGE_SIZE - off, left);
+			off = 0;
+			curr = pgs[idx++];
+			pg_addr = kmap_local_page(curr);
+		}
+
+		len = ublk_copy_bv(&bv, &bv_addr, pg_addr, &pg_off, &pg_len,
+				to_rq);
+		/* either one of the two has been consumed */
+		WARN_ON_ONCE(bv.bv_len && pg_len);
+		start += len;
+		left -= len;
+
+		/* overflow */
+		WARN_ON_ONCE(left > rq_bytes);
+		WARN_ON_ONCE(bv.bv_len > bv_len);
+		if (bv.bv_len)
+			goto refill;
+
+		bv.bv_len = bv_len;
+		bv.bv_offset = bv_off;
+	}
+	if (pg_addr) {

drivers/block/ublk_drv.c line 319

Quoted 10 lines
drivers/block/ublk_drv.c new file +10 -0
+		kunmap_local(pg_addr);
+		if (!to_rq)
+			set_page_dirty_lock(curr);
+	}
+	ublk_release_pages(ubq, pgs, nr_pin);
+
+exit:
+	return rq_bytes - left;
+}
+

Hi Ming,

Quoted 4 lines

I note that you pin the user buffer's pages, memcpy() and release them immediately.

1) I think maybe copy_page_from_iter() is another choice for copying user buffer to biovecs since copy_page_from_iter() do not pin pages(But it may raise page fault).

copy_page_from_iter/copy_page_to_iter needs the userspage page, then copy between the userspace page and bvec_iter pages, what it does is just kmap/copy/kunmap.

Not see it is useful here.

Quoted 5 lines

2) Or will you design some mechanism such as LRU to manage these pinned pages? For example pin those pages frequently required for a long time and release those pages not used for a long time.
I remember you have talked about this LRU on pinned pages?

I'd explain it a bit.

When I worked on v1/v2, 'perf report' shows that get_user_pages_fast() as one of top samples. Turns out it is a bug, which is fixed in

https://github.com/ming1/linux/commit/3c9fd476951759858cc548dee4cedc074194d0b0

After the issue is fixed, not see get_user_pages_fast() being hot spot any more. I actually implemented one patch which pins all pages in the ubd device whole lifetime, but not see obvious improvement, so I gave up the idea.

In the test VM on my laptop, single job ubd/null randwrite can reach 700K iops.

Quoted 3 lines

Which one do you think is better? copy_page_from_iter() or pin pages with LRU? Maybe it depends on the user's workload?

So far in the enablement stage, I think the current approach is just fine, but we still can improve it in future.

Thanks,
Ming

#4 lore raw
Quoted 137 lines · Ming Lei
Quoted 136 lines · Ziyang Zhang

On 2022/6/29 00:08, Ming Lei wrote:

[...]

Quoted 117 lines
drivers/block/ublk_drv.c new file +116 -0
+#define UBLK_MAX_PIN_PAGES	32
+
+static inline void ublk_release_pages(struct ublk_queue *ubq, struct page **pages,
+		int nr_pages)
+{
+	int i;
+
+	for (i = 0; i < nr_pages; i++)
+		put_page(pages[i]);
+}
+
+static inline int ublk_pin_user_pages(struct ublk_queue *ubq, u64 start_vm,
+		unsigned int nr_pages, unsigned int gup_flags,
+		struct page **pages)
+{
+	return get_user_pages_fast(start_vm, nr_pages, gup_flags, pages);
+}
 
+
+static inline unsigned ublk_copy_bv(struct bio_vec *bv, void **bv_addr,
+		void *pg_addr, unsigned int *pg_off,
+		unsigned int *pg_len, bool to_bv)
+{
+	unsigned len = min_t(unsigned, bv->bv_len, *pg_len);
+
+	if (*bv_addr == NULL)
+		*bv_addr = kmap_local_page(bv->bv_page);
+
+	if (to_bv)
+		memcpy(*bv_addr + bv->bv_offset, pg_addr + *pg_off, len);
+	else
+		memcpy(pg_addr + *pg_off, *bv_addr + bv->bv_offset, len);
+
+	bv->bv_offset += len;
+	bv->bv_len -= len;
+	*pg_off += len;
+	*pg_len -= len;
+
+	if (!bv->bv_len) {
+		kunmap_local(*bv_addr);
+		*bv_addr = NULL;
+	}
+
+	return len;
+}
+
+/* copy rq pages to ublksrv vm address pointed by io->addr */
+static int ublk_copy_pages(struct ublk_queue *ubq, struct request *rq, bool to_rq,
+		unsigned int max_bytes)
+{
+	unsigned int gup_flags = to_rq ? 0 : FOLL_WRITE;
+	struct ublk_io *io = &ubq->ios[rq->tag];
+	struct page *pgs[UBLK_MAX_PIN_PAGES];
+	struct req_iterator req_iter;
+	struct bio_vec bv;
+	const unsigned int rq_bytes = min(blk_rq_bytes(rq), max_bytes);
+	unsigned long start = io->addr, left = rq_bytes;
+	unsigned int idx = 0, pg_len = 0, pg_off = 0;
+	int nr_pin = 0;
+	void *pg_addr = NULL;
+	struct page *curr = NULL;
+
+	rq_for_each_segment(bv, rq, req_iter) {
+		unsigned len, bv_off = bv.bv_offset, bv_len = bv.bv_len;
+		void *bv_addr = NULL;
+
+refill:
+		if (pg_len == 0) {
+			unsigned int off = 0;
+
+			if (pg_addr) {
+				kunmap_local(pg_addr);
+				if (!to_rq)
+					set_page_dirty_lock(curr);
+				pg_addr = NULL;
+			}
+
+			/* refill pages */
+			if (idx >= nr_pin) {
+				unsigned int max_pages;
+
+				ublk_release_pages(ubq, pgs, nr_pin);
+
+				off = start & (PAGE_SIZE - 1);
+				max_pages = min_t(unsigned, (off + left +
+						PAGE_SIZE - 1) >> PAGE_SHIFT,
+						UBLK_MAX_PIN_PAGES);
+				nr_pin = ublk_pin_user_pages(ubq, start,
+						max_pages, gup_flags, pgs);
+				if (nr_pin < 0)
+					goto exit;
+				idx = 0;
+			}
+			pg_off = off;
+			pg_len = min(PAGE_SIZE - off, left);
+			off = 0;
+			curr = pgs[idx++];
+			pg_addr = kmap_local_page(curr);
+		}
+
+		len = ublk_copy_bv(&bv, &bv_addr, pg_addr, &pg_off, &pg_len,
+				to_rq);
+		/* either one of the two has been consumed */
+		WARN_ON_ONCE(bv.bv_len && pg_len);
+		start += len;
+		left -= len;
+
+		/* overflow */
+		WARN_ON_ONCE(left > rq_bytes);
+		WARN_ON_ONCE(bv.bv_len > bv_len);
+		if (bv.bv_len)
+			goto refill;
+
+		bv.bv_len = bv_len;
+		bv.bv_offset = bv_off;
+	}
+	if (pg_addr) {

drivers/block/ublk_drv.c line 319

Quoted 10 lines
drivers/block/ublk_drv.c new file +10 -0
+		kunmap_local(pg_addr);
+		if (!to_rq)
+			set_page_dirty_lock(curr);
+	}
+	ublk_release_pages(ubq, pgs, nr_pin);
+
+exit:
+	return rq_bytes - left;
+}
+

Hi Ming,

I note that you pin the user buffer's pages, memcpy() and release them immediately.

Quoted 8 lines
Quoted 2 lines

1) I think maybe copy_page_from_iter() is another choice for copying user buffer to biovecs since copy_page_from_iter() do not pin pages(But it may raise page fault).

copy_page_from_iter/copy_page_to_iter needs the userspage page, then copy between the userspace page and bvec_iter pages, what it does is just kmap/copy/kunmap.

Not see it is useful here.

No, I don't agree.
copy_page_from_iter(): copy data from an iovec to kernel pages(such as bio's bv pages). It finally calls raw_copy_from_user().

Here the src(iovec, here it is from user) is actually generated from a single void __user *ubuf, not a userspace page.

In copy_page_from_iter() I only find kmap/kunmap for the dest(kernel pages) but it is unnecessary to kmap/kunmap the src iovec(from user)
and please check the exception table usage in this routine.
I think raw_copy_from_user() inside copy_page_from_iter() should handle page faults.

You may find blk_rq_map_user() and bio_copy_from_iter() use copy_page_from_iter() to copy from void __user *ubuf to bio's bv pages.

Quoted 31 lines
Quoted 6 lines

2) Or will you design some mechanism such as LRU to manage these pinned pages? For example pin those pages frequently required for a long time and release those pages not used for a long time.
I remember you have talked about this LRU on pinned pages?

I'd explain it a bit.

When I worked on v1/v2, 'perf report' shows that get_user_pages_fast() as one of top samples. Turns out it is a bug, which is fixed in

https://github.com/ming1/linux/commit/3c9fd476951759858cc548dee4cedc074194d0b0

After the issue is fixed, not see get_user_pages_fast() being hot spot any more. I actually implemented one patch which pins all pages in the ubd device whole lifetime, but not see obvious improvement, so I gave up the idea.

In the test VM on my laptop, single job ubd/null randwrite can reach 700K iops.

Quoted 3 lines

Which one do you think is better? copy_page_from_iter() or pin pages with LRU? Maybe it depends on the user's workload?

So far in the enablement stage, I think the current approach is just fine, but we still can improve it in future.

Thanks,
Ming

author
#5 lore raw
Quoted 155 lines · Ziyang Zhang
Quoted 137 lines · Ming Lei
Quoted 136 lines · Ziyang Zhang

On 2022/6/29 00:08, Ming Lei wrote:

[...]

Quoted 117 lines
drivers/block/ublk_drv.c new file +116 -0
+#define UBLK_MAX_PIN_PAGES	32
+
+static inline void ublk_release_pages(struct ublk_queue *ubq, struct page **pages,
+		int nr_pages)
+{
+	int i;
+
+	for (i = 0; i < nr_pages; i++)
+		put_page(pages[i]);
+}
+
+static inline int ublk_pin_user_pages(struct ublk_queue *ubq, u64 start_vm,
+		unsigned int nr_pages, unsigned int gup_flags,
+		struct page **pages)
+{
+	return get_user_pages_fast(start_vm, nr_pages, gup_flags, pages);
+}
 
+
+static inline unsigned ublk_copy_bv(struct bio_vec *bv, void **bv_addr,
+		void *pg_addr, unsigned int *pg_off,
+		unsigned int *pg_len, bool to_bv)
+{
+	unsigned len = min_t(unsigned, bv->bv_len, *pg_len);
+
+	if (*bv_addr == NULL)
+		*bv_addr = kmap_local_page(bv->bv_page);
+
+	if (to_bv)
+		memcpy(*bv_addr + bv->bv_offset, pg_addr + *pg_off, len);
+	else
+		memcpy(pg_addr + *pg_off, *bv_addr + bv->bv_offset, len);
+
+	bv->bv_offset += len;
+	bv->bv_len -= len;
+	*pg_off += len;
+	*pg_len -= len;
+
+	if (!bv->bv_len) {
+		kunmap_local(*bv_addr);
+		*bv_addr = NULL;
+	}
+
+	return len;
+}
+
+/* copy rq pages to ublksrv vm address pointed by io->addr */
+static int ublk_copy_pages(struct ublk_queue *ubq, struct request *rq, bool to_rq,
+		unsigned int max_bytes)
+{
+	unsigned int gup_flags = to_rq ? 0 : FOLL_WRITE;
+	struct ublk_io *io = &ubq->ios[rq->tag];
+	struct page *pgs[UBLK_MAX_PIN_PAGES];
+	struct req_iterator req_iter;
+	struct bio_vec bv;
+	const unsigned int rq_bytes = min(blk_rq_bytes(rq), max_bytes);
+	unsigned long start = io->addr, left = rq_bytes;
+	unsigned int idx = 0, pg_len = 0, pg_off = 0;
+	int nr_pin = 0;
+	void *pg_addr = NULL;
+	struct page *curr = NULL;
+
+	rq_for_each_segment(bv, rq, req_iter) {
+		unsigned len, bv_off = bv.bv_offset, bv_len = bv.bv_len;
+		void *bv_addr = NULL;
+
+refill:
+		if (pg_len == 0) {
+			unsigned int off = 0;
+
+			if (pg_addr) {
+				kunmap_local(pg_addr);
+				if (!to_rq)
+					set_page_dirty_lock(curr);
+				pg_addr = NULL;
+			}
+
+			/* refill pages */
+			if (idx >= nr_pin) {
+				unsigned int max_pages;
+
+				ublk_release_pages(ubq, pgs, nr_pin);
+
+				off = start & (PAGE_SIZE - 1);
+				max_pages = min_t(unsigned, (off + left +
+						PAGE_SIZE - 1) >> PAGE_SHIFT,
+						UBLK_MAX_PIN_PAGES);
+				nr_pin = ublk_pin_user_pages(ubq, start,
+						max_pages, gup_flags, pgs);
+				if (nr_pin < 0)
+					goto exit;
+				idx = 0;
+			}
+			pg_off = off;
+			pg_len = min(PAGE_SIZE - off, left);
+			off = 0;
+			curr = pgs[idx++];
+			pg_addr = kmap_local_page(curr);
+		}
+
+		len = ublk_copy_bv(&bv, &bv_addr, pg_addr, &pg_off, &pg_len,
+				to_rq);
+		/* either one of the two has been consumed */
+		WARN_ON_ONCE(bv.bv_len && pg_len);
+		start += len;
+		left -= len;
+
+		/* overflow */
+		WARN_ON_ONCE(left > rq_bytes);
+		WARN_ON_ONCE(bv.bv_len > bv_len);
+		if (bv.bv_len)
+			goto refill;
+
+		bv.bv_len = bv_len;
+		bv.bv_offset = bv_off;
+	}
+	if (pg_addr) {

drivers/block/ublk_drv.c line 319

Quoted 10 lines
drivers/block/ublk_drv.c new file +10 -0
+		kunmap_local(pg_addr);
+		if (!to_rq)
+			set_page_dirty_lock(curr);
+	}
+	ublk_release_pages(ubq, pgs, nr_pin);
+
+exit:
+	return rq_bytes - left;
+}
+

Hi Ming,

I note that you pin the user buffer's pages, memcpy() and release them immediately.

Quoted 8 lines
Quoted 2 lines

1) I think maybe copy_page_from_iter() is another choice for copying user buffer to biovecs since copy_page_from_iter() do not pin pages(But it may raise page fault).

copy_page_from_iter/copy_page_to_iter needs the userspage page, then copy between the userspace page and bvec_iter pages, what it does is just kmap/copy/kunmap.

Not see it is useful here.

No, I don't agree.
copy_page_from_iter(): copy data from an iovec to kernel pages(such as bio's bv pages). It finally calls raw_copy_from_user().

Here the src(iovec, here it is from user) is actually generated from a single void __user *ubuf, not a userspace page.

Quoted 7 lines

In copy_page_from_iter() I only find kmap/kunmap for the dest(kernel pages) but it is unnecessary to kmap/kunmap the src iovec(from user)
and please check the exception table usage in this routine.
I think raw_copy_from_user() inside copy_page_from_iter() should handle page faults.

You may find blk_rq_map_user() and bio_copy_from_iter() use copy_page_from_iter() to copy from void __user *ubuf to bio's bv pages.

OK, maybe I misunderstood your point, but I don't think it is good idea:

1) get_user_page_fast() has been proved to be efficient in fast io path, and relying kernel to handle user page fault should be slower

2) in future, maybe v4, we can extend the pinned page lifetime to cover the io's lifetime, in this way we can call madvise(MADV_DONTNEED) in advance for user io buffer before starting ubd device, then once io is completed, pages pinned for this io can be reclaimed by mm without needing to swap out, this way will improve memory utilization much.

Thanks,
Ming

#6 lore raw
In reply to Ming Lei
Quoted 58 lines

This is the driver part of userspace block driver(ublk driver), the other part is userspace daemon part(ublksrv)[1].

The two parts communicate by io_uring's IORING_OP_URING_CMD with one shared cmd buffer for storing io command, and the buffer is read only for ublksrv, each io command is indexed by io request tag directly, and is written by ublk driver.

For example, when one READ io request is submitted to ublk block driver, ublk driver stores the io command into cmd buffer first, then completes one IORING_OP_URING_CMD for notifying ublksrv, and the URING_CMD is issued to ublk driver beforehand by ublksrv for getting notification of any new io request, and each URING_CMD is associated with one io request by tag.

After ublksrv gets the io command, it translates and handles the ublk io request, such as, for the ublk-loop target, ublksrv translates the request into same request on another file or disk, like the kernel loop block driver. In ublksrv's implementation, the io is still handled by io_uring, and share same ring with IORING_OP_URING_CMD command. When the target io request is done, the same IORING_OP_URING_CMD is issued to ublk driver for both committing io request result and getting future notification of new io request.

Another thing done by ublk driver is to copy data between kernel io request and ublksrv's io buffer:

1) before ubsrv handles WRITE request, copy the request's data into ublksrv's userspace io buffer, so that ublksrv can handle the write request

2) after ubsrv handles READ request, copy ublksrv's userspace io buffer into this READ request, then ublk driver can complete the READ request

Zero copy may be switched if mm is ready to support it.

ublk driver doesn't handle any logic of the specific user space driver, so it should be small/simple enough.

[1] ublksrv

https://github.com/ming1/ubdsrv

---
  drivers/block/Kconfig         |    6 +
  drivers/block/Makefile        |    2 +
  drivers/block/ublk_drv.c      | 1603 +++++++++++++++++++++++++++++++++
  include/uapi/linux/ublk_cmd.h |  158 ++++
  4 files changed, 1769 insertions(+)

create mode 100644 drivers/block/ublk_drv.c create mode 100644 include/uapi/linux/ublk_cmd.h

drivers/block/Kconfig +0 -0
index fdb81f2794cd..d218089cdbec 100644

drivers/block/Kconfig config BLK_DEV_RBD · line 412

Quoted 5 lines
drivers/block/Kconfig +2 -0
@@ -408,6 +408,12 @@ config BLK_DEV_RBD
 
  	  If unsure, say N.
 
+config BLK_DEV_UBLK
+	bool "Userspace block driver"

Really? why compile this to the kernel and not tristate as loadable module?

author
#7 lore raw
Quoted 53 lines · Sagi Grimberg
Quoted 53 lines

This is the driver part of userspace block driver(ublk driver), the other part is userspace daemon part(ublksrv)[1].

The two parts communicate by io_uring's IORING_OP_URING_CMD with one shared cmd buffer for storing io command, and the buffer is read only for ublksrv, each io command is indexed by io request tag directly, and is written by ublk driver.

For example, when one READ io request is submitted to ublk block driver, ublk driver stores the io command into cmd buffer first, then completes one IORING_OP_URING_CMD for notifying ublksrv, and the URING_CMD is issued to ublk driver beforehand by ublksrv for getting notification of any new io request, and each URING_CMD is associated with one io request by tag.

After ublksrv gets the io command, it translates and handles the ublk io request, such as, for the ublk-loop target, ublksrv translates the request into same request on another file or disk, like the kernel loop block driver. In ublksrv's implementation, the io is still handled by io_uring, and share same ring with IORING_OP_URING_CMD command. When the target io request is done, the same IORING_OP_URING_CMD is issued to ublk driver for both committing io request result and getting future notification of new io request.

Another thing done by ublk driver is to copy data between kernel io request and ublksrv's io buffer:

1) before ubsrv handles WRITE request, copy the request's data into ublksrv's userspace io buffer, so that ublksrv can handle the write request

2) after ubsrv handles READ request, copy ublksrv's userspace io buffer into this READ request, then ublk driver can complete the READ request

Zero copy may be switched if mm is ready to support it.

ublk driver doesn't handle any logic of the specific user space driver, so it should be small/simple enough.

[1] ublksrv

https://github.com/ming1/ubdsrv

---
  drivers/block/Kconfig         |    6 +
  drivers/block/Makefile        |    2 +
  drivers/block/ublk_drv.c      | 1603 +++++++++++++++++++++++++++++++++
  include/uapi/linux/ublk_cmd.h |  158 ++++
  4 files changed, 1769 insertions(+)

create mode 100644 drivers/block/ublk_drv.c create mode 100644 include/uapi/linux/ublk_cmd.h

Quoted 11 lines

drivers/block/Kconfig config BLK_DEV_RBD · line 410

Quoted 8 lines
drivers/block/Kconfig +2 -0
index fdb81f2794cd..d218089cdbec 100644
@@ -408,6 +408,12 @@ config BLK_DEV_RBD
  	  If unsure, say N.
+config BLK_DEV_UBLK
+	bool "Userspace block driver"

Really? why compile this to the kernel and not tristate as loadable module?

So far, this is only one reason: task_work_add() is required, which isn't exported for modules.

Thanks,
Ming

#8 lore raw
Quoted 13 lines
Quoted 12 lines

drivers/block/Kconfig config BLK_DEV_RBD · line 410

Quoted 9 lines
drivers/block/Kconfig +2 -0
index fdb81f2794cd..d218089cdbec 100644
@@ -408,6 +408,12 @@ config BLK_DEV_RBD
   	  If unsure, say N.
+config BLK_DEV_UBLK
+	bool "Userspace block driver"

Really? why compile this to the kernel and not tristate as loadable module?

Quoted 2 lines

So far, this is only one reason: task_work_add() is required, which isn't exported for modules.

So why not exporting it?
Doesn't seem like a good justification to build it into the kernel.

#9 lore raw
Quoted 11 lines · Sagi Grimberg
Quoted 11 lines
Quoted 11 lines

drivers/block/Kconfig config BLK_DEV_RBD · line 410

Quoted 8 lines
drivers/block/Kconfig +2 -0
index fdb81f2794cd..d218089cdbec 100644
@@ -408,6 +408,12 @@ config BLK_DEV_RBD
   	  If unsure, say N.
+config BLK_DEV_UBLK
+	bool "Userspace block driver"

Really? why compile this to the kernel and not tristate as loadable module?

Quoted 5 lines
Quoted 2 lines

So far, this is only one reason: task_work_add() is required, which isn't exported for modules.

So why not exporting it?
Doesn't seem like a good justification to build it into the kernel.

Sagi,

If I understand correctly, the task_work_add function is quite a core API that we probably want to avoid exposing directly to (out-of-tree) modules? I agree, though, it would be great to have this buildable as a module for general use cases. Would it make sense to have it exposed through a thin built-in wrapper, specific to UBD, which is exported, and therefore able to invoke that function? Is it a reasonable approach?

Signature · 1 line
Gabriel Krisman Bertazi
#10 lore raw
Quoted 18 lines
Quoted 12 lines
Quoted 12 lines
Quoted 12 lines

drivers/block/Kconfig config BLK_DEV_RBD · line 410

Quoted 9 lines
drivers/block/Kconfig +2 -0
index fdb81f2794cd..d218089cdbec 100644
@@ -408,6 +408,12 @@ config BLK_DEV_RBD
    	  If unsure, say N.
+config BLK_DEV_UBLK
+	bool "Userspace block driver"

Really? why compile this to the kernel and not tristate as loadable module?

Quoted 5 lines
Quoted 2 lines

So far, this is only one reason: task_work_add() is required, which isn't exported for modules.

So why not exporting it?
Doesn't seem like a good justification to build it into the kernel.

Quoted 8 lines

Sagi,

If I understand correctly, the task_work_add function is quite a core API that we probably want to avoid exposing directly to (out-of-tree) modules? I agree, though, it would be great to have this buildable as a module for general use cases. Would it make sense to have it exposed through a thin built-in wrapper, specific to UBD, which is exported, and therefore able to invoke that function? Is it a reasonable approach?

All I'm saying is that either we should expose it (or an interface to it) if it has merit, or use something else (use a workqueue). Having a block driver driver builtin is probably not the answer.

author
#11 lore raw
Quoted 27 lines · Sagi Grimberg
Quoted 18 lines
Quoted 12 lines
Quoted 12 lines
Quoted 12 lines

drivers/block/Kconfig config BLK_DEV_RBD · line 410

Quoted 9 lines
drivers/block/Kconfig +2 -0
index fdb81f2794cd..d218089cdbec 100644
@@ -408,6 +408,12 @@ config BLK_DEV_RBD
    	  If unsure, say N.
+config BLK_DEV_UBLK
+	bool "Userspace block driver"

Really? why compile this to the kernel and not tristate as loadable module?

Quoted 5 lines
Quoted 2 lines

So far, this is only one reason: task_work_add() is required, which isn't exported for modules.

So why not exporting it?
Doesn't seem like a good justification to build it into the kernel.

Quoted 8 lines

Sagi,

If I understand correctly, the task_work_add function is quite a core API that we probably want to avoid exposing directly to (out-of-tree) modules? I agree, though, it would be great to have this buildable as a module for general use cases. Would it make sense to have it exposed through a thin built-in wrapper, specific to UBD, which is exported, and therefore able to invoke that function? Is it a reasonable approach?

Quoted 2 lines

All I'm saying is that either we should expose it (or an interface to it) if it has merit, or use something else (use a workqueue).

There isn't replacement for task_work_add().

If module has to be supported, we can add one command for running the work function in the ubq context, that will add some cost.

Quoted 1 line

Having a block driver driver builtin is probably not the answer.

Not sure, there are at least two drivers which use the API.

Thanks,
Ming

#12 lore raw
In reply to Ming Lei
Quoted 35 lines · Ming Lei

This is the driver part of userspace block driver(ublk driver), the other part is userspace daemon part(ublksrv)[1].

The two parts communicate by io_uring's IORING_OP_URING_CMD with one shared cmd buffer for storing io command, and the buffer is read only for ublksrv, each io command is indexed by io request tag directly, and is written by ublk driver.

For example, when one READ io request is submitted to ublk block driver, ublk driver stores the io command into cmd buffer first, then completes one IORING_OP_URING_CMD for notifying ublksrv, and the URING_CMD is issued to ublk driver beforehand by ublksrv for getting notification of any new io request, and each URING_CMD is associated with one io request by tag.

After ublksrv gets the io command, it translates and handles the ublk io request, such as, for the ublk-loop target, ublksrv translates the request into same request on another file or disk, like the kernel loop block driver. In ublksrv's implementation, the io is still handled by io_uring, and share same ring with IORING_OP_URING_CMD command. When the target io request is done, the same IORING_OP_URING_CMD is issued to ublk driver for both committing io request result and getting future notification of new io request.

Another thing done by ublk driver is to copy data between kernel io request and ublksrv's io buffer:

1) before ubsrv handles WRITE request, copy the request's data into ublksrv's userspace io buffer, so that ublksrv can handle the write request

2) after ubsrv handles READ request, copy ublksrv's userspace io buffer into this READ request, then ublk driver can complete the READ request

Zero copy may be switched if mm is ready to support it.

Quoted 8 lines

ublk driver doesn't handle any logic of the specific user space driver, so it should be small/simple enough.

[1] ublksrv

https://github.com/ming1/ubdsrv

Hi Ming,

A few comments inline:

Quoted 5 lines
drivers/block/ublk_drv.c new file +5 -0
+#define UBLK_MINORS		(1U << MINORBITS)
+
+struct ublk_rq_data {
+	struct callback_head work;
+};

drivers/block/ublk_drv.c line 61

Quoted 10 lines
drivers/block/ublk_drv.c new file +10 -0
+
+/* io cmd is active: sqe cmd is received, and its cqe isn't done */
+#define UBLK_IO_FLAG_ACTIVE	0x01
+
+/*
+ * FETCH io cmd is completed via cqe, and the io cmd is being handled by
+ * ublksrv, and not committed yet
+ */
+#define UBLK_IO_FLAG_OWNED_BY_SRV 0x02
+

Minor nit: I wonder if the IO life cycle isn't better represented as a state machine than flags:

enum {
UBLK_IO_FREE,
UBLK_IO_QUEUED
UBLK_IO_OWNED_BY_SRV
UBLK_IO_COMPLETED,
UBLK_IO_ABORTED,
}

Since currently, IO_FLAG_ACTIVE and IO_OWNED_BY_SRV should (almost) be mutually exclusive.

Quoted 8 lines
drivers/block/ublk_drv.c new file +8 -0
+
+static int ublk_ctrl_stop_dev(struct ublk_device *ub)
+{
+	ublk_stop_dev(ub);
+	cancel_work_sync(&ub->stop_work);
+	return 0;
+}
+

drivers/block/ublk_drv.c line 846

Quoted 10 lines
drivers/block/ublk_drv.c new file +10 -0
+static inline bool ublk_queue_ready(struct ublk_queue *ubq)
+{
+	return ubq->nr_io_ready == ubq->q_depth;
+}
+
+/* device can only be started after all IOs are ready */
+static void ublk_mark_io_ready(struct ublk_device *ub, struct ublk_queue *ubq)
+{
+	mutex_lock(&ub->mutex);
+	ubq->nr_io_ready++;

I think this is still problematic for the case where a FETCH_IO is sent from a different thread than the one originally set in ubq_daemon (i.e. a userspace bug). Since ubq_daemon is used to decide what task context will do the data copy, If an IO_FETCH_RQ is sent to the same queue from two threads, the data copy can happen in the context of the wrong task. I'd suggest something like the check below at the beginning of mark_io_ready and a similar on for IO_COMMIT_AND_FETCH_RQ

	mutex_lock(&ub->mutex);
        if (ub->ubq_daemon && ub->ubq_daemon != current) {
           mutex_unlock(&ub->mutex);
           return -EINVAL;
        }
	ubq->nr_io_ready++;
        ...
Quoted 11 lines
drivers/block/ublk_drv.c new file +11 -0
+	if (ublk_queue_ready(ubq)) {
+		ubq->ubq_daemon = current;
+		get_task_struct(ubq->ubq_daemon);
+		ub->nr_queues_ready++;
+	}
+	if (ub->nr_queues_ready == ub->dev_info.nr_hw_queues)
+		complete_all(&ub->completion);
+	mutex_unlock(&ub->mutex);
+}
+
+static int ublk_ch_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags)

drivers/block/ublk_drv.c line 867

Quoted 10 lines
drivers/block/ublk_drv.c new file +10 -0
+{
+	struct ublksrv_io_cmd *ub_cmd = (struct ublksrv_io_cmd *)cmd->cmd;
+	struct ublk_device *ub = cmd->file->private_data;
+	struct ublk_queue *ubq;
+	struct ublk_io *io;
+	u32 cmd_op = cmd->cmd_op;
+	unsigned tag = ub_cmd->tag;
+	int ret = -EINVAL;
+
+	pr_devel("%s: receieved: cmd op %d queue %d tag %d result %d\n",
                         ^^^
                         received

drivers/block/ublk_drv.c line 875

Quoted 8 lines
drivers/block/ublk_drv.c new file +8 -0
+			__func__, cmd->cmd_op, ub_cmd->q_id, tag,
+			ub_cmd->result);
+
+	if (!(issue_flags & IO_URING_F_SQE128))
+		goto out;
+
+	ubq = ublk_get_queue(ub, ub_cmd->q_id);
+	if (!ubq || ub_cmd->q_id != ubq->q_id)

q_id is coming from userspace and is used to access an array inside ublk_get_queue(). I think you need to ensure qid < ub->dev_info.nr_hw_queues before calling ublk_get_queue() to protect from a kernel bad memory access triggered by userspace.

drivers/block/ublk_drv.c line 878

Quoted 3 lines
drivers/block/ublk_drv.c new file +3 -0
+		goto out;
+
+	if (WARN_ON_ONCE(tag >= ubq->q_depth))

Userspace shouldn't be able to easily trigger a WARN_ON.

Quoted 4 lines
drivers/block/ublk_drv.c new file +4 -0
+		goto out;
+
+	io = &ubq->ios[tag];
+

drivers/block/ublk_drv.c line 892

Quoted 10 lines
drivers/block/ublk_drv.c new file +10 -0
+	/* there is pending io cmd, something must be wrong */
+	if (io->flags & UBLK_IO_FLAG_ACTIVE) {b
+		ret = -EBUSY;
+		goto out;
+	}
+
+	switch (cmd_op) {
+	case UBLK_IO_FETCH_REQ:
+		/* UBLK_IO_FETCH_REQ is only allowed before queue is setup */
+		if (WARN_ON_ONCE(ublk_queue_ready(ubq))) {

Likewise, this shouldn't trigger a WARN_ON, IMO.

Quoted 22 lines
drivers/block/ublk_drv.c new file +22 -0
+			ret = -EBUSY;
+			goto out;
+		}
+		/*
+		 * The io is being handled by server, so COMMIT_RQ is expected
+		 * instead of FETCH_REQ
+		 */
+		if (io->flags & UBLK_IO_FLAG_OWNED_BY_SRV)
+			goto out;
+		/* FETCH_RQ has to provide IO buffer */
+		if (!ub_cmd->addr)
+			goto out;
+		io->cmd = cmd;
+		io->flags |= UBLK_IO_FLAG_ACTIVE;
+		io->addr = ub_cmd->addr;
+
+		ublk_mark_io_ready(ub, ubq);
+		break;
+	case UBLK_IO_COMMIT_AND_FETCH_REQ:
+		/* FETCH_RQ has to provide IO buffer */
+		if (!ub_cmd->addr)
+			goto out;

drivers/block/ublk_drv.c line 924

Quoted 10 lines
drivers/block/ublk_drv.c new file +10 -0
+		io->addr = ub_cmd->addr;
+		io->flags |= UBLK_IO_FLAG_ACTIVE;
+		fallthrough;
+	case UBLK_IO_COMMIT_REQ:
+		io->cmd = cmd;
+		if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV))
+			goto out;
+		ublk_commit_completion(ub, ub_cmd);
+
+		/* COMMIT_REQ is supposed to not fetch req */

I wonder if we could make it without IO_COMMIT_REQ. Is it useful to be able to commit without fetching a new request?

Quoted 8 lines
drivers/block/ublk_drv.c new file +8 -0
+		if (cmd_op == UBLK_IO_COMMIT_REQ) {
+			ret = UBLK_IO_RES_OK;
+			goto out;
+		}
+		break;
+	default:
+		goto out;
+	}

drivers/block/ublk_drv.c line 942

Quoted 10 lines
drivers/block/ublk_drv.c new file +10 -0
+	return -EIOCBQUEUED;
+
+ out:
+	io->flags &= ~UBLK_IO_FLAG_ACTIVE;
+	io_uring_cmd_done(cmd, ret, 0);
+	pr_devel("%s: complete: cmd op %d, tag %d ret %x io_flags %x\n",
+			__func__, cmd_op, tag, ret, io->flags);
+	return -EIOCBQUEUED;
+}
+

Thanks!

Signature · 1 line
Gabriel Krisman Bertazi
#13 lore raw
Quoted 206 lines · Gabriel Krisman Bertazi
Quoted 35 lines · Ming Lei

This is the driver part of userspace block driver(ublk driver), the other part is userspace daemon part(ublksrv)[1].

The two parts communicate by io_uring's IORING_OP_URING_CMD with one shared cmd buffer for storing io command, and the buffer is read only for ublksrv, each io command is indexed by io request tag directly, and is written by ublk driver.

For example, when one READ io request is submitted to ublk block driver, ublk driver stores the io command into cmd buffer first, then completes one IORING_OP_URING_CMD for notifying ublksrv, and the URING_CMD is issued to ublk driver beforehand by ublksrv for getting notification of any new io request, and each URING_CMD is associated with one io request by tag.

After ublksrv gets the io command, it translates and handles the ublk io request, such as, for the ublk-loop target, ublksrv translates the request into same request on another file or disk, like the kernel loop block driver. In ublksrv's implementation, the io is still handled by io_uring, and share same ring with IORING_OP_URING_CMD command. When the target io request is done, the same IORING_OP_URING_CMD is issued to ublk driver for both committing io request result and getting future notification of new io request.

Another thing done by ublk driver is to copy data between kernel io request and ublksrv's io buffer:

1) before ubsrv handles WRITE request, copy the request's data into ublksrv's userspace io buffer, so that ublksrv can handle the write request

2) after ubsrv handles READ request, copy ublksrv's userspace io buffer into this READ request, then ublk driver can complete the READ request

Zero copy may be switched if mm is ready to support it.

Quoted 8 lines

ublk driver doesn't handle any logic of the specific user space driver, so it should be small/simple enough.

[1] ublksrv

https://github.com/ming1/ubdsrv

Hi Ming,

A few comments inline:

Quoted 5 lines
drivers/block/ublk_drv.c new file +5 -0
+#define UBLK_MINORS		(1U << MINORBITS)
+
+struct ublk_rq_data {
+	struct callback_head work;
+};

drivers/block/ublk_drv.c line 61

Quoted 10 lines
drivers/block/ublk_drv.c new file +10 -0
+
+/* io cmd is active: sqe cmd is received, and its cqe isn't done */
+#define UBLK_IO_FLAG_ACTIVE	0x01
+
+/*
+ * FETCH io cmd is completed via cqe, and the io cmd is being handled by
+ * ublksrv, and not committed yet
+ */
+#define UBLK_IO_FLAG_OWNED_BY_SRV 0x02
+

Minor nit: I wonder if the IO life cycle isn't better represented as a state machine than flags:

enum {
UBLK_IO_FREE,
UBLK_IO_QUEUED
UBLK_IO_OWNED_BY_SRV
UBLK_IO_COMPLETED,
UBLK_IO_ABORTED,
}

Since currently, IO_FLAG_ACTIVE and IO_OWNED_BY_SRV should (almost) be mutually exclusive.

Quoted 8 lines
drivers/block/ublk_drv.c new file +8 -0
+
+static int ublk_ctrl_stop_dev(struct ublk_device *ub)
+{
+	ublk_stop_dev(ub);
+	cancel_work_sync(&ub->stop_work);
+	return 0;
+}
+

drivers/block/ublk_drv.c line 846

Quoted 10 lines
drivers/block/ublk_drv.c new file +10 -0
+static inline bool ublk_queue_ready(struct ublk_queue *ubq)
+{
+	return ubq->nr_io_ready == ubq->q_depth;
+}
+
+/* device can only be started after all IOs are ready */
+static void ublk_mark_io_ready(struct ublk_device *ub, struct ublk_queue *ubq)
+{
+	mutex_lock(&ub->mutex);
+	ubq->nr_io_ready++;

I think this is still problematic for the case where a FETCH_IO is sent from a different thread than the one originally set in ubq_daemon (i.e. a userspace bug). Since ubq_daemon is used to decide what task context will do the data copy, If an IO_FETCH_RQ is sent to the same queue from two threads, the data copy can happen in the context of the wrong task. I'd suggest something like the check below at the beginning of mark_io_ready and a similar on for IO_COMMIT_AND_FETCH_RQ

	mutex_lock(&ub->mutex);
        if (ub->ubq_daemon && ub->ubq_daemon != current) {
           mutex_unlock(&ub->mutex);
           return -EINVAL;
        }
	ubq->nr_io_ready++;
        ...
Quoted 11 lines
drivers/block/ublk_drv.c new file +11 -0
+	if (ublk_queue_ready(ubq)) {
+		ubq->ubq_daemon = current;
+		get_task_struct(ubq->ubq_daemon);
+		ub->nr_queues_ready++;
+	}
+	if (ub->nr_queues_ready == ub->dev_info.nr_hw_queues)
+		complete_all(&ub->completion);
+	mutex_unlock(&ub->mutex);
+}
+
+static int ublk_ch_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags)

drivers/block/ublk_drv.c line 867

Quoted 10 lines
drivers/block/ublk_drv.c new file +10 -0
+{
+	struct ublksrv_io_cmd *ub_cmd = (struct ublksrv_io_cmd *)cmd->cmd;
+	struct ublk_device *ub = cmd->file->private_data;
+	struct ublk_queue *ubq;
+	struct ublk_io *io;
+	u32 cmd_op = cmd->cmd_op;
+	unsigned tag = ub_cmd->tag;
+	int ret = -EINVAL;
+
+	pr_devel("%s: receieved: cmd op %d queue %d tag %d result %d\n",
                         ^^^
                         received

drivers/block/ublk_drv.c line 875

Quoted 8 lines
drivers/block/ublk_drv.c new file +8 -0
+			__func__, cmd->cmd_op, ub_cmd->q_id, tag,
+			ub_cmd->result);
+
+	if (!(issue_flags & IO_URING_F_SQE128))
+		goto out;
+
+	ubq = ublk_get_queue(ub, ub_cmd->q_id);
+	if (!ubq || ub_cmd->q_id != ubq->q_id)

q_id is coming from userspace and is used to access an array inside ublk_get_queue(). I think you need to ensure qid < ub->dev_info.nr_hw_queues before calling ublk_get_queue() to protect from a kernel bad memory access triggered by userspace.

drivers/block/ublk_drv.c line 878

Quoted 3 lines
drivers/block/ublk_drv.c new file +3 -0
+		goto out;
+
+	if (WARN_ON_ONCE(tag >= ubq->q_depth))

Userspace shouldn't be able to easily trigger a WARN_ON.

Quoted 4 lines
drivers/block/ublk_drv.c new file +4 -0
+		goto out;
+
+	io = &ubq->ios[tag];
+

drivers/block/ublk_drv.c line 892

Quoted 10 lines
drivers/block/ublk_drv.c new file +10 -0
+	/* there is pending io cmd, something must be wrong */
+	if (io->flags & UBLK_IO_FLAG_ACTIVE) {b
+		ret = -EBUSY;
+		goto out;
+	}
+
+	switch (cmd_op) {
+	case UBLK_IO_FETCH_REQ:
+		/* UBLK_IO_FETCH_REQ is only allowed before queue is setup */
+		if (WARN_ON_ONCE(ublk_queue_ready(ubq))) {

Likewise, this shouldn't trigger a WARN_ON, IMO.

Quoted 27 lines
drivers/block/ublk_drv.c new file +27 -0
+			ret = -EBUSY;
+			goto out;
+		}
+		/*
+		 * The io is being handled by server, so COMMIT_RQ is expected
+		 * instead of FETCH_REQ
+		 */
+		if (io->flags & UBLK_IO_FLAG_OWNED_BY_SRV)
+			goto out;
+		/* FETCH_RQ has to provide IO buffer */
+		if (!ub_cmd->addr)
+			goto out;
+		io->cmd = cmd;
+		io->flags |= UBLK_IO_FLAG_ACTIVE;
+		io->addr = ub_cmd->addr;
+
+		ublk_mark_io_ready(ub, ubq);
+		break;
+	case UBLK_IO_COMMIT_AND_FETCH_REQ:
+		/* FETCH_RQ has to provide IO buffer */
+		if (!ub_cmd->addr)
+			goto out;
+		io->addr = ub_cmd->addr;
+		io->flags |= UBLK_IO_FLAG_ACTIVE;
+		fallthrough;
+	case UBLK_IO_COMMIT_REQ:
+		io->cmd = cmd;
Quoted 8 lines

drivers/block/ublk_drv.c line 924

Quoted 5 lines
drivers/block/ublk_drv.c new file +5 -0
+		if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV))
+			goto out;
+		ublk_commit_completion(ub, ub_cmd);
+
+		/* COMMIT_REQ is supposed to not fetch req */

I wonder if we could make it without IO_COMMIT_REQ. Is it useful to be able to commit without fetching a new request?

UBLK_IO_COMMIT_REQ is not necessary, IMO.
In current version of ubd_drv.c I find UBLK_IO_COMMIT_REQ is sent by ublksrv after it gets one UBD_IO_RES_ABORT beacuse ubd_drv wants to abort IOs and let the ublk daemon exit.

We can use UBLK_IO_COMMIT_AND_FETCH_REQ to replace UBLK_IO_COMMIT_REQ. The data flow could be:

1) UBLK_IO_COMMIT_AND_FETCH_REQ from ublksrv

2) ubd_drv receives IO's sqe with UBLK_IO_COMMIT_AND_FETCH_REQ and sets the IO's status to UBLK_IO_QUEUED

3) ubd_drv wants to abort IOs so it just completes this IO's cqe(UBD_IO_RES_ABORT)

I successfully removed UBLK_IO_COMMIT_REQ when developing libubd although I choose the earliest version of ubd_drv.c(v5.17-ubd-dev) which may be a buggy version.

Quoted 22 lines
Quoted 9 lines
drivers/block/ublk_drv.c new file +8 -0
+		if (cmd_op == UBLK_IO_COMMIT_REQ) {
+			ret = UBLK_IO_RES_OK;
+			goto out;
+		}
+		break;
+	default:
+		goto out;
+	}

drivers/block/ublk_drv.c line 942

Quoted 10 lines
drivers/block/ublk_drv.c new file +10 -0
+	return -EIOCBQUEUED;
+
+ out:
+	io->flags &= ~UBLK_IO_FLAG_ACTIVE;
+	io_uring_cmd_done(cmd, ret, 0);
+	pr_devel("%s: complete: cmd op %d, tag %d ret %x io_flags %x\n",
+			__func__, cmd_op, tag, ret, io->flags);
+	return -EIOCBQUEUED;
+}
+

Thanks!

author
#14 lore raw
Quoted 221 lines · Ziyang Zhang
Quoted 206 lines · Gabriel Krisman Bertazi
Quoted 35 lines · Ming Lei

This is the driver part of userspace block driver(ublk driver), the other part is userspace daemon part(ublksrv)[1].

The two parts communicate by io_uring's IORING_OP_URING_CMD with one shared cmd buffer for storing io command, and the buffer is read only for ublksrv, each io command is indexed by io request tag directly, and is written by ublk driver.

For example, when one READ io request is submitted to ublk block driver, ublk driver stores the io command into cmd buffer first, then completes one IORING_OP_URING_CMD for notifying ublksrv, and the URING_CMD is issued to ublk driver beforehand by ublksrv for getting notification of any new io request, and each URING_CMD is associated with one io request by tag.

After ublksrv gets the io command, it translates and handles the ublk io request, such as, for the ublk-loop target, ublksrv translates the request into same request on another file or disk, like the kernel loop block driver. In ublksrv's implementation, the io is still handled by io_uring, and share same ring with IORING_OP_URING_CMD command. When the target io request is done, the same IORING_OP_URING_CMD is issued to ublk driver for both committing io request result and getting future notification of new io request.

Another thing done by ublk driver is to copy data between kernel io request and ublksrv's io buffer:

1) before ubsrv handles WRITE request, copy the request's data into ublksrv's userspace io buffer, so that ublksrv can handle the write request

2) after ubsrv handles READ request, copy ublksrv's userspace io buffer into this READ request, then ublk driver can complete the READ request

Zero copy may be switched if mm is ready to support it.

Quoted 8 lines

ublk driver doesn't handle any logic of the specific user space driver, so it should be small/simple enough.

[1] ublksrv

https://github.com/ming1/ubdsrv

Hi Ming,

A few comments inline:

Quoted 5 lines
(quoted diff) +5 -0
+#define UBLK_MINORS		(1U << MINORBITS)
+
+struct ublk_rq_data {
+	struct callback_head work;
+};

Review

Quoted 10 lines
(quoted diff) +10 -0
+
+/* io cmd is active: sqe cmd is received, and its cqe isn't done */
+#define UBLK_IO_FLAG_ACTIVE	0x01
+
+/*
+ * FETCH io cmd is completed via cqe, and the io cmd is being handled by
+ * ublksrv, and not committed yet
+ */
+#define UBLK_IO_FLAG_OWNED_BY_SRV 0x02
+

Minor nit: I wonder if the IO life cycle isn't better represented as a state machine than flags:

enum {
UBLK_IO_FREE,
UBLK_IO_QUEUED
UBLK_IO_OWNED_BY_SRV
UBLK_IO_COMPLETED,
UBLK_IO_ABORTED,
}

Since currently, IO_FLAG_ACTIVE and IO_OWNED_BY_SRV should (almost) be mutually exclusive.

Quoted 8 lines
(quoted diff) +8 -0
+
+static int ublk_ctrl_stop_dev(struct ublk_device *ub)
+{
+	ublk_stop_dev(ub);
+	cancel_work_sync(&ub->stop_work);
+	return 0;
+}
+

Review

Quoted 10 lines
(quoted diff) +10 -0
+static inline bool ublk_queue_ready(struct ublk_queue *ubq)
+{
+	return ubq->nr_io_ready == ubq->q_depth;
+}
+
+/* device can only be started after all IOs are ready */
+static void ublk_mark_io_ready(struct ublk_device *ub, struct ublk_queue *ubq)
+{
+	mutex_lock(&ub->mutex);
+	ubq->nr_io_ready++;

I think this is still problematic for the case where a FETCH_IO is sent from a different thread than the one originally set in ubq_daemon (i.e. a userspace bug). Since ubq_daemon is used to decide what task context will do the data copy, If an IO_FETCH_RQ is sent to the same queue from two threads, the data copy can happen in the context of the wrong task. I'd suggest something like the check below at the beginning of mark_io_ready and a similar on for IO_COMMIT_AND_FETCH_RQ

	mutex_lock(&ub->mutex);
        if (ub->ubq_daemon && ub->ubq_daemon != current) {
           mutex_unlock(&ub->mutex);
           return -EINVAL;
        }
	ubq->nr_io_ready++;
        ...
Quoted 11 lines
(quoted diff) +11 -0
+	if (ublk_queue_ready(ubq)) {
+		ubq->ubq_daemon = current;
+		get_task_struct(ubq->ubq_daemon);
+		ub->nr_queues_ready++;
+	}
+	if (ub->nr_queues_ready == ub->dev_info.nr_hw_queues)
+		complete_all(&ub->completion);
+	mutex_unlock(&ub->mutex);
+}
+
+static int ublk_ch_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags)

Review

Quoted 10 lines
(quoted diff) +10 -0
+{
+	struct ublksrv_io_cmd *ub_cmd = (struct ublksrv_io_cmd *)cmd->cmd;
+	struct ublk_device *ub = cmd->file->private_data;
+	struct ublk_queue *ubq;
+	struct ublk_io *io;
+	u32 cmd_op = cmd->cmd_op;
+	unsigned tag = ub_cmd->tag;
+	int ret = -EINVAL;
+
+	pr_devel("%s: receieved: cmd op %d queue %d tag %d result %d\n",
                         ^^^
                         received

Review

Quoted 8 lines
(quoted diff) +8 -0
+			__func__, cmd->cmd_op, ub_cmd->q_id, tag,
+			ub_cmd->result);
+
+	if (!(issue_flags & IO_URING_F_SQE128))
+		goto out;
+
+	ubq = ublk_get_queue(ub, ub_cmd->q_id);
+	if (!ubq || ub_cmd->q_id != ubq->q_id)

q_id is coming from userspace and is used to access an array inside ublk_get_queue(). I think you need to ensure qid < ub->dev_info.nr_hw_queues before calling ublk_get_queue() to protect from a kernel bad memory access triggered by userspace.

Review

Quoted 3 lines
(quoted diff) +3 -0
+		goto out;
+
+	if (WARN_ON_ONCE(tag >= ubq->q_depth))

Userspace shouldn't be able to easily trigger a WARN_ON.

Quoted 4 lines
(quoted diff) +4 -0
+		goto out;
+
+	io = &ubq->ios[tag];
+

Review

Quoted 10 lines
(quoted diff) +10 -0
+	/* there is pending io cmd, something must be wrong */
+	if (io->flags & UBLK_IO_FLAG_ACTIVE) {b
+		ret = -EBUSY;
+		goto out;
+	}
+
+	switch (cmd_op) {
+	case UBLK_IO_FETCH_REQ:
+		/* UBLK_IO_FETCH_REQ is only allowed before queue is setup */
+		if (WARN_ON_ONCE(ublk_queue_ready(ubq))) {

Likewise, this shouldn't trigger a WARN_ON, IMO.

Quoted 27 lines
(quoted diff) +27 -0
+			ret = -EBUSY;
+			goto out;
+		}
+		/*
+		 * The io is being handled by server, so COMMIT_RQ is expected
+		 * instead of FETCH_REQ
+		 */
+		if (io->flags & UBLK_IO_FLAG_OWNED_BY_SRV)
+			goto out;
+		/* FETCH_RQ has to provide IO buffer */
+		if (!ub_cmd->addr)
+			goto out;
+		io->cmd = cmd;
+		io->flags |= UBLK_IO_FLAG_ACTIVE;
+		io->addr = ub_cmd->addr;
+
+		ublk_mark_io_ready(ub, ubq);
+		break;
+	case UBLK_IO_COMMIT_AND_FETCH_REQ:
+		/* FETCH_RQ has to provide IO buffer */
+		if (!ub_cmd->addr)
+			goto out;
+		io->addr = ub_cmd->addr;
+		io->flags |= UBLK_IO_FLAG_ACTIVE;
+		fallthrough;
+	case UBLK_IO_COMMIT_REQ:
+		io->cmd = cmd;
Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+		if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV))
+			goto out;
+		ublk_commit_completion(ub, ub_cmd);
+
+		/* COMMIT_REQ is supposed to not fetch req */

I wonder if we could make it without IO_COMMIT_REQ. Is it useful to be able to commit without fetching a new request?

UBLK_IO_COMMIT_REQ is not necessary, IMO.
In current version of ubd_drv.c I find UBLK_IO_COMMIT_REQ is sent by ublksrv after it gets one UBD_IO_RES_ABORT beacuse ubd_drv wants to abort IOs and let the ublk daemon exit.

Quoted 7 lines

We can use UBLK_IO_COMMIT_AND_FETCH_REQ to replace UBLK_IO_COMMIT_REQ. The data flow could be:

1) UBLK_IO_COMMIT_AND_FETCH_REQ from ublksrv

2) ubd_drv receives IO's sqe with UBLK_IO_COMMIT_AND_FETCH_REQ and sets the IO's status to UBLK_IO_QUEUED

Not see where UBLK_IO_QUEUED is? :-)

Quoted 7 lines

3) ubd_drv wants to abort IOs so it just completes this IO's cqe(UBD_IO_RES_ABORT)

I successfully removed UBLK_IO_COMMIT_REQ when developing libubd although I choose the earliest version of ubd_drv.c(v5.17-ubd-dev) which may be a buggy version.

You can verify it with latest ublksrv(libublksrv has been in master) too by the following patch, then 'make test T=generic' can run successfully.

lib/ublksrv.c +1 -1
index c4bb2f4..aee71a0 100644
@@ -150,7 +150,7 @@ static inline int ublksrv_queue_io_cmd(struct ublksrv_queue *q,
                else
                        cmd_op = UBLK_IO_FETCH_REQ;
        } else if (io->flags & UBLKSRV_NEED_COMMIT_RQ_COMP) {
-                       cmd_op = UBLK_IO_COMMIT_REQ;
+                       cmd_op = UBLK_IO_COMMIT_AND_FETCH_REQ;
        } else {
                syslog(LOG_ERR, "io flags is zero, tag %d\n",
                                (int)cmd->tag);

ublk_cancel_queue() will cancel all these io commands.

Thanks,
Ming

author
#15 lore raw
In reply to Gabriel Krisman Bertazi
Quoted 42 lines · Gabriel Krisman Bertazi
Quoted 40 lines · Ming Lei

This is the driver part of userspace block driver(ublk driver), the other part is userspace daemon part(ublksrv)[1].

The two parts communicate by io_uring's IORING_OP_URING_CMD with one shared cmd buffer for storing io command, and the buffer is read only for ublksrv, each io command is indexed by io request tag directly, and is written by ublk driver.

For example, when one READ io request is submitted to ublk block driver, ublk driver stores the io command into cmd buffer first, then completes one IORING_OP_URING_CMD for notifying ublksrv, and the URING_CMD is issued to ublk driver beforehand by ublksrv for getting notification of any new io request, and each URING_CMD is associated with one io request by tag.

After ublksrv gets the io command, it translates and handles the ublk io request, such as, for the ublk-loop target, ublksrv translates the request into same request on another file or disk, like the kernel loop block driver. In ublksrv's implementation, the io is still handled by io_uring, and share same ring with IORING_OP_URING_CMD command. When the target io request is done, the same IORING_OP_URING_CMD is issued to ublk driver for both committing io request result and getting future notification of new io request.

Another thing done by ublk driver is to copy data between kernel io request and ublksrv's io buffer:

1) before ubsrv handles WRITE request, copy the request's data into ublksrv's userspace io buffer, so that ublksrv can handle the write request

2) after ubsrv handles READ request, copy ublksrv's userspace io buffer into this READ request, then ublk driver can complete the READ request

Zero copy may be switched if mm is ready to support it.

ublk driver doesn't handle any logic of the specific user space driver, so it should be small/simple enough.

[1] ublksrv

Quoted 7 lines
Quoted 3 lines

https://github.com/ming1/ubdsrv

Hi Ming,

A few comments inline:

Hi Gabriel,

Thanks for your review!

Quoted 29 lines
Quoted 7 lines
drivers/block/ublk_drv.c new file +5 -0
+#define UBLK_MINORS		(1U << MINORBITS)
+
+struct ublk_rq_data {
+	struct callback_head work;
+};

drivers/block/ublk_drv.c line 61

Quoted 10 lines
drivers/block/ublk_drv.c new file +10 -0
+
+/* io cmd is active: sqe cmd is received, and its cqe isn't done */
+#define UBLK_IO_FLAG_ACTIVE	0x01
+
+/*
+ * FETCH io cmd is completed via cqe, and the io cmd is being handled by
+ * ublksrv, and not committed yet
+ */
+#define UBLK_IO_FLAG_OWNED_BY_SRV 0x02
+

Minor nit: I wonder if the IO life cycle isn't better represented as a state machine than flags:

enum {
UBLK_IO_FREE,
UBLK_IO_QUEUED
UBLK_IO_OWNED_BY_SRV
UBLK_IO_COMPLETED,
UBLK_IO_ABORTED,
}

Quoted 2 lines

Since currently, IO_FLAG_ACTIVE and IO_OWNED_BY_SRV should (almost) be mutually exclusive.

Right, IO_OWNED_BY_SRV can be killed, and its only purpose could be just cross-verification.

So only two flags of IO_FLAG_ACTIVE and IO_FLAG_REQ_FAILED are useful:

1) IO_FLAG_ACTIVE means the io command is owned by ublk driver, and it becomes zero after completing the io_uring io command, triggered by one incoming ublk block io request.

2) IO_FLAG_REQ_FAILED is set after aborting is triggered, any inflight ublk io request and to-be-queued request via this slot should be ended immediately.

At least it works for current requirements.

Io state machine may not work perfectly here, especially more states results in more complicated handling, such as, N states may need

	N * (N - 1)

transitions.

Also there isn't UBLK_IO_FREE state, the io slot is always used, either in ublk driver side, or ublk server side.

No UBLK_IO_QUEUED state too, the handling is to complete the io command for notifying ublksrv to handle the request, and hard to abstract the QUEUED state.

UBLK_IO_OWNED_BY_SRV is same with !IO_FLAG_ACTIVE.

UBLK_IO_COMPLETED is basically same with !IO_FLAG_ACTIVE->IO_FLAG_ACTIVE, and it is one transient state.

UBLK_IO_ABORTED is basically same with IO_FLAG_REQ_FAILED.

So we can solve the problem with simpler abstraction, instead of making it over complicated.

Quoted 29 lines
Quoted 10 lines
drivers/block/ublk_drv.c new file +8 -0
+
+static int ublk_ctrl_stop_dev(struct ublk_device *ub)
+{
+	ublk_stop_dev(ub);
+	cancel_work_sync(&ub->stop_work);
+	return 0;
+}
+

drivers/block/ublk_drv.c line 846

Quoted 10 lines
drivers/block/ublk_drv.c new file +10 -0
+static inline bool ublk_queue_ready(struct ublk_queue *ubq)
+{
+	return ubq->nr_io_ready == ubq->q_depth;
+}
+
+/* device can only be started after all IOs are ready */
+static void ublk_mark_io_ready(struct ublk_device *ub, struct ublk_queue *ubq)
+{
+	mutex_lock(&ub->mutex);
+	ubq->nr_io_ready++;

I think this is still problematic for the case where a FETCH_IO is sent from a different thread than the one originally set in ubq_daemon (i.e. a userspace bug). Since ubq_daemon is used to decide what task context will do the data copy, If an IO_FETCH_RQ is sent to the same queue from two threads, the data copy can happen in the context of the wrong task. I'd suggest something like the check below at the beginning of mark_io_ready and a similar on for IO_COMMIT_AND_FETCH_RQ

Quoted 6 lines
	mutex_lock(&ub->mutex);
        if (ub->ubq_daemon && ub->ubq_daemon != current) {
           mutex_unlock(&ub->mutex);
           return -EINVAL;
        }
	ubq->nr_io_ready++;

The check is good, will add it, but ub->mutex isn't required, especially IO_COMMIT_AND_FETCH_RQ is in fast path.

Quoted 17 lines
        ...
Quoted 16 lines
drivers/block/ublk_drv.c new file +16 -0
+	if (ublk_queue_ready(ubq)) {
+		ubq->ubq_daemon = current;
+		get_task_struct(ubq->ubq_daemon);
+		ub->nr_queues_ready++;
+	}
+	if (ub->nr_queues_ready == ub->dev_info.nr_hw_queues)
+		complete_all(&ub->completion);
+	mutex_unlock(&ub->mutex);
+}
+
+static int ublk_ch_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags)
+{
+	struct ublksrv_io_cmd *ub_cmd = (struct ublksrv_io_cmd *)cmd->cmd;
+	struct ublk_device *ub = cmd->file->private_data;
+	struct ublk_queue *ubq;
+	struct ublk_io *io;
Quoted 8 lines

drivers/block/ublk_drv.c line 867

Quoted 5 lines
drivers/block/ublk_drv.c new file +5 -0
+	u32 cmd_op = cmd->cmd_op;
+	unsigned tag = ub_cmd->tag;
+	int ret = -EINVAL;
+
+	pr_devel("%s: receieved: cmd op %d queue %d tag %d result %d\n",
                         ^^^
                         received

OK.

Quoted 15 lines

drivers/block/ublk_drv.c line 875

Quoted 10 lines
drivers/block/ublk_drv.c new file +8 -0
+			__func__, cmd->cmd_op, ub_cmd->q_id, tag,
+			ub_cmd->result);
+
+	if (!(issue_flags & IO_URING_F_SQE128))
+		goto out;
+
+	ubq = ublk_get_queue(ub, ub_cmd->q_id);
+	if (!ubq || ub_cmd->q_id != ubq->q_id)

q_id is coming from userspace and is used to access an array inside ublk_get_queue(). I think you need to ensure qid < ub->dev_info.nr_hw_queues before calling ublk_get_queue() to protect from a kernel bad memory access triggered by userspace.

Good catch!

Quoted 6 lines

drivers/block/ublk_drv.c line 878

Quoted 4 lines
drivers/block/ublk_drv.c new file +3 -0
+		goto out;
+
+	if (WARN_ON_ONCE(tag >= ubq->q_depth))

Userspace shouldn't be able to easily trigger a WARN_ON.

OK, we can simply fail the io command submission.

Quoted 17 lines
Quoted 5 lines
drivers/block/ublk_drv.c new file +4 -0
+		goto out;
+
+	io = &ubq->ios[tag];
+

drivers/block/ublk_drv.c line 892

Quoted 10 lines
drivers/block/ublk_drv.c new file +10 -0
+	/* there is pending io cmd, something must be wrong */
+	if (io->flags & UBLK_IO_FLAG_ACTIVE) {b
+		ret = -EBUSY;
+		goto out;
+	}
+
+	switch (cmd_op) {
+	case UBLK_IO_FETCH_REQ:
+		/* UBLK_IO_FETCH_REQ is only allowed before queue is setup */
+		if (WARN_ON_ONCE(ublk_queue_ready(ubq))) {

Likewise, this shouldn't trigger a WARN_ON, IMO.

OK.

Quoted 28 lines
Quoted 28 lines
drivers/block/ublk_drv.c new file +27 -0
+			ret = -EBUSY;
+			goto out;
+		}
+		/*
+		 * The io is being handled by server, so COMMIT_RQ is expected
+		 * instead of FETCH_REQ
+		 */
+		if (io->flags & UBLK_IO_FLAG_OWNED_BY_SRV)
+			goto out;
+		/* FETCH_RQ has to provide IO buffer */
+		if (!ub_cmd->addr)
+			goto out;
+		io->cmd = cmd;
+		io->flags |= UBLK_IO_FLAG_ACTIVE;
+		io->addr = ub_cmd->addr;
+
+		ublk_mark_io_ready(ub, ubq);
+		break;
+	case UBLK_IO_COMMIT_AND_FETCH_REQ:
+		/* FETCH_RQ has to provide IO buffer */
+		if (!ub_cmd->addr)
+			goto out;
+		io->addr = ub_cmd->addr;
+		io->flags |= UBLK_IO_FLAG_ACTIVE;
+		fallthrough;
+	case UBLK_IO_COMMIT_REQ:
+		io->cmd = cmd;
Quoted 8 lines

drivers/block/ublk_drv.c line 924

Quoted 5 lines
drivers/block/ublk_drv.c new file +5 -0
+		if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV))
+			goto out;
+		ublk_commit_completion(ub, ub_cmd);
+
+		/* COMMIT_REQ is supposed to not fetch req */

I wonder if we could make it without IO_COMMIT_REQ. Is it useful to be able to commit without fetching a new request?

UBLK_IO_COMMIT_AND_FETCH_REQ should cover both, since IO_COMMIT_REQ is only submitted after aborting, and at that time the fetch action of IO_COMMIT_AND_FETCH_REQ will be failed in ublk_cancel_queue. So I think we can remove IO_COMMIT_REQ.

Thanks,
Ming

author
#16 lore raw
Quoted 2 lines · Ming Lei
Quoted 1 line · Gabriel Krisman Bertazi

Ming Lei <[email protected]> writes:

...

Quoted 17 lines
Quoted 16 lines

drivers/block/ublk_drv.c line 875

Quoted 11 lines
drivers/block/ublk_drv.c new file +8 -0
+			__func__, cmd->cmd_op, ub_cmd->q_id, tag,
+			ub_cmd->result);
+
+	if (!(issue_flags & IO_URING_F_SQE128))
+		goto out;
+
+	ubq = ublk_get_queue(ub, ub_cmd->q_id);
+	if (!ubq || ub_cmd->q_id != ubq->q_id)

q_id is coming from userspace and is used to access an array inside ublk_get_queue(). I think you need to ensure qid < ub->dev_info.nr_hw_queues before calling ublk_get_queue() to protect from a kernel bad memory access triggered by userspace.

Quoted 1 line

Good catch!

Turns out the check on 'qid < ub->dev_info.nr_hw_queues' isn't needed, since the condition of 'ub_cmd->q_id != ubq->q_id' is more strict.

Thanks,
Ming

author
#17 lore raw
Quoted 22 lines · Ming Lei
Quoted 2 lines · Ming Lei
Quoted 1 line · Gabriel Krisman Bertazi

Ming Lei <[email protected]> writes:

...

Quoted 17 lines
Quoted 16 lines

drivers/block/ublk_drv.c line 875

Quoted 11 lines
drivers/block/ublk_drv.c new file +8 -0
+			__func__, cmd->cmd_op, ub_cmd->q_id, tag,
+			ub_cmd->result);
+
+	if (!(issue_flags & IO_URING_F_SQE128))
+		goto out;
+
+	ubq = ublk_get_queue(ub, ub_cmd->q_id);
+	if (!ubq || ub_cmd->q_id != ubq->q_id)

q_id is coming from userspace and is used to access an array inside ublk_get_queue(). I think you need to ensure qid < ub->dev_info.nr_hw_queues before calling ublk_get_queue() to protect from a kernel bad memory access triggered by userspace.

Quoted 4 lines
Quoted 1 line

Good catch!

Turns out the check on 'qid < ub->dev_info.nr_hw_queues' isn't needed, since the condition of 'ub_cmd->q_id != ubq->q_id' is more strict.

But ubq is retrieved via ->q_id, so we do need the validation.

Sorry for the noise.

Thanks,
Ming