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