xref: /openbmc/linux/drivers/block/ublk_drv.c (revision ffcdf473)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Userspace block device - block device which IO is handled from userspace
4  *
5  * Take full use of io_uring passthrough command for communicating with
6  * ublk userspace daemon(ublksrvd) for handling basic IO request.
7  *
8  * Copyright 2022 Ming Lei <ming.lei@redhat.com>
9  *
10  * (part of code stolen from loop.c)
11  */
12 #include <linux/module.h>
13 #include <linux/moduleparam.h>
14 #include <linux/sched.h>
15 #include <linux/fs.h>
16 #include <linux/pagemap.h>
17 #include <linux/file.h>
18 #include <linux/stat.h>
19 #include <linux/errno.h>
20 #include <linux/major.h>
21 #include <linux/wait.h>
22 #include <linux/blkdev.h>
23 #include <linux/init.h>
24 #include <linux/swap.h>
25 #include <linux/slab.h>
26 #include <linux/compat.h>
27 #include <linux/mutex.h>
28 #include <linux/writeback.h>
29 #include <linux/completion.h>
30 #include <linux/highmem.h>
31 #include <linux/sysfs.h>
32 #include <linux/miscdevice.h>
33 #include <linux/falloc.h>
34 #include <linux/uio.h>
35 #include <linux/ioprio.h>
36 #include <linux/sched/mm.h>
37 #include <linux/uaccess.h>
38 #include <linux/cdev.h>
39 #include <linux/io_uring.h>
40 #include <linux/blk-mq.h>
41 #include <linux/delay.h>
42 #include <linux/mm.h>
43 #include <asm/page.h>
44 #include <linux/task_work.h>
45 #include <linux/namei.h>
46 #include <uapi/linux/ublk_cmd.h>
47 
48 #define UBLK_MINORS		(1U << MINORBITS)
49 
50 /* All UBLK_F_* have to be included into UBLK_F_ALL */
51 #define UBLK_F_ALL (UBLK_F_SUPPORT_ZERO_COPY \
52 		| UBLK_F_URING_CMD_COMP_IN_TASK \
53 		| UBLK_F_NEED_GET_DATA \
54 		| UBLK_F_USER_RECOVERY \
55 		| UBLK_F_USER_RECOVERY_REISSUE \
56 		| UBLK_F_UNPRIVILEGED_DEV \
57 		| UBLK_F_CMD_IOCTL_ENCODE)
58 
59 /* All UBLK_PARAM_TYPE_* should be included here */
60 #define UBLK_PARAM_TYPE_ALL (UBLK_PARAM_TYPE_BASIC | \
61 		UBLK_PARAM_TYPE_DISCARD | UBLK_PARAM_TYPE_DEVT)
62 
63 struct ublk_rq_data {
64 	struct llist_node node;
65 	struct callback_head work;
66 };
67 
68 struct ublk_uring_cmd_pdu {
69 	struct ublk_queue *ubq;
70 };
71 
72 /*
73  * io command is active: sqe cmd is received, and its cqe isn't done
74  *
75  * If the flag is set, the io command is owned by ublk driver, and waited
76  * for incoming blk-mq request from the ublk block device.
77  *
78  * If the flag is cleared, the io command will be completed, and owned by
79  * ublk server.
80  */
81 #define UBLK_IO_FLAG_ACTIVE	0x01
82 
83 /*
84  * IO command is completed via cqe, and it is being handled by ublksrv, and
85  * not committed yet
86  *
87  * Basically exclusively with UBLK_IO_FLAG_ACTIVE, so can be served for
88  * cross verification
89  */
90 #define UBLK_IO_FLAG_OWNED_BY_SRV 0x02
91 
92 /*
93  * IO command is aborted, so this flag is set in case of
94  * !UBLK_IO_FLAG_ACTIVE.
95  *
96  * After this flag is observed, any pending or new incoming request
97  * associated with this io command will be failed immediately
98  */
99 #define UBLK_IO_FLAG_ABORTED 0x04
100 
101 /*
102  * UBLK_IO_FLAG_NEED_GET_DATA is set because IO command requires
103  * get data buffer address from ublksrv.
104  *
105  * Then, bio data could be copied into this data buffer for a WRITE request
106  * after the IO command is issued again and UBLK_IO_FLAG_NEED_GET_DATA is unset.
107  */
108 #define UBLK_IO_FLAG_NEED_GET_DATA 0x08
109 
110 struct ublk_io {
111 	/* userspace buffer address from io cmd */
112 	__u64	addr;
113 	unsigned int flags;
114 	int res;
115 
116 	struct io_uring_cmd *cmd;
117 };
118 
119 struct ublk_queue {
120 	int q_id;
121 	int q_depth;
122 
123 	unsigned long flags;
124 	struct task_struct	*ubq_daemon;
125 	char *io_cmd_buf;
126 
127 	struct llist_head	io_cmds;
128 
129 	unsigned long io_addr;	/* mapped vm address */
130 	unsigned int max_io_sz;
131 	bool force_abort;
132 	bool timeout;
133 	unsigned short nr_io_ready;	/* how many ios setup */
134 	struct ublk_device *dev;
135 	struct ublk_io ios[];
136 };
137 
138 #define UBLK_DAEMON_MONITOR_PERIOD	(5 * HZ)
139 
140 struct ublk_device {
141 	struct gendisk		*ub_disk;
142 
143 	char	*__queues;
144 
145 	unsigned int	queue_size;
146 	struct ublksrv_ctrl_dev_info	dev_info;
147 
148 	struct blk_mq_tag_set	tag_set;
149 
150 	struct cdev		cdev;
151 	struct device		cdev_dev;
152 
153 #define UB_STATE_OPEN		0
154 #define UB_STATE_USED		1
155 #define UB_STATE_DELETED	2
156 	unsigned long		state;
157 	int			ub_number;
158 
159 	struct mutex		mutex;
160 
161 	spinlock_t		mm_lock;
162 	struct mm_struct	*mm;
163 
164 	struct ublk_params	params;
165 
166 	struct completion	completion;
167 	unsigned int		nr_queues_ready;
168 	unsigned int		nr_privileged_daemon;
169 
170 	/*
171 	 * Our ubq->daemon may be killed without any notification, so
172 	 * monitor each queue's daemon periodically
173 	 */
174 	struct delayed_work	monitor_work;
175 	struct work_struct	quiesce_work;
176 	struct work_struct	stop_work;
177 };
178 
179 /* header of ublk_params */
180 struct ublk_params_header {
181 	__u32	len;
182 	__u32	types;
183 };
184 
185 static dev_t ublk_chr_devt;
186 static struct class *ublk_chr_class;
187 
188 static DEFINE_IDR(ublk_index_idr);
189 static DEFINE_SPINLOCK(ublk_idr_lock);
190 static wait_queue_head_t ublk_idr_wq;	/* wait until one idr is freed */
191 
192 static DEFINE_MUTEX(ublk_ctl_mutex);
193 
194 /*
195  * Max ublk devices allowed to add
196  *
197  * It can be extended to one per-user limit in future or even controlled
198  * by cgroup.
199  */
200 static unsigned int ublks_max = 64;
201 static unsigned int ublks_added;	/* protected by ublk_ctl_mutex */
202 
203 static struct miscdevice ublk_misc;
204 
205 static void ublk_dev_param_basic_apply(struct ublk_device *ub)
206 {
207 	struct request_queue *q = ub->ub_disk->queue;
208 	const struct ublk_param_basic *p = &ub->params.basic;
209 
210 	blk_queue_logical_block_size(q, 1 << p->logical_bs_shift);
211 	blk_queue_physical_block_size(q, 1 << p->physical_bs_shift);
212 	blk_queue_io_min(q, 1 << p->io_min_shift);
213 	blk_queue_io_opt(q, 1 << p->io_opt_shift);
214 
215 	blk_queue_write_cache(q, p->attrs & UBLK_ATTR_VOLATILE_CACHE,
216 			p->attrs & UBLK_ATTR_FUA);
217 	if (p->attrs & UBLK_ATTR_ROTATIONAL)
218 		blk_queue_flag_clear(QUEUE_FLAG_NONROT, q);
219 	else
220 		blk_queue_flag_set(QUEUE_FLAG_NONROT, q);
221 
222 	blk_queue_max_hw_sectors(q, p->max_sectors);
223 	blk_queue_chunk_sectors(q, p->chunk_sectors);
224 	blk_queue_virt_boundary(q, p->virt_boundary_mask);
225 
226 	if (p->attrs & UBLK_ATTR_READ_ONLY)
227 		set_disk_ro(ub->ub_disk, true);
228 
229 	set_capacity(ub->ub_disk, p->dev_sectors);
230 }
231 
232 static void ublk_dev_param_discard_apply(struct ublk_device *ub)
233 {
234 	struct request_queue *q = ub->ub_disk->queue;
235 	const struct ublk_param_discard *p = &ub->params.discard;
236 
237 	q->limits.discard_alignment = p->discard_alignment;
238 	q->limits.discard_granularity = p->discard_granularity;
239 	blk_queue_max_discard_sectors(q, p->max_discard_sectors);
240 	blk_queue_max_write_zeroes_sectors(q,
241 			p->max_write_zeroes_sectors);
242 	blk_queue_max_discard_segments(q, p->max_discard_segments);
243 }
244 
245 static int ublk_validate_params(const struct ublk_device *ub)
246 {
247 	/* basic param is the only one which must be set */
248 	if (ub->params.types & UBLK_PARAM_TYPE_BASIC) {
249 		const struct ublk_param_basic *p = &ub->params.basic;
250 
251 		if (p->logical_bs_shift > PAGE_SHIFT || p->logical_bs_shift < 9)
252 			return -EINVAL;
253 
254 		if (p->logical_bs_shift > p->physical_bs_shift)
255 			return -EINVAL;
256 
257 		if (p->max_sectors > (ub->dev_info.max_io_buf_bytes >> 9))
258 			return -EINVAL;
259 	} else
260 		return -EINVAL;
261 
262 	if (ub->params.types & UBLK_PARAM_TYPE_DISCARD) {
263 		const struct ublk_param_discard *p = &ub->params.discard;
264 
265 		/* So far, only support single segment discard */
266 		if (p->max_discard_sectors && p->max_discard_segments != 1)
267 			return -EINVAL;
268 
269 		if (!p->discard_granularity)
270 			return -EINVAL;
271 	}
272 
273 	/* dev_t is read-only */
274 	if (ub->params.types & UBLK_PARAM_TYPE_DEVT)
275 		return -EINVAL;
276 
277 	return 0;
278 }
279 
280 static int ublk_apply_params(struct ublk_device *ub)
281 {
282 	if (!(ub->params.types & UBLK_PARAM_TYPE_BASIC))
283 		return -EINVAL;
284 
285 	ublk_dev_param_basic_apply(ub);
286 
287 	if (ub->params.types & UBLK_PARAM_TYPE_DISCARD)
288 		ublk_dev_param_discard_apply(ub);
289 
290 	return 0;
291 }
292 
293 static inline bool ublk_can_use_task_work(const struct ublk_queue *ubq)
294 {
295 	if (IS_BUILTIN(CONFIG_BLK_DEV_UBLK) &&
296 			!(ubq->flags & UBLK_F_URING_CMD_COMP_IN_TASK))
297 		return true;
298 	return false;
299 }
300 
301 static inline bool ublk_need_get_data(const struct ublk_queue *ubq)
302 {
303 	return ubq->flags & UBLK_F_NEED_GET_DATA;
304 }
305 
306 static struct ublk_device *ublk_get_device(struct ublk_device *ub)
307 {
308 	if (kobject_get_unless_zero(&ub->cdev_dev.kobj))
309 		return ub;
310 	return NULL;
311 }
312 
313 static void ublk_put_device(struct ublk_device *ub)
314 {
315 	put_device(&ub->cdev_dev);
316 }
317 
318 static inline struct ublk_queue *ublk_get_queue(struct ublk_device *dev,
319 		int qid)
320 {
321        return (struct ublk_queue *)&(dev->__queues[qid * dev->queue_size]);
322 }
323 
324 static inline bool ublk_rq_has_data(const struct request *rq)
325 {
326 	return bio_has_data(rq->bio);
327 }
328 
329 static inline struct ublksrv_io_desc *ublk_get_iod(struct ublk_queue *ubq,
330 		int tag)
331 {
332 	return (struct ublksrv_io_desc *)
333 		&(ubq->io_cmd_buf[tag * sizeof(struct ublksrv_io_desc)]);
334 }
335 
336 static inline char *ublk_queue_cmd_buf(struct ublk_device *ub, int q_id)
337 {
338 	return ublk_get_queue(ub, q_id)->io_cmd_buf;
339 }
340 
341 static inline int ublk_queue_cmd_buf_size(struct ublk_device *ub, int q_id)
342 {
343 	struct ublk_queue *ubq = ublk_get_queue(ub, q_id);
344 
345 	return round_up(ubq->q_depth * sizeof(struct ublksrv_io_desc),
346 			PAGE_SIZE);
347 }
348 
349 static inline bool ublk_queue_can_use_recovery_reissue(
350 		struct ublk_queue *ubq)
351 {
352 	return (ubq->flags & UBLK_F_USER_RECOVERY) &&
353 			(ubq->flags & UBLK_F_USER_RECOVERY_REISSUE);
354 }
355 
356 static inline bool ublk_queue_can_use_recovery(
357 		struct ublk_queue *ubq)
358 {
359 	return ubq->flags & UBLK_F_USER_RECOVERY;
360 }
361 
362 static inline bool ublk_can_use_recovery(struct ublk_device *ub)
363 {
364 	return ub->dev_info.flags & UBLK_F_USER_RECOVERY;
365 }
366 
367 static void ublk_free_disk(struct gendisk *disk)
368 {
369 	struct ublk_device *ub = disk->private_data;
370 
371 	clear_bit(UB_STATE_USED, &ub->state);
372 	put_device(&ub->cdev_dev);
373 }
374 
375 static void ublk_store_owner_uid_gid(unsigned int *owner_uid,
376 		unsigned int *owner_gid)
377 {
378 	kuid_t uid;
379 	kgid_t gid;
380 
381 	current_uid_gid(&uid, &gid);
382 
383 	*owner_uid = from_kuid(&init_user_ns, uid);
384 	*owner_gid = from_kgid(&init_user_ns, gid);
385 }
386 
387 static int ublk_open(struct block_device *bdev, fmode_t mode)
388 {
389 	struct ublk_device *ub = bdev->bd_disk->private_data;
390 
391 	if (capable(CAP_SYS_ADMIN))
392 		return 0;
393 
394 	/*
395 	 * If it is one unprivileged device, only owner can open
396 	 * the disk. Otherwise it could be one trap made by one
397 	 * evil user who grants this disk's privileges to other
398 	 * users deliberately.
399 	 *
400 	 * This way is reasonable too given anyone can create
401 	 * unprivileged device, and no need other's grant.
402 	 */
403 	if (ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV) {
404 		unsigned int curr_uid, curr_gid;
405 
406 		ublk_store_owner_uid_gid(&curr_uid, &curr_gid);
407 
408 		if (curr_uid != ub->dev_info.owner_uid || curr_gid !=
409 				ub->dev_info.owner_gid)
410 			return -EPERM;
411 	}
412 
413 	return 0;
414 }
415 
416 static const struct block_device_operations ub_fops = {
417 	.owner =	THIS_MODULE,
418 	.open =		ublk_open,
419 	.free_disk =	ublk_free_disk,
420 };
421 
422 #define UBLK_MAX_PIN_PAGES	32
423 
424 struct ublk_map_data {
425 	const struct request *rq;
426 	unsigned long	ubuf;
427 	unsigned int	len;
428 };
429 
430 struct ublk_io_iter {
431 	struct page *pages[UBLK_MAX_PIN_PAGES];
432 	unsigned pg_off;	/* offset in the 1st page in pages */
433 	int nr_pages;		/* how many page pointers in pages */
434 	struct bio *bio;
435 	struct bvec_iter iter;
436 };
437 
438 static inline unsigned ublk_copy_io_pages(struct ublk_io_iter *data,
439 		unsigned max_bytes, bool to_vm)
440 {
441 	const unsigned total = min_t(unsigned, max_bytes,
442 			PAGE_SIZE - data->pg_off +
443 			((data->nr_pages - 1) << PAGE_SHIFT));
444 	unsigned done = 0;
445 	unsigned pg_idx = 0;
446 
447 	while (done < total) {
448 		struct bio_vec bv = bio_iter_iovec(data->bio, data->iter);
449 		const unsigned int bytes = min3(bv.bv_len, total - done,
450 				(unsigned)(PAGE_SIZE - data->pg_off));
451 		void *bv_buf = bvec_kmap_local(&bv);
452 		void *pg_buf = kmap_local_page(data->pages[pg_idx]);
453 
454 		if (to_vm)
455 			memcpy(pg_buf + data->pg_off, bv_buf, bytes);
456 		else
457 			memcpy(bv_buf, pg_buf + data->pg_off, bytes);
458 
459 		kunmap_local(pg_buf);
460 		kunmap_local(bv_buf);
461 
462 		/* advance page array */
463 		data->pg_off += bytes;
464 		if (data->pg_off == PAGE_SIZE) {
465 			pg_idx += 1;
466 			data->pg_off = 0;
467 		}
468 
469 		done += bytes;
470 
471 		/* advance bio */
472 		bio_advance_iter_single(data->bio, &data->iter, bytes);
473 		if (!data->iter.bi_size) {
474 			data->bio = data->bio->bi_next;
475 			if (data->bio == NULL)
476 				break;
477 			data->iter = data->bio->bi_iter;
478 		}
479 	}
480 
481 	return done;
482 }
483 
484 static int ublk_copy_user_pages(struct ublk_map_data *data, bool to_vm)
485 {
486 	const unsigned int gup_flags = to_vm ? FOLL_WRITE : 0;
487 	const unsigned long start_vm = data->ubuf;
488 	unsigned int done = 0;
489 	struct ublk_io_iter iter = {
490 		.pg_off	= start_vm & (PAGE_SIZE - 1),
491 		.bio	= data->rq->bio,
492 		.iter	= data->rq->bio->bi_iter,
493 	};
494 	const unsigned int nr_pages = round_up(data->len +
495 			(start_vm & (PAGE_SIZE - 1)), PAGE_SIZE) >> PAGE_SHIFT;
496 
497 	while (done < nr_pages) {
498 		const unsigned to_pin = min_t(unsigned, UBLK_MAX_PIN_PAGES,
499 				nr_pages - done);
500 		unsigned i, len;
501 
502 		iter.nr_pages = get_user_pages_fast(start_vm +
503 				(done << PAGE_SHIFT), to_pin, gup_flags,
504 				iter.pages);
505 		if (iter.nr_pages <= 0)
506 			return done == 0 ? iter.nr_pages : done;
507 		len = ublk_copy_io_pages(&iter, data->len, to_vm);
508 		for (i = 0; i < iter.nr_pages; i++) {
509 			if (to_vm)
510 				set_page_dirty(iter.pages[i]);
511 			put_page(iter.pages[i]);
512 		}
513 		data->len -= len;
514 		done += iter.nr_pages;
515 	}
516 
517 	return done;
518 }
519 
520 static inline bool ublk_need_map_req(const struct request *req)
521 {
522 	return ublk_rq_has_data(req) && req_op(req) == REQ_OP_WRITE;
523 }
524 
525 static inline bool ublk_need_unmap_req(const struct request *req)
526 {
527 	return ublk_rq_has_data(req) && req_op(req) == REQ_OP_READ;
528 }
529 
530 static int ublk_map_io(const struct ublk_queue *ubq, const struct request *req,
531 		struct ublk_io *io)
532 {
533 	const unsigned int rq_bytes = blk_rq_bytes(req);
534 
535 	/*
536 	 * no zero copy, we delay copy WRITE request data into ublksrv
537 	 * context and the big benefit is that pinning pages in current
538 	 * context is pretty fast, see ublk_pin_user_pages
539 	 */
540 	if (ublk_need_map_req(req)) {
541 		struct ublk_map_data data = {
542 			.rq	=	req,
543 			.ubuf	=	io->addr,
544 			.len	=	rq_bytes,
545 		};
546 
547 		ublk_copy_user_pages(&data, true);
548 
549 		return rq_bytes - data.len;
550 	}
551 	return rq_bytes;
552 }
553 
554 static int ublk_unmap_io(const struct ublk_queue *ubq,
555 		const struct request *req,
556 		struct ublk_io *io)
557 {
558 	const unsigned int rq_bytes = blk_rq_bytes(req);
559 
560 	if (ublk_need_unmap_req(req)) {
561 		struct ublk_map_data data = {
562 			.rq	=	req,
563 			.ubuf	=	io->addr,
564 			.len	=	io->res,
565 		};
566 
567 		WARN_ON_ONCE(io->res > rq_bytes);
568 
569 		ublk_copy_user_pages(&data, false);
570 
571 		return io->res - data.len;
572 	}
573 	return rq_bytes;
574 }
575 
576 static inline unsigned int ublk_req_build_flags(struct request *req)
577 {
578 	unsigned flags = 0;
579 
580 	if (req->cmd_flags & REQ_FAILFAST_DEV)
581 		flags |= UBLK_IO_F_FAILFAST_DEV;
582 
583 	if (req->cmd_flags & REQ_FAILFAST_TRANSPORT)
584 		flags |= UBLK_IO_F_FAILFAST_TRANSPORT;
585 
586 	if (req->cmd_flags & REQ_FAILFAST_DRIVER)
587 		flags |= UBLK_IO_F_FAILFAST_DRIVER;
588 
589 	if (req->cmd_flags & REQ_META)
590 		flags |= UBLK_IO_F_META;
591 
592 	if (req->cmd_flags & REQ_FUA)
593 		flags |= UBLK_IO_F_FUA;
594 
595 	if (req->cmd_flags & REQ_NOUNMAP)
596 		flags |= UBLK_IO_F_NOUNMAP;
597 
598 	if (req->cmd_flags & REQ_SWAP)
599 		flags |= UBLK_IO_F_SWAP;
600 
601 	return flags;
602 }
603 
604 static blk_status_t ublk_setup_iod(struct ublk_queue *ubq, struct request *req)
605 {
606 	struct ublksrv_io_desc *iod = ublk_get_iod(ubq, req->tag);
607 	struct ublk_io *io = &ubq->ios[req->tag];
608 	u32 ublk_op;
609 
610 	switch (req_op(req)) {
611 	case REQ_OP_READ:
612 		ublk_op = UBLK_IO_OP_READ;
613 		break;
614 	case REQ_OP_WRITE:
615 		ublk_op = UBLK_IO_OP_WRITE;
616 		break;
617 	case REQ_OP_FLUSH:
618 		ublk_op = UBLK_IO_OP_FLUSH;
619 		break;
620 	case REQ_OP_DISCARD:
621 		ublk_op = UBLK_IO_OP_DISCARD;
622 		break;
623 	case REQ_OP_WRITE_ZEROES:
624 		ublk_op = UBLK_IO_OP_WRITE_ZEROES;
625 		break;
626 	default:
627 		return BLK_STS_IOERR;
628 	}
629 
630 	/* need to translate since kernel may change */
631 	iod->op_flags = ublk_op | ublk_req_build_flags(req);
632 	iod->nr_sectors = blk_rq_sectors(req);
633 	iod->start_sector = blk_rq_pos(req);
634 	iod->addr = io->addr;
635 
636 	return BLK_STS_OK;
637 }
638 
639 static inline struct ublk_uring_cmd_pdu *ublk_get_uring_cmd_pdu(
640 		struct io_uring_cmd *ioucmd)
641 {
642 	return (struct ublk_uring_cmd_pdu *)&ioucmd->pdu;
643 }
644 
645 static inline bool ubq_daemon_is_dying(struct ublk_queue *ubq)
646 {
647 	return ubq->ubq_daemon->flags & PF_EXITING;
648 }
649 
650 /* todo: handle partial completion */
651 static void ublk_complete_rq(struct request *req)
652 {
653 	struct ublk_queue *ubq = req->mq_hctx->driver_data;
654 	struct ublk_io *io = &ubq->ios[req->tag];
655 	unsigned int unmapped_bytes;
656 	blk_status_t res = BLK_STS_OK;
657 
658 	/* failed read IO if nothing is read */
659 	if (!io->res && req_op(req) == REQ_OP_READ)
660 		io->res = -EIO;
661 
662 	if (io->res < 0) {
663 		res = errno_to_blk_status(io->res);
664 		goto exit;
665 	}
666 
667 	/*
668 	 * FLUSH, DISCARD or WRITE_ZEROES usually won't return bytes returned, so end them
669 	 * directly.
670 	 *
671 	 * Both the two needn't unmap.
672 	 */
673 	if (req_op(req) != REQ_OP_READ && req_op(req) != REQ_OP_WRITE)
674 		goto exit;
675 
676 	/* for READ request, writing data in iod->addr to rq buffers */
677 	unmapped_bytes = ublk_unmap_io(ubq, req, io);
678 
679 	/*
680 	 * Extremely impossible since we got data filled in just before
681 	 *
682 	 * Re-read simply for this unlikely case.
683 	 */
684 	if (unlikely(unmapped_bytes < io->res))
685 		io->res = unmapped_bytes;
686 
687 	if (blk_update_request(req, BLK_STS_OK, io->res))
688 		blk_mq_requeue_request(req, true);
689 	else
690 		__blk_mq_end_request(req, BLK_STS_OK);
691 
692 	return;
693 exit:
694 	blk_mq_end_request(req, res);
695 }
696 
697 /*
698  * Since __ublk_rq_task_work always fails requests immediately during
699  * exiting, __ublk_fail_req() is only called from abort context during
700  * exiting. So lock is unnecessary.
701  *
702  * Also aborting may not be started yet, keep in mind that one failed
703  * request may be issued by block layer again.
704  */
705 static void __ublk_fail_req(struct ublk_queue *ubq, struct ublk_io *io,
706 		struct request *req)
707 {
708 	WARN_ON_ONCE(io->flags & UBLK_IO_FLAG_ACTIVE);
709 
710 	if (!(io->flags & UBLK_IO_FLAG_ABORTED)) {
711 		io->flags |= UBLK_IO_FLAG_ABORTED;
712 		if (ublk_queue_can_use_recovery_reissue(ubq))
713 			blk_mq_requeue_request(req, false);
714 		else
715 			blk_mq_end_request(req, BLK_STS_IOERR);
716 	}
717 }
718 
719 static void ubq_complete_io_cmd(struct ublk_io *io, int res,
720 				unsigned issue_flags)
721 {
722 	/* mark this cmd owned by ublksrv */
723 	io->flags |= UBLK_IO_FLAG_OWNED_BY_SRV;
724 
725 	/*
726 	 * clear ACTIVE since we are done with this sqe/cmd slot
727 	 * We can only accept io cmd in case of being not active.
728 	 */
729 	io->flags &= ~UBLK_IO_FLAG_ACTIVE;
730 
731 	/* tell ublksrv one io request is coming */
732 	io_uring_cmd_done(io->cmd, res, 0, issue_flags);
733 }
734 
735 #define UBLK_REQUEUE_DELAY_MS	3
736 
737 static inline void __ublk_abort_rq(struct ublk_queue *ubq,
738 		struct request *rq)
739 {
740 	/* We cannot process this rq so just requeue it. */
741 	if (ublk_queue_can_use_recovery(ubq))
742 		blk_mq_requeue_request(rq, false);
743 	else
744 		blk_mq_end_request(rq, BLK_STS_IOERR);
745 
746 	mod_delayed_work(system_wq, &ubq->dev->monitor_work, 0);
747 }
748 
749 static inline void __ublk_rq_task_work(struct request *req,
750 				       unsigned issue_flags)
751 {
752 	struct ublk_queue *ubq = req->mq_hctx->driver_data;
753 	int tag = req->tag;
754 	struct ublk_io *io = &ubq->ios[tag];
755 	unsigned int mapped_bytes;
756 
757 	pr_devel("%s: complete: op %d, qid %d tag %d io_flags %x addr %llx\n",
758 			__func__, io->cmd->cmd_op, ubq->q_id, req->tag, io->flags,
759 			ublk_get_iod(ubq, req->tag)->addr);
760 
761 	/*
762 	 * Task is exiting if either:
763 	 *
764 	 * (1) current != ubq_daemon.
765 	 * io_uring_cmd_complete_in_task() tries to run task_work
766 	 * in a workqueue if ubq_daemon(cmd's task) is PF_EXITING.
767 	 *
768 	 * (2) current->flags & PF_EXITING.
769 	 */
770 	if (unlikely(current != ubq->ubq_daemon || current->flags & PF_EXITING)) {
771 		__ublk_abort_rq(ubq, req);
772 		return;
773 	}
774 
775 	if (ublk_need_get_data(ubq) && ublk_need_map_req(req)) {
776 		/*
777 		 * We have not handled UBLK_IO_NEED_GET_DATA command yet,
778 		 * so immepdately pass UBLK_IO_RES_NEED_GET_DATA to ublksrv
779 		 * and notify it.
780 		 */
781 		if (!(io->flags & UBLK_IO_FLAG_NEED_GET_DATA)) {
782 			io->flags |= UBLK_IO_FLAG_NEED_GET_DATA;
783 			pr_devel("%s: need get data. op %d, qid %d tag %d io_flags %x\n",
784 					__func__, io->cmd->cmd_op, ubq->q_id,
785 					req->tag, io->flags);
786 			ubq_complete_io_cmd(io, UBLK_IO_RES_NEED_GET_DATA, issue_flags);
787 			return;
788 		}
789 		/*
790 		 * We have handled UBLK_IO_NEED_GET_DATA command,
791 		 * so clear UBLK_IO_FLAG_NEED_GET_DATA now and just
792 		 * do the copy work.
793 		 */
794 		io->flags &= ~UBLK_IO_FLAG_NEED_GET_DATA;
795 		/* update iod->addr because ublksrv may have passed a new io buffer */
796 		ublk_get_iod(ubq, req->tag)->addr = io->addr;
797 		pr_devel("%s: update iod->addr: op %d, qid %d tag %d io_flags %x addr %llx\n",
798 				__func__, io->cmd->cmd_op, ubq->q_id, req->tag, io->flags,
799 				ublk_get_iod(ubq, req->tag)->addr);
800 	}
801 
802 	mapped_bytes = ublk_map_io(ubq, req, io);
803 
804 	/* partially mapped, update io descriptor */
805 	if (unlikely(mapped_bytes != blk_rq_bytes(req))) {
806 		/*
807 		 * Nothing mapped, retry until we succeed.
808 		 *
809 		 * We may never succeed in mapping any bytes here because
810 		 * of OOM. TODO: reserve one buffer with single page pinned
811 		 * for providing forward progress guarantee.
812 		 */
813 		if (unlikely(!mapped_bytes)) {
814 			blk_mq_requeue_request(req, false);
815 			blk_mq_delay_kick_requeue_list(req->q,
816 					UBLK_REQUEUE_DELAY_MS);
817 			return;
818 		}
819 
820 		ublk_get_iod(ubq, req->tag)->nr_sectors =
821 			mapped_bytes >> 9;
822 	}
823 
824 	ubq_complete_io_cmd(io, UBLK_IO_RES_OK, issue_flags);
825 }
826 
827 static inline void ublk_forward_io_cmds(struct ublk_queue *ubq,
828 					unsigned issue_flags)
829 {
830 	struct llist_node *io_cmds = llist_del_all(&ubq->io_cmds);
831 	struct ublk_rq_data *data, *tmp;
832 
833 	io_cmds = llist_reverse_order(io_cmds);
834 	llist_for_each_entry_safe(data, tmp, io_cmds, node)
835 		__ublk_rq_task_work(blk_mq_rq_from_pdu(data), issue_flags);
836 }
837 
838 static inline void ublk_abort_io_cmds(struct ublk_queue *ubq)
839 {
840 	struct llist_node *io_cmds = llist_del_all(&ubq->io_cmds);
841 	struct ublk_rq_data *data, *tmp;
842 
843 	llist_for_each_entry_safe(data, tmp, io_cmds, node)
844 		__ublk_abort_rq(ubq, blk_mq_rq_from_pdu(data));
845 }
846 
847 static void ublk_rq_task_work_cb(struct io_uring_cmd *cmd, unsigned issue_flags)
848 {
849 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
850 	struct ublk_queue *ubq = pdu->ubq;
851 
852 	ublk_forward_io_cmds(ubq, issue_flags);
853 }
854 
855 static void ublk_rq_task_work_fn(struct callback_head *work)
856 {
857 	struct ublk_rq_data *data = container_of(work,
858 			struct ublk_rq_data, work);
859 	struct request *req = blk_mq_rq_from_pdu(data);
860 	struct ublk_queue *ubq = req->mq_hctx->driver_data;
861 	unsigned issue_flags = IO_URING_F_UNLOCKED;
862 
863 	ublk_forward_io_cmds(ubq, issue_flags);
864 }
865 
866 static void ublk_queue_cmd(struct ublk_queue *ubq, struct request *rq)
867 {
868 	struct ublk_rq_data *data = blk_mq_rq_to_pdu(rq);
869 	struct ublk_io *io;
870 
871 	if (!llist_add(&data->node, &ubq->io_cmds))
872 		return;
873 
874 	io = &ubq->ios[rq->tag];
875 	/*
876 	 * If the check pass, we know that this is a re-issued request aborted
877 	 * previously in monitor_work because the ubq_daemon(cmd's task) is
878 	 * PF_EXITING. We cannot call io_uring_cmd_complete_in_task() anymore
879 	 * because this ioucmd's io_uring context may be freed now if no inflight
880 	 * ioucmd exists. Otherwise we may cause null-deref in ctx->fallback_work.
881 	 *
882 	 * Note: monitor_work sets UBLK_IO_FLAG_ABORTED and ends this request(releasing
883 	 * the tag). Then the request is re-started(allocating the tag) and we are here.
884 	 * Since releasing/allocating a tag implies smp_mb(), finding UBLK_IO_FLAG_ABORTED
885 	 * guarantees that here is a re-issued request aborted previously.
886 	 */
887 	if (unlikely(io->flags & UBLK_IO_FLAG_ABORTED)) {
888 		ublk_abort_io_cmds(ubq);
889 	} else if (ublk_can_use_task_work(ubq)) {
890 		if (task_work_add(ubq->ubq_daemon, &data->work,
891 					TWA_SIGNAL_NO_IPI))
892 			ublk_abort_io_cmds(ubq);
893 	} else {
894 		struct io_uring_cmd *cmd = io->cmd;
895 		struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
896 
897 		pdu->ubq = ubq;
898 		io_uring_cmd_complete_in_task(cmd, ublk_rq_task_work_cb);
899 	}
900 }
901 
902 static enum blk_eh_timer_return ublk_timeout(struct request *rq)
903 {
904 	struct ublk_queue *ubq = rq->mq_hctx->driver_data;
905 
906 	if (ubq->flags & UBLK_F_UNPRIVILEGED_DEV) {
907 		if (!ubq->timeout) {
908 			send_sig(SIGKILL, ubq->ubq_daemon, 0);
909 			ubq->timeout = true;
910 		}
911 
912 		return BLK_EH_DONE;
913 	}
914 
915 	return BLK_EH_RESET_TIMER;
916 }
917 
918 static blk_status_t ublk_queue_rq(struct blk_mq_hw_ctx *hctx,
919 		const struct blk_mq_queue_data *bd)
920 {
921 	struct ublk_queue *ubq = hctx->driver_data;
922 	struct request *rq = bd->rq;
923 	blk_status_t res;
924 
925 	/* fill iod to slot in io cmd buffer */
926 	res = ublk_setup_iod(ubq, rq);
927 	if (unlikely(res != BLK_STS_OK))
928 		return BLK_STS_IOERR;
929 
930 	/* With recovery feature enabled, force_abort is set in
931 	 * ublk_stop_dev() before calling del_gendisk(). We have to
932 	 * abort all requeued and new rqs here to let del_gendisk()
933 	 * move on. Besides, we cannot not call io_uring_cmd_complete_in_task()
934 	 * to avoid UAF on io_uring ctx.
935 	 *
936 	 * Note: force_abort is guaranteed to be seen because it is set
937 	 * before request queue is unqiuesced.
938 	 */
939 	if (ublk_queue_can_use_recovery(ubq) && unlikely(ubq->force_abort))
940 		return BLK_STS_IOERR;
941 
942 	blk_mq_start_request(bd->rq);
943 
944 	if (unlikely(ubq_daemon_is_dying(ubq))) {
945 		__ublk_abort_rq(ubq, rq);
946 		return BLK_STS_OK;
947 	}
948 
949 	ublk_queue_cmd(ubq, rq);
950 
951 	return BLK_STS_OK;
952 }
953 
954 static int ublk_init_hctx(struct blk_mq_hw_ctx *hctx, void *driver_data,
955 		unsigned int hctx_idx)
956 {
957 	struct ublk_device *ub = driver_data;
958 	struct ublk_queue *ubq = ublk_get_queue(ub, hctx->queue_num);
959 
960 	hctx->driver_data = ubq;
961 	return 0;
962 }
963 
964 static int ublk_init_rq(struct blk_mq_tag_set *set, struct request *req,
965 		unsigned int hctx_idx, unsigned int numa_node)
966 {
967 	struct ublk_rq_data *data = blk_mq_rq_to_pdu(req);
968 
969 	init_task_work(&data->work, ublk_rq_task_work_fn);
970 	return 0;
971 }
972 
973 static const struct blk_mq_ops ublk_mq_ops = {
974 	.queue_rq       = ublk_queue_rq,
975 	.init_hctx	= ublk_init_hctx,
976 	.init_request   = ublk_init_rq,
977 	.timeout	= ublk_timeout,
978 };
979 
980 static int ublk_ch_open(struct inode *inode, struct file *filp)
981 {
982 	struct ublk_device *ub = container_of(inode->i_cdev,
983 			struct ublk_device, cdev);
984 
985 	if (test_and_set_bit(UB_STATE_OPEN, &ub->state))
986 		return -EBUSY;
987 	filp->private_data = ub;
988 	return 0;
989 }
990 
991 static int ublk_ch_release(struct inode *inode, struct file *filp)
992 {
993 	struct ublk_device *ub = filp->private_data;
994 
995 	clear_bit(UB_STATE_OPEN, &ub->state);
996 	return 0;
997 }
998 
999 /* map pre-allocated per-queue cmd buffer to ublksrv daemon */
1000 static int ublk_ch_mmap(struct file *filp, struct vm_area_struct *vma)
1001 {
1002 	struct ublk_device *ub = filp->private_data;
1003 	size_t sz = vma->vm_end - vma->vm_start;
1004 	unsigned max_sz = UBLK_MAX_QUEUE_DEPTH * sizeof(struct ublksrv_io_desc);
1005 	unsigned long pfn, end, phys_off = vma->vm_pgoff << PAGE_SHIFT;
1006 	int q_id, ret = 0;
1007 
1008 	spin_lock(&ub->mm_lock);
1009 	if (!ub->mm)
1010 		ub->mm = current->mm;
1011 	if (current->mm != ub->mm)
1012 		ret = -EINVAL;
1013 	spin_unlock(&ub->mm_lock);
1014 
1015 	if (ret)
1016 		return ret;
1017 
1018 	if (vma->vm_flags & VM_WRITE)
1019 		return -EPERM;
1020 
1021 	end = UBLKSRV_CMD_BUF_OFFSET + ub->dev_info.nr_hw_queues * max_sz;
1022 	if (phys_off < UBLKSRV_CMD_BUF_OFFSET || phys_off >= end)
1023 		return -EINVAL;
1024 
1025 	q_id = (phys_off - UBLKSRV_CMD_BUF_OFFSET) / max_sz;
1026 	pr_devel("%s: qid %d, pid %d, addr %lx pg_off %lx sz %lu\n",
1027 			__func__, q_id, current->pid, vma->vm_start,
1028 			phys_off, (unsigned long)sz);
1029 
1030 	if (sz != ublk_queue_cmd_buf_size(ub, q_id))
1031 		return -EINVAL;
1032 
1033 	pfn = virt_to_phys(ublk_queue_cmd_buf(ub, q_id)) >> PAGE_SHIFT;
1034 	return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
1035 }
1036 
1037 static void ublk_commit_completion(struct ublk_device *ub,
1038 		const struct ublksrv_io_cmd *ub_cmd)
1039 {
1040 	u32 qid = ub_cmd->q_id, tag = ub_cmd->tag;
1041 	struct ublk_queue *ubq = ublk_get_queue(ub, qid);
1042 	struct ublk_io *io = &ubq->ios[tag];
1043 	struct request *req;
1044 
1045 	/* now this cmd slot is owned by nbd driver */
1046 	io->flags &= ~UBLK_IO_FLAG_OWNED_BY_SRV;
1047 	io->res = ub_cmd->result;
1048 
1049 	/* find the io request and complete */
1050 	req = blk_mq_tag_to_rq(ub->tag_set.tags[qid], tag);
1051 
1052 	if (req && likely(!blk_should_fake_timeout(req->q)))
1053 		ublk_complete_rq(req);
1054 }
1055 
1056 /*
1057  * When ->ubq_daemon is exiting, either new request is ended immediately,
1058  * or any queued io command is drained, so it is safe to abort queue
1059  * lockless
1060  */
1061 static void ublk_abort_queue(struct ublk_device *ub, struct ublk_queue *ubq)
1062 {
1063 	int i;
1064 
1065 	if (!ublk_get_device(ub))
1066 		return;
1067 
1068 	for (i = 0; i < ubq->q_depth; i++) {
1069 		struct ublk_io *io = &ubq->ios[i];
1070 
1071 		if (!(io->flags & UBLK_IO_FLAG_ACTIVE)) {
1072 			struct request *rq;
1073 
1074 			/*
1075 			 * Either we fail the request or ublk_rq_task_work_fn
1076 			 * will do it
1077 			 */
1078 			rq = blk_mq_tag_to_rq(ub->tag_set.tags[ubq->q_id], i);
1079 			if (rq)
1080 				__ublk_fail_req(ubq, io, rq);
1081 		}
1082 	}
1083 	ublk_put_device(ub);
1084 }
1085 
1086 static void ublk_daemon_monitor_work(struct work_struct *work)
1087 {
1088 	struct ublk_device *ub =
1089 		container_of(work, struct ublk_device, monitor_work.work);
1090 	int i;
1091 
1092 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++) {
1093 		struct ublk_queue *ubq = ublk_get_queue(ub, i);
1094 
1095 		if (ubq_daemon_is_dying(ubq)) {
1096 			if (ublk_queue_can_use_recovery(ubq))
1097 				schedule_work(&ub->quiesce_work);
1098 			else
1099 				schedule_work(&ub->stop_work);
1100 
1101 			/* abort queue is for making forward progress */
1102 			ublk_abort_queue(ub, ubq);
1103 		}
1104 	}
1105 
1106 	/*
1107 	 * We can't schedule monitor work after ub's state is not UBLK_S_DEV_LIVE.
1108 	 * after ublk_remove() or __ublk_quiesce_dev() is started.
1109 	 *
1110 	 * No need ub->mutex, monitor work are canceled after state is marked
1111 	 * as not LIVE, so new state is observed reliably.
1112 	 */
1113 	if (ub->dev_info.state == UBLK_S_DEV_LIVE)
1114 		schedule_delayed_work(&ub->monitor_work,
1115 				UBLK_DAEMON_MONITOR_PERIOD);
1116 }
1117 
1118 static inline bool ublk_queue_ready(struct ublk_queue *ubq)
1119 {
1120 	return ubq->nr_io_ready == ubq->q_depth;
1121 }
1122 
1123 static void ublk_cmd_cancel_cb(struct io_uring_cmd *cmd, unsigned issue_flags)
1124 {
1125 	io_uring_cmd_done(cmd, UBLK_IO_RES_ABORT, 0, issue_flags);
1126 }
1127 
1128 static void ublk_cancel_queue(struct ublk_queue *ubq)
1129 {
1130 	int i;
1131 
1132 	if (!ublk_queue_ready(ubq))
1133 		return;
1134 
1135 	for (i = 0; i < ubq->q_depth; i++) {
1136 		struct ublk_io *io = &ubq->ios[i];
1137 
1138 		if (io->flags & UBLK_IO_FLAG_ACTIVE)
1139 			io_uring_cmd_complete_in_task(io->cmd,
1140 						      ublk_cmd_cancel_cb);
1141 	}
1142 
1143 	/* all io commands are canceled */
1144 	ubq->nr_io_ready = 0;
1145 }
1146 
1147 /* Cancel all pending commands, must be called after del_gendisk() returns */
1148 static void ublk_cancel_dev(struct ublk_device *ub)
1149 {
1150 	int i;
1151 
1152 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1153 		ublk_cancel_queue(ublk_get_queue(ub, i));
1154 }
1155 
1156 static bool ublk_check_inflight_rq(struct request *rq, void *data)
1157 {
1158 	bool *idle = data;
1159 
1160 	if (blk_mq_request_started(rq)) {
1161 		*idle = false;
1162 		return false;
1163 	}
1164 	return true;
1165 }
1166 
1167 static void ublk_wait_tagset_rqs_idle(struct ublk_device *ub)
1168 {
1169 	bool idle;
1170 
1171 	WARN_ON_ONCE(!blk_queue_quiesced(ub->ub_disk->queue));
1172 	while (true) {
1173 		idle = true;
1174 		blk_mq_tagset_busy_iter(&ub->tag_set,
1175 				ublk_check_inflight_rq, &idle);
1176 		if (idle)
1177 			break;
1178 		msleep(UBLK_REQUEUE_DELAY_MS);
1179 	}
1180 }
1181 
1182 static void __ublk_quiesce_dev(struct ublk_device *ub)
1183 {
1184 	pr_devel("%s: quiesce ub: dev_id %d state %s\n",
1185 			__func__, ub->dev_info.dev_id,
1186 			ub->dev_info.state == UBLK_S_DEV_LIVE ?
1187 			"LIVE" : "QUIESCED");
1188 	blk_mq_quiesce_queue(ub->ub_disk->queue);
1189 	ublk_wait_tagset_rqs_idle(ub);
1190 	ub->dev_info.state = UBLK_S_DEV_QUIESCED;
1191 	ublk_cancel_dev(ub);
1192 	/* we are going to release task_struct of ubq_daemon and resets
1193 	 * ->ubq_daemon to NULL. So in monitor_work, check on ubq_daemon causes UAF.
1194 	 * Besides, monitor_work is not necessary in QUIESCED state since we have
1195 	 * already scheduled quiesce_work and quiesced all ubqs.
1196 	 *
1197 	 * Do not let monitor_work schedule itself if state it QUIESCED. And we cancel
1198 	 * it here and re-schedule it in END_USER_RECOVERY to avoid UAF.
1199 	 */
1200 	cancel_delayed_work_sync(&ub->monitor_work);
1201 }
1202 
1203 static void ublk_quiesce_work_fn(struct work_struct *work)
1204 {
1205 	struct ublk_device *ub =
1206 		container_of(work, struct ublk_device, quiesce_work);
1207 
1208 	mutex_lock(&ub->mutex);
1209 	if (ub->dev_info.state != UBLK_S_DEV_LIVE)
1210 		goto unlock;
1211 	__ublk_quiesce_dev(ub);
1212  unlock:
1213 	mutex_unlock(&ub->mutex);
1214 }
1215 
1216 static void ublk_unquiesce_dev(struct ublk_device *ub)
1217 {
1218 	int i;
1219 
1220 	pr_devel("%s: unquiesce ub: dev_id %d state %s\n",
1221 			__func__, ub->dev_info.dev_id,
1222 			ub->dev_info.state == UBLK_S_DEV_LIVE ?
1223 			"LIVE" : "QUIESCED");
1224 	/* quiesce_work has run. We let requeued rqs be aborted
1225 	 * before running fallback_wq. "force_abort" must be seen
1226 	 * after request queue is unqiuesced. Then del_gendisk()
1227 	 * can move on.
1228 	 */
1229 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1230 		ublk_get_queue(ub, i)->force_abort = true;
1231 
1232 	blk_mq_unquiesce_queue(ub->ub_disk->queue);
1233 	/* We may have requeued some rqs in ublk_quiesce_queue() */
1234 	blk_mq_kick_requeue_list(ub->ub_disk->queue);
1235 }
1236 
1237 static void ublk_stop_dev(struct ublk_device *ub)
1238 {
1239 	mutex_lock(&ub->mutex);
1240 	if (ub->dev_info.state == UBLK_S_DEV_DEAD)
1241 		goto unlock;
1242 	if (ublk_can_use_recovery(ub)) {
1243 		if (ub->dev_info.state == UBLK_S_DEV_LIVE)
1244 			__ublk_quiesce_dev(ub);
1245 		ublk_unquiesce_dev(ub);
1246 	}
1247 	del_gendisk(ub->ub_disk);
1248 	ub->dev_info.state = UBLK_S_DEV_DEAD;
1249 	ub->dev_info.ublksrv_pid = -1;
1250 	put_disk(ub->ub_disk);
1251 	ub->ub_disk = NULL;
1252  unlock:
1253 	ublk_cancel_dev(ub);
1254 	mutex_unlock(&ub->mutex);
1255 	cancel_delayed_work_sync(&ub->monitor_work);
1256 }
1257 
1258 /* device can only be started after all IOs are ready */
1259 static void ublk_mark_io_ready(struct ublk_device *ub, struct ublk_queue *ubq)
1260 {
1261 	mutex_lock(&ub->mutex);
1262 	ubq->nr_io_ready++;
1263 	if (ublk_queue_ready(ubq)) {
1264 		ubq->ubq_daemon = current;
1265 		get_task_struct(ubq->ubq_daemon);
1266 		ub->nr_queues_ready++;
1267 
1268 		if (capable(CAP_SYS_ADMIN))
1269 			ub->nr_privileged_daemon++;
1270 	}
1271 	if (ub->nr_queues_ready == ub->dev_info.nr_hw_queues)
1272 		complete_all(&ub->completion);
1273 	mutex_unlock(&ub->mutex);
1274 }
1275 
1276 static void ublk_handle_need_get_data(struct ublk_device *ub, int q_id,
1277 		int tag)
1278 {
1279 	struct ublk_queue *ubq = ublk_get_queue(ub, q_id);
1280 	struct request *req = blk_mq_tag_to_rq(ub->tag_set.tags[q_id], tag);
1281 
1282 	ublk_queue_cmd(ubq, req);
1283 }
1284 
1285 static inline int ublk_check_cmd_op(u32 cmd_op)
1286 {
1287 	u32 ioc_type = _IOC_TYPE(cmd_op);
1288 
1289 	if (!IS_ENABLED(CONFIG_BLKDEV_UBLK_LEGACY_OPCODES) && ioc_type != 'u')
1290 		return -EOPNOTSUPP;
1291 
1292 	if (ioc_type != 'u' && ioc_type != 0)
1293 		return -EOPNOTSUPP;
1294 
1295 	return 0;
1296 }
1297 
1298 static int __ublk_ch_uring_cmd(struct io_uring_cmd *cmd,
1299 			       unsigned int issue_flags,
1300 			       const struct ublksrv_io_cmd *ub_cmd)
1301 {
1302 	struct ublk_device *ub = cmd->file->private_data;
1303 	struct ublk_queue *ubq;
1304 	struct ublk_io *io;
1305 	u32 cmd_op = cmd->cmd_op;
1306 	unsigned tag = ub_cmd->tag;
1307 	int ret = -EINVAL;
1308 	struct request *req;
1309 
1310 	pr_devel("%s: received: cmd op %d queue %d tag %d result %d\n",
1311 			__func__, cmd->cmd_op, ub_cmd->q_id, tag,
1312 			ub_cmd->result);
1313 
1314 	if (ub_cmd->q_id >= ub->dev_info.nr_hw_queues)
1315 		goto out;
1316 
1317 	ubq = ublk_get_queue(ub, ub_cmd->q_id);
1318 	if (!ubq || ub_cmd->q_id != ubq->q_id)
1319 		goto out;
1320 
1321 	if (ubq->ubq_daemon && ubq->ubq_daemon != current)
1322 		goto out;
1323 
1324 	if (tag >= ubq->q_depth)
1325 		goto out;
1326 
1327 	io = &ubq->ios[tag];
1328 
1329 	/* there is pending io cmd, something must be wrong */
1330 	if (io->flags & UBLK_IO_FLAG_ACTIVE) {
1331 		ret = -EBUSY;
1332 		goto out;
1333 	}
1334 
1335 	/*
1336 	 * ensure that the user issues UBLK_IO_NEED_GET_DATA
1337 	 * iff the driver have set the UBLK_IO_FLAG_NEED_GET_DATA.
1338 	 */
1339 	if ((!!(io->flags & UBLK_IO_FLAG_NEED_GET_DATA))
1340 			^ (_IOC_NR(cmd_op) == UBLK_IO_NEED_GET_DATA))
1341 		goto out;
1342 
1343 	ret = ublk_check_cmd_op(cmd_op);
1344 	if (ret)
1345 		goto out;
1346 
1347 	ret = -EINVAL;
1348 	switch (_IOC_NR(cmd_op)) {
1349 	case UBLK_IO_FETCH_REQ:
1350 		/* UBLK_IO_FETCH_REQ is only allowed before queue is setup */
1351 		if (ublk_queue_ready(ubq)) {
1352 			ret = -EBUSY;
1353 			goto out;
1354 		}
1355 		/*
1356 		 * The io is being handled by server, so COMMIT_RQ is expected
1357 		 * instead of FETCH_REQ
1358 		 */
1359 		if (io->flags & UBLK_IO_FLAG_OWNED_BY_SRV)
1360 			goto out;
1361 		/* FETCH_RQ has to provide IO buffer if NEED GET DATA is not enabled */
1362 		if (!ub_cmd->addr && !ublk_need_get_data(ubq))
1363 			goto out;
1364 		io->cmd = cmd;
1365 		io->flags |= UBLK_IO_FLAG_ACTIVE;
1366 		io->addr = ub_cmd->addr;
1367 
1368 		ublk_mark_io_ready(ub, ubq);
1369 		break;
1370 	case UBLK_IO_COMMIT_AND_FETCH_REQ:
1371 		req = blk_mq_tag_to_rq(ub->tag_set.tags[ub_cmd->q_id], tag);
1372 		/*
1373 		 * COMMIT_AND_FETCH_REQ has to provide IO buffer if NEED GET DATA is
1374 		 * not enabled or it is Read IO.
1375 		 */
1376 		if (!ub_cmd->addr && (!ublk_need_get_data(ubq) || req_op(req) == REQ_OP_READ))
1377 			goto out;
1378 		if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV))
1379 			goto out;
1380 		io->addr = ub_cmd->addr;
1381 		io->flags |= UBLK_IO_FLAG_ACTIVE;
1382 		io->cmd = cmd;
1383 		ublk_commit_completion(ub, ub_cmd);
1384 		break;
1385 	case UBLK_IO_NEED_GET_DATA:
1386 		if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV))
1387 			goto out;
1388 		io->addr = ub_cmd->addr;
1389 		io->cmd = cmd;
1390 		io->flags |= UBLK_IO_FLAG_ACTIVE;
1391 		ublk_handle_need_get_data(ub, ub_cmd->q_id, ub_cmd->tag);
1392 		break;
1393 	default:
1394 		goto out;
1395 	}
1396 	return -EIOCBQUEUED;
1397 
1398  out:
1399 	io_uring_cmd_done(cmd, ret, 0, issue_flags);
1400 	pr_devel("%s: complete: cmd op %d, tag %d ret %x io_flags %x\n",
1401 			__func__, cmd_op, tag, ret, io->flags);
1402 	return -EIOCBQUEUED;
1403 }
1404 
1405 static int ublk_ch_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags)
1406 {
1407 	/*
1408 	 * Not necessary for async retry, but let's keep it simple and always
1409 	 * copy the values to avoid any potential reuse.
1410 	 */
1411 	const struct ublksrv_io_cmd *ub_src = io_uring_sqe_cmd(cmd->sqe);
1412 	const struct ublksrv_io_cmd ub_cmd = {
1413 		.q_id = READ_ONCE(ub_src->q_id),
1414 		.tag = READ_ONCE(ub_src->tag),
1415 		.result = READ_ONCE(ub_src->result),
1416 		.addr = READ_ONCE(ub_src->addr)
1417 	};
1418 
1419 	return __ublk_ch_uring_cmd(cmd, issue_flags, &ub_cmd);
1420 }
1421 
1422 static const struct file_operations ublk_ch_fops = {
1423 	.owner = THIS_MODULE,
1424 	.open = ublk_ch_open,
1425 	.release = ublk_ch_release,
1426 	.llseek = no_llseek,
1427 	.uring_cmd = ublk_ch_uring_cmd,
1428 	.mmap = ublk_ch_mmap,
1429 };
1430 
1431 static void ublk_deinit_queue(struct ublk_device *ub, int q_id)
1432 {
1433 	int size = ublk_queue_cmd_buf_size(ub, q_id);
1434 	struct ublk_queue *ubq = ublk_get_queue(ub, q_id);
1435 
1436 	if (ubq->ubq_daemon)
1437 		put_task_struct(ubq->ubq_daemon);
1438 	if (ubq->io_cmd_buf)
1439 		free_pages((unsigned long)ubq->io_cmd_buf, get_order(size));
1440 }
1441 
1442 static int ublk_init_queue(struct ublk_device *ub, int q_id)
1443 {
1444 	struct ublk_queue *ubq = ublk_get_queue(ub, q_id);
1445 	gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO;
1446 	void *ptr;
1447 	int size;
1448 
1449 	ubq->flags = ub->dev_info.flags;
1450 	ubq->q_id = q_id;
1451 	ubq->q_depth = ub->dev_info.queue_depth;
1452 	size = ublk_queue_cmd_buf_size(ub, q_id);
1453 
1454 	ptr = (void *) __get_free_pages(gfp_flags, get_order(size));
1455 	if (!ptr)
1456 		return -ENOMEM;
1457 
1458 	ubq->io_cmd_buf = ptr;
1459 	ubq->dev = ub;
1460 	return 0;
1461 }
1462 
1463 static void ublk_deinit_queues(struct ublk_device *ub)
1464 {
1465 	int nr_queues = ub->dev_info.nr_hw_queues;
1466 	int i;
1467 
1468 	if (!ub->__queues)
1469 		return;
1470 
1471 	for (i = 0; i < nr_queues; i++)
1472 		ublk_deinit_queue(ub, i);
1473 	kfree(ub->__queues);
1474 }
1475 
1476 static int ublk_init_queues(struct ublk_device *ub)
1477 {
1478 	int nr_queues = ub->dev_info.nr_hw_queues;
1479 	int depth = ub->dev_info.queue_depth;
1480 	int ubq_size = sizeof(struct ublk_queue) + depth * sizeof(struct ublk_io);
1481 	int i, ret = -ENOMEM;
1482 
1483 	ub->queue_size = ubq_size;
1484 	ub->__queues = kcalloc(nr_queues, ubq_size, GFP_KERNEL);
1485 	if (!ub->__queues)
1486 		return ret;
1487 
1488 	for (i = 0; i < nr_queues; i++) {
1489 		if (ublk_init_queue(ub, i))
1490 			goto fail;
1491 	}
1492 
1493 	init_completion(&ub->completion);
1494 	return 0;
1495 
1496  fail:
1497 	ublk_deinit_queues(ub);
1498 	return ret;
1499 }
1500 
1501 static int ublk_alloc_dev_number(struct ublk_device *ub, int idx)
1502 {
1503 	int i = idx;
1504 	int err;
1505 
1506 	spin_lock(&ublk_idr_lock);
1507 	/* allocate id, if @id >= 0, we're requesting that specific id */
1508 	if (i >= 0) {
1509 		err = idr_alloc(&ublk_index_idr, ub, i, i + 1, GFP_NOWAIT);
1510 		if (err == -ENOSPC)
1511 			err = -EEXIST;
1512 	} else {
1513 		err = idr_alloc(&ublk_index_idr, ub, 0, 0, GFP_NOWAIT);
1514 	}
1515 	spin_unlock(&ublk_idr_lock);
1516 
1517 	if (err >= 0)
1518 		ub->ub_number = err;
1519 
1520 	return err;
1521 }
1522 
1523 static void ublk_free_dev_number(struct ublk_device *ub)
1524 {
1525 	spin_lock(&ublk_idr_lock);
1526 	idr_remove(&ublk_index_idr, ub->ub_number);
1527 	wake_up_all(&ublk_idr_wq);
1528 	spin_unlock(&ublk_idr_lock);
1529 }
1530 
1531 static void ublk_cdev_rel(struct device *dev)
1532 {
1533 	struct ublk_device *ub = container_of(dev, struct ublk_device, cdev_dev);
1534 
1535 	blk_mq_free_tag_set(&ub->tag_set);
1536 	ublk_deinit_queues(ub);
1537 	ublk_free_dev_number(ub);
1538 	mutex_destroy(&ub->mutex);
1539 	kfree(ub);
1540 }
1541 
1542 static int ublk_add_chdev(struct ublk_device *ub)
1543 {
1544 	struct device *dev = &ub->cdev_dev;
1545 	int minor = ub->ub_number;
1546 	int ret;
1547 
1548 	dev->parent = ublk_misc.this_device;
1549 	dev->devt = MKDEV(MAJOR(ublk_chr_devt), minor);
1550 	dev->class = ublk_chr_class;
1551 	dev->release = ublk_cdev_rel;
1552 	device_initialize(dev);
1553 
1554 	ret = dev_set_name(dev, "ublkc%d", minor);
1555 	if (ret)
1556 		goto fail;
1557 
1558 	cdev_init(&ub->cdev, &ublk_ch_fops);
1559 	ret = cdev_device_add(&ub->cdev, dev);
1560 	if (ret)
1561 		goto fail;
1562 
1563 	ublks_added++;
1564 	return 0;
1565  fail:
1566 	put_device(dev);
1567 	return ret;
1568 }
1569 
1570 static void ublk_stop_work_fn(struct work_struct *work)
1571 {
1572 	struct ublk_device *ub =
1573 		container_of(work, struct ublk_device, stop_work);
1574 
1575 	ublk_stop_dev(ub);
1576 }
1577 
1578 /* align max io buffer size with PAGE_SIZE */
1579 static void ublk_align_max_io_size(struct ublk_device *ub)
1580 {
1581 	unsigned int max_io_bytes = ub->dev_info.max_io_buf_bytes;
1582 
1583 	ub->dev_info.max_io_buf_bytes =
1584 		round_down(max_io_bytes, PAGE_SIZE);
1585 }
1586 
1587 static int ublk_add_tag_set(struct ublk_device *ub)
1588 {
1589 	ub->tag_set.ops = &ublk_mq_ops;
1590 	ub->tag_set.nr_hw_queues = ub->dev_info.nr_hw_queues;
1591 	ub->tag_set.queue_depth = ub->dev_info.queue_depth;
1592 	ub->tag_set.numa_node = NUMA_NO_NODE;
1593 	ub->tag_set.cmd_size = sizeof(struct ublk_rq_data);
1594 	ub->tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
1595 	ub->tag_set.driver_data = ub;
1596 	return blk_mq_alloc_tag_set(&ub->tag_set);
1597 }
1598 
1599 static void ublk_remove(struct ublk_device *ub)
1600 {
1601 	ublk_stop_dev(ub);
1602 	cancel_work_sync(&ub->stop_work);
1603 	cancel_work_sync(&ub->quiesce_work);
1604 	cdev_device_del(&ub->cdev, &ub->cdev_dev);
1605 	put_device(&ub->cdev_dev);
1606 	ublks_added--;
1607 }
1608 
1609 static struct ublk_device *ublk_get_device_from_id(int idx)
1610 {
1611 	struct ublk_device *ub = NULL;
1612 
1613 	if (idx < 0)
1614 		return NULL;
1615 
1616 	spin_lock(&ublk_idr_lock);
1617 	ub = idr_find(&ublk_index_idr, idx);
1618 	if (ub)
1619 		ub = ublk_get_device(ub);
1620 	spin_unlock(&ublk_idr_lock);
1621 
1622 	return ub;
1623 }
1624 
1625 static int ublk_ctrl_start_dev(struct ublk_device *ub, struct io_uring_cmd *cmd)
1626 {
1627 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
1628 	int ublksrv_pid = (int)header->data[0];
1629 	struct gendisk *disk;
1630 	int ret = -EINVAL;
1631 
1632 	if (ublksrv_pid <= 0)
1633 		return -EINVAL;
1634 
1635 	wait_for_completion_interruptible(&ub->completion);
1636 
1637 	schedule_delayed_work(&ub->monitor_work, UBLK_DAEMON_MONITOR_PERIOD);
1638 
1639 	mutex_lock(&ub->mutex);
1640 	if (ub->dev_info.state == UBLK_S_DEV_LIVE ||
1641 	    test_bit(UB_STATE_USED, &ub->state)) {
1642 		ret = -EEXIST;
1643 		goto out_unlock;
1644 	}
1645 
1646 	disk = blk_mq_alloc_disk(&ub->tag_set, NULL);
1647 	if (IS_ERR(disk)) {
1648 		ret = PTR_ERR(disk);
1649 		goto out_unlock;
1650 	}
1651 	sprintf(disk->disk_name, "ublkb%d", ub->ub_number);
1652 	disk->fops = &ub_fops;
1653 	disk->private_data = ub;
1654 
1655 	ub->dev_info.ublksrv_pid = ublksrv_pid;
1656 	ub->ub_disk = disk;
1657 
1658 	ret = ublk_apply_params(ub);
1659 	if (ret)
1660 		goto out_put_disk;
1661 
1662 	/* don't probe partitions if any one ubq daemon is un-trusted */
1663 	if (ub->nr_privileged_daemon != ub->nr_queues_ready)
1664 		set_bit(GD_SUPPRESS_PART_SCAN, &disk->state);
1665 
1666 	get_device(&ub->cdev_dev);
1667 	ub->dev_info.state = UBLK_S_DEV_LIVE;
1668 	ret = add_disk(disk);
1669 	if (ret) {
1670 		/*
1671 		 * Has to drop the reference since ->free_disk won't be
1672 		 * called in case of add_disk failure.
1673 		 */
1674 		ub->dev_info.state = UBLK_S_DEV_DEAD;
1675 		ublk_put_device(ub);
1676 		goto out_put_disk;
1677 	}
1678 	set_bit(UB_STATE_USED, &ub->state);
1679 out_put_disk:
1680 	if (ret)
1681 		put_disk(disk);
1682 out_unlock:
1683 	mutex_unlock(&ub->mutex);
1684 	return ret;
1685 }
1686 
1687 static int ublk_ctrl_get_queue_affinity(struct ublk_device *ub,
1688 		struct io_uring_cmd *cmd)
1689 {
1690 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
1691 	void __user *argp = (void __user *)(unsigned long)header->addr;
1692 	cpumask_var_t cpumask;
1693 	unsigned long queue;
1694 	unsigned int retlen;
1695 	unsigned int i;
1696 	int ret;
1697 
1698 	if (header->len * BITS_PER_BYTE < nr_cpu_ids)
1699 		return -EINVAL;
1700 	if (header->len & (sizeof(unsigned long)-1))
1701 		return -EINVAL;
1702 	if (!header->addr)
1703 		return -EINVAL;
1704 
1705 	queue = header->data[0];
1706 	if (queue >= ub->dev_info.nr_hw_queues)
1707 		return -EINVAL;
1708 
1709 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
1710 		return -ENOMEM;
1711 
1712 	for_each_possible_cpu(i) {
1713 		if (ub->tag_set.map[HCTX_TYPE_DEFAULT].mq_map[i] == queue)
1714 			cpumask_set_cpu(i, cpumask);
1715 	}
1716 
1717 	ret = -EFAULT;
1718 	retlen = min_t(unsigned short, header->len, cpumask_size());
1719 	if (copy_to_user(argp, cpumask, retlen))
1720 		goto out_free_cpumask;
1721 	if (retlen != header->len &&
1722 	    clear_user(argp + retlen, header->len - retlen))
1723 		goto out_free_cpumask;
1724 
1725 	ret = 0;
1726 out_free_cpumask:
1727 	free_cpumask_var(cpumask);
1728 	return ret;
1729 }
1730 
1731 static inline void ublk_dump_dev_info(struct ublksrv_ctrl_dev_info *info)
1732 {
1733 	pr_devel("%s: dev id %d flags %llx\n", __func__,
1734 			info->dev_id, info->flags);
1735 	pr_devel("\t nr_hw_queues %d queue_depth %d\n",
1736 			info->nr_hw_queues, info->queue_depth);
1737 }
1738 
1739 static int ublk_ctrl_add_dev(struct io_uring_cmd *cmd)
1740 {
1741 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
1742 	void __user *argp = (void __user *)(unsigned long)header->addr;
1743 	struct ublksrv_ctrl_dev_info info;
1744 	struct ublk_device *ub;
1745 	int ret = -EINVAL;
1746 
1747 	if (header->len < sizeof(info) || !header->addr)
1748 		return -EINVAL;
1749 	if (header->queue_id != (u16)-1) {
1750 		pr_warn("%s: queue_id is wrong %x\n",
1751 			__func__, header->queue_id);
1752 		return -EINVAL;
1753 	}
1754 
1755 	if (copy_from_user(&info, argp, sizeof(info)))
1756 		return -EFAULT;
1757 
1758 	if (capable(CAP_SYS_ADMIN))
1759 		info.flags &= ~UBLK_F_UNPRIVILEGED_DEV;
1760 	else if (!(info.flags & UBLK_F_UNPRIVILEGED_DEV))
1761 		return -EPERM;
1762 
1763 	/*
1764 	 * unprivileged device can't be trusted, but RECOVERY and
1765 	 * RECOVERY_REISSUE still may hang error handling, so can't
1766 	 * support recovery features for unprivileged ublk now
1767 	 *
1768 	 * TODO: provide forward progress for RECOVERY handler, so that
1769 	 * unprivileged device can benefit from it
1770 	 */
1771 	if (info.flags & UBLK_F_UNPRIVILEGED_DEV)
1772 		info.flags &= ~(UBLK_F_USER_RECOVERY_REISSUE |
1773 				UBLK_F_USER_RECOVERY);
1774 
1775 	/* the created device is always owned by current user */
1776 	ublk_store_owner_uid_gid(&info.owner_uid, &info.owner_gid);
1777 
1778 	if (header->dev_id != info.dev_id) {
1779 		pr_warn("%s: dev id not match %u %u\n",
1780 			__func__, header->dev_id, info.dev_id);
1781 		return -EINVAL;
1782 	}
1783 
1784 	ublk_dump_dev_info(&info);
1785 
1786 	ret = mutex_lock_killable(&ublk_ctl_mutex);
1787 	if (ret)
1788 		return ret;
1789 
1790 	ret = -EACCES;
1791 	if (ublks_added >= ublks_max)
1792 		goto out_unlock;
1793 
1794 	ret = -ENOMEM;
1795 	ub = kzalloc(sizeof(*ub), GFP_KERNEL);
1796 	if (!ub)
1797 		goto out_unlock;
1798 	mutex_init(&ub->mutex);
1799 	spin_lock_init(&ub->mm_lock);
1800 	INIT_WORK(&ub->quiesce_work, ublk_quiesce_work_fn);
1801 	INIT_WORK(&ub->stop_work, ublk_stop_work_fn);
1802 	INIT_DELAYED_WORK(&ub->monitor_work, ublk_daemon_monitor_work);
1803 
1804 	ret = ublk_alloc_dev_number(ub, header->dev_id);
1805 	if (ret < 0)
1806 		goto out_free_ub;
1807 
1808 	memcpy(&ub->dev_info, &info, sizeof(info));
1809 
1810 	/* update device id */
1811 	ub->dev_info.dev_id = ub->ub_number;
1812 
1813 	/*
1814 	 * 64bit flags will be copied back to userspace as feature
1815 	 * negotiation result, so have to clear flags which driver
1816 	 * doesn't support yet, then userspace can get correct flags
1817 	 * (features) to handle.
1818 	 */
1819 	ub->dev_info.flags &= UBLK_F_ALL;
1820 
1821 	if (!IS_BUILTIN(CONFIG_BLK_DEV_UBLK))
1822 		ub->dev_info.flags |= UBLK_F_URING_CMD_COMP_IN_TASK;
1823 
1824 	ub->dev_info.flags |= UBLK_F_CMD_IOCTL_ENCODE;
1825 
1826 	/* We are not ready to support zero copy */
1827 	ub->dev_info.flags &= ~UBLK_F_SUPPORT_ZERO_COPY;
1828 
1829 	ub->dev_info.nr_hw_queues = min_t(unsigned int,
1830 			ub->dev_info.nr_hw_queues, nr_cpu_ids);
1831 	ublk_align_max_io_size(ub);
1832 
1833 	ret = ublk_init_queues(ub);
1834 	if (ret)
1835 		goto out_free_dev_number;
1836 
1837 	ret = ublk_add_tag_set(ub);
1838 	if (ret)
1839 		goto out_deinit_queues;
1840 
1841 	ret = -EFAULT;
1842 	if (copy_to_user(argp, &ub->dev_info, sizeof(info)))
1843 		goto out_free_tag_set;
1844 
1845 	/*
1846 	 * Add the char dev so that ublksrv daemon can be setup.
1847 	 * ublk_add_chdev() will cleanup everything if it fails.
1848 	 */
1849 	ret = ublk_add_chdev(ub);
1850 	goto out_unlock;
1851 
1852 out_free_tag_set:
1853 	blk_mq_free_tag_set(&ub->tag_set);
1854 out_deinit_queues:
1855 	ublk_deinit_queues(ub);
1856 out_free_dev_number:
1857 	ublk_free_dev_number(ub);
1858 out_free_ub:
1859 	mutex_destroy(&ub->mutex);
1860 	kfree(ub);
1861 out_unlock:
1862 	mutex_unlock(&ublk_ctl_mutex);
1863 	return ret;
1864 }
1865 
1866 static inline bool ublk_idr_freed(int id)
1867 {
1868 	void *ptr;
1869 
1870 	spin_lock(&ublk_idr_lock);
1871 	ptr = idr_find(&ublk_index_idr, id);
1872 	spin_unlock(&ublk_idr_lock);
1873 
1874 	return ptr == NULL;
1875 }
1876 
1877 static int ublk_ctrl_del_dev(struct ublk_device **p_ub)
1878 {
1879 	struct ublk_device *ub = *p_ub;
1880 	int idx = ub->ub_number;
1881 	int ret;
1882 
1883 	ret = mutex_lock_killable(&ublk_ctl_mutex);
1884 	if (ret)
1885 		return ret;
1886 
1887 	if (!test_bit(UB_STATE_DELETED, &ub->state)) {
1888 		ublk_remove(ub);
1889 		set_bit(UB_STATE_DELETED, &ub->state);
1890 	}
1891 
1892 	/* Mark the reference as consumed */
1893 	*p_ub = NULL;
1894 	ublk_put_device(ub);
1895 	mutex_unlock(&ublk_ctl_mutex);
1896 
1897 	/*
1898 	 * Wait until the idr is removed, then it can be reused after
1899 	 * DEL_DEV command is returned.
1900 	 *
1901 	 * If we returns because of user interrupt, future delete command
1902 	 * may come:
1903 	 *
1904 	 * - the device number isn't freed, this device won't or needn't
1905 	 *   be deleted again, since UB_STATE_DELETED is set, and device
1906 	 *   will be released after the last reference is dropped
1907 	 *
1908 	 * - the device number is freed already, we will not find this
1909 	 *   device via ublk_get_device_from_id()
1910 	 */
1911 	wait_event_interruptible(ublk_idr_wq, ublk_idr_freed(idx));
1912 
1913 	return 0;
1914 }
1915 
1916 static inline void ublk_ctrl_cmd_dump(struct io_uring_cmd *cmd)
1917 {
1918 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
1919 
1920 	pr_devel("%s: cmd_op %x, dev id %d qid %d data %llx buf %llx len %u\n",
1921 			__func__, cmd->cmd_op, header->dev_id, header->queue_id,
1922 			header->data[0], header->addr, header->len);
1923 }
1924 
1925 static int ublk_ctrl_stop_dev(struct ublk_device *ub)
1926 {
1927 	ublk_stop_dev(ub);
1928 	cancel_work_sync(&ub->stop_work);
1929 	cancel_work_sync(&ub->quiesce_work);
1930 
1931 	return 0;
1932 }
1933 
1934 static int ublk_ctrl_get_dev_info(struct ublk_device *ub,
1935 		struct io_uring_cmd *cmd)
1936 {
1937 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
1938 	void __user *argp = (void __user *)(unsigned long)header->addr;
1939 
1940 	if (header->len < sizeof(struct ublksrv_ctrl_dev_info) || !header->addr)
1941 		return -EINVAL;
1942 
1943 	if (copy_to_user(argp, &ub->dev_info, sizeof(ub->dev_info)))
1944 		return -EFAULT;
1945 
1946 	return 0;
1947 }
1948 
1949 /* TYPE_DEVT is readonly, so fill it up before returning to userspace */
1950 static void ublk_ctrl_fill_params_devt(struct ublk_device *ub)
1951 {
1952 	ub->params.devt.char_major = MAJOR(ub->cdev_dev.devt);
1953 	ub->params.devt.char_minor = MINOR(ub->cdev_dev.devt);
1954 
1955 	if (ub->ub_disk) {
1956 		ub->params.devt.disk_major = MAJOR(disk_devt(ub->ub_disk));
1957 		ub->params.devt.disk_minor = MINOR(disk_devt(ub->ub_disk));
1958 	} else {
1959 		ub->params.devt.disk_major = 0;
1960 		ub->params.devt.disk_minor = 0;
1961 	}
1962 	ub->params.types |= UBLK_PARAM_TYPE_DEVT;
1963 }
1964 
1965 static int ublk_ctrl_get_params(struct ublk_device *ub,
1966 		struct io_uring_cmd *cmd)
1967 {
1968 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
1969 	void __user *argp = (void __user *)(unsigned long)header->addr;
1970 	struct ublk_params_header ph;
1971 	int ret;
1972 
1973 	if (header->len <= sizeof(ph) || !header->addr)
1974 		return -EINVAL;
1975 
1976 	if (copy_from_user(&ph, argp, sizeof(ph)))
1977 		return -EFAULT;
1978 
1979 	if (ph.len > header->len || !ph.len)
1980 		return -EINVAL;
1981 
1982 	if (ph.len > sizeof(struct ublk_params))
1983 		ph.len = sizeof(struct ublk_params);
1984 
1985 	mutex_lock(&ub->mutex);
1986 	ublk_ctrl_fill_params_devt(ub);
1987 	if (copy_to_user(argp, &ub->params, ph.len))
1988 		ret = -EFAULT;
1989 	else
1990 		ret = 0;
1991 	mutex_unlock(&ub->mutex);
1992 
1993 	return ret;
1994 }
1995 
1996 static int ublk_ctrl_set_params(struct ublk_device *ub,
1997 		struct io_uring_cmd *cmd)
1998 {
1999 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2000 	void __user *argp = (void __user *)(unsigned long)header->addr;
2001 	struct ublk_params_header ph;
2002 	int ret = -EFAULT;
2003 
2004 	if (header->len <= sizeof(ph) || !header->addr)
2005 		return -EINVAL;
2006 
2007 	if (copy_from_user(&ph, argp, sizeof(ph)))
2008 		return -EFAULT;
2009 
2010 	if (ph.len > header->len || !ph.len || !ph.types)
2011 		return -EINVAL;
2012 
2013 	if (ph.len > sizeof(struct ublk_params))
2014 		ph.len = sizeof(struct ublk_params);
2015 
2016 	/* parameters can only be changed when device isn't live */
2017 	mutex_lock(&ub->mutex);
2018 	if (ub->dev_info.state == UBLK_S_DEV_LIVE) {
2019 		ret = -EACCES;
2020 	} else if (copy_from_user(&ub->params, argp, ph.len)) {
2021 		ret = -EFAULT;
2022 	} else {
2023 		/* clear all we don't support yet */
2024 		ub->params.types &= UBLK_PARAM_TYPE_ALL;
2025 		ret = ublk_validate_params(ub);
2026 		if (ret)
2027 			ub->params.types = 0;
2028 	}
2029 	mutex_unlock(&ub->mutex);
2030 
2031 	return ret;
2032 }
2033 
2034 static void ublk_queue_reinit(struct ublk_device *ub, struct ublk_queue *ubq)
2035 {
2036 	int i;
2037 
2038 	WARN_ON_ONCE(!(ubq->ubq_daemon && ubq_daemon_is_dying(ubq)));
2039 	/* All old ioucmds have to be completed */
2040 	WARN_ON_ONCE(ubq->nr_io_ready);
2041 	/* old daemon is PF_EXITING, put it now */
2042 	put_task_struct(ubq->ubq_daemon);
2043 	/* We have to reset it to NULL, otherwise ub won't accept new FETCH_REQ */
2044 	ubq->ubq_daemon = NULL;
2045 	ubq->timeout = false;
2046 
2047 	for (i = 0; i < ubq->q_depth; i++) {
2048 		struct ublk_io *io = &ubq->ios[i];
2049 
2050 		/* forget everything now and be ready for new FETCH_REQ */
2051 		io->flags = 0;
2052 		io->cmd = NULL;
2053 		io->addr = 0;
2054 	}
2055 }
2056 
2057 static int ublk_ctrl_start_recovery(struct ublk_device *ub,
2058 		struct io_uring_cmd *cmd)
2059 {
2060 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2061 	int ret = -EINVAL;
2062 	int i;
2063 
2064 	mutex_lock(&ub->mutex);
2065 	if (!ublk_can_use_recovery(ub))
2066 		goto out_unlock;
2067 	/*
2068 	 * START_RECOVERY is only allowd after:
2069 	 *
2070 	 * (1) UB_STATE_OPEN is not set, which means the dying process is exited
2071 	 *     and related io_uring ctx is freed so file struct of /dev/ublkcX is
2072 	 *     released.
2073 	 *
2074 	 * (2) UBLK_S_DEV_QUIESCED is set, which means the quiesce_work:
2075 	 *     (a)has quiesced request queue
2076 	 *     (b)has requeued every inflight rqs whose io_flags is ACTIVE
2077 	 *     (c)has requeued/aborted every inflight rqs whose io_flags is NOT ACTIVE
2078 	 *     (d)has completed/camceled all ioucmds owned by ther dying process
2079 	 */
2080 	if (test_bit(UB_STATE_OPEN, &ub->state) ||
2081 			ub->dev_info.state != UBLK_S_DEV_QUIESCED) {
2082 		ret = -EBUSY;
2083 		goto out_unlock;
2084 	}
2085 	pr_devel("%s: start recovery for dev id %d.\n", __func__, header->dev_id);
2086 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
2087 		ublk_queue_reinit(ub, ublk_get_queue(ub, i));
2088 	/* set to NULL, otherwise new ubq_daemon cannot mmap the io_cmd_buf */
2089 	ub->mm = NULL;
2090 	ub->nr_queues_ready = 0;
2091 	ub->nr_privileged_daemon = 0;
2092 	init_completion(&ub->completion);
2093 	ret = 0;
2094  out_unlock:
2095 	mutex_unlock(&ub->mutex);
2096 	return ret;
2097 }
2098 
2099 static int ublk_ctrl_end_recovery(struct ublk_device *ub,
2100 		struct io_uring_cmd *cmd)
2101 {
2102 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2103 	int ublksrv_pid = (int)header->data[0];
2104 	int ret = -EINVAL;
2105 
2106 	pr_devel("%s: Waiting for new ubq_daemons(nr: %d) are ready, dev id %d...\n",
2107 			__func__, ub->dev_info.nr_hw_queues, header->dev_id);
2108 	/* wait until new ubq_daemon sending all FETCH_REQ */
2109 	wait_for_completion_interruptible(&ub->completion);
2110 	pr_devel("%s: All new ubq_daemons(nr: %d) are ready, dev id %d\n",
2111 			__func__, ub->dev_info.nr_hw_queues, header->dev_id);
2112 
2113 	mutex_lock(&ub->mutex);
2114 	if (!ublk_can_use_recovery(ub))
2115 		goto out_unlock;
2116 
2117 	if (ub->dev_info.state != UBLK_S_DEV_QUIESCED) {
2118 		ret = -EBUSY;
2119 		goto out_unlock;
2120 	}
2121 	ub->dev_info.ublksrv_pid = ublksrv_pid;
2122 	pr_devel("%s: new ublksrv_pid %d, dev id %d\n",
2123 			__func__, ublksrv_pid, header->dev_id);
2124 	blk_mq_unquiesce_queue(ub->ub_disk->queue);
2125 	pr_devel("%s: queue unquiesced, dev id %d.\n",
2126 			__func__, header->dev_id);
2127 	blk_mq_kick_requeue_list(ub->ub_disk->queue);
2128 	ub->dev_info.state = UBLK_S_DEV_LIVE;
2129 	schedule_delayed_work(&ub->monitor_work, UBLK_DAEMON_MONITOR_PERIOD);
2130 	ret = 0;
2131  out_unlock:
2132 	mutex_unlock(&ub->mutex);
2133 	return ret;
2134 }
2135 
2136 /*
2137  * All control commands are sent via /dev/ublk-control, so we have to check
2138  * the destination device's permission
2139  */
2140 static int ublk_char_dev_permission(struct ublk_device *ub,
2141 		const char *dev_path, int mask)
2142 {
2143 	int err;
2144 	struct path path;
2145 	struct kstat stat;
2146 
2147 	err = kern_path(dev_path, LOOKUP_FOLLOW, &path);
2148 	if (err)
2149 		return err;
2150 
2151 	err = vfs_getattr(&path, &stat, STATX_TYPE, AT_STATX_SYNC_AS_STAT);
2152 	if (err)
2153 		goto exit;
2154 
2155 	err = -EPERM;
2156 	if (stat.rdev != ub->cdev_dev.devt || !S_ISCHR(stat.mode))
2157 		goto exit;
2158 
2159 	err = inode_permission(&nop_mnt_idmap,
2160 			d_backing_inode(path.dentry), mask);
2161 exit:
2162 	path_put(&path);
2163 	return err;
2164 }
2165 
2166 static int ublk_ctrl_uring_cmd_permission(struct ublk_device *ub,
2167 		struct io_uring_cmd *cmd)
2168 {
2169 	struct ublksrv_ctrl_cmd *header = (struct ublksrv_ctrl_cmd *)io_uring_sqe_cmd(cmd->sqe);
2170 	bool unprivileged = ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV;
2171 	void __user *argp = (void __user *)(unsigned long)header->addr;
2172 	char *dev_path = NULL;
2173 	int ret = 0;
2174 	int mask;
2175 
2176 	if (!unprivileged) {
2177 		if (!capable(CAP_SYS_ADMIN))
2178 			return -EPERM;
2179 		/*
2180 		 * The new added command of UBLK_CMD_GET_DEV_INFO2 includes
2181 		 * char_dev_path in payload too, since userspace may not
2182 		 * know if the specified device is created as unprivileged
2183 		 * mode.
2184 		 */
2185 		if (_IOC_NR(cmd->cmd_op) != UBLK_CMD_GET_DEV_INFO2)
2186 			return 0;
2187 	}
2188 
2189 	/*
2190 	 * User has to provide the char device path for unprivileged ublk
2191 	 *
2192 	 * header->addr always points to the dev path buffer, and
2193 	 * header->dev_path_len records length of dev path buffer.
2194 	 */
2195 	if (!header->dev_path_len || header->dev_path_len > PATH_MAX)
2196 		return -EINVAL;
2197 
2198 	if (header->len < header->dev_path_len)
2199 		return -EINVAL;
2200 
2201 	dev_path = kmalloc(header->dev_path_len + 1, GFP_KERNEL);
2202 	if (!dev_path)
2203 		return -ENOMEM;
2204 
2205 	ret = -EFAULT;
2206 	if (copy_from_user(dev_path, argp, header->dev_path_len))
2207 		goto exit;
2208 	dev_path[header->dev_path_len] = 0;
2209 
2210 	ret = -EINVAL;
2211 	switch (_IOC_NR(cmd->cmd_op)) {
2212 	case UBLK_CMD_GET_DEV_INFO:
2213 	case UBLK_CMD_GET_DEV_INFO2:
2214 	case UBLK_CMD_GET_QUEUE_AFFINITY:
2215 	case UBLK_CMD_GET_PARAMS:
2216 		mask = MAY_READ;
2217 		break;
2218 	case UBLK_CMD_START_DEV:
2219 	case UBLK_CMD_STOP_DEV:
2220 	case UBLK_CMD_ADD_DEV:
2221 	case UBLK_CMD_DEL_DEV:
2222 	case UBLK_CMD_SET_PARAMS:
2223 	case UBLK_CMD_START_USER_RECOVERY:
2224 	case UBLK_CMD_END_USER_RECOVERY:
2225 		mask = MAY_READ | MAY_WRITE;
2226 		break;
2227 	default:
2228 		goto exit;
2229 	}
2230 
2231 	ret = ublk_char_dev_permission(ub, dev_path, mask);
2232 	if (!ret) {
2233 		header->len -= header->dev_path_len;
2234 		header->addr += header->dev_path_len;
2235 	}
2236 	pr_devel("%s: dev id %d cmd_op %x uid %d gid %d path %s ret %d\n",
2237 			__func__, ub->ub_number, cmd->cmd_op,
2238 			ub->dev_info.owner_uid, ub->dev_info.owner_gid,
2239 			dev_path, ret);
2240 exit:
2241 	kfree(dev_path);
2242 	return ret;
2243 }
2244 
2245 static int ublk_ctrl_uring_cmd(struct io_uring_cmd *cmd,
2246 		unsigned int issue_flags)
2247 {
2248 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2249 	struct ublk_device *ub = NULL;
2250 	u32 cmd_op = cmd->cmd_op;
2251 	int ret = -EINVAL;
2252 
2253 	if (issue_flags & IO_URING_F_NONBLOCK)
2254 		return -EAGAIN;
2255 
2256 	ublk_ctrl_cmd_dump(cmd);
2257 
2258 	if (!(issue_flags & IO_URING_F_SQE128))
2259 		goto out;
2260 
2261 	ret = ublk_check_cmd_op(cmd_op);
2262 	if (ret)
2263 		goto out;
2264 
2265 	if (_IOC_NR(cmd_op) != UBLK_CMD_ADD_DEV) {
2266 		ret = -ENODEV;
2267 		ub = ublk_get_device_from_id(header->dev_id);
2268 		if (!ub)
2269 			goto out;
2270 
2271 		ret = ublk_ctrl_uring_cmd_permission(ub, cmd);
2272 		if (ret)
2273 			goto put_dev;
2274 	}
2275 
2276 	switch (_IOC_NR(cmd_op)) {
2277 	case UBLK_CMD_START_DEV:
2278 		ret = ublk_ctrl_start_dev(ub, cmd);
2279 		break;
2280 	case UBLK_CMD_STOP_DEV:
2281 		ret = ublk_ctrl_stop_dev(ub);
2282 		break;
2283 	case UBLK_CMD_GET_DEV_INFO:
2284 	case UBLK_CMD_GET_DEV_INFO2:
2285 		ret = ublk_ctrl_get_dev_info(ub, cmd);
2286 		break;
2287 	case UBLK_CMD_ADD_DEV:
2288 		ret = ublk_ctrl_add_dev(cmd);
2289 		break;
2290 	case UBLK_CMD_DEL_DEV:
2291 		ret = ublk_ctrl_del_dev(&ub);
2292 		break;
2293 	case UBLK_CMD_GET_QUEUE_AFFINITY:
2294 		ret = ublk_ctrl_get_queue_affinity(ub, cmd);
2295 		break;
2296 	case UBLK_CMD_GET_PARAMS:
2297 		ret = ublk_ctrl_get_params(ub, cmd);
2298 		break;
2299 	case UBLK_CMD_SET_PARAMS:
2300 		ret = ublk_ctrl_set_params(ub, cmd);
2301 		break;
2302 	case UBLK_CMD_START_USER_RECOVERY:
2303 		ret = ublk_ctrl_start_recovery(ub, cmd);
2304 		break;
2305 	case UBLK_CMD_END_USER_RECOVERY:
2306 		ret = ublk_ctrl_end_recovery(ub, cmd);
2307 		break;
2308 	default:
2309 		ret = -ENOTSUPP;
2310 		break;
2311 	}
2312 
2313  put_dev:
2314 	if (ub)
2315 		ublk_put_device(ub);
2316  out:
2317 	io_uring_cmd_done(cmd, ret, 0, issue_flags);
2318 	pr_devel("%s: cmd done ret %d cmd_op %x, dev id %d qid %d\n",
2319 			__func__, ret, cmd->cmd_op, header->dev_id, header->queue_id);
2320 	return -EIOCBQUEUED;
2321 }
2322 
2323 static const struct file_operations ublk_ctl_fops = {
2324 	.open		= nonseekable_open,
2325 	.uring_cmd      = ublk_ctrl_uring_cmd,
2326 	.owner		= THIS_MODULE,
2327 	.llseek		= noop_llseek,
2328 };
2329 
2330 static struct miscdevice ublk_misc = {
2331 	.minor		= MISC_DYNAMIC_MINOR,
2332 	.name		= "ublk-control",
2333 	.fops		= &ublk_ctl_fops,
2334 };
2335 
2336 static int __init ublk_init(void)
2337 {
2338 	int ret;
2339 
2340 	init_waitqueue_head(&ublk_idr_wq);
2341 
2342 	ret = misc_register(&ublk_misc);
2343 	if (ret)
2344 		return ret;
2345 
2346 	ret = alloc_chrdev_region(&ublk_chr_devt, 0, UBLK_MINORS, "ublk-char");
2347 	if (ret)
2348 		goto unregister_mis;
2349 
2350 	ublk_chr_class = class_create("ublk-char");
2351 	if (IS_ERR(ublk_chr_class)) {
2352 		ret = PTR_ERR(ublk_chr_class);
2353 		goto free_chrdev_region;
2354 	}
2355 	return 0;
2356 
2357 free_chrdev_region:
2358 	unregister_chrdev_region(ublk_chr_devt, UBLK_MINORS);
2359 unregister_mis:
2360 	misc_deregister(&ublk_misc);
2361 	return ret;
2362 }
2363 
2364 static void __exit ublk_exit(void)
2365 {
2366 	struct ublk_device *ub;
2367 	int id;
2368 
2369 	idr_for_each_entry(&ublk_index_idr, ub, id)
2370 		ublk_remove(ub);
2371 
2372 	class_destroy(ublk_chr_class);
2373 	misc_deregister(&ublk_misc);
2374 
2375 	idr_destroy(&ublk_index_idr);
2376 	unregister_chrdev_region(ublk_chr_devt, UBLK_MINORS);
2377 }
2378 
2379 module_init(ublk_init);
2380 module_exit(ublk_exit);
2381 
2382 module_param(ublks_max, int, 0444);
2383 MODULE_PARM_DESC(ublks_max, "max number of ublk devices allowed to add(default: 64)");
2384 
2385 MODULE_AUTHOR("Ming Lei <ming.lei@redhat.com>");
2386 MODULE_LICENSE("GPL");
2387