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