xref: /openbmc/linux/drivers/block/ublk_drv.c (revision 66c98360)
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_cancel_queue(struct ublk_queue *ubq)
1124 {
1125 	int i;
1126 
1127 	if (!ublk_queue_ready(ubq))
1128 		return;
1129 
1130 	for (i = 0; i < ubq->q_depth; i++) {
1131 		struct ublk_io *io = &ubq->ios[i];
1132 
1133 		if (io->flags & UBLK_IO_FLAG_ACTIVE)
1134 			io_uring_cmd_done(io->cmd, UBLK_IO_RES_ABORT, 0,
1135 						IO_URING_F_UNLOCKED);
1136 	}
1137 
1138 	/* all io commands are canceled */
1139 	ubq->nr_io_ready = 0;
1140 }
1141 
1142 /* Cancel all pending commands, must be called after del_gendisk() returns */
1143 static void ublk_cancel_dev(struct ublk_device *ub)
1144 {
1145 	int i;
1146 
1147 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1148 		ublk_cancel_queue(ublk_get_queue(ub, i));
1149 }
1150 
1151 static bool ublk_check_inflight_rq(struct request *rq, void *data)
1152 {
1153 	bool *idle = data;
1154 
1155 	if (blk_mq_request_started(rq)) {
1156 		*idle = false;
1157 		return false;
1158 	}
1159 	return true;
1160 }
1161 
1162 static void ublk_wait_tagset_rqs_idle(struct ublk_device *ub)
1163 {
1164 	bool idle;
1165 
1166 	WARN_ON_ONCE(!blk_queue_quiesced(ub->ub_disk->queue));
1167 	while (true) {
1168 		idle = true;
1169 		blk_mq_tagset_busy_iter(&ub->tag_set,
1170 				ublk_check_inflight_rq, &idle);
1171 		if (idle)
1172 			break;
1173 		msleep(UBLK_REQUEUE_DELAY_MS);
1174 	}
1175 }
1176 
1177 static void __ublk_quiesce_dev(struct ublk_device *ub)
1178 {
1179 	pr_devel("%s: quiesce ub: dev_id %d state %s\n",
1180 			__func__, ub->dev_info.dev_id,
1181 			ub->dev_info.state == UBLK_S_DEV_LIVE ?
1182 			"LIVE" : "QUIESCED");
1183 	blk_mq_quiesce_queue(ub->ub_disk->queue);
1184 	ublk_wait_tagset_rqs_idle(ub);
1185 	ub->dev_info.state = UBLK_S_DEV_QUIESCED;
1186 	ublk_cancel_dev(ub);
1187 	/* we are going to release task_struct of ubq_daemon and resets
1188 	 * ->ubq_daemon to NULL. So in monitor_work, check on ubq_daemon causes UAF.
1189 	 * Besides, monitor_work is not necessary in QUIESCED state since we have
1190 	 * already scheduled quiesce_work and quiesced all ubqs.
1191 	 *
1192 	 * Do not let monitor_work schedule itself if state it QUIESCED. And we cancel
1193 	 * it here and re-schedule it in END_USER_RECOVERY to avoid UAF.
1194 	 */
1195 	cancel_delayed_work_sync(&ub->monitor_work);
1196 }
1197 
1198 static void ublk_quiesce_work_fn(struct work_struct *work)
1199 {
1200 	struct ublk_device *ub =
1201 		container_of(work, struct ublk_device, quiesce_work);
1202 
1203 	mutex_lock(&ub->mutex);
1204 	if (ub->dev_info.state != UBLK_S_DEV_LIVE)
1205 		goto unlock;
1206 	__ublk_quiesce_dev(ub);
1207  unlock:
1208 	mutex_unlock(&ub->mutex);
1209 }
1210 
1211 static void ublk_unquiesce_dev(struct ublk_device *ub)
1212 {
1213 	int i;
1214 
1215 	pr_devel("%s: unquiesce ub: dev_id %d state %s\n",
1216 			__func__, ub->dev_info.dev_id,
1217 			ub->dev_info.state == UBLK_S_DEV_LIVE ?
1218 			"LIVE" : "QUIESCED");
1219 	/* quiesce_work has run. We let requeued rqs be aborted
1220 	 * before running fallback_wq. "force_abort" must be seen
1221 	 * after request queue is unqiuesced. Then del_gendisk()
1222 	 * can move on.
1223 	 */
1224 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1225 		ublk_get_queue(ub, i)->force_abort = true;
1226 
1227 	blk_mq_unquiesce_queue(ub->ub_disk->queue);
1228 	/* We may have requeued some rqs in ublk_quiesce_queue() */
1229 	blk_mq_kick_requeue_list(ub->ub_disk->queue);
1230 }
1231 
1232 static void ublk_stop_dev(struct ublk_device *ub)
1233 {
1234 	mutex_lock(&ub->mutex);
1235 	if (ub->dev_info.state == UBLK_S_DEV_DEAD)
1236 		goto unlock;
1237 	if (ublk_can_use_recovery(ub)) {
1238 		if (ub->dev_info.state == UBLK_S_DEV_LIVE)
1239 			__ublk_quiesce_dev(ub);
1240 		ublk_unquiesce_dev(ub);
1241 	}
1242 	del_gendisk(ub->ub_disk);
1243 	ub->dev_info.state = UBLK_S_DEV_DEAD;
1244 	ub->dev_info.ublksrv_pid = -1;
1245 	put_disk(ub->ub_disk);
1246 	ub->ub_disk = NULL;
1247  unlock:
1248 	ublk_cancel_dev(ub);
1249 	mutex_unlock(&ub->mutex);
1250 	cancel_delayed_work_sync(&ub->monitor_work);
1251 }
1252 
1253 /* device can only be started after all IOs are ready */
1254 static void ublk_mark_io_ready(struct ublk_device *ub, struct ublk_queue *ubq)
1255 {
1256 	mutex_lock(&ub->mutex);
1257 	ubq->nr_io_ready++;
1258 	if (ublk_queue_ready(ubq)) {
1259 		ubq->ubq_daemon = current;
1260 		get_task_struct(ubq->ubq_daemon);
1261 		ub->nr_queues_ready++;
1262 
1263 		if (capable(CAP_SYS_ADMIN))
1264 			ub->nr_privileged_daemon++;
1265 	}
1266 	if (ub->nr_queues_ready == ub->dev_info.nr_hw_queues)
1267 		complete_all(&ub->completion);
1268 	mutex_unlock(&ub->mutex);
1269 }
1270 
1271 static void ublk_handle_need_get_data(struct ublk_device *ub, int q_id,
1272 		int tag)
1273 {
1274 	struct ublk_queue *ubq = ublk_get_queue(ub, q_id);
1275 	struct request *req = blk_mq_tag_to_rq(ub->tag_set.tags[q_id], tag);
1276 
1277 	ublk_queue_cmd(ubq, req);
1278 }
1279 
1280 static inline int ublk_check_cmd_op(u32 cmd_op)
1281 {
1282 	u32 ioc_type = _IOC_TYPE(cmd_op);
1283 
1284 	if (!IS_ENABLED(CONFIG_BLKDEV_UBLK_LEGACY_OPCODES) && ioc_type != 'u')
1285 		return -EOPNOTSUPP;
1286 
1287 	if (ioc_type != 'u' && ioc_type != 0)
1288 		return -EOPNOTSUPP;
1289 
1290 	return 0;
1291 }
1292 
1293 static int __ublk_ch_uring_cmd(struct io_uring_cmd *cmd,
1294 			       unsigned int issue_flags,
1295 			       const struct ublksrv_io_cmd *ub_cmd)
1296 {
1297 	struct ublk_device *ub = cmd->file->private_data;
1298 	struct ublk_queue *ubq;
1299 	struct ublk_io *io;
1300 	u32 cmd_op = cmd->cmd_op;
1301 	unsigned tag = ub_cmd->tag;
1302 	int ret = -EINVAL;
1303 	struct request *req;
1304 
1305 	pr_devel("%s: received: cmd op %d queue %d tag %d result %d\n",
1306 			__func__, cmd->cmd_op, ub_cmd->q_id, tag,
1307 			ub_cmd->result);
1308 
1309 	if (ub_cmd->q_id >= ub->dev_info.nr_hw_queues)
1310 		goto out;
1311 
1312 	ubq = ublk_get_queue(ub, ub_cmd->q_id);
1313 	if (!ubq || ub_cmd->q_id != ubq->q_id)
1314 		goto out;
1315 
1316 	if (ubq->ubq_daemon && ubq->ubq_daemon != current)
1317 		goto out;
1318 
1319 	if (tag >= ubq->q_depth)
1320 		goto out;
1321 
1322 	io = &ubq->ios[tag];
1323 
1324 	/* there is pending io cmd, something must be wrong */
1325 	if (io->flags & UBLK_IO_FLAG_ACTIVE) {
1326 		ret = -EBUSY;
1327 		goto out;
1328 	}
1329 
1330 	/*
1331 	 * ensure that the user issues UBLK_IO_NEED_GET_DATA
1332 	 * iff the driver have set the UBLK_IO_FLAG_NEED_GET_DATA.
1333 	 */
1334 	if ((!!(io->flags & UBLK_IO_FLAG_NEED_GET_DATA))
1335 			^ (_IOC_NR(cmd_op) == UBLK_IO_NEED_GET_DATA))
1336 		goto out;
1337 
1338 	ret = ublk_check_cmd_op(cmd_op);
1339 	if (ret)
1340 		goto out;
1341 
1342 	ret = -EINVAL;
1343 	switch (_IOC_NR(cmd_op)) {
1344 	case UBLK_IO_FETCH_REQ:
1345 		/* UBLK_IO_FETCH_REQ is only allowed before queue is setup */
1346 		if (ublk_queue_ready(ubq)) {
1347 			ret = -EBUSY;
1348 			goto out;
1349 		}
1350 		/*
1351 		 * The io is being handled by server, so COMMIT_RQ is expected
1352 		 * instead of FETCH_REQ
1353 		 */
1354 		if (io->flags & UBLK_IO_FLAG_OWNED_BY_SRV)
1355 			goto out;
1356 		/* FETCH_RQ has to provide IO buffer if NEED GET DATA is not enabled */
1357 		if (!ub_cmd->addr && !ublk_need_get_data(ubq))
1358 			goto out;
1359 		io->cmd = cmd;
1360 		io->flags |= UBLK_IO_FLAG_ACTIVE;
1361 		io->addr = ub_cmd->addr;
1362 
1363 		ublk_mark_io_ready(ub, ubq);
1364 		break;
1365 	case UBLK_IO_COMMIT_AND_FETCH_REQ:
1366 		req = blk_mq_tag_to_rq(ub->tag_set.tags[ub_cmd->q_id], tag);
1367 		/*
1368 		 * COMMIT_AND_FETCH_REQ has to provide IO buffer if NEED GET DATA is
1369 		 * not enabled or it is Read IO.
1370 		 */
1371 		if (!ub_cmd->addr && (!ublk_need_get_data(ubq) || req_op(req) == REQ_OP_READ))
1372 			goto out;
1373 		if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV))
1374 			goto out;
1375 		io->addr = ub_cmd->addr;
1376 		io->flags |= UBLK_IO_FLAG_ACTIVE;
1377 		io->cmd = cmd;
1378 		ublk_commit_completion(ub, ub_cmd);
1379 		break;
1380 	case UBLK_IO_NEED_GET_DATA:
1381 		if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV))
1382 			goto out;
1383 		io->addr = ub_cmd->addr;
1384 		io->cmd = cmd;
1385 		io->flags |= UBLK_IO_FLAG_ACTIVE;
1386 		ublk_handle_need_get_data(ub, ub_cmd->q_id, ub_cmd->tag);
1387 		break;
1388 	default:
1389 		goto out;
1390 	}
1391 	return -EIOCBQUEUED;
1392 
1393  out:
1394 	io_uring_cmd_done(cmd, ret, 0, issue_flags);
1395 	pr_devel("%s: complete: cmd op %d, tag %d ret %x io_flags %x\n",
1396 			__func__, cmd_op, tag, ret, io->flags);
1397 	return -EIOCBQUEUED;
1398 }
1399 
1400 static int ublk_ch_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags)
1401 {
1402 	/*
1403 	 * Not necessary for async retry, but let's keep it simple and always
1404 	 * copy the values to avoid any potential reuse.
1405 	 */
1406 	const struct ublksrv_io_cmd *ub_src = io_uring_sqe_cmd(cmd->sqe);
1407 	const struct ublksrv_io_cmd ub_cmd = {
1408 		.q_id = READ_ONCE(ub_src->q_id),
1409 		.tag = READ_ONCE(ub_src->tag),
1410 		.result = READ_ONCE(ub_src->result),
1411 		.addr = READ_ONCE(ub_src->addr)
1412 	};
1413 
1414 	return __ublk_ch_uring_cmd(cmd, issue_flags, &ub_cmd);
1415 }
1416 
1417 static const struct file_operations ublk_ch_fops = {
1418 	.owner = THIS_MODULE,
1419 	.open = ublk_ch_open,
1420 	.release = ublk_ch_release,
1421 	.llseek = no_llseek,
1422 	.uring_cmd = ublk_ch_uring_cmd,
1423 	.mmap = ublk_ch_mmap,
1424 };
1425 
1426 static void ublk_deinit_queue(struct ublk_device *ub, int q_id)
1427 {
1428 	int size = ublk_queue_cmd_buf_size(ub, q_id);
1429 	struct ublk_queue *ubq = ublk_get_queue(ub, q_id);
1430 
1431 	if (ubq->ubq_daemon)
1432 		put_task_struct(ubq->ubq_daemon);
1433 	if (ubq->io_cmd_buf)
1434 		free_pages((unsigned long)ubq->io_cmd_buf, get_order(size));
1435 }
1436 
1437 static int ublk_init_queue(struct ublk_device *ub, int q_id)
1438 {
1439 	struct ublk_queue *ubq = ublk_get_queue(ub, q_id);
1440 	gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO;
1441 	void *ptr;
1442 	int size;
1443 
1444 	ubq->flags = ub->dev_info.flags;
1445 	ubq->q_id = q_id;
1446 	ubq->q_depth = ub->dev_info.queue_depth;
1447 	size = ublk_queue_cmd_buf_size(ub, q_id);
1448 
1449 	ptr = (void *) __get_free_pages(gfp_flags, get_order(size));
1450 	if (!ptr)
1451 		return -ENOMEM;
1452 
1453 	ubq->io_cmd_buf = ptr;
1454 	ubq->dev = ub;
1455 	return 0;
1456 }
1457 
1458 static void ublk_deinit_queues(struct ublk_device *ub)
1459 {
1460 	int nr_queues = ub->dev_info.nr_hw_queues;
1461 	int i;
1462 
1463 	if (!ub->__queues)
1464 		return;
1465 
1466 	for (i = 0; i < nr_queues; i++)
1467 		ublk_deinit_queue(ub, i);
1468 	kfree(ub->__queues);
1469 }
1470 
1471 static int ublk_init_queues(struct ublk_device *ub)
1472 {
1473 	int nr_queues = ub->dev_info.nr_hw_queues;
1474 	int depth = ub->dev_info.queue_depth;
1475 	int ubq_size = sizeof(struct ublk_queue) + depth * sizeof(struct ublk_io);
1476 	int i, ret = -ENOMEM;
1477 
1478 	ub->queue_size = ubq_size;
1479 	ub->__queues = kcalloc(nr_queues, ubq_size, GFP_KERNEL);
1480 	if (!ub->__queues)
1481 		return ret;
1482 
1483 	for (i = 0; i < nr_queues; i++) {
1484 		if (ublk_init_queue(ub, i))
1485 			goto fail;
1486 	}
1487 
1488 	init_completion(&ub->completion);
1489 	return 0;
1490 
1491  fail:
1492 	ublk_deinit_queues(ub);
1493 	return ret;
1494 }
1495 
1496 static int ublk_alloc_dev_number(struct ublk_device *ub, int idx)
1497 {
1498 	int i = idx;
1499 	int err;
1500 
1501 	spin_lock(&ublk_idr_lock);
1502 	/* allocate id, if @id >= 0, we're requesting that specific id */
1503 	if (i >= 0) {
1504 		err = idr_alloc(&ublk_index_idr, ub, i, i + 1, GFP_NOWAIT);
1505 		if (err == -ENOSPC)
1506 			err = -EEXIST;
1507 	} else {
1508 		err = idr_alloc(&ublk_index_idr, ub, 0, 0, GFP_NOWAIT);
1509 	}
1510 	spin_unlock(&ublk_idr_lock);
1511 
1512 	if (err >= 0)
1513 		ub->ub_number = err;
1514 
1515 	return err;
1516 }
1517 
1518 static void ublk_free_dev_number(struct ublk_device *ub)
1519 {
1520 	spin_lock(&ublk_idr_lock);
1521 	idr_remove(&ublk_index_idr, ub->ub_number);
1522 	wake_up_all(&ublk_idr_wq);
1523 	spin_unlock(&ublk_idr_lock);
1524 }
1525 
1526 static void ublk_cdev_rel(struct device *dev)
1527 {
1528 	struct ublk_device *ub = container_of(dev, struct ublk_device, cdev_dev);
1529 
1530 	blk_mq_free_tag_set(&ub->tag_set);
1531 	ublk_deinit_queues(ub);
1532 	ublk_free_dev_number(ub);
1533 	mutex_destroy(&ub->mutex);
1534 	kfree(ub);
1535 }
1536 
1537 static int ublk_add_chdev(struct ublk_device *ub)
1538 {
1539 	struct device *dev = &ub->cdev_dev;
1540 	int minor = ub->ub_number;
1541 	int ret;
1542 
1543 	dev->parent = ublk_misc.this_device;
1544 	dev->devt = MKDEV(MAJOR(ublk_chr_devt), minor);
1545 	dev->class = ublk_chr_class;
1546 	dev->release = ublk_cdev_rel;
1547 	device_initialize(dev);
1548 
1549 	ret = dev_set_name(dev, "ublkc%d", minor);
1550 	if (ret)
1551 		goto fail;
1552 
1553 	cdev_init(&ub->cdev, &ublk_ch_fops);
1554 	ret = cdev_device_add(&ub->cdev, dev);
1555 	if (ret)
1556 		goto fail;
1557 
1558 	ublks_added++;
1559 	return 0;
1560  fail:
1561 	put_device(dev);
1562 	return ret;
1563 }
1564 
1565 static void ublk_stop_work_fn(struct work_struct *work)
1566 {
1567 	struct ublk_device *ub =
1568 		container_of(work, struct ublk_device, stop_work);
1569 
1570 	ublk_stop_dev(ub);
1571 }
1572 
1573 /* align max io buffer size with PAGE_SIZE */
1574 static void ublk_align_max_io_size(struct ublk_device *ub)
1575 {
1576 	unsigned int max_io_bytes = ub->dev_info.max_io_buf_bytes;
1577 
1578 	ub->dev_info.max_io_buf_bytes =
1579 		round_down(max_io_bytes, PAGE_SIZE);
1580 }
1581 
1582 static int ublk_add_tag_set(struct ublk_device *ub)
1583 {
1584 	ub->tag_set.ops = &ublk_mq_ops;
1585 	ub->tag_set.nr_hw_queues = ub->dev_info.nr_hw_queues;
1586 	ub->tag_set.queue_depth = ub->dev_info.queue_depth;
1587 	ub->tag_set.numa_node = NUMA_NO_NODE;
1588 	ub->tag_set.cmd_size = sizeof(struct ublk_rq_data);
1589 	ub->tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
1590 	ub->tag_set.driver_data = ub;
1591 	return blk_mq_alloc_tag_set(&ub->tag_set);
1592 }
1593 
1594 static void ublk_remove(struct ublk_device *ub)
1595 {
1596 	ublk_stop_dev(ub);
1597 	cancel_work_sync(&ub->stop_work);
1598 	cancel_work_sync(&ub->quiesce_work);
1599 	cdev_device_del(&ub->cdev, &ub->cdev_dev);
1600 	put_device(&ub->cdev_dev);
1601 	ublks_added--;
1602 }
1603 
1604 static struct ublk_device *ublk_get_device_from_id(int idx)
1605 {
1606 	struct ublk_device *ub = NULL;
1607 
1608 	if (idx < 0)
1609 		return NULL;
1610 
1611 	spin_lock(&ublk_idr_lock);
1612 	ub = idr_find(&ublk_index_idr, idx);
1613 	if (ub)
1614 		ub = ublk_get_device(ub);
1615 	spin_unlock(&ublk_idr_lock);
1616 
1617 	return ub;
1618 }
1619 
1620 static int ublk_ctrl_start_dev(struct ublk_device *ub, struct io_uring_cmd *cmd)
1621 {
1622 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
1623 	int ublksrv_pid = (int)header->data[0];
1624 	struct gendisk *disk;
1625 	int ret = -EINVAL;
1626 
1627 	if (ublksrv_pid <= 0)
1628 		return -EINVAL;
1629 
1630 	wait_for_completion_interruptible(&ub->completion);
1631 
1632 	schedule_delayed_work(&ub->monitor_work, UBLK_DAEMON_MONITOR_PERIOD);
1633 
1634 	mutex_lock(&ub->mutex);
1635 	if (ub->dev_info.state == UBLK_S_DEV_LIVE ||
1636 	    test_bit(UB_STATE_USED, &ub->state)) {
1637 		ret = -EEXIST;
1638 		goto out_unlock;
1639 	}
1640 
1641 	disk = blk_mq_alloc_disk(&ub->tag_set, NULL);
1642 	if (IS_ERR(disk)) {
1643 		ret = PTR_ERR(disk);
1644 		goto out_unlock;
1645 	}
1646 	sprintf(disk->disk_name, "ublkb%d", ub->ub_number);
1647 	disk->fops = &ub_fops;
1648 	disk->private_data = ub;
1649 
1650 	ub->dev_info.ublksrv_pid = ublksrv_pid;
1651 	ub->ub_disk = disk;
1652 
1653 	ret = ublk_apply_params(ub);
1654 	if (ret)
1655 		goto out_put_disk;
1656 
1657 	/* don't probe partitions if any one ubq daemon is un-trusted */
1658 	if (ub->nr_privileged_daemon != ub->nr_queues_ready)
1659 		set_bit(GD_SUPPRESS_PART_SCAN, &disk->state);
1660 
1661 	get_device(&ub->cdev_dev);
1662 	ub->dev_info.state = UBLK_S_DEV_LIVE;
1663 	ret = add_disk(disk);
1664 	if (ret) {
1665 		/*
1666 		 * Has to drop the reference since ->free_disk won't be
1667 		 * called in case of add_disk failure.
1668 		 */
1669 		ub->dev_info.state = UBLK_S_DEV_DEAD;
1670 		ublk_put_device(ub);
1671 		goto out_put_disk;
1672 	}
1673 	set_bit(UB_STATE_USED, &ub->state);
1674 out_put_disk:
1675 	if (ret)
1676 		put_disk(disk);
1677 out_unlock:
1678 	mutex_unlock(&ub->mutex);
1679 	return ret;
1680 }
1681 
1682 static int ublk_ctrl_get_queue_affinity(struct ublk_device *ub,
1683 		struct io_uring_cmd *cmd)
1684 {
1685 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
1686 	void __user *argp = (void __user *)(unsigned long)header->addr;
1687 	cpumask_var_t cpumask;
1688 	unsigned long queue;
1689 	unsigned int retlen;
1690 	unsigned int i;
1691 	int ret;
1692 
1693 	if (header->len * BITS_PER_BYTE < nr_cpu_ids)
1694 		return -EINVAL;
1695 	if (header->len & (sizeof(unsigned long)-1))
1696 		return -EINVAL;
1697 	if (!header->addr)
1698 		return -EINVAL;
1699 
1700 	queue = header->data[0];
1701 	if (queue >= ub->dev_info.nr_hw_queues)
1702 		return -EINVAL;
1703 
1704 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
1705 		return -ENOMEM;
1706 
1707 	for_each_possible_cpu(i) {
1708 		if (ub->tag_set.map[HCTX_TYPE_DEFAULT].mq_map[i] == queue)
1709 			cpumask_set_cpu(i, cpumask);
1710 	}
1711 
1712 	ret = -EFAULT;
1713 	retlen = min_t(unsigned short, header->len, cpumask_size());
1714 	if (copy_to_user(argp, cpumask, retlen))
1715 		goto out_free_cpumask;
1716 	if (retlen != header->len &&
1717 	    clear_user(argp + retlen, header->len - retlen))
1718 		goto out_free_cpumask;
1719 
1720 	ret = 0;
1721 out_free_cpumask:
1722 	free_cpumask_var(cpumask);
1723 	return ret;
1724 }
1725 
1726 static inline void ublk_dump_dev_info(struct ublksrv_ctrl_dev_info *info)
1727 {
1728 	pr_devel("%s: dev id %d flags %llx\n", __func__,
1729 			info->dev_id, info->flags);
1730 	pr_devel("\t nr_hw_queues %d queue_depth %d\n",
1731 			info->nr_hw_queues, info->queue_depth);
1732 }
1733 
1734 static int ublk_ctrl_add_dev(struct io_uring_cmd *cmd)
1735 {
1736 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
1737 	void __user *argp = (void __user *)(unsigned long)header->addr;
1738 	struct ublksrv_ctrl_dev_info info;
1739 	struct ublk_device *ub;
1740 	int ret = -EINVAL;
1741 
1742 	if (header->len < sizeof(info) || !header->addr)
1743 		return -EINVAL;
1744 	if (header->queue_id != (u16)-1) {
1745 		pr_warn("%s: queue_id is wrong %x\n",
1746 			__func__, header->queue_id);
1747 		return -EINVAL;
1748 	}
1749 
1750 	if (copy_from_user(&info, argp, sizeof(info)))
1751 		return -EFAULT;
1752 
1753 	if (capable(CAP_SYS_ADMIN))
1754 		info.flags &= ~UBLK_F_UNPRIVILEGED_DEV;
1755 	else if (!(info.flags & UBLK_F_UNPRIVILEGED_DEV))
1756 		return -EPERM;
1757 
1758 	/*
1759 	 * unprivileged device can't be trusted, but RECOVERY and
1760 	 * RECOVERY_REISSUE still may hang error handling, so can't
1761 	 * support recovery features for unprivileged ublk now
1762 	 *
1763 	 * TODO: provide forward progress for RECOVERY handler, so that
1764 	 * unprivileged device can benefit from it
1765 	 */
1766 	if (info.flags & UBLK_F_UNPRIVILEGED_DEV)
1767 		info.flags &= ~(UBLK_F_USER_RECOVERY_REISSUE |
1768 				UBLK_F_USER_RECOVERY);
1769 
1770 	/* the created device is always owned by current user */
1771 	ublk_store_owner_uid_gid(&info.owner_uid, &info.owner_gid);
1772 
1773 	if (header->dev_id != info.dev_id) {
1774 		pr_warn("%s: dev id not match %u %u\n",
1775 			__func__, header->dev_id, info.dev_id);
1776 		return -EINVAL;
1777 	}
1778 
1779 	ublk_dump_dev_info(&info);
1780 
1781 	ret = mutex_lock_killable(&ublk_ctl_mutex);
1782 	if (ret)
1783 		return ret;
1784 
1785 	ret = -EACCES;
1786 	if (ublks_added >= ublks_max)
1787 		goto out_unlock;
1788 
1789 	ret = -ENOMEM;
1790 	ub = kzalloc(sizeof(*ub), GFP_KERNEL);
1791 	if (!ub)
1792 		goto out_unlock;
1793 	mutex_init(&ub->mutex);
1794 	spin_lock_init(&ub->mm_lock);
1795 	INIT_WORK(&ub->quiesce_work, ublk_quiesce_work_fn);
1796 	INIT_WORK(&ub->stop_work, ublk_stop_work_fn);
1797 	INIT_DELAYED_WORK(&ub->monitor_work, ublk_daemon_monitor_work);
1798 
1799 	ret = ublk_alloc_dev_number(ub, header->dev_id);
1800 	if (ret < 0)
1801 		goto out_free_ub;
1802 
1803 	memcpy(&ub->dev_info, &info, sizeof(info));
1804 
1805 	/* update device id */
1806 	ub->dev_info.dev_id = ub->ub_number;
1807 
1808 	/*
1809 	 * 64bit flags will be copied back to userspace as feature
1810 	 * negotiation result, so have to clear flags which driver
1811 	 * doesn't support yet, then userspace can get correct flags
1812 	 * (features) to handle.
1813 	 */
1814 	ub->dev_info.flags &= UBLK_F_ALL;
1815 
1816 	if (!IS_BUILTIN(CONFIG_BLK_DEV_UBLK))
1817 		ub->dev_info.flags |= UBLK_F_URING_CMD_COMP_IN_TASK;
1818 
1819 	ub->dev_info.flags |= UBLK_F_CMD_IOCTL_ENCODE;
1820 
1821 	/* We are not ready to support zero copy */
1822 	ub->dev_info.flags &= ~UBLK_F_SUPPORT_ZERO_COPY;
1823 
1824 	ub->dev_info.nr_hw_queues = min_t(unsigned int,
1825 			ub->dev_info.nr_hw_queues, nr_cpu_ids);
1826 	ublk_align_max_io_size(ub);
1827 
1828 	ret = ublk_init_queues(ub);
1829 	if (ret)
1830 		goto out_free_dev_number;
1831 
1832 	ret = ublk_add_tag_set(ub);
1833 	if (ret)
1834 		goto out_deinit_queues;
1835 
1836 	ret = -EFAULT;
1837 	if (copy_to_user(argp, &ub->dev_info, sizeof(info)))
1838 		goto out_free_tag_set;
1839 
1840 	/*
1841 	 * Add the char dev so that ublksrv daemon can be setup.
1842 	 * ublk_add_chdev() will cleanup everything if it fails.
1843 	 */
1844 	ret = ublk_add_chdev(ub);
1845 	goto out_unlock;
1846 
1847 out_free_tag_set:
1848 	blk_mq_free_tag_set(&ub->tag_set);
1849 out_deinit_queues:
1850 	ublk_deinit_queues(ub);
1851 out_free_dev_number:
1852 	ublk_free_dev_number(ub);
1853 out_free_ub:
1854 	mutex_destroy(&ub->mutex);
1855 	kfree(ub);
1856 out_unlock:
1857 	mutex_unlock(&ublk_ctl_mutex);
1858 	return ret;
1859 }
1860 
1861 static inline bool ublk_idr_freed(int id)
1862 {
1863 	void *ptr;
1864 
1865 	spin_lock(&ublk_idr_lock);
1866 	ptr = idr_find(&ublk_index_idr, id);
1867 	spin_unlock(&ublk_idr_lock);
1868 
1869 	return ptr == NULL;
1870 }
1871 
1872 static int ublk_ctrl_del_dev(struct ublk_device **p_ub)
1873 {
1874 	struct ublk_device *ub = *p_ub;
1875 	int idx = ub->ub_number;
1876 	int ret;
1877 
1878 	ret = mutex_lock_killable(&ublk_ctl_mutex);
1879 	if (ret)
1880 		return ret;
1881 
1882 	if (!test_bit(UB_STATE_DELETED, &ub->state)) {
1883 		ublk_remove(ub);
1884 		set_bit(UB_STATE_DELETED, &ub->state);
1885 	}
1886 
1887 	/* Mark the reference as consumed */
1888 	*p_ub = NULL;
1889 	ublk_put_device(ub);
1890 	mutex_unlock(&ublk_ctl_mutex);
1891 
1892 	/*
1893 	 * Wait until the idr is removed, then it can be reused after
1894 	 * DEL_DEV command is returned.
1895 	 *
1896 	 * If we returns because of user interrupt, future delete command
1897 	 * may come:
1898 	 *
1899 	 * - the device number isn't freed, this device won't or needn't
1900 	 *   be deleted again, since UB_STATE_DELETED is set, and device
1901 	 *   will be released after the last reference is dropped
1902 	 *
1903 	 * - the device number is freed already, we will not find this
1904 	 *   device via ublk_get_device_from_id()
1905 	 */
1906 	wait_event_interruptible(ublk_idr_wq, ublk_idr_freed(idx));
1907 
1908 	return 0;
1909 }
1910 
1911 static inline void ublk_ctrl_cmd_dump(struct io_uring_cmd *cmd)
1912 {
1913 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
1914 
1915 	pr_devel("%s: cmd_op %x, dev id %d qid %d data %llx buf %llx len %u\n",
1916 			__func__, cmd->cmd_op, header->dev_id, header->queue_id,
1917 			header->data[0], header->addr, header->len);
1918 }
1919 
1920 static int ublk_ctrl_stop_dev(struct ublk_device *ub)
1921 {
1922 	ublk_stop_dev(ub);
1923 	cancel_work_sync(&ub->stop_work);
1924 	cancel_work_sync(&ub->quiesce_work);
1925 
1926 	return 0;
1927 }
1928 
1929 static int ublk_ctrl_get_dev_info(struct ublk_device *ub,
1930 		struct io_uring_cmd *cmd)
1931 {
1932 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
1933 	void __user *argp = (void __user *)(unsigned long)header->addr;
1934 
1935 	if (header->len < sizeof(struct ublksrv_ctrl_dev_info) || !header->addr)
1936 		return -EINVAL;
1937 
1938 	if (copy_to_user(argp, &ub->dev_info, sizeof(ub->dev_info)))
1939 		return -EFAULT;
1940 
1941 	return 0;
1942 }
1943 
1944 /* TYPE_DEVT is readonly, so fill it up before returning to userspace */
1945 static void ublk_ctrl_fill_params_devt(struct ublk_device *ub)
1946 {
1947 	ub->params.devt.char_major = MAJOR(ub->cdev_dev.devt);
1948 	ub->params.devt.char_minor = MINOR(ub->cdev_dev.devt);
1949 
1950 	if (ub->ub_disk) {
1951 		ub->params.devt.disk_major = MAJOR(disk_devt(ub->ub_disk));
1952 		ub->params.devt.disk_minor = MINOR(disk_devt(ub->ub_disk));
1953 	} else {
1954 		ub->params.devt.disk_major = 0;
1955 		ub->params.devt.disk_minor = 0;
1956 	}
1957 	ub->params.types |= UBLK_PARAM_TYPE_DEVT;
1958 }
1959 
1960 static int ublk_ctrl_get_params(struct ublk_device *ub,
1961 		struct io_uring_cmd *cmd)
1962 {
1963 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
1964 	void __user *argp = (void __user *)(unsigned long)header->addr;
1965 	struct ublk_params_header ph;
1966 	int ret;
1967 
1968 	if (header->len <= sizeof(ph) || !header->addr)
1969 		return -EINVAL;
1970 
1971 	if (copy_from_user(&ph, argp, sizeof(ph)))
1972 		return -EFAULT;
1973 
1974 	if (ph.len > header->len || !ph.len)
1975 		return -EINVAL;
1976 
1977 	if (ph.len > sizeof(struct ublk_params))
1978 		ph.len = sizeof(struct ublk_params);
1979 
1980 	mutex_lock(&ub->mutex);
1981 	ublk_ctrl_fill_params_devt(ub);
1982 	if (copy_to_user(argp, &ub->params, ph.len))
1983 		ret = -EFAULT;
1984 	else
1985 		ret = 0;
1986 	mutex_unlock(&ub->mutex);
1987 
1988 	return ret;
1989 }
1990 
1991 static int ublk_ctrl_set_params(struct ublk_device *ub,
1992 		struct io_uring_cmd *cmd)
1993 {
1994 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
1995 	void __user *argp = (void __user *)(unsigned long)header->addr;
1996 	struct ublk_params_header ph;
1997 	int ret = -EFAULT;
1998 
1999 	if (header->len <= sizeof(ph) || !header->addr)
2000 		return -EINVAL;
2001 
2002 	if (copy_from_user(&ph, argp, sizeof(ph)))
2003 		return -EFAULT;
2004 
2005 	if (ph.len > header->len || !ph.len || !ph.types)
2006 		return -EINVAL;
2007 
2008 	if (ph.len > sizeof(struct ublk_params))
2009 		ph.len = sizeof(struct ublk_params);
2010 
2011 	/* parameters can only be changed when device isn't live */
2012 	mutex_lock(&ub->mutex);
2013 	if (ub->dev_info.state == UBLK_S_DEV_LIVE) {
2014 		ret = -EACCES;
2015 	} else if (copy_from_user(&ub->params, argp, ph.len)) {
2016 		ret = -EFAULT;
2017 	} else {
2018 		/* clear all we don't support yet */
2019 		ub->params.types &= UBLK_PARAM_TYPE_ALL;
2020 		ret = ublk_validate_params(ub);
2021 		if (ret)
2022 			ub->params.types = 0;
2023 	}
2024 	mutex_unlock(&ub->mutex);
2025 
2026 	return ret;
2027 }
2028 
2029 static void ublk_queue_reinit(struct ublk_device *ub, struct ublk_queue *ubq)
2030 {
2031 	int i;
2032 
2033 	WARN_ON_ONCE(!(ubq->ubq_daemon && ubq_daemon_is_dying(ubq)));
2034 	/* All old ioucmds have to be completed */
2035 	WARN_ON_ONCE(ubq->nr_io_ready);
2036 	/* old daemon is PF_EXITING, put it now */
2037 	put_task_struct(ubq->ubq_daemon);
2038 	/* We have to reset it to NULL, otherwise ub won't accept new FETCH_REQ */
2039 	ubq->ubq_daemon = NULL;
2040 	ubq->timeout = false;
2041 
2042 	for (i = 0; i < ubq->q_depth; i++) {
2043 		struct ublk_io *io = &ubq->ios[i];
2044 
2045 		/* forget everything now and be ready for new FETCH_REQ */
2046 		io->flags = 0;
2047 		io->cmd = NULL;
2048 		io->addr = 0;
2049 	}
2050 }
2051 
2052 static int ublk_ctrl_start_recovery(struct ublk_device *ub,
2053 		struct io_uring_cmd *cmd)
2054 {
2055 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2056 	int ret = -EINVAL;
2057 	int i;
2058 
2059 	mutex_lock(&ub->mutex);
2060 	if (!ublk_can_use_recovery(ub))
2061 		goto out_unlock;
2062 	/*
2063 	 * START_RECOVERY is only allowd after:
2064 	 *
2065 	 * (1) UB_STATE_OPEN is not set, which means the dying process is exited
2066 	 *     and related io_uring ctx is freed so file struct of /dev/ublkcX is
2067 	 *     released.
2068 	 *
2069 	 * (2) UBLK_S_DEV_QUIESCED is set, which means the quiesce_work:
2070 	 *     (a)has quiesced request queue
2071 	 *     (b)has requeued every inflight rqs whose io_flags is ACTIVE
2072 	 *     (c)has requeued/aborted every inflight rqs whose io_flags is NOT ACTIVE
2073 	 *     (d)has completed/camceled all ioucmds owned by ther dying process
2074 	 */
2075 	if (test_bit(UB_STATE_OPEN, &ub->state) ||
2076 			ub->dev_info.state != UBLK_S_DEV_QUIESCED) {
2077 		ret = -EBUSY;
2078 		goto out_unlock;
2079 	}
2080 	pr_devel("%s: start recovery for dev id %d.\n", __func__, header->dev_id);
2081 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
2082 		ublk_queue_reinit(ub, ublk_get_queue(ub, i));
2083 	/* set to NULL, otherwise new ubq_daemon cannot mmap the io_cmd_buf */
2084 	ub->mm = NULL;
2085 	ub->nr_queues_ready = 0;
2086 	ub->nr_privileged_daemon = 0;
2087 	init_completion(&ub->completion);
2088 	ret = 0;
2089  out_unlock:
2090 	mutex_unlock(&ub->mutex);
2091 	return ret;
2092 }
2093 
2094 static int ublk_ctrl_end_recovery(struct ublk_device *ub,
2095 		struct io_uring_cmd *cmd)
2096 {
2097 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2098 	int ublksrv_pid = (int)header->data[0];
2099 	int ret = -EINVAL;
2100 
2101 	pr_devel("%s: Waiting for new ubq_daemons(nr: %d) are ready, dev id %d...\n",
2102 			__func__, ub->dev_info.nr_hw_queues, header->dev_id);
2103 	/* wait until new ubq_daemon sending all FETCH_REQ */
2104 	wait_for_completion_interruptible(&ub->completion);
2105 	pr_devel("%s: All new ubq_daemons(nr: %d) are ready, dev id %d\n",
2106 			__func__, ub->dev_info.nr_hw_queues, header->dev_id);
2107 
2108 	mutex_lock(&ub->mutex);
2109 	if (!ublk_can_use_recovery(ub))
2110 		goto out_unlock;
2111 
2112 	if (ub->dev_info.state != UBLK_S_DEV_QUIESCED) {
2113 		ret = -EBUSY;
2114 		goto out_unlock;
2115 	}
2116 	ub->dev_info.ublksrv_pid = ublksrv_pid;
2117 	pr_devel("%s: new ublksrv_pid %d, dev id %d\n",
2118 			__func__, ublksrv_pid, header->dev_id);
2119 	blk_mq_unquiesce_queue(ub->ub_disk->queue);
2120 	pr_devel("%s: queue unquiesced, dev id %d.\n",
2121 			__func__, header->dev_id);
2122 	blk_mq_kick_requeue_list(ub->ub_disk->queue);
2123 	ub->dev_info.state = UBLK_S_DEV_LIVE;
2124 	schedule_delayed_work(&ub->monitor_work, UBLK_DAEMON_MONITOR_PERIOD);
2125 	ret = 0;
2126  out_unlock:
2127 	mutex_unlock(&ub->mutex);
2128 	return ret;
2129 }
2130 
2131 /*
2132  * All control commands are sent via /dev/ublk-control, so we have to check
2133  * the destination device's permission
2134  */
2135 static int ublk_char_dev_permission(struct ublk_device *ub,
2136 		const char *dev_path, int mask)
2137 {
2138 	int err;
2139 	struct path path;
2140 	struct kstat stat;
2141 
2142 	err = kern_path(dev_path, LOOKUP_FOLLOW, &path);
2143 	if (err)
2144 		return err;
2145 
2146 	err = vfs_getattr(&path, &stat, STATX_TYPE, AT_STATX_SYNC_AS_STAT);
2147 	if (err)
2148 		goto exit;
2149 
2150 	err = -EPERM;
2151 	if (stat.rdev != ub->cdev_dev.devt || !S_ISCHR(stat.mode))
2152 		goto exit;
2153 
2154 	err = inode_permission(&nop_mnt_idmap,
2155 			d_backing_inode(path.dentry), mask);
2156 exit:
2157 	path_put(&path);
2158 	return err;
2159 }
2160 
2161 static int ublk_ctrl_uring_cmd_permission(struct ublk_device *ub,
2162 		struct io_uring_cmd *cmd)
2163 {
2164 	struct ublksrv_ctrl_cmd *header = (struct ublksrv_ctrl_cmd *)io_uring_sqe_cmd(cmd->sqe);
2165 	bool unprivileged = ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV;
2166 	void __user *argp = (void __user *)(unsigned long)header->addr;
2167 	char *dev_path = NULL;
2168 	int ret = 0;
2169 	int mask;
2170 
2171 	if (!unprivileged) {
2172 		if (!capable(CAP_SYS_ADMIN))
2173 			return -EPERM;
2174 		/*
2175 		 * The new added command of UBLK_CMD_GET_DEV_INFO2 includes
2176 		 * char_dev_path in payload too, since userspace may not
2177 		 * know if the specified device is created as unprivileged
2178 		 * mode.
2179 		 */
2180 		if (_IOC_NR(cmd->cmd_op) != UBLK_CMD_GET_DEV_INFO2)
2181 			return 0;
2182 	}
2183 
2184 	/*
2185 	 * User has to provide the char device path for unprivileged ublk
2186 	 *
2187 	 * header->addr always points to the dev path buffer, and
2188 	 * header->dev_path_len records length of dev path buffer.
2189 	 */
2190 	if (!header->dev_path_len || header->dev_path_len > PATH_MAX)
2191 		return -EINVAL;
2192 
2193 	if (header->len < header->dev_path_len)
2194 		return -EINVAL;
2195 
2196 	dev_path = kmalloc(header->dev_path_len + 1, GFP_KERNEL);
2197 	if (!dev_path)
2198 		return -ENOMEM;
2199 
2200 	ret = -EFAULT;
2201 	if (copy_from_user(dev_path, argp, header->dev_path_len))
2202 		goto exit;
2203 	dev_path[header->dev_path_len] = 0;
2204 
2205 	ret = -EINVAL;
2206 	switch (_IOC_NR(cmd->cmd_op)) {
2207 	case UBLK_CMD_GET_DEV_INFO:
2208 	case UBLK_CMD_GET_DEV_INFO2:
2209 	case UBLK_CMD_GET_QUEUE_AFFINITY:
2210 	case UBLK_CMD_GET_PARAMS:
2211 		mask = MAY_READ;
2212 		break;
2213 	case UBLK_CMD_START_DEV:
2214 	case UBLK_CMD_STOP_DEV:
2215 	case UBLK_CMD_ADD_DEV:
2216 	case UBLK_CMD_DEL_DEV:
2217 	case UBLK_CMD_SET_PARAMS:
2218 	case UBLK_CMD_START_USER_RECOVERY:
2219 	case UBLK_CMD_END_USER_RECOVERY:
2220 		mask = MAY_READ | MAY_WRITE;
2221 		break;
2222 	default:
2223 		goto exit;
2224 	}
2225 
2226 	ret = ublk_char_dev_permission(ub, dev_path, mask);
2227 	if (!ret) {
2228 		header->len -= header->dev_path_len;
2229 		header->addr += header->dev_path_len;
2230 	}
2231 	pr_devel("%s: dev id %d cmd_op %x uid %d gid %d path %s ret %d\n",
2232 			__func__, ub->ub_number, cmd->cmd_op,
2233 			ub->dev_info.owner_uid, ub->dev_info.owner_gid,
2234 			dev_path, ret);
2235 exit:
2236 	kfree(dev_path);
2237 	return ret;
2238 }
2239 
2240 static int ublk_ctrl_uring_cmd(struct io_uring_cmd *cmd,
2241 		unsigned int issue_flags)
2242 {
2243 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2244 	struct ublk_device *ub = NULL;
2245 	u32 cmd_op = cmd->cmd_op;
2246 	int ret = -EINVAL;
2247 
2248 	if (issue_flags & IO_URING_F_NONBLOCK)
2249 		return -EAGAIN;
2250 
2251 	ublk_ctrl_cmd_dump(cmd);
2252 
2253 	if (!(issue_flags & IO_URING_F_SQE128))
2254 		goto out;
2255 
2256 	ret = ublk_check_cmd_op(cmd_op);
2257 	if (ret)
2258 		goto out;
2259 
2260 	if (_IOC_NR(cmd_op) != UBLK_CMD_ADD_DEV) {
2261 		ret = -ENODEV;
2262 		ub = ublk_get_device_from_id(header->dev_id);
2263 		if (!ub)
2264 			goto out;
2265 
2266 		ret = ublk_ctrl_uring_cmd_permission(ub, cmd);
2267 		if (ret)
2268 			goto put_dev;
2269 	}
2270 
2271 	switch (_IOC_NR(cmd_op)) {
2272 	case UBLK_CMD_START_DEV:
2273 		ret = ublk_ctrl_start_dev(ub, cmd);
2274 		break;
2275 	case UBLK_CMD_STOP_DEV:
2276 		ret = ublk_ctrl_stop_dev(ub);
2277 		break;
2278 	case UBLK_CMD_GET_DEV_INFO:
2279 	case UBLK_CMD_GET_DEV_INFO2:
2280 		ret = ublk_ctrl_get_dev_info(ub, cmd);
2281 		break;
2282 	case UBLK_CMD_ADD_DEV:
2283 		ret = ublk_ctrl_add_dev(cmd);
2284 		break;
2285 	case UBLK_CMD_DEL_DEV:
2286 		ret = ublk_ctrl_del_dev(&ub);
2287 		break;
2288 	case UBLK_CMD_GET_QUEUE_AFFINITY:
2289 		ret = ublk_ctrl_get_queue_affinity(ub, cmd);
2290 		break;
2291 	case UBLK_CMD_GET_PARAMS:
2292 		ret = ublk_ctrl_get_params(ub, cmd);
2293 		break;
2294 	case UBLK_CMD_SET_PARAMS:
2295 		ret = ublk_ctrl_set_params(ub, cmd);
2296 		break;
2297 	case UBLK_CMD_START_USER_RECOVERY:
2298 		ret = ublk_ctrl_start_recovery(ub, cmd);
2299 		break;
2300 	case UBLK_CMD_END_USER_RECOVERY:
2301 		ret = ublk_ctrl_end_recovery(ub, cmd);
2302 		break;
2303 	default:
2304 		ret = -ENOTSUPP;
2305 		break;
2306 	}
2307 
2308  put_dev:
2309 	if (ub)
2310 		ublk_put_device(ub);
2311  out:
2312 	io_uring_cmd_done(cmd, ret, 0, issue_flags);
2313 	pr_devel("%s: cmd done ret %d cmd_op %x, dev id %d qid %d\n",
2314 			__func__, ret, cmd->cmd_op, header->dev_id, header->queue_id);
2315 	return -EIOCBQUEUED;
2316 }
2317 
2318 static const struct file_operations ublk_ctl_fops = {
2319 	.open		= nonseekable_open,
2320 	.uring_cmd      = ublk_ctrl_uring_cmd,
2321 	.owner		= THIS_MODULE,
2322 	.llseek		= noop_llseek,
2323 };
2324 
2325 static struct miscdevice ublk_misc = {
2326 	.minor		= MISC_DYNAMIC_MINOR,
2327 	.name		= "ublk-control",
2328 	.fops		= &ublk_ctl_fops,
2329 };
2330 
2331 static int __init ublk_init(void)
2332 {
2333 	int ret;
2334 
2335 	init_waitqueue_head(&ublk_idr_wq);
2336 
2337 	ret = misc_register(&ublk_misc);
2338 	if (ret)
2339 		return ret;
2340 
2341 	ret = alloc_chrdev_region(&ublk_chr_devt, 0, UBLK_MINORS, "ublk-char");
2342 	if (ret)
2343 		goto unregister_mis;
2344 
2345 	ublk_chr_class = class_create("ublk-char");
2346 	if (IS_ERR(ublk_chr_class)) {
2347 		ret = PTR_ERR(ublk_chr_class);
2348 		goto free_chrdev_region;
2349 	}
2350 	return 0;
2351 
2352 free_chrdev_region:
2353 	unregister_chrdev_region(ublk_chr_devt, UBLK_MINORS);
2354 unregister_mis:
2355 	misc_deregister(&ublk_misc);
2356 	return ret;
2357 }
2358 
2359 static void __exit ublk_exit(void)
2360 {
2361 	struct ublk_device *ub;
2362 	int id;
2363 
2364 	idr_for_each_entry(&ublk_index_idr, ub, id)
2365 		ublk_remove(ub);
2366 
2367 	class_destroy(ublk_chr_class);
2368 	misc_deregister(&ublk_misc);
2369 
2370 	idr_destroy(&ublk_index_idr);
2371 	unregister_chrdev_region(ublk_chr_devt, UBLK_MINORS);
2372 }
2373 
2374 module_init(ublk_init);
2375 module_exit(ublk_exit);
2376 
2377 module_param(ublks_max, int, 0444);
2378 MODULE_PARM_DESC(ublks_max, "max number of ublk devices allowed to add(default: 64)");
2379 
2380 MODULE_AUTHOR("Ming Lei <ming.lei@redhat.com>");
2381 MODULE_LICENSE("GPL");
2382