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