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