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