xref: /linux/drivers/block/ublk_drv.c (revision cc25df3e2e22a956d3a0d427369367b4a901d203)
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 #define UBLK_INVALID_BUF_IDX 	((u16)-1)
52 
53 /* private ioctl command mirror */
54 #define UBLK_CMD_DEL_DEV_ASYNC	_IOC_NR(UBLK_U_CMD_DEL_DEV_ASYNC)
55 #define UBLK_CMD_UPDATE_SIZE	_IOC_NR(UBLK_U_CMD_UPDATE_SIZE)
56 #define UBLK_CMD_QUIESCE_DEV	_IOC_NR(UBLK_U_CMD_QUIESCE_DEV)
57 
58 #define UBLK_IO_REGISTER_IO_BUF		_IOC_NR(UBLK_U_IO_REGISTER_IO_BUF)
59 #define UBLK_IO_UNREGISTER_IO_BUF	_IOC_NR(UBLK_U_IO_UNREGISTER_IO_BUF)
60 
61 /* All UBLK_F_* have to be included into UBLK_F_ALL */
62 #define UBLK_F_ALL (UBLK_F_SUPPORT_ZERO_COPY \
63 		| UBLK_F_URING_CMD_COMP_IN_TASK \
64 		| UBLK_F_NEED_GET_DATA \
65 		| UBLK_F_USER_RECOVERY \
66 		| UBLK_F_USER_RECOVERY_REISSUE \
67 		| UBLK_F_UNPRIVILEGED_DEV \
68 		| UBLK_F_CMD_IOCTL_ENCODE \
69 		| UBLK_F_USER_COPY \
70 		| UBLK_F_ZONED \
71 		| UBLK_F_USER_RECOVERY_FAIL_IO \
72 		| UBLK_F_UPDATE_SIZE \
73 		| UBLK_F_AUTO_BUF_REG \
74 		| UBLK_F_QUIESCE \
75 		| UBLK_F_PER_IO_DAEMON \
76 		| UBLK_F_BUF_REG_OFF_DAEMON)
77 
78 #define UBLK_F_ALL_RECOVERY_FLAGS (UBLK_F_USER_RECOVERY \
79 		| UBLK_F_USER_RECOVERY_REISSUE \
80 		| UBLK_F_USER_RECOVERY_FAIL_IO)
81 
82 /* All UBLK_PARAM_TYPE_* should be included here */
83 #define UBLK_PARAM_TYPE_ALL                                \
84 	(UBLK_PARAM_TYPE_BASIC | UBLK_PARAM_TYPE_DISCARD | \
85 	 UBLK_PARAM_TYPE_DEVT | UBLK_PARAM_TYPE_ZONED |    \
86 	 UBLK_PARAM_TYPE_DMA_ALIGN | UBLK_PARAM_TYPE_SEGMENT)
87 
88 struct ublk_uring_cmd_pdu {
89 	/*
90 	 * Store requests in same batch temporarily for queuing them to
91 	 * daemon context.
92 	 *
93 	 * It should have been stored to request payload, but we do want
94 	 * to avoid extra pre-allocation, and uring_cmd payload is always
95 	 * free for us
96 	 */
97 	union {
98 		struct request *req;
99 		struct request *req_list;
100 	};
101 
102 	/*
103 	 * The following two are valid in this cmd whole lifetime, and
104 	 * setup in ublk uring_cmd handler
105 	 */
106 	struct ublk_queue *ubq;
107 
108 	u16 tag;
109 };
110 
111 /*
112  * io command is active: sqe cmd is received, and its cqe isn't done
113  *
114  * If the flag is set, the io command is owned by ublk driver, and waited
115  * for incoming blk-mq request from the ublk block device.
116  *
117  * If the flag is cleared, the io command will be completed, and owned by
118  * ublk server.
119  */
120 #define UBLK_IO_FLAG_ACTIVE	0x01
121 
122 /*
123  * IO command is completed via cqe, and it is being handled by ublksrv, and
124  * not committed yet
125  *
126  * Basically exclusively with UBLK_IO_FLAG_ACTIVE, so can be served for
127  * cross verification
128  */
129 #define UBLK_IO_FLAG_OWNED_BY_SRV 0x02
130 
131 /*
132  * UBLK_IO_FLAG_NEED_GET_DATA is set because IO command requires
133  * get data buffer address from ublksrv.
134  *
135  * Then, bio data could be copied into this data buffer for a WRITE request
136  * after the IO command is issued again and UBLK_IO_FLAG_NEED_GET_DATA is unset.
137  */
138 #define UBLK_IO_FLAG_NEED_GET_DATA 0x08
139 
140 /*
141  * request buffer is registered automatically, so we have to unregister it
142  * before completing this request.
143  *
144  * io_uring will unregister buffer automatically for us during exiting.
145  */
146 #define UBLK_IO_FLAG_AUTO_BUF_REG 	0x10
147 
148 /* atomic RW with ubq->cancel_lock */
149 #define UBLK_IO_FLAG_CANCELED	0x80000000
150 
151 /*
152  * Initialize refcount to a large number to include any registered buffers.
153  * UBLK_IO_COMMIT_AND_FETCH_REQ will release these references minus those for
154  * any buffers registered on the io daemon task.
155  */
156 #define UBLK_REFCOUNT_INIT (REFCOUNT_MAX / 2)
157 
158 union ublk_io_buf {
159 	__u64	addr;
160 	struct ublk_auto_buf_reg auto_reg;
161 };
162 
163 struct ublk_io {
164 	union ublk_io_buf buf;
165 	unsigned int flags;
166 	int res;
167 
168 	union {
169 		/* valid if UBLK_IO_FLAG_ACTIVE is set */
170 		struct io_uring_cmd *cmd;
171 		/* valid if UBLK_IO_FLAG_OWNED_BY_SRV is set */
172 		struct request *req;
173 	};
174 
175 	struct task_struct *task;
176 
177 	/*
178 	 * The number of uses of this I/O by the ublk server
179 	 * if user copy or zero copy are enabled:
180 	 * - UBLK_REFCOUNT_INIT from dispatch to the server
181 	 *   until UBLK_IO_COMMIT_AND_FETCH_REQ
182 	 * - 1 for each inflight ublk_ch_{read,write}_iter() call
183 	 * - 1 for each io_uring registered buffer not registered on task
184 	 * The I/O can only be completed once all references are dropped.
185 	 * User copy and buffer registration operations are only permitted
186 	 * if the reference count is nonzero.
187 	 */
188 	refcount_t ref;
189 	/* Count of buffers registered on task and not yet unregistered */
190 	unsigned task_registered_buffers;
191 
192 	void *buf_ctx_handle;
193 } ____cacheline_aligned_in_smp;
194 
195 struct ublk_queue {
196 	int q_id;
197 	int q_depth;
198 
199 	unsigned long flags;
200 	struct ublksrv_io_desc *io_cmd_buf;
201 
202 	bool force_abort;
203 	bool canceling;
204 	bool fail_io; /* copy of dev->state == UBLK_S_DEV_FAIL_IO */
205 	spinlock_t		cancel_lock;
206 	struct ublk_device *dev;
207 	struct ublk_io ios[] __counted_by(q_depth);
208 };
209 
210 struct ublk_device {
211 	struct gendisk		*ub_disk;
212 
213 	struct ublksrv_ctrl_dev_info	dev_info;
214 
215 	struct blk_mq_tag_set	tag_set;
216 
217 	struct cdev		cdev;
218 	struct device		cdev_dev;
219 
220 #define UB_STATE_OPEN		0
221 #define UB_STATE_USED		1
222 #define UB_STATE_DELETED	2
223 	unsigned long		state;
224 	int			ub_number;
225 
226 	struct mutex		mutex;
227 
228 	spinlock_t		lock;
229 	struct mm_struct	*mm;
230 
231 	struct ublk_params	params;
232 
233 	struct completion	completion;
234 	u32			nr_io_ready;
235 	bool 			unprivileged_daemons;
236 	struct mutex cancel_mutex;
237 	bool canceling;
238 	pid_t 	ublksrv_tgid;
239 	struct delayed_work	exit_work;
240 
241 	struct ublk_queue       *queues[];
242 };
243 
244 /* header of ublk_params */
245 struct ublk_params_header {
246 	__u32	len;
247 	__u32	types;
248 };
249 
250 static void ublk_io_release(void *priv);
251 static void ublk_stop_dev_unlocked(struct ublk_device *ub);
252 static void ublk_abort_queue(struct ublk_device *ub, struct ublk_queue *ubq);
253 static inline struct request *__ublk_check_and_get_req(struct ublk_device *ub,
254 		u16 q_id, u16 tag, struct ublk_io *io, size_t offset);
255 static inline unsigned int ublk_req_build_flags(struct request *req);
256 
257 static inline struct ublksrv_io_desc *
258 ublk_get_iod(const struct ublk_queue *ubq, unsigned tag)
259 {
260 	return &ubq->io_cmd_buf[tag];
261 }
262 
263 static inline bool ublk_dev_is_zoned(const struct ublk_device *ub)
264 {
265 	return ub->dev_info.flags & UBLK_F_ZONED;
266 }
267 
268 static inline bool ublk_queue_is_zoned(const struct ublk_queue *ubq)
269 {
270 	return ubq->flags & UBLK_F_ZONED;
271 }
272 
273 #ifdef CONFIG_BLK_DEV_ZONED
274 
275 struct ublk_zoned_report_desc {
276 	__u64 sector;
277 	__u32 operation;
278 	__u32 nr_zones;
279 };
280 
281 static DEFINE_XARRAY(ublk_zoned_report_descs);
282 
283 static int ublk_zoned_insert_report_desc(const struct request *req,
284 		struct ublk_zoned_report_desc *desc)
285 {
286 	return xa_insert(&ublk_zoned_report_descs, (unsigned long)req,
287 			    desc, GFP_KERNEL);
288 }
289 
290 static struct ublk_zoned_report_desc *ublk_zoned_erase_report_desc(
291 		const struct request *req)
292 {
293 	return xa_erase(&ublk_zoned_report_descs, (unsigned long)req);
294 }
295 
296 static struct ublk_zoned_report_desc *ublk_zoned_get_report_desc(
297 		const struct request *req)
298 {
299 	return xa_load(&ublk_zoned_report_descs, (unsigned long)req);
300 }
301 
302 static int ublk_get_nr_zones(const struct ublk_device *ub)
303 {
304 	const struct ublk_param_basic *p = &ub->params.basic;
305 
306 	/* Zone size is a power of 2 */
307 	return p->dev_sectors >> ilog2(p->chunk_sectors);
308 }
309 
310 static int ublk_revalidate_disk_zones(struct ublk_device *ub)
311 {
312 	return blk_revalidate_disk_zones(ub->ub_disk);
313 }
314 
315 static int ublk_dev_param_zoned_validate(const struct ublk_device *ub)
316 {
317 	const struct ublk_param_zoned *p = &ub->params.zoned;
318 	int nr_zones;
319 
320 	if (!ublk_dev_is_zoned(ub))
321 		return -EINVAL;
322 
323 	if (!p->max_zone_append_sectors)
324 		return -EINVAL;
325 
326 	nr_zones = ublk_get_nr_zones(ub);
327 
328 	if (p->max_active_zones > nr_zones)
329 		return -EINVAL;
330 
331 	if (p->max_open_zones > nr_zones)
332 		return -EINVAL;
333 
334 	return 0;
335 }
336 
337 static void ublk_dev_param_zoned_apply(struct ublk_device *ub)
338 {
339 	ub->ub_disk->nr_zones = ublk_get_nr_zones(ub);
340 }
341 
342 /* Based on virtblk_alloc_report_buffer */
343 static void *ublk_alloc_report_buffer(struct ublk_device *ublk,
344 				      unsigned int nr_zones, size_t *buflen)
345 {
346 	struct request_queue *q = ublk->ub_disk->queue;
347 	size_t bufsize;
348 	void *buf;
349 
350 	nr_zones = min_t(unsigned int, nr_zones,
351 			 ublk->ub_disk->nr_zones);
352 
353 	bufsize = nr_zones * sizeof(struct blk_zone);
354 	bufsize =
355 		min_t(size_t, bufsize, queue_max_hw_sectors(q) << SECTOR_SHIFT);
356 
357 	while (bufsize >= sizeof(struct blk_zone)) {
358 		buf = kvmalloc(bufsize, GFP_KERNEL | __GFP_NORETRY);
359 		if (buf) {
360 			*buflen = bufsize;
361 			return buf;
362 		}
363 		bufsize >>= 1;
364 	}
365 
366 	*buflen = 0;
367 	return NULL;
368 }
369 
370 static int ublk_report_zones(struct gendisk *disk, sector_t sector,
371 		      unsigned int nr_zones, struct blk_report_zones_args *args)
372 {
373 	struct ublk_device *ub = disk->private_data;
374 	unsigned int zone_size_sectors = disk->queue->limits.chunk_sectors;
375 	unsigned int first_zone = sector >> ilog2(zone_size_sectors);
376 	unsigned int done_zones = 0;
377 	unsigned int max_zones_per_request;
378 	int ret;
379 	struct blk_zone *buffer;
380 	size_t buffer_length;
381 
382 	nr_zones = min_t(unsigned int, ub->ub_disk->nr_zones - first_zone,
383 			 nr_zones);
384 
385 	buffer = ublk_alloc_report_buffer(ub, nr_zones, &buffer_length);
386 	if (!buffer)
387 		return -ENOMEM;
388 
389 	max_zones_per_request = buffer_length / sizeof(struct blk_zone);
390 
391 	while (done_zones < nr_zones) {
392 		unsigned int remaining_zones = nr_zones - done_zones;
393 		unsigned int zones_in_request =
394 			min_t(unsigned int, remaining_zones, max_zones_per_request);
395 		struct request *req;
396 		struct ublk_zoned_report_desc desc;
397 		blk_status_t status;
398 
399 		memset(buffer, 0, buffer_length);
400 
401 		req = blk_mq_alloc_request(disk->queue, REQ_OP_DRV_IN, 0);
402 		if (IS_ERR(req)) {
403 			ret = PTR_ERR(req);
404 			goto out;
405 		}
406 
407 		desc.operation = UBLK_IO_OP_REPORT_ZONES;
408 		desc.sector = sector;
409 		desc.nr_zones = zones_in_request;
410 		ret = ublk_zoned_insert_report_desc(req, &desc);
411 		if (ret)
412 			goto free_req;
413 
414 		ret = blk_rq_map_kern(req, buffer, buffer_length, GFP_KERNEL);
415 		if (ret)
416 			goto erase_desc;
417 
418 		status = blk_execute_rq(req, 0);
419 		ret = blk_status_to_errno(status);
420 erase_desc:
421 		ublk_zoned_erase_report_desc(req);
422 free_req:
423 		blk_mq_free_request(req);
424 		if (ret)
425 			goto out;
426 
427 		for (unsigned int i = 0; i < zones_in_request; i++) {
428 			struct blk_zone *zone = buffer + i;
429 
430 			/* A zero length zone means no more zones in this response */
431 			if (!zone->len)
432 				break;
433 
434 			ret = disk_report_zone(disk, zone, i, args);
435 			if (ret)
436 				goto out;
437 
438 			done_zones++;
439 			sector += zone_size_sectors;
440 
441 		}
442 	}
443 
444 	ret = done_zones;
445 
446 out:
447 	kvfree(buffer);
448 	return ret;
449 }
450 
451 static blk_status_t ublk_setup_iod_zoned(struct ublk_queue *ubq,
452 					 struct request *req)
453 {
454 	struct ublksrv_io_desc *iod = ublk_get_iod(ubq, req->tag);
455 	struct ublk_io *io = &ubq->ios[req->tag];
456 	struct ublk_zoned_report_desc *desc;
457 	u32 ublk_op;
458 
459 	switch (req_op(req)) {
460 	case REQ_OP_ZONE_OPEN:
461 		ublk_op = UBLK_IO_OP_ZONE_OPEN;
462 		break;
463 	case REQ_OP_ZONE_CLOSE:
464 		ublk_op = UBLK_IO_OP_ZONE_CLOSE;
465 		break;
466 	case REQ_OP_ZONE_FINISH:
467 		ublk_op = UBLK_IO_OP_ZONE_FINISH;
468 		break;
469 	case REQ_OP_ZONE_RESET:
470 		ublk_op = UBLK_IO_OP_ZONE_RESET;
471 		break;
472 	case REQ_OP_ZONE_APPEND:
473 		ublk_op = UBLK_IO_OP_ZONE_APPEND;
474 		break;
475 	case REQ_OP_ZONE_RESET_ALL:
476 		ublk_op = UBLK_IO_OP_ZONE_RESET_ALL;
477 		break;
478 	case REQ_OP_DRV_IN:
479 		desc = ublk_zoned_get_report_desc(req);
480 		if (!desc)
481 			return BLK_STS_IOERR;
482 		ublk_op = desc->operation;
483 		switch (ublk_op) {
484 		case UBLK_IO_OP_REPORT_ZONES:
485 			iod->op_flags = ublk_op | ublk_req_build_flags(req);
486 			iod->nr_zones = desc->nr_zones;
487 			iod->start_sector = desc->sector;
488 			return BLK_STS_OK;
489 		default:
490 			return BLK_STS_IOERR;
491 		}
492 	case REQ_OP_DRV_OUT:
493 		/* We do not support drv_out */
494 		return BLK_STS_NOTSUPP;
495 	default:
496 		return BLK_STS_IOERR;
497 	}
498 
499 	iod->op_flags = ublk_op | ublk_req_build_flags(req);
500 	iod->nr_sectors = blk_rq_sectors(req);
501 	iod->start_sector = blk_rq_pos(req);
502 	iod->addr = io->buf.addr;
503 
504 	return BLK_STS_OK;
505 }
506 
507 #else
508 
509 #define ublk_report_zones (NULL)
510 
511 static int ublk_dev_param_zoned_validate(const struct ublk_device *ub)
512 {
513 	return -EOPNOTSUPP;
514 }
515 
516 static void ublk_dev_param_zoned_apply(struct ublk_device *ub)
517 {
518 }
519 
520 static int ublk_revalidate_disk_zones(struct ublk_device *ub)
521 {
522 	return 0;
523 }
524 
525 static blk_status_t ublk_setup_iod_zoned(struct ublk_queue *ubq,
526 					 struct request *req)
527 {
528 	return BLK_STS_NOTSUPP;
529 }
530 
531 #endif
532 
533 static inline void __ublk_complete_rq(struct request *req, struct ublk_io *io,
534 				      bool need_map);
535 
536 static dev_t ublk_chr_devt;
537 static const struct class ublk_chr_class = {
538 	.name = "ublk-char",
539 };
540 
541 static DEFINE_IDR(ublk_index_idr);
542 static DEFINE_SPINLOCK(ublk_idr_lock);
543 static wait_queue_head_t ublk_idr_wq;	/* wait until one idr is freed */
544 
545 static DEFINE_MUTEX(ublk_ctl_mutex);
546 
547 
548 #define UBLK_MAX_UBLKS UBLK_MINORS
549 
550 /*
551  * Max unprivileged ublk devices allowed to add
552  *
553  * It can be extended to one per-user limit in future or even controlled
554  * by cgroup.
555  */
556 static unsigned int unprivileged_ublks_max = 64;
557 static unsigned int unprivileged_ublks_added; /* protected by ublk_ctl_mutex */
558 
559 static struct miscdevice ublk_misc;
560 
561 static inline unsigned ublk_pos_to_hwq(loff_t pos)
562 {
563 	return ((pos - UBLKSRV_IO_BUF_OFFSET) >> UBLK_QID_OFF) &
564 		UBLK_QID_BITS_MASK;
565 }
566 
567 static inline unsigned ublk_pos_to_buf_off(loff_t pos)
568 {
569 	return (pos - UBLKSRV_IO_BUF_OFFSET) & UBLK_IO_BUF_BITS_MASK;
570 }
571 
572 static inline unsigned ublk_pos_to_tag(loff_t pos)
573 {
574 	return ((pos - UBLKSRV_IO_BUF_OFFSET) >> UBLK_TAG_OFF) &
575 		UBLK_TAG_BITS_MASK;
576 }
577 
578 static void ublk_dev_param_basic_apply(struct ublk_device *ub)
579 {
580 	const struct ublk_param_basic *p = &ub->params.basic;
581 
582 	if (p->attrs & UBLK_ATTR_READ_ONLY)
583 		set_disk_ro(ub->ub_disk, true);
584 
585 	set_capacity(ub->ub_disk, p->dev_sectors);
586 }
587 
588 static int ublk_validate_params(const struct ublk_device *ub)
589 {
590 	/* basic param is the only one which must be set */
591 	if (ub->params.types & UBLK_PARAM_TYPE_BASIC) {
592 		const struct ublk_param_basic *p = &ub->params.basic;
593 
594 		if (p->logical_bs_shift > PAGE_SHIFT || p->logical_bs_shift < 9)
595 			return -EINVAL;
596 
597 		if (p->logical_bs_shift > p->physical_bs_shift)
598 			return -EINVAL;
599 
600 		if (p->max_sectors > (ub->dev_info.max_io_buf_bytes >> 9))
601 			return -EINVAL;
602 
603 		if (ublk_dev_is_zoned(ub) && !p->chunk_sectors)
604 			return -EINVAL;
605 	} else
606 		return -EINVAL;
607 
608 	if (ub->params.types & UBLK_PARAM_TYPE_DISCARD) {
609 		const struct ublk_param_discard *p = &ub->params.discard;
610 
611 		/* So far, only support single segment discard */
612 		if (p->max_discard_sectors && p->max_discard_segments != 1)
613 			return -EINVAL;
614 
615 		if (!p->discard_granularity)
616 			return -EINVAL;
617 	}
618 
619 	/* dev_t is read-only */
620 	if (ub->params.types & UBLK_PARAM_TYPE_DEVT)
621 		return -EINVAL;
622 
623 	if (ub->params.types & UBLK_PARAM_TYPE_ZONED)
624 		return ublk_dev_param_zoned_validate(ub);
625 	else if (ublk_dev_is_zoned(ub))
626 		return -EINVAL;
627 
628 	if (ub->params.types & UBLK_PARAM_TYPE_DMA_ALIGN) {
629 		const struct ublk_param_dma_align *p = &ub->params.dma;
630 
631 		if (p->alignment >= PAGE_SIZE)
632 			return -EINVAL;
633 
634 		if (!is_power_of_2(p->alignment + 1))
635 			return -EINVAL;
636 	}
637 
638 	if (ub->params.types & UBLK_PARAM_TYPE_SEGMENT) {
639 		const struct ublk_param_segment *p = &ub->params.seg;
640 
641 		if (!is_power_of_2(p->seg_boundary_mask + 1))
642 			return -EINVAL;
643 
644 		if (p->seg_boundary_mask + 1 < UBLK_MIN_SEGMENT_SIZE)
645 			return -EINVAL;
646 		if (p->max_segment_size < UBLK_MIN_SEGMENT_SIZE)
647 			return -EINVAL;
648 	}
649 
650 	return 0;
651 }
652 
653 static void ublk_apply_params(struct ublk_device *ub)
654 {
655 	ublk_dev_param_basic_apply(ub);
656 
657 	if (ub->params.types & UBLK_PARAM_TYPE_ZONED)
658 		ublk_dev_param_zoned_apply(ub);
659 }
660 
661 static inline bool ublk_support_zero_copy(const struct ublk_queue *ubq)
662 {
663 	return ubq->flags & UBLK_F_SUPPORT_ZERO_COPY;
664 }
665 
666 static inline bool ublk_dev_support_zero_copy(const struct ublk_device *ub)
667 {
668 	return ub->dev_info.flags & UBLK_F_SUPPORT_ZERO_COPY;
669 }
670 
671 static inline bool ublk_support_auto_buf_reg(const struct ublk_queue *ubq)
672 {
673 	return ubq->flags & UBLK_F_AUTO_BUF_REG;
674 }
675 
676 static inline bool ublk_dev_support_auto_buf_reg(const struct ublk_device *ub)
677 {
678 	return ub->dev_info.flags & UBLK_F_AUTO_BUF_REG;
679 }
680 
681 static inline bool ublk_support_user_copy(const struct ublk_queue *ubq)
682 {
683 	return ubq->flags & UBLK_F_USER_COPY;
684 }
685 
686 static inline bool ublk_dev_support_user_copy(const struct ublk_device *ub)
687 {
688 	return ub->dev_info.flags & UBLK_F_USER_COPY;
689 }
690 
691 static inline bool ublk_need_map_io(const struct ublk_queue *ubq)
692 {
693 	return !ublk_support_user_copy(ubq) && !ublk_support_zero_copy(ubq) &&
694 		!ublk_support_auto_buf_reg(ubq);
695 }
696 
697 static inline bool ublk_dev_need_map_io(const struct ublk_device *ub)
698 {
699 	return !ublk_dev_support_user_copy(ub) &&
700 	       !ublk_dev_support_zero_copy(ub) &&
701 	       !ublk_dev_support_auto_buf_reg(ub);
702 }
703 
704 static inline bool ublk_need_req_ref(const struct ublk_queue *ubq)
705 {
706 	/*
707 	 * read()/write() is involved in user copy, so request reference
708 	 * has to be grabbed
709 	 *
710 	 * for zero copy, request buffer need to be registered to io_uring
711 	 * buffer table, so reference is needed
712 	 *
713 	 * For auto buffer register, ublk server still may issue
714 	 * UBLK_IO_COMMIT_AND_FETCH_REQ before one registered buffer is used up,
715 	 * so reference is required too.
716 	 */
717 	return ublk_support_user_copy(ubq) || ublk_support_zero_copy(ubq) ||
718 		ublk_support_auto_buf_reg(ubq);
719 }
720 
721 static inline bool ublk_dev_need_req_ref(const struct ublk_device *ub)
722 {
723 	return ublk_dev_support_user_copy(ub) ||
724 	       ublk_dev_support_zero_copy(ub) ||
725 	       ublk_dev_support_auto_buf_reg(ub);
726 }
727 
728 static inline void ublk_init_req_ref(const struct ublk_queue *ubq,
729 		struct ublk_io *io)
730 {
731 	if (ublk_need_req_ref(ubq))
732 		refcount_set(&io->ref, UBLK_REFCOUNT_INIT);
733 }
734 
735 static inline bool ublk_get_req_ref(struct ublk_io *io)
736 {
737 	return refcount_inc_not_zero(&io->ref);
738 }
739 
740 static inline void ublk_put_req_ref(struct ublk_io *io, struct request *req)
741 {
742 	if (!refcount_dec_and_test(&io->ref))
743 		return;
744 
745 	/* ublk_need_map_io() and ublk_need_req_ref() are mutually exclusive */
746 	__ublk_complete_rq(req, io, false);
747 }
748 
749 static inline bool ublk_sub_req_ref(struct ublk_io *io)
750 {
751 	unsigned sub_refs = UBLK_REFCOUNT_INIT - io->task_registered_buffers;
752 
753 	io->task_registered_buffers = 0;
754 	return refcount_sub_and_test(sub_refs, &io->ref);
755 }
756 
757 static inline bool ublk_need_get_data(const struct ublk_queue *ubq)
758 {
759 	return ubq->flags & UBLK_F_NEED_GET_DATA;
760 }
761 
762 static inline bool ublk_dev_need_get_data(const struct ublk_device *ub)
763 {
764 	return ub->dev_info.flags & UBLK_F_NEED_GET_DATA;
765 }
766 
767 /* Called in slow path only, keep it noinline for trace purpose */
768 static noinline struct ublk_device *ublk_get_device(struct ublk_device *ub)
769 {
770 	if (kobject_get_unless_zero(&ub->cdev_dev.kobj))
771 		return ub;
772 	return NULL;
773 }
774 
775 /* Called in slow path only, keep it noinline for trace purpose */
776 static noinline void ublk_put_device(struct ublk_device *ub)
777 {
778 	put_device(&ub->cdev_dev);
779 }
780 
781 static inline struct ublk_queue *ublk_get_queue(struct ublk_device *dev,
782 		int qid)
783 {
784 	return dev->queues[qid];
785 }
786 
787 static inline bool ublk_rq_has_data(const struct request *rq)
788 {
789 	return bio_has_data(rq->bio);
790 }
791 
792 static inline struct ublksrv_io_desc *
793 ublk_queue_cmd_buf(struct ublk_device *ub, int q_id)
794 {
795 	return ublk_get_queue(ub, q_id)->io_cmd_buf;
796 }
797 
798 static inline int __ublk_queue_cmd_buf_size(int depth)
799 {
800 	return round_up(depth * sizeof(struct ublksrv_io_desc), PAGE_SIZE);
801 }
802 
803 static inline int ublk_queue_cmd_buf_size(struct ublk_device *ub)
804 {
805 	return __ublk_queue_cmd_buf_size(ub->dev_info.queue_depth);
806 }
807 
808 static int ublk_max_cmd_buf_size(void)
809 {
810 	return __ublk_queue_cmd_buf_size(UBLK_MAX_QUEUE_DEPTH);
811 }
812 
813 /*
814  * Should I/O outstanding to the ublk server when it exits be reissued?
815  * If not, outstanding I/O will get errors.
816  */
817 static inline bool ublk_nosrv_should_reissue_outstanding(struct ublk_device *ub)
818 {
819 	return (ub->dev_info.flags & UBLK_F_USER_RECOVERY) &&
820 	       (ub->dev_info.flags & UBLK_F_USER_RECOVERY_REISSUE);
821 }
822 
823 /*
824  * Should I/O issued while there is no ublk server queue? If not, I/O
825  * issued while there is no ublk server will get errors.
826  */
827 static inline bool ublk_nosrv_dev_should_queue_io(struct ublk_device *ub)
828 {
829 	return (ub->dev_info.flags & UBLK_F_USER_RECOVERY) &&
830 	       !(ub->dev_info.flags & UBLK_F_USER_RECOVERY_FAIL_IO);
831 }
832 
833 /*
834  * Same as ublk_nosrv_dev_should_queue_io, but uses a queue-local copy
835  * of the device flags for smaller cache footprint - better for fast
836  * paths.
837  */
838 static inline bool ublk_nosrv_should_queue_io(struct ublk_queue *ubq)
839 {
840 	return (ubq->flags & UBLK_F_USER_RECOVERY) &&
841 	       !(ubq->flags & UBLK_F_USER_RECOVERY_FAIL_IO);
842 }
843 
844 /*
845  * Should ublk devices be stopped (i.e. no recovery possible) when the
846  * ublk server exits? If not, devices can be used again by a future
847  * incarnation of a ublk server via the start_recovery/end_recovery
848  * commands.
849  */
850 static inline bool ublk_nosrv_should_stop_dev(struct ublk_device *ub)
851 {
852 	return !(ub->dev_info.flags & UBLK_F_USER_RECOVERY);
853 }
854 
855 static inline bool ublk_dev_in_recoverable_state(struct ublk_device *ub)
856 {
857 	return ub->dev_info.state == UBLK_S_DEV_QUIESCED ||
858 	       ub->dev_info.state == UBLK_S_DEV_FAIL_IO;
859 }
860 
861 static void ublk_free_disk(struct gendisk *disk)
862 {
863 	struct ublk_device *ub = disk->private_data;
864 
865 	clear_bit(UB_STATE_USED, &ub->state);
866 	ublk_put_device(ub);
867 }
868 
869 static void ublk_store_owner_uid_gid(unsigned int *owner_uid,
870 		unsigned int *owner_gid)
871 {
872 	kuid_t uid;
873 	kgid_t gid;
874 
875 	current_uid_gid(&uid, &gid);
876 
877 	*owner_uid = from_kuid(&init_user_ns, uid);
878 	*owner_gid = from_kgid(&init_user_ns, gid);
879 }
880 
881 static int ublk_open(struct gendisk *disk, blk_mode_t mode)
882 {
883 	struct ublk_device *ub = disk->private_data;
884 
885 	if (capable(CAP_SYS_ADMIN))
886 		return 0;
887 
888 	/*
889 	 * If it is one unprivileged device, only owner can open
890 	 * the disk. Otherwise it could be one trap made by one
891 	 * evil user who grants this disk's privileges to other
892 	 * users deliberately.
893 	 *
894 	 * This way is reasonable too given anyone can create
895 	 * unprivileged device, and no need other's grant.
896 	 */
897 	if (ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV) {
898 		unsigned int curr_uid, curr_gid;
899 
900 		ublk_store_owner_uid_gid(&curr_uid, &curr_gid);
901 
902 		if (curr_uid != ub->dev_info.owner_uid || curr_gid !=
903 				ub->dev_info.owner_gid)
904 			return -EPERM;
905 	}
906 
907 	return 0;
908 }
909 
910 static const struct block_device_operations ub_fops = {
911 	.owner =	THIS_MODULE,
912 	.open =		ublk_open,
913 	.free_disk =	ublk_free_disk,
914 	.report_zones =	ublk_report_zones,
915 };
916 
917 /*
918  * Copy data between request pages and io_iter, and 'offset'
919  * is the start point of linear offset of request.
920  */
921 static size_t ublk_copy_user_pages(const struct request *req,
922 		unsigned offset, struct iov_iter *uiter, int dir)
923 {
924 	struct req_iterator iter;
925 	struct bio_vec bv;
926 	size_t done = 0;
927 
928 	rq_for_each_segment(bv, req, iter) {
929 		void *bv_buf;
930 		size_t copied;
931 
932 		if (offset >= bv.bv_len) {
933 			offset -= bv.bv_len;
934 			continue;
935 		}
936 
937 		bv.bv_offset += offset;
938 		bv.bv_len -= offset;
939 		bv_buf = bvec_kmap_local(&bv);
940 		if (dir == ITER_DEST)
941 			copied = copy_to_iter(bv_buf, bv.bv_len, uiter);
942 		else
943 			copied = copy_from_iter(bv_buf, bv.bv_len, uiter);
944 
945 		kunmap_local(bv_buf);
946 
947 		done += copied;
948 		if (copied < bv.bv_len)
949 			break;
950 
951 		offset = 0;
952 	}
953 	return done;
954 }
955 
956 static inline bool ublk_need_map_req(const struct request *req)
957 {
958 	return ublk_rq_has_data(req) && req_op(req) == REQ_OP_WRITE;
959 }
960 
961 static inline bool ublk_need_unmap_req(const struct request *req)
962 {
963 	return ublk_rq_has_data(req) &&
964 	       (req_op(req) == REQ_OP_READ || req_op(req) == REQ_OP_DRV_IN);
965 }
966 
967 static unsigned int ublk_map_io(const struct ublk_queue *ubq,
968 				const struct request *req,
969 				const struct ublk_io *io)
970 {
971 	const unsigned int rq_bytes = blk_rq_bytes(req);
972 
973 	if (!ublk_need_map_io(ubq))
974 		return rq_bytes;
975 
976 	/*
977 	 * no zero copy, we delay copy WRITE request data into ublksrv
978 	 * context and the big benefit is that pinning pages in current
979 	 * context is pretty fast, see ublk_pin_user_pages
980 	 */
981 	if (ublk_need_map_req(req)) {
982 		struct iov_iter iter;
983 		const int dir = ITER_DEST;
984 
985 		import_ubuf(dir, u64_to_user_ptr(io->buf.addr), rq_bytes, &iter);
986 		return ublk_copy_user_pages(req, 0, &iter, dir);
987 	}
988 	return rq_bytes;
989 }
990 
991 static unsigned int ublk_unmap_io(bool need_map,
992 		const struct request *req,
993 		const struct ublk_io *io)
994 {
995 	const unsigned int rq_bytes = blk_rq_bytes(req);
996 
997 	if (!need_map)
998 		return rq_bytes;
999 
1000 	if (ublk_need_unmap_req(req)) {
1001 		struct iov_iter iter;
1002 		const int dir = ITER_SOURCE;
1003 
1004 		WARN_ON_ONCE(io->res > rq_bytes);
1005 
1006 		import_ubuf(dir, u64_to_user_ptr(io->buf.addr), io->res, &iter);
1007 		return ublk_copy_user_pages(req, 0, &iter, dir);
1008 	}
1009 	return rq_bytes;
1010 }
1011 
1012 static inline unsigned int ublk_req_build_flags(struct request *req)
1013 {
1014 	unsigned flags = 0;
1015 
1016 	if (req->cmd_flags & REQ_FAILFAST_DEV)
1017 		flags |= UBLK_IO_F_FAILFAST_DEV;
1018 
1019 	if (req->cmd_flags & REQ_FAILFAST_TRANSPORT)
1020 		flags |= UBLK_IO_F_FAILFAST_TRANSPORT;
1021 
1022 	if (req->cmd_flags & REQ_FAILFAST_DRIVER)
1023 		flags |= UBLK_IO_F_FAILFAST_DRIVER;
1024 
1025 	if (req->cmd_flags & REQ_META)
1026 		flags |= UBLK_IO_F_META;
1027 
1028 	if (req->cmd_flags & REQ_FUA)
1029 		flags |= UBLK_IO_F_FUA;
1030 
1031 	if (req->cmd_flags & REQ_NOUNMAP)
1032 		flags |= UBLK_IO_F_NOUNMAP;
1033 
1034 	if (req->cmd_flags & REQ_SWAP)
1035 		flags |= UBLK_IO_F_SWAP;
1036 
1037 	return flags;
1038 }
1039 
1040 static blk_status_t ublk_setup_iod(struct ublk_queue *ubq, struct request *req)
1041 {
1042 	struct ublksrv_io_desc *iod = ublk_get_iod(ubq, req->tag);
1043 	struct ublk_io *io = &ubq->ios[req->tag];
1044 	u32 ublk_op;
1045 
1046 	switch (req_op(req)) {
1047 	case REQ_OP_READ:
1048 		ublk_op = UBLK_IO_OP_READ;
1049 		break;
1050 	case REQ_OP_WRITE:
1051 		ublk_op = UBLK_IO_OP_WRITE;
1052 		break;
1053 	case REQ_OP_FLUSH:
1054 		ublk_op = UBLK_IO_OP_FLUSH;
1055 		break;
1056 	case REQ_OP_DISCARD:
1057 		ublk_op = UBLK_IO_OP_DISCARD;
1058 		break;
1059 	case REQ_OP_WRITE_ZEROES:
1060 		ublk_op = UBLK_IO_OP_WRITE_ZEROES;
1061 		break;
1062 	default:
1063 		if (ublk_queue_is_zoned(ubq))
1064 			return ublk_setup_iod_zoned(ubq, req);
1065 		return BLK_STS_IOERR;
1066 	}
1067 
1068 	/* need to translate since kernel may change */
1069 	iod->op_flags = ublk_op | ublk_req_build_flags(req);
1070 	iod->nr_sectors = blk_rq_sectors(req);
1071 	iod->start_sector = blk_rq_pos(req);
1072 	iod->addr = io->buf.addr;
1073 
1074 	return BLK_STS_OK;
1075 }
1076 
1077 static inline struct ublk_uring_cmd_pdu *ublk_get_uring_cmd_pdu(
1078 		struct io_uring_cmd *ioucmd)
1079 {
1080 	return io_uring_cmd_to_pdu(ioucmd, struct ublk_uring_cmd_pdu);
1081 }
1082 
1083 /* todo: handle partial completion */
1084 static inline void __ublk_complete_rq(struct request *req, struct ublk_io *io,
1085 				      bool need_map)
1086 {
1087 	unsigned int unmapped_bytes;
1088 	blk_status_t res = BLK_STS_OK;
1089 
1090 	/* failed read IO if nothing is read */
1091 	if (!io->res && req_op(req) == REQ_OP_READ)
1092 		io->res = -EIO;
1093 
1094 	if (io->res < 0) {
1095 		res = errno_to_blk_status(io->res);
1096 		goto exit;
1097 	}
1098 
1099 	/*
1100 	 * FLUSH, DISCARD or WRITE_ZEROES usually won't return bytes returned, so end them
1101 	 * directly.
1102 	 *
1103 	 * Both the two needn't unmap.
1104 	 */
1105 	if (req_op(req) != REQ_OP_READ && req_op(req) != REQ_OP_WRITE &&
1106 	    req_op(req) != REQ_OP_DRV_IN)
1107 		goto exit;
1108 
1109 	/* for READ request, writing data in iod->addr to rq buffers */
1110 	unmapped_bytes = ublk_unmap_io(need_map, req, io);
1111 
1112 	/*
1113 	 * Extremely impossible since we got data filled in just before
1114 	 *
1115 	 * Re-read simply for this unlikely case.
1116 	 */
1117 	if (unlikely(unmapped_bytes < io->res))
1118 		io->res = unmapped_bytes;
1119 
1120 	if (blk_update_request(req, BLK_STS_OK, io->res))
1121 		blk_mq_requeue_request(req, true);
1122 	else if (likely(!blk_should_fake_timeout(req->q)))
1123 		__blk_mq_end_request(req, BLK_STS_OK);
1124 
1125 	return;
1126 exit:
1127 	blk_mq_end_request(req, res);
1128 }
1129 
1130 static struct io_uring_cmd *__ublk_prep_compl_io_cmd(struct ublk_io *io,
1131 						     struct request *req)
1132 {
1133 	/* read cmd first because req will overwrite it */
1134 	struct io_uring_cmd *cmd = io->cmd;
1135 
1136 	/* mark this cmd owned by ublksrv */
1137 	io->flags |= UBLK_IO_FLAG_OWNED_BY_SRV;
1138 
1139 	/*
1140 	 * clear ACTIVE since we are done with this sqe/cmd slot
1141 	 * We can only accept io cmd in case of being not active.
1142 	 */
1143 	io->flags &= ~UBLK_IO_FLAG_ACTIVE;
1144 
1145 	io->req = req;
1146 	return cmd;
1147 }
1148 
1149 static void ublk_complete_io_cmd(struct ublk_io *io, struct request *req,
1150 				 int res, unsigned issue_flags)
1151 {
1152 	struct io_uring_cmd *cmd = __ublk_prep_compl_io_cmd(io, req);
1153 
1154 	/* tell ublksrv one io request is coming */
1155 	io_uring_cmd_done(cmd, res, issue_flags);
1156 }
1157 
1158 #define UBLK_REQUEUE_DELAY_MS	3
1159 
1160 static inline void __ublk_abort_rq(struct ublk_queue *ubq,
1161 		struct request *rq)
1162 {
1163 	/* We cannot process this rq so just requeue it. */
1164 	if (ublk_nosrv_dev_should_queue_io(ubq->dev))
1165 		blk_mq_requeue_request(rq, false);
1166 	else
1167 		blk_mq_end_request(rq, BLK_STS_IOERR);
1168 }
1169 
1170 static void
1171 ublk_auto_buf_reg_fallback(const struct ublk_queue *ubq, unsigned tag)
1172 {
1173 	struct ublksrv_io_desc *iod = ublk_get_iod(ubq, tag);
1174 
1175 	iod->op_flags |= UBLK_IO_F_NEED_REG_BUF;
1176 }
1177 
1178 enum auto_buf_reg_res {
1179 	AUTO_BUF_REG_FAIL,
1180 	AUTO_BUF_REG_FALLBACK,
1181 	AUTO_BUF_REG_OK,
1182 };
1183 
1184 static void ublk_prep_auto_buf_reg_io(const struct ublk_queue *ubq,
1185 				      struct request *req, struct ublk_io *io,
1186 				      struct io_uring_cmd *cmd,
1187 				      enum auto_buf_reg_res res)
1188 {
1189 	if (res == AUTO_BUF_REG_OK) {
1190 		io->task_registered_buffers = 1;
1191 		io->buf_ctx_handle = io_uring_cmd_ctx_handle(cmd);
1192 		io->flags |= UBLK_IO_FLAG_AUTO_BUF_REG;
1193 	}
1194 	ublk_init_req_ref(ubq, io);
1195 	__ublk_prep_compl_io_cmd(io, req);
1196 }
1197 
1198 static enum auto_buf_reg_res
1199 __ublk_do_auto_buf_reg(const struct ublk_queue *ubq, struct request *req,
1200 		       struct ublk_io *io, struct io_uring_cmd *cmd,
1201 		       unsigned int issue_flags)
1202 {
1203 	int ret;
1204 
1205 	ret = io_buffer_register_bvec(cmd, req, ublk_io_release,
1206 				      io->buf.auto_reg.index, issue_flags);
1207 	if (ret) {
1208 		if (io->buf.auto_reg.flags & UBLK_AUTO_BUF_REG_FALLBACK) {
1209 			ublk_auto_buf_reg_fallback(ubq, req->tag);
1210 			return AUTO_BUF_REG_FALLBACK;
1211 		}
1212 		blk_mq_end_request(req, BLK_STS_IOERR);
1213 		return AUTO_BUF_REG_FAIL;
1214 	}
1215 
1216 	return AUTO_BUF_REG_OK;
1217 }
1218 
1219 static void ublk_do_auto_buf_reg(const struct ublk_queue *ubq, struct request *req,
1220 				 struct ublk_io *io, struct io_uring_cmd *cmd,
1221 				 unsigned int issue_flags)
1222 {
1223 	enum auto_buf_reg_res res = __ublk_do_auto_buf_reg(ubq, req, io, cmd,
1224 			issue_flags);
1225 
1226 	if (res != AUTO_BUF_REG_FAIL) {
1227 		ublk_prep_auto_buf_reg_io(ubq, req, io, cmd, res);
1228 		io_uring_cmd_done(cmd, UBLK_IO_RES_OK, issue_flags);
1229 	}
1230 }
1231 
1232 static bool ublk_start_io(const struct ublk_queue *ubq, struct request *req,
1233 			  struct ublk_io *io)
1234 {
1235 	unsigned mapped_bytes = ublk_map_io(ubq, req, io);
1236 
1237 	/* partially mapped, update io descriptor */
1238 	if (unlikely(mapped_bytes != blk_rq_bytes(req))) {
1239 		/*
1240 		 * Nothing mapped, retry until we succeed.
1241 		 *
1242 		 * We may never succeed in mapping any bytes here because
1243 		 * of OOM. TODO: reserve one buffer with single page pinned
1244 		 * for providing forward progress guarantee.
1245 		 */
1246 		if (unlikely(!mapped_bytes)) {
1247 			blk_mq_requeue_request(req, false);
1248 			blk_mq_delay_kick_requeue_list(req->q,
1249 					UBLK_REQUEUE_DELAY_MS);
1250 			return false;
1251 		}
1252 
1253 		ublk_get_iod(ubq, req->tag)->nr_sectors =
1254 			mapped_bytes >> 9;
1255 	}
1256 
1257 	return true;
1258 }
1259 
1260 static void ublk_dispatch_req(struct ublk_queue *ubq, struct request *req)
1261 {
1262 	unsigned int issue_flags = IO_URING_CMD_TASK_WORK_ISSUE_FLAGS;
1263 	int tag = req->tag;
1264 	struct ublk_io *io = &ubq->ios[tag];
1265 
1266 	pr_devel("%s: complete: qid %d tag %d io_flags %x addr %llx\n",
1267 			__func__, ubq->q_id, req->tag, io->flags,
1268 			ublk_get_iod(ubq, req->tag)->addr);
1269 
1270 	/*
1271 	 * Task is exiting if either:
1272 	 *
1273 	 * (1) current != io->task.
1274 	 * io_uring_cmd_complete_in_task() tries to run task_work
1275 	 * in a workqueue if cmd's task is PF_EXITING.
1276 	 *
1277 	 * (2) current->flags & PF_EXITING.
1278 	 */
1279 	if (unlikely(current != io->task || current->flags & PF_EXITING)) {
1280 		__ublk_abort_rq(ubq, req);
1281 		return;
1282 	}
1283 
1284 	if (ublk_need_get_data(ubq) && ublk_need_map_req(req)) {
1285 		/*
1286 		 * We have not handled UBLK_IO_NEED_GET_DATA command yet,
1287 		 * so immediately pass UBLK_IO_RES_NEED_GET_DATA to ublksrv
1288 		 * and notify it.
1289 		 */
1290 		io->flags |= UBLK_IO_FLAG_NEED_GET_DATA;
1291 		pr_devel("%s: need get data. qid %d tag %d io_flags %x\n",
1292 				__func__, ubq->q_id, req->tag, io->flags);
1293 		ublk_complete_io_cmd(io, req, UBLK_IO_RES_NEED_GET_DATA,
1294 				     issue_flags);
1295 		return;
1296 	}
1297 
1298 	if (!ublk_start_io(ubq, req, io))
1299 		return;
1300 
1301 	if (ublk_support_auto_buf_reg(ubq) && ublk_rq_has_data(req)) {
1302 		ublk_do_auto_buf_reg(ubq, req, io, io->cmd, issue_flags);
1303 	} else {
1304 		ublk_init_req_ref(ubq, io);
1305 		ublk_complete_io_cmd(io, req, UBLK_IO_RES_OK, issue_flags);
1306 	}
1307 }
1308 
1309 static void ublk_cmd_tw_cb(struct io_tw_req tw_req, io_tw_token_t tw)
1310 {
1311 	struct io_uring_cmd *cmd = io_uring_cmd_from_tw(tw_req);
1312 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
1313 	struct ublk_queue *ubq = pdu->ubq;
1314 
1315 	ublk_dispatch_req(ubq, pdu->req);
1316 }
1317 
1318 static void ublk_queue_cmd(struct ublk_queue *ubq, struct request *rq)
1319 {
1320 	struct io_uring_cmd *cmd = ubq->ios[rq->tag].cmd;
1321 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
1322 
1323 	pdu->req = rq;
1324 	io_uring_cmd_complete_in_task(cmd, ublk_cmd_tw_cb);
1325 }
1326 
1327 static void ublk_cmd_list_tw_cb(struct io_tw_req tw_req, io_tw_token_t tw)
1328 {
1329 	struct io_uring_cmd *cmd = io_uring_cmd_from_tw(tw_req);
1330 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
1331 	struct request *rq = pdu->req_list;
1332 	struct request *next;
1333 
1334 	do {
1335 		next = rq->rq_next;
1336 		rq->rq_next = NULL;
1337 		ublk_dispatch_req(rq->mq_hctx->driver_data, rq);
1338 		rq = next;
1339 	} while (rq);
1340 }
1341 
1342 static void ublk_queue_cmd_list(struct ublk_io *io, struct rq_list *l)
1343 {
1344 	struct io_uring_cmd *cmd = io->cmd;
1345 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
1346 
1347 	pdu->req_list = rq_list_peek(l);
1348 	rq_list_init(l);
1349 	io_uring_cmd_complete_in_task(cmd, ublk_cmd_list_tw_cb);
1350 }
1351 
1352 static enum blk_eh_timer_return ublk_timeout(struct request *rq)
1353 {
1354 	struct ublk_queue *ubq = rq->mq_hctx->driver_data;
1355 	pid_t tgid = ubq->dev->ublksrv_tgid;
1356 	struct task_struct *p;
1357 	struct pid *pid;
1358 
1359 	if (!(ubq->flags & UBLK_F_UNPRIVILEGED_DEV))
1360 		return BLK_EH_RESET_TIMER;
1361 
1362 	if (unlikely(!tgid))
1363 		return BLK_EH_RESET_TIMER;
1364 
1365 	rcu_read_lock();
1366 	pid = find_vpid(tgid);
1367 	p = pid_task(pid, PIDTYPE_PID);
1368 	if (p)
1369 		send_sig(SIGKILL, p, 0);
1370 	rcu_read_unlock();
1371 	return BLK_EH_DONE;
1372 }
1373 
1374 static blk_status_t ublk_prep_req(struct ublk_queue *ubq, struct request *rq,
1375 				  bool check_cancel)
1376 {
1377 	blk_status_t res;
1378 
1379 	if (unlikely(READ_ONCE(ubq->fail_io)))
1380 		return BLK_STS_TARGET;
1381 
1382 	/* With recovery feature enabled, force_abort is set in
1383 	 * ublk_stop_dev() before calling del_gendisk(). We have to
1384 	 * abort all requeued and new rqs here to let del_gendisk()
1385 	 * move on. Besides, we cannot not call io_uring_cmd_complete_in_task()
1386 	 * to avoid UAF on io_uring ctx.
1387 	 *
1388 	 * Note: force_abort is guaranteed to be seen because it is set
1389 	 * before request queue is unqiuesced.
1390 	 */
1391 	if (ublk_nosrv_should_queue_io(ubq) &&
1392 	    unlikely(READ_ONCE(ubq->force_abort)))
1393 		return BLK_STS_IOERR;
1394 
1395 	if (check_cancel && unlikely(ubq->canceling))
1396 		return BLK_STS_IOERR;
1397 
1398 	/* fill iod to slot in io cmd buffer */
1399 	res = ublk_setup_iod(ubq, rq);
1400 	if (unlikely(res != BLK_STS_OK))
1401 		return BLK_STS_IOERR;
1402 
1403 	blk_mq_start_request(rq);
1404 	return BLK_STS_OK;
1405 }
1406 
1407 static blk_status_t ublk_queue_rq(struct blk_mq_hw_ctx *hctx,
1408 		const struct blk_mq_queue_data *bd)
1409 {
1410 	struct ublk_queue *ubq = hctx->driver_data;
1411 	struct request *rq = bd->rq;
1412 	blk_status_t res;
1413 
1414 	res = ublk_prep_req(ubq, rq, false);
1415 	if (res != BLK_STS_OK)
1416 		return res;
1417 
1418 	/*
1419 	 * ->canceling has to be handled after ->force_abort and ->fail_io
1420 	 * is dealt with, otherwise this request may not be failed in case
1421 	 * of recovery, and cause hang when deleting disk
1422 	 */
1423 	if (unlikely(ubq->canceling)) {
1424 		__ublk_abort_rq(ubq, rq);
1425 		return BLK_STS_OK;
1426 	}
1427 
1428 	ublk_queue_cmd(ubq, rq);
1429 	return BLK_STS_OK;
1430 }
1431 
1432 static inline bool ublk_belong_to_same_batch(const struct ublk_io *io,
1433 					     const struct ublk_io *io2)
1434 {
1435 	return (io_uring_cmd_ctx_handle(io->cmd) ==
1436 		io_uring_cmd_ctx_handle(io2->cmd)) &&
1437 		(io->task == io2->task);
1438 }
1439 
1440 static void ublk_queue_rqs(struct rq_list *rqlist)
1441 {
1442 	struct rq_list requeue_list = { };
1443 	struct rq_list submit_list = { };
1444 	struct ublk_io *io = NULL;
1445 	struct request *req;
1446 
1447 	while ((req = rq_list_pop(rqlist))) {
1448 		struct ublk_queue *this_q = req->mq_hctx->driver_data;
1449 		struct ublk_io *this_io = &this_q->ios[req->tag];
1450 
1451 		if (ublk_prep_req(this_q, req, true) != BLK_STS_OK) {
1452 			rq_list_add_tail(&requeue_list, req);
1453 			continue;
1454 		}
1455 
1456 		if (io && !ublk_belong_to_same_batch(io, this_io) &&
1457 				!rq_list_empty(&submit_list))
1458 			ublk_queue_cmd_list(io, &submit_list);
1459 		io = this_io;
1460 		rq_list_add_tail(&submit_list, req);
1461 	}
1462 
1463 	if (!rq_list_empty(&submit_list))
1464 		ublk_queue_cmd_list(io, &submit_list);
1465 	*rqlist = requeue_list;
1466 }
1467 
1468 static int ublk_init_hctx(struct blk_mq_hw_ctx *hctx, void *driver_data,
1469 		unsigned int hctx_idx)
1470 {
1471 	struct ublk_device *ub = driver_data;
1472 	struct ublk_queue *ubq = ublk_get_queue(ub, hctx->queue_num);
1473 
1474 	hctx->driver_data = ubq;
1475 	return 0;
1476 }
1477 
1478 static const struct blk_mq_ops ublk_mq_ops = {
1479 	.queue_rq       = ublk_queue_rq,
1480 	.queue_rqs      = ublk_queue_rqs,
1481 	.init_hctx	= ublk_init_hctx,
1482 	.timeout	= ublk_timeout,
1483 };
1484 
1485 static void ublk_queue_reinit(struct ublk_device *ub, struct ublk_queue *ubq)
1486 {
1487 	int i;
1488 
1489 	for (i = 0; i < ubq->q_depth; i++) {
1490 		struct ublk_io *io = &ubq->ios[i];
1491 
1492 		/*
1493 		 * UBLK_IO_FLAG_CANCELED is kept for avoiding to touch
1494 		 * io->cmd
1495 		 */
1496 		io->flags &= UBLK_IO_FLAG_CANCELED;
1497 		io->cmd = NULL;
1498 		io->buf.addr = 0;
1499 
1500 		/*
1501 		 * old task is PF_EXITING, put it now
1502 		 *
1503 		 * It could be NULL in case of closing one quiesced
1504 		 * device.
1505 		 */
1506 		if (io->task) {
1507 			put_task_struct(io->task);
1508 			io->task = NULL;
1509 		}
1510 
1511 		WARN_ON_ONCE(refcount_read(&io->ref));
1512 		WARN_ON_ONCE(io->task_registered_buffers);
1513 	}
1514 }
1515 
1516 static int ublk_ch_open(struct inode *inode, struct file *filp)
1517 {
1518 	struct ublk_device *ub = container_of(inode->i_cdev,
1519 			struct ublk_device, cdev);
1520 
1521 	if (test_and_set_bit(UB_STATE_OPEN, &ub->state))
1522 		return -EBUSY;
1523 	filp->private_data = ub;
1524 	ub->ublksrv_tgid = current->tgid;
1525 	return 0;
1526 }
1527 
1528 static void ublk_reset_ch_dev(struct ublk_device *ub)
1529 {
1530 	int i;
1531 
1532 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1533 		ublk_queue_reinit(ub, ublk_get_queue(ub, i));
1534 
1535 	/* set to NULL, otherwise new tasks cannot mmap io_cmd_buf */
1536 	ub->mm = NULL;
1537 	ub->nr_io_ready = 0;
1538 	ub->unprivileged_daemons = false;
1539 	ub->ublksrv_tgid = -1;
1540 }
1541 
1542 static struct gendisk *ublk_get_disk(struct ublk_device *ub)
1543 {
1544 	struct gendisk *disk;
1545 
1546 	spin_lock(&ub->lock);
1547 	disk = ub->ub_disk;
1548 	if (disk)
1549 		get_device(disk_to_dev(disk));
1550 	spin_unlock(&ub->lock);
1551 
1552 	return disk;
1553 }
1554 
1555 static void ublk_put_disk(struct gendisk *disk)
1556 {
1557 	if (disk)
1558 		put_device(disk_to_dev(disk));
1559 }
1560 
1561 /*
1562  * Use this function to ensure that ->canceling is consistently set for
1563  * the device and all queues. Do not set these flags directly.
1564  *
1565  * Caller must ensure that:
1566  * - cancel_mutex is held. This ensures that there is no concurrent
1567  *   access to ub->canceling and no concurrent writes to ubq->canceling.
1568  * - there are no concurrent reads of ubq->canceling from the queue_rq
1569  *   path. This can be done by quiescing the queue, or through other
1570  *   means.
1571  */
1572 static void ublk_set_canceling(struct ublk_device *ub, bool canceling)
1573 	__must_hold(&ub->cancel_mutex)
1574 {
1575 	int i;
1576 
1577 	ub->canceling = canceling;
1578 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1579 		ublk_get_queue(ub, i)->canceling = canceling;
1580 }
1581 
1582 static bool ublk_check_and_reset_active_ref(struct ublk_device *ub)
1583 {
1584 	int i, j;
1585 
1586 	if (!(ub->dev_info.flags & (UBLK_F_SUPPORT_ZERO_COPY |
1587 					UBLK_F_AUTO_BUF_REG)))
1588 		return false;
1589 
1590 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++) {
1591 		struct ublk_queue *ubq = ublk_get_queue(ub, i);
1592 
1593 		for (j = 0; j < ubq->q_depth; j++) {
1594 			struct ublk_io *io = &ubq->ios[j];
1595 			unsigned int refs = refcount_read(&io->ref) +
1596 				io->task_registered_buffers;
1597 
1598 			/*
1599 			 * UBLK_REFCOUNT_INIT or zero means no active
1600 			 * reference
1601 			 */
1602 			if (refs != UBLK_REFCOUNT_INIT && refs != 0)
1603 				return true;
1604 
1605 			/* reset to zero if the io hasn't active references */
1606 			refcount_set(&io->ref, 0);
1607 			io->task_registered_buffers = 0;
1608 		}
1609 	}
1610 	return false;
1611 }
1612 
1613 static void ublk_ch_release_work_fn(struct work_struct *work)
1614 {
1615 	struct ublk_device *ub =
1616 		container_of(work, struct ublk_device, exit_work.work);
1617 	struct gendisk *disk;
1618 	int i;
1619 
1620 	/*
1621 	 * For zero-copy and auto buffer register modes, I/O references
1622 	 * might not be dropped naturally when the daemon is killed, but
1623 	 * io_uring guarantees that registered bvec kernel buffers are
1624 	 * unregistered finally when freeing io_uring context, then the
1625 	 * active references are dropped.
1626 	 *
1627 	 * Wait until active references are dropped for avoiding use-after-free
1628 	 *
1629 	 * registered buffer may be unregistered in io_ring's release hander,
1630 	 * so have to wait by scheduling work function for avoiding the two
1631 	 * file release dependency.
1632 	 */
1633 	if (ublk_check_and_reset_active_ref(ub)) {
1634 		schedule_delayed_work(&ub->exit_work, 1);
1635 		return;
1636 	}
1637 
1638 	/*
1639 	 * disk isn't attached yet, either device isn't live, or it has
1640 	 * been removed already, so we needn't to do anything
1641 	 */
1642 	disk = ublk_get_disk(ub);
1643 	if (!disk)
1644 		goto out;
1645 
1646 	/*
1647 	 * All uring_cmd are done now, so abort any request outstanding to
1648 	 * the ublk server
1649 	 *
1650 	 * This can be done in lockless way because ublk server has been
1651 	 * gone
1652 	 *
1653 	 * More importantly, we have to provide forward progress guarantee
1654 	 * without holding ub->mutex, otherwise control task grabbing
1655 	 * ub->mutex triggers deadlock
1656 	 *
1657 	 * All requests may be inflight, so ->canceling may not be set, set
1658 	 * it now.
1659 	 */
1660 	mutex_lock(&ub->cancel_mutex);
1661 	ublk_set_canceling(ub, true);
1662 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1663 		ublk_abort_queue(ub, ublk_get_queue(ub, i));
1664 	mutex_unlock(&ub->cancel_mutex);
1665 	blk_mq_kick_requeue_list(disk->queue);
1666 
1667 	/*
1668 	 * All infligh requests have been completed or requeued and any new
1669 	 * request will be failed or requeued via `->canceling` now, so it is
1670 	 * fine to grab ub->mutex now.
1671 	 */
1672 	mutex_lock(&ub->mutex);
1673 
1674 	/* double check after grabbing lock */
1675 	if (!ub->ub_disk)
1676 		goto unlock;
1677 
1678 	/*
1679 	 * Transition the device to the nosrv state. What exactly this
1680 	 * means depends on the recovery flags
1681 	 */
1682 	if (ublk_nosrv_should_stop_dev(ub)) {
1683 		/*
1684 		 * Allow any pending/future I/O to pass through quickly
1685 		 * with an error. This is needed because del_gendisk
1686 		 * waits for all pending I/O to complete
1687 		 */
1688 		for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1689 			WRITE_ONCE(ublk_get_queue(ub, i)->force_abort, true);
1690 
1691 		ublk_stop_dev_unlocked(ub);
1692 	} else {
1693 		if (ublk_nosrv_dev_should_queue_io(ub)) {
1694 			/* ->canceling is set and all requests are aborted */
1695 			ub->dev_info.state = UBLK_S_DEV_QUIESCED;
1696 		} else {
1697 			ub->dev_info.state = UBLK_S_DEV_FAIL_IO;
1698 			for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1699 				WRITE_ONCE(ublk_get_queue(ub, i)->fail_io, true);
1700 		}
1701 	}
1702 unlock:
1703 	mutex_unlock(&ub->mutex);
1704 	ublk_put_disk(disk);
1705 
1706 	/* all uring_cmd has been done now, reset device & ubq */
1707 	ublk_reset_ch_dev(ub);
1708 out:
1709 	clear_bit(UB_STATE_OPEN, &ub->state);
1710 
1711 	/* put the reference grabbed in ublk_ch_release() */
1712 	ublk_put_device(ub);
1713 }
1714 
1715 static int ublk_ch_release(struct inode *inode, struct file *filp)
1716 {
1717 	struct ublk_device *ub = filp->private_data;
1718 
1719 	/*
1720 	 * Grab ublk device reference, so it won't be gone until we are
1721 	 * really released from work function.
1722 	 */
1723 	ublk_get_device(ub);
1724 
1725 	INIT_DELAYED_WORK(&ub->exit_work, ublk_ch_release_work_fn);
1726 	schedule_delayed_work(&ub->exit_work, 0);
1727 	return 0;
1728 }
1729 
1730 /* map pre-allocated per-queue cmd buffer to ublksrv daemon */
1731 static int ublk_ch_mmap(struct file *filp, struct vm_area_struct *vma)
1732 {
1733 	struct ublk_device *ub = filp->private_data;
1734 	size_t sz = vma->vm_end - vma->vm_start;
1735 	unsigned max_sz = ublk_max_cmd_buf_size();
1736 	unsigned long pfn, end, phys_off = vma->vm_pgoff << PAGE_SHIFT;
1737 	int q_id, ret = 0;
1738 
1739 	spin_lock(&ub->lock);
1740 	if (!ub->mm)
1741 		ub->mm = current->mm;
1742 	if (current->mm != ub->mm)
1743 		ret = -EINVAL;
1744 	spin_unlock(&ub->lock);
1745 
1746 	if (ret)
1747 		return ret;
1748 
1749 	if (vma->vm_flags & VM_WRITE)
1750 		return -EPERM;
1751 
1752 	end = UBLKSRV_CMD_BUF_OFFSET + ub->dev_info.nr_hw_queues * max_sz;
1753 	if (phys_off < UBLKSRV_CMD_BUF_OFFSET || phys_off >= end)
1754 		return -EINVAL;
1755 
1756 	q_id = (phys_off - UBLKSRV_CMD_BUF_OFFSET) / max_sz;
1757 	pr_devel("%s: qid %d, pid %d, addr %lx pg_off %lx sz %lu\n",
1758 			__func__, q_id, current->pid, vma->vm_start,
1759 			phys_off, (unsigned long)sz);
1760 
1761 	if (sz != ublk_queue_cmd_buf_size(ub))
1762 		return -EINVAL;
1763 
1764 	pfn = virt_to_phys(ublk_queue_cmd_buf(ub, q_id)) >> PAGE_SHIFT;
1765 	return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
1766 }
1767 
1768 static void __ublk_fail_req(struct ublk_device *ub, struct ublk_io *io,
1769 		struct request *req)
1770 {
1771 	WARN_ON_ONCE(io->flags & UBLK_IO_FLAG_ACTIVE);
1772 
1773 	if (ublk_nosrv_should_reissue_outstanding(ub))
1774 		blk_mq_requeue_request(req, false);
1775 	else {
1776 		io->res = -EIO;
1777 		__ublk_complete_rq(req, io, ublk_dev_need_map_io(ub));
1778 	}
1779 }
1780 
1781 /*
1782  * Called from ublk char device release handler, when any uring_cmd is
1783  * done, meantime request queue is "quiesced" since all inflight requests
1784  * can't be completed because ublk server is dead.
1785  *
1786  * So no one can hold our request IO reference any more, simply ignore the
1787  * reference, and complete the request immediately
1788  */
1789 static void ublk_abort_queue(struct ublk_device *ub, struct ublk_queue *ubq)
1790 {
1791 	int i;
1792 
1793 	for (i = 0; i < ubq->q_depth; i++) {
1794 		struct ublk_io *io = &ubq->ios[i];
1795 
1796 		if (io->flags & UBLK_IO_FLAG_OWNED_BY_SRV)
1797 			__ublk_fail_req(ub, io, io->req);
1798 	}
1799 }
1800 
1801 static void ublk_start_cancel(struct ublk_device *ub)
1802 {
1803 	struct gendisk *disk = ublk_get_disk(ub);
1804 
1805 	/* Our disk has been dead */
1806 	if (!disk)
1807 		return;
1808 
1809 	mutex_lock(&ub->cancel_mutex);
1810 	if (ub->canceling)
1811 		goto out;
1812 	/*
1813 	 * Now we are serialized with ublk_queue_rq()
1814 	 *
1815 	 * Make sure that ubq->canceling is set when queue is frozen,
1816 	 * because ublk_queue_rq() has to rely on this flag for avoiding to
1817 	 * touch completed uring_cmd
1818 	 */
1819 	blk_mq_quiesce_queue(disk->queue);
1820 	ublk_set_canceling(ub, true);
1821 	blk_mq_unquiesce_queue(disk->queue);
1822 out:
1823 	mutex_unlock(&ub->cancel_mutex);
1824 	ublk_put_disk(disk);
1825 }
1826 
1827 static void ublk_cancel_cmd(struct ublk_queue *ubq, unsigned tag,
1828 		unsigned int issue_flags)
1829 {
1830 	struct ublk_io *io = &ubq->ios[tag];
1831 	struct ublk_device *ub = ubq->dev;
1832 	struct request *req;
1833 	bool done;
1834 
1835 	if (!(io->flags & UBLK_IO_FLAG_ACTIVE))
1836 		return;
1837 
1838 	/*
1839 	 * Don't try to cancel this command if the request is started for
1840 	 * avoiding race between io_uring_cmd_done() and
1841 	 * io_uring_cmd_complete_in_task().
1842 	 *
1843 	 * Either the started request will be aborted via __ublk_abort_rq(),
1844 	 * then this uring_cmd is canceled next time, or it will be done in
1845 	 * task work function ublk_dispatch_req() because io_uring guarantees
1846 	 * that ublk_dispatch_req() is always called
1847 	 */
1848 	req = blk_mq_tag_to_rq(ub->tag_set.tags[ubq->q_id], tag);
1849 	if (req && blk_mq_request_started(req) && req->tag == tag)
1850 		return;
1851 
1852 	spin_lock(&ubq->cancel_lock);
1853 	done = !!(io->flags & UBLK_IO_FLAG_CANCELED);
1854 	if (!done)
1855 		io->flags |= UBLK_IO_FLAG_CANCELED;
1856 	spin_unlock(&ubq->cancel_lock);
1857 
1858 	if (!done)
1859 		io_uring_cmd_done(io->cmd, UBLK_IO_RES_ABORT, issue_flags);
1860 }
1861 
1862 /*
1863  * The ublk char device won't be closed when calling cancel fn, so both
1864  * ublk device and queue are guaranteed to be live
1865  *
1866  * Two-stage cancel:
1867  *
1868  * - make every active uring_cmd done in ->cancel_fn()
1869  *
1870  * - aborting inflight ublk IO requests in ublk char device release handler,
1871  *   which depends on 1st stage because device can only be closed iff all
1872  *   uring_cmd are done
1873  *
1874  * Do _not_ try to acquire ub->mutex before all inflight requests are
1875  * aborted, otherwise deadlock may be caused.
1876  */
1877 static void ublk_uring_cmd_cancel_fn(struct io_uring_cmd *cmd,
1878 		unsigned int issue_flags)
1879 {
1880 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
1881 	struct ublk_queue *ubq = pdu->ubq;
1882 	struct task_struct *task;
1883 	struct ublk_io *io;
1884 
1885 	if (WARN_ON_ONCE(!ubq))
1886 		return;
1887 
1888 	if (WARN_ON_ONCE(pdu->tag >= ubq->q_depth))
1889 		return;
1890 
1891 	task = io_uring_cmd_get_task(cmd);
1892 	io = &ubq->ios[pdu->tag];
1893 	if (WARN_ON_ONCE(task && task != io->task))
1894 		return;
1895 
1896 	ublk_start_cancel(ubq->dev);
1897 
1898 	WARN_ON_ONCE(io->cmd != cmd);
1899 	ublk_cancel_cmd(ubq, pdu->tag, issue_flags);
1900 }
1901 
1902 static inline bool ublk_dev_ready(const struct ublk_device *ub)
1903 {
1904 	u32 total = (u32)ub->dev_info.nr_hw_queues * ub->dev_info.queue_depth;
1905 
1906 	return ub->nr_io_ready == total;
1907 }
1908 
1909 static void ublk_cancel_queue(struct ublk_queue *ubq)
1910 {
1911 	int i;
1912 
1913 	for (i = 0; i < ubq->q_depth; i++)
1914 		ublk_cancel_cmd(ubq, i, IO_URING_F_UNLOCKED);
1915 }
1916 
1917 /* Cancel all pending commands, must be called after del_gendisk() returns */
1918 static void ublk_cancel_dev(struct ublk_device *ub)
1919 {
1920 	int i;
1921 
1922 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1923 		ublk_cancel_queue(ublk_get_queue(ub, i));
1924 }
1925 
1926 static bool ublk_check_inflight_rq(struct request *rq, void *data)
1927 {
1928 	bool *idle = data;
1929 
1930 	if (blk_mq_request_started(rq)) {
1931 		*idle = false;
1932 		return false;
1933 	}
1934 	return true;
1935 }
1936 
1937 static void ublk_wait_tagset_rqs_idle(struct ublk_device *ub)
1938 {
1939 	bool idle;
1940 
1941 	WARN_ON_ONCE(!blk_queue_quiesced(ub->ub_disk->queue));
1942 	while (true) {
1943 		idle = true;
1944 		blk_mq_tagset_busy_iter(&ub->tag_set,
1945 				ublk_check_inflight_rq, &idle);
1946 		if (idle)
1947 			break;
1948 		msleep(UBLK_REQUEUE_DELAY_MS);
1949 	}
1950 }
1951 
1952 static void ublk_force_abort_dev(struct ublk_device *ub)
1953 {
1954 	int i;
1955 
1956 	pr_devel("%s: force abort ub: dev_id %d state %s\n",
1957 			__func__, ub->dev_info.dev_id,
1958 			ub->dev_info.state == UBLK_S_DEV_LIVE ?
1959 			"LIVE" : "QUIESCED");
1960 	blk_mq_quiesce_queue(ub->ub_disk->queue);
1961 	if (ub->dev_info.state == UBLK_S_DEV_LIVE)
1962 		ublk_wait_tagset_rqs_idle(ub);
1963 
1964 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1965 		ublk_get_queue(ub, i)->force_abort = true;
1966 	blk_mq_unquiesce_queue(ub->ub_disk->queue);
1967 	/* We may have requeued some rqs in ublk_quiesce_queue() */
1968 	blk_mq_kick_requeue_list(ub->ub_disk->queue);
1969 }
1970 
1971 static struct gendisk *ublk_detach_disk(struct ublk_device *ub)
1972 {
1973 	struct gendisk *disk;
1974 
1975 	/* Sync with ublk_abort_queue() by holding the lock */
1976 	spin_lock(&ub->lock);
1977 	disk = ub->ub_disk;
1978 	ub->dev_info.state = UBLK_S_DEV_DEAD;
1979 	ub->dev_info.ublksrv_pid = -1;
1980 	ub->ub_disk = NULL;
1981 	spin_unlock(&ub->lock);
1982 
1983 	return disk;
1984 }
1985 
1986 static void ublk_stop_dev_unlocked(struct ublk_device *ub)
1987 	__must_hold(&ub->mutex)
1988 {
1989 	struct gendisk *disk;
1990 
1991 	if (ub->dev_info.state == UBLK_S_DEV_DEAD)
1992 		return;
1993 
1994 	if (ublk_nosrv_dev_should_queue_io(ub))
1995 		ublk_force_abort_dev(ub);
1996 	del_gendisk(ub->ub_disk);
1997 	disk = ublk_detach_disk(ub);
1998 	put_disk(disk);
1999 }
2000 
2001 static void ublk_stop_dev(struct ublk_device *ub)
2002 {
2003 	mutex_lock(&ub->mutex);
2004 	ublk_stop_dev_unlocked(ub);
2005 	mutex_unlock(&ub->mutex);
2006 	ublk_cancel_dev(ub);
2007 }
2008 
2009 /* reset ublk io_uring queue & io flags */
2010 static void ublk_reset_io_flags(struct ublk_device *ub)
2011 {
2012 	int i, j;
2013 
2014 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++) {
2015 		struct ublk_queue *ubq = ublk_get_queue(ub, i);
2016 
2017 		/* UBLK_IO_FLAG_CANCELED can be cleared now */
2018 		spin_lock(&ubq->cancel_lock);
2019 		for (j = 0; j < ubq->q_depth; j++)
2020 			ubq->ios[j].flags &= ~UBLK_IO_FLAG_CANCELED;
2021 		spin_unlock(&ubq->cancel_lock);
2022 		ubq->fail_io = false;
2023 	}
2024 	mutex_lock(&ub->cancel_mutex);
2025 	ublk_set_canceling(ub, false);
2026 	mutex_unlock(&ub->cancel_mutex);
2027 }
2028 
2029 /* device can only be started after all IOs are ready */
2030 static void ublk_mark_io_ready(struct ublk_device *ub)
2031 	__must_hold(&ub->mutex)
2032 {
2033 	if (!ub->unprivileged_daemons && !capable(CAP_SYS_ADMIN))
2034 		ub->unprivileged_daemons = true;
2035 
2036 	ub->nr_io_ready++;
2037 	if (ublk_dev_ready(ub)) {
2038 		/* now we are ready for handling ublk io request */
2039 		ublk_reset_io_flags(ub);
2040 		complete_all(&ub->completion);
2041 	}
2042 }
2043 
2044 static inline int ublk_check_cmd_op(u32 cmd_op)
2045 {
2046 	u32 ioc_type = _IOC_TYPE(cmd_op);
2047 
2048 	if (!IS_ENABLED(CONFIG_BLKDEV_UBLK_LEGACY_OPCODES) && ioc_type != 'u')
2049 		return -EOPNOTSUPP;
2050 
2051 	if (ioc_type != 'u' && ioc_type != 0)
2052 		return -EOPNOTSUPP;
2053 
2054 	return 0;
2055 }
2056 
2057 static inline int ublk_set_auto_buf_reg(struct ublk_io *io, struct io_uring_cmd *cmd)
2058 {
2059 	struct ublk_auto_buf_reg buf;
2060 
2061 	buf = ublk_sqe_addr_to_auto_buf_reg(READ_ONCE(cmd->sqe->addr));
2062 
2063 	if (buf.reserved0 || buf.reserved1)
2064 		return -EINVAL;
2065 
2066 	if (buf.flags & ~UBLK_AUTO_BUF_REG_F_MASK)
2067 		return -EINVAL;
2068 	io->buf.auto_reg = buf;
2069 	return 0;
2070 }
2071 
2072 static int ublk_handle_auto_buf_reg(struct ublk_io *io,
2073 				    struct io_uring_cmd *cmd,
2074 				    u16 *buf_idx)
2075 {
2076 	if (io->flags & UBLK_IO_FLAG_AUTO_BUF_REG) {
2077 		io->flags &= ~UBLK_IO_FLAG_AUTO_BUF_REG;
2078 
2079 		/*
2080 		 * `UBLK_F_AUTO_BUF_REG` only works iff `UBLK_IO_FETCH_REQ`
2081 		 * and `UBLK_IO_COMMIT_AND_FETCH_REQ` are issued from same
2082 		 * `io_ring_ctx`.
2083 		 *
2084 		 * If this uring_cmd's io_ring_ctx isn't same with the
2085 		 * one for registering the buffer, it is ublk server's
2086 		 * responsibility for unregistering the buffer, otherwise
2087 		 * this ublk request gets stuck.
2088 		 */
2089 		if (io->buf_ctx_handle == io_uring_cmd_ctx_handle(cmd))
2090 			*buf_idx = io->buf.auto_reg.index;
2091 	}
2092 
2093 	return ublk_set_auto_buf_reg(io, cmd);
2094 }
2095 
2096 /* Once we return, `io->req` can't be used any more */
2097 static inline struct request *
2098 ublk_fill_io_cmd(struct ublk_io *io, struct io_uring_cmd *cmd)
2099 {
2100 	struct request *req = io->req;
2101 
2102 	io->cmd = cmd;
2103 	io->flags |= UBLK_IO_FLAG_ACTIVE;
2104 	/* now this cmd slot is owned by ublk driver */
2105 	io->flags &= ~UBLK_IO_FLAG_OWNED_BY_SRV;
2106 
2107 	return req;
2108 }
2109 
2110 static inline int
2111 ublk_config_io_buf(const struct ublk_device *ub, struct ublk_io *io,
2112 		   struct io_uring_cmd *cmd, unsigned long buf_addr,
2113 		   u16 *buf_idx)
2114 {
2115 	if (ublk_dev_support_auto_buf_reg(ub))
2116 		return ublk_handle_auto_buf_reg(io, cmd, buf_idx);
2117 
2118 	io->buf.addr = buf_addr;
2119 	return 0;
2120 }
2121 
2122 static inline void ublk_prep_cancel(struct io_uring_cmd *cmd,
2123 				    unsigned int issue_flags,
2124 				    struct ublk_queue *ubq, unsigned int tag)
2125 {
2126 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
2127 
2128 	/*
2129 	 * Safe to refer to @ubq since ublk_queue won't be died until its
2130 	 * commands are completed
2131 	 */
2132 	pdu->ubq = ubq;
2133 	pdu->tag = tag;
2134 	io_uring_cmd_mark_cancelable(cmd, issue_flags);
2135 }
2136 
2137 static void ublk_io_release(void *priv)
2138 {
2139 	struct request *rq = priv;
2140 	struct ublk_queue *ubq = rq->mq_hctx->driver_data;
2141 	struct ublk_io *io = &ubq->ios[rq->tag];
2142 
2143 	/*
2144 	 * task_registered_buffers may be 0 if buffers were registered off task
2145 	 * but unregistered on task. Or after UBLK_IO_COMMIT_AND_FETCH_REQ.
2146 	 */
2147 	if (current == io->task && io->task_registered_buffers)
2148 		io->task_registered_buffers--;
2149 	else
2150 		ublk_put_req_ref(io, rq);
2151 }
2152 
2153 static int ublk_register_io_buf(struct io_uring_cmd *cmd,
2154 				struct ublk_device *ub,
2155 				u16 q_id, u16 tag,
2156 				struct ublk_io *io,
2157 				unsigned int index, unsigned int issue_flags)
2158 {
2159 	struct request *req;
2160 	int ret;
2161 
2162 	if (!ublk_dev_support_zero_copy(ub))
2163 		return -EINVAL;
2164 
2165 	req = __ublk_check_and_get_req(ub, q_id, tag, io, 0);
2166 	if (!req)
2167 		return -EINVAL;
2168 
2169 	ret = io_buffer_register_bvec(cmd, req, ublk_io_release, index,
2170 				      issue_flags);
2171 	if (ret) {
2172 		ublk_put_req_ref(io, req);
2173 		return ret;
2174 	}
2175 
2176 	return 0;
2177 }
2178 
2179 static int
2180 ublk_daemon_register_io_buf(struct io_uring_cmd *cmd,
2181 			    struct ublk_device *ub,
2182 			    u16 q_id, u16 tag, struct ublk_io *io,
2183 			    unsigned index, unsigned issue_flags)
2184 {
2185 	unsigned new_registered_buffers;
2186 	struct request *req = io->req;
2187 	int ret;
2188 
2189 	/*
2190 	 * Ensure there are still references for ublk_sub_req_ref() to release.
2191 	 * If not, fall back on the thread-safe buffer registration.
2192 	 */
2193 	new_registered_buffers = io->task_registered_buffers + 1;
2194 	if (unlikely(new_registered_buffers >= UBLK_REFCOUNT_INIT))
2195 		return ublk_register_io_buf(cmd, ub, q_id, tag, io, index,
2196 					    issue_flags);
2197 
2198 	if (!ublk_dev_support_zero_copy(ub) || !ublk_rq_has_data(req))
2199 		return -EINVAL;
2200 
2201 	ret = io_buffer_register_bvec(cmd, req, ublk_io_release, index,
2202 				      issue_flags);
2203 	if (ret)
2204 		return ret;
2205 
2206 	io->task_registered_buffers = new_registered_buffers;
2207 	return 0;
2208 }
2209 
2210 static int ublk_unregister_io_buf(struct io_uring_cmd *cmd,
2211 				  const struct ublk_device *ub,
2212 				  unsigned int index, unsigned int issue_flags)
2213 {
2214 	if (!(ub->dev_info.flags & UBLK_F_SUPPORT_ZERO_COPY))
2215 		return -EINVAL;
2216 
2217 	return io_buffer_unregister_bvec(cmd, index, issue_flags);
2218 }
2219 
2220 static int ublk_check_fetch_buf(const struct ublk_device *ub, __u64 buf_addr)
2221 {
2222 	if (ublk_dev_need_map_io(ub)) {
2223 		/*
2224 		 * FETCH_RQ has to provide IO buffer if NEED GET
2225 		 * DATA is not enabled
2226 		 */
2227 		if (!buf_addr && !ublk_dev_need_get_data(ub))
2228 			return -EINVAL;
2229 	} else if (buf_addr) {
2230 		/* User copy requires addr to be unset */
2231 		return -EINVAL;
2232 	}
2233 	return 0;
2234 }
2235 
2236 static int __ublk_fetch(struct io_uring_cmd *cmd, struct ublk_device *ub,
2237 			struct ublk_io *io)
2238 {
2239 	/* UBLK_IO_FETCH_REQ is only allowed before dev is setup */
2240 	if (ublk_dev_ready(ub))
2241 		return -EBUSY;
2242 
2243 	/* allow each command to be FETCHed at most once */
2244 	if (io->flags & UBLK_IO_FLAG_ACTIVE)
2245 		return -EINVAL;
2246 
2247 	WARN_ON_ONCE(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV);
2248 
2249 	ublk_fill_io_cmd(io, cmd);
2250 
2251 	WRITE_ONCE(io->task, get_task_struct(current));
2252 	ublk_mark_io_ready(ub);
2253 
2254 	return 0;
2255 }
2256 
2257 static int ublk_fetch(struct io_uring_cmd *cmd, struct ublk_device *ub,
2258 		      struct ublk_io *io, __u64 buf_addr)
2259 {
2260 	int ret;
2261 
2262 	/*
2263 	 * When handling FETCH command for setting up ublk uring queue,
2264 	 * ub->mutex is the innermost lock, and we won't block for handling
2265 	 * FETCH, so it is fine even for IO_URING_F_NONBLOCK.
2266 	 */
2267 	mutex_lock(&ub->mutex);
2268 	ret = __ublk_fetch(cmd, ub, io);
2269 	if (!ret)
2270 		ret = ublk_config_io_buf(ub, io, cmd, buf_addr, NULL);
2271 	mutex_unlock(&ub->mutex);
2272 	return ret;
2273 }
2274 
2275 static int ublk_check_commit_and_fetch(const struct ublk_device *ub,
2276 				       struct ublk_io *io, __u64 buf_addr)
2277 {
2278 	struct request *req = io->req;
2279 
2280 	if (ublk_dev_need_map_io(ub)) {
2281 		/*
2282 		 * COMMIT_AND_FETCH_REQ has to provide IO buffer if
2283 		 * NEED GET DATA is not enabled or it is Read IO.
2284 		 */
2285 		if (!buf_addr && (!ublk_dev_need_get_data(ub) ||
2286 					req_op(req) == REQ_OP_READ))
2287 			return -EINVAL;
2288 	} else if (req_op(req) != REQ_OP_ZONE_APPEND && buf_addr) {
2289 		/*
2290 		 * User copy requires addr to be unset when command is
2291 		 * not zone append
2292 		 */
2293 		return -EINVAL;
2294 	}
2295 
2296 	return 0;
2297 }
2298 
2299 static bool ublk_need_complete_req(const struct ublk_device *ub,
2300 				   struct ublk_io *io)
2301 {
2302 	if (ublk_dev_need_req_ref(ub))
2303 		return ublk_sub_req_ref(io);
2304 	return true;
2305 }
2306 
2307 static bool ublk_get_data(const struct ublk_queue *ubq, struct ublk_io *io,
2308 			  struct request *req)
2309 {
2310 	/*
2311 	 * We have handled UBLK_IO_NEED_GET_DATA command,
2312 	 * so clear UBLK_IO_FLAG_NEED_GET_DATA now and just
2313 	 * do the copy work.
2314 	 */
2315 	io->flags &= ~UBLK_IO_FLAG_NEED_GET_DATA;
2316 	/* update iod->addr because ublksrv may have passed a new io buffer */
2317 	ublk_get_iod(ubq, req->tag)->addr = io->buf.addr;
2318 	pr_devel("%s: update iod->addr: qid %d tag %d io_flags %x addr %llx\n",
2319 			__func__, ubq->q_id, req->tag, io->flags,
2320 			ublk_get_iod(ubq, req->tag)->addr);
2321 
2322 	return ublk_start_io(ubq, req, io);
2323 }
2324 
2325 static int ublk_ch_uring_cmd_local(struct io_uring_cmd *cmd,
2326 		unsigned int issue_flags)
2327 {
2328 	/* May point to userspace-mapped memory */
2329 	const struct ublksrv_io_cmd *ub_src = io_uring_sqe_cmd(cmd->sqe);
2330 	u16 buf_idx = UBLK_INVALID_BUF_IDX;
2331 	struct ublk_device *ub = cmd->file->private_data;
2332 	struct ublk_queue *ubq;
2333 	struct ublk_io *io = NULL;
2334 	u32 cmd_op = cmd->cmd_op;
2335 	u16 q_id = READ_ONCE(ub_src->q_id);
2336 	u16 tag = READ_ONCE(ub_src->tag);
2337 	s32 result = READ_ONCE(ub_src->result);
2338 	u64 addr = READ_ONCE(ub_src->addr); /* unioned with zone_append_lba */
2339 	struct request *req;
2340 	int ret;
2341 	bool compl;
2342 
2343 	WARN_ON_ONCE(issue_flags & IO_URING_F_UNLOCKED);
2344 
2345 	pr_devel("%s: received: cmd op %d queue %d tag %d result %d\n",
2346 			__func__, cmd->cmd_op, q_id, tag, result);
2347 
2348 	ret = ublk_check_cmd_op(cmd_op);
2349 	if (ret)
2350 		goto out;
2351 
2352 	/*
2353 	 * io_buffer_unregister_bvec() doesn't access the ubq or io,
2354 	 * so no need to validate the q_id, tag, or task
2355 	 */
2356 	if (_IOC_NR(cmd_op) == UBLK_IO_UNREGISTER_IO_BUF)
2357 		return ublk_unregister_io_buf(cmd, ub, addr, issue_flags);
2358 
2359 	ret = -EINVAL;
2360 	if (q_id >= ub->dev_info.nr_hw_queues)
2361 		goto out;
2362 
2363 	ubq = ublk_get_queue(ub, q_id);
2364 
2365 	if (tag >= ub->dev_info.queue_depth)
2366 		goto out;
2367 
2368 	io = &ubq->ios[tag];
2369 	/* UBLK_IO_FETCH_REQ can be handled on any task, which sets io->task */
2370 	if (unlikely(_IOC_NR(cmd_op) == UBLK_IO_FETCH_REQ)) {
2371 		ret = ublk_check_fetch_buf(ub, addr);
2372 		if (ret)
2373 			goto out;
2374 		ret = ublk_fetch(cmd, ub, io, addr);
2375 		if (ret)
2376 			goto out;
2377 
2378 		ublk_prep_cancel(cmd, issue_flags, ubq, tag);
2379 		return -EIOCBQUEUED;
2380 	}
2381 
2382 	if (READ_ONCE(io->task) != current) {
2383 		/*
2384 		 * ublk_register_io_buf() accesses only the io's refcount,
2385 		 * so can be handled on any task
2386 		 */
2387 		if (_IOC_NR(cmd_op) == UBLK_IO_REGISTER_IO_BUF)
2388 			return ublk_register_io_buf(cmd, ub, q_id, tag, io,
2389 						    addr, issue_flags);
2390 
2391 		goto out;
2392 	}
2393 
2394 	/* there is pending io cmd, something must be wrong */
2395 	if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV)) {
2396 		ret = -EBUSY;
2397 		goto out;
2398 	}
2399 
2400 	/*
2401 	 * ensure that the user issues UBLK_IO_NEED_GET_DATA
2402 	 * iff the driver have set the UBLK_IO_FLAG_NEED_GET_DATA.
2403 	 */
2404 	if ((!!(io->flags & UBLK_IO_FLAG_NEED_GET_DATA))
2405 			^ (_IOC_NR(cmd_op) == UBLK_IO_NEED_GET_DATA))
2406 		goto out;
2407 
2408 	switch (_IOC_NR(cmd_op)) {
2409 	case UBLK_IO_REGISTER_IO_BUF:
2410 		return ublk_daemon_register_io_buf(cmd, ub, q_id, tag, io, addr,
2411 						   issue_flags);
2412 	case UBLK_IO_COMMIT_AND_FETCH_REQ:
2413 		ret = ublk_check_commit_and_fetch(ub, io, addr);
2414 		if (ret)
2415 			goto out;
2416 		io->res = result;
2417 		req = ublk_fill_io_cmd(io, cmd);
2418 		ret = ublk_config_io_buf(ub, io, cmd, addr, &buf_idx);
2419 		compl = ublk_need_complete_req(ub, io);
2420 
2421 		/* can't touch 'ublk_io' any more */
2422 		if (buf_idx != UBLK_INVALID_BUF_IDX)
2423 			io_buffer_unregister_bvec(cmd, buf_idx, issue_flags);
2424 		if (req_op(req) == REQ_OP_ZONE_APPEND)
2425 			req->__sector = addr;
2426 		if (compl)
2427 			__ublk_complete_rq(req, io, ublk_dev_need_map_io(ub));
2428 
2429 		if (ret)
2430 			goto out;
2431 		break;
2432 	case UBLK_IO_NEED_GET_DATA:
2433 		/*
2434 		 * ublk_get_data() may fail and fallback to requeue, so keep
2435 		 * uring_cmd active first and prepare for handling new requeued
2436 		 * request
2437 		 */
2438 		req = ublk_fill_io_cmd(io, cmd);
2439 		ret = ublk_config_io_buf(ub, io, cmd, addr, NULL);
2440 		WARN_ON_ONCE(ret);
2441 		if (likely(ublk_get_data(ubq, io, req))) {
2442 			__ublk_prep_compl_io_cmd(io, req);
2443 			return UBLK_IO_RES_OK;
2444 		}
2445 		break;
2446 	default:
2447 		goto out;
2448 	}
2449 	ublk_prep_cancel(cmd, issue_flags, ubq, tag);
2450 	return -EIOCBQUEUED;
2451 
2452  out:
2453 	pr_devel("%s: complete: cmd op %d, tag %d ret %x io_flags %x\n",
2454 			__func__, cmd_op, tag, ret, io ? io->flags : 0);
2455 	return ret;
2456 }
2457 
2458 static inline struct request *__ublk_check_and_get_req(struct ublk_device *ub,
2459 		u16 q_id, u16 tag, struct ublk_io *io, size_t offset)
2460 {
2461 	struct request *req;
2462 
2463 	/*
2464 	 * can't use io->req in case of concurrent UBLK_IO_COMMIT_AND_FETCH_REQ,
2465 	 * which would overwrite it with io->cmd
2466 	 */
2467 	req = blk_mq_tag_to_rq(ub->tag_set.tags[q_id], tag);
2468 	if (!req)
2469 		return NULL;
2470 
2471 	if (!ublk_get_req_ref(io))
2472 		return NULL;
2473 
2474 	if (unlikely(!blk_mq_request_started(req) || req->tag != tag))
2475 		goto fail_put;
2476 
2477 	if (!ublk_rq_has_data(req))
2478 		goto fail_put;
2479 
2480 	if (offset > blk_rq_bytes(req))
2481 		goto fail_put;
2482 
2483 	return req;
2484 fail_put:
2485 	ublk_put_req_ref(io, req);
2486 	return NULL;
2487 }
2488 
2489 static void ublk_ch_uring_cmd_cb(struct io_tw_req tw_req, io_tw_token_t tw)
2490 {
2491 	unsigned int issue_flags = IO_URING_CMD_TASK_WORK_ISSUE_FLAGS;
2492 	struct io_uring_cmd *cmd = io_uring_cmd_from_tw(tw_req);
2493 	int ret = ublk_ch_uring_cmd_local(cmd, issue_flags);
2494 
2495 	if (ret != -EIOCBQUEUED)
2496 		io_uring_cmd_done(cmd, ret, issue_flags);
2497 }
2498 
2499 static int ublk_ch_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags)
2500 {
2501 	if (unlikely(issue_flags & IO_URING_F_CANCEL)) {
2502 		ublk_uring_cmd_cancel_fn(cmd, issue_flags);
2503 		return 0;
2504 	}
2505 
2506 	/* well-implemented server won't run into unlocked */
2507 	if (unlikely(issue_flags & IO_URING_F_UNLOCKED)) {
2508 		io_uring_cmd_complete_in_task(cmd, ublk_ch_uring_cmd_cb);
2509 		return -EIOCBQUEUED;
2510 	}
2511 
2512 	return ublk_ch_uring_cmd_local(cmd, issue_flags);
2513 }
2514 
2515 static inline bool ublk_check_ubuf_dir(const struct request *req,
2516 		int ubuf_dir)
2517 {
2518 	/* copy ubuf to request pages */
2519 	if ((req_op(req) == REQ_OP_READ || req_op(req) == REQ_OP_DRV_IN) &&
2520 	    ubuf_dir == ITER_SOURCE)
2521 		return true;
2522 
2523 	/* copy request pages to ubuf */
2524 	if ((req_op(req) == REQ_OP_WRITE ||
2525 	     req_op(req) == REQ_OP_ZONE_APPEND) &&
2526 	    ubuf_dir == ITER_DEST)
2527 		return true;
2528 
2529 	return false;
2530 }
2531 
2532 static struct request *ublk_check_and_get_req(struct kiocb *iocb,
2533 		struct iov_iter *iter, size_t *off, int dir,
2534 		struct ublk_io **io)
2535 {
2536 	struct ublk_device *ub = iocb->ki_filp->private_data;
2537 	struct ublk_queue *ubq;
2538 	struct request *req;
2539 	size_t buf_off;
2540 	u16 tag, q_id;
2541 
2542 	if (!user_backed_iter(iter))
2543 		return ERR_PTR(-EACCES);
2544 
2545 	if (ub->dev_info.state == UBLK_S_DEV_DEAD)
2546 		return ERR_PTR(-EACCES);
2547 
2548 	tag = ublk_pos_to_tag(iocb->ki_pos);
2549 	q_id = ublk_pos_to_hwq(iocb->ki_pos);
2550 	buf_off = ublk_pos_to_buf_off(iocb->ki_pos);
2551 
2552 	if (q_id >= ub->dev_info.nr_hw_queues)
2553 		return ERR_PTR(-EINVAL);
2554 
2555 	ubq = ublk_get_queue(ub, q_id);
2556 	if (!ublk_dev_support_user_copy(ub))
2557 		return ERR_PTR(-EACCES);
2558 
2559 	if (tag >= ub->dev_info.queue_depth)
2560 		return ERR_PTR(-EINVAL);
2561 
2562 	*io = &ubq->ios[tag];
2563 	req = __ublk_check_and_get_req(ub, q_id, tag, *io, buf_off);
2564 	if (!req)
2565 		return ERR_PTR(-EINVAL);
2566 
2567 	if (!ublk_check_ubuf_dir(req, dir))
2568 		goto fail;
2569 
2570 	*off = buf_off;
2571 	return req;
2572 fail:
2573 	ublk_put_req_ref(*io, req);
2574 	return ERR_PTR(-EACCES);
2575 }
2576 
2577 static ssize_t ublk_ch_read_iter(struct kiocb *iocb, struct iov_iter *to)
2578 {
2579 	struct request *req;
2580 	struct ublk_io *io;
2581 	size_t buf_off;
2582 	size_t ret;
2583 
2584 	req = ublk_check_and_get_req(iocb, to, &buf_off, ITER_DEST, &io);
2585 	if (IS_ERR(req))
2586 		return PTR_ERR(req);
2587 
2588 	ret = ublk_copy_user_pages(req, buf_off, to, ITER_DEST);
2589 	ublk_put_req_ref(io, req);
2590 
2591 	return ret;
2592 }
2593 
2594 static ssize_t ublk_ch_write_iter(struct kiocb *iocb, struct iov_iter *from)
2595 {
2596 	struct request *req;
2597 	struct ublk_io *io;
2598 	size_t buf_off;
2599 	size_t ret;
2600 
2601 	req = ublk_check_and_get_req(iocb, from, &buf_off, ITER_SOURCE, &io);
2602 	if (IS_ERR(req))
2603 		return PTR_ERR(req);
2604 
2605 	ret = ublk_copy_user_pages(req, buf_off, from, ITER_SOURCE);
2606 	ublk_put_req_ref(io, req);
2607 
2608 	return ret;
2609 }
2610 
2611 static const struct file_operations ublk_ch_fops = {
2612 	.owner = THIS_MODULE,
2613 	.open = ublk_ch_open,
2614 	.release = ublk_ch_release,
2615 	.read_iter = ublk_ch_read_iter,
2616 	.write_iter = ublk_ch_write_iter,
2617 	.uring_cmd = ublk_ch_uring_cmd,
2618 	.mmap = ublk_ch_mmap,
2619 };
2620 
2621 static void ublk_deinit_queue(struct ublk_device *ub, int q_id)
2622 {
2623 	struct ublk_queue *ubq = ub->queues[q_id];
2624 	int size, i;
2625 
2626 	if (!ubq)
2627 		return;
2628 
2629 	size = ublk_queue_cmd_buf_size(ub);
2630 
2631 	for (i = 0; i < ubq->q_depth; i++) {
2632 		struct ublk_io *io = &ubq->ios[i];
2633 		if (io->task)
2634 			put_task_struct(io->task);
2635 		WARN_ON_ONCE(refcount_read(&io->ref));
2636 		WARN_ON_ONCE(io->task_registered_buffers);
2637 	}
2638 
2639 	if (ubq->io_cmd_buf)
2640 		free_pages((unsigned long)ubq->io_cmd_buf, get_order(size));
2641 
2642 	kvfree(ubq);
2643 	ub->queues[q_id] = NULL;
2644 }
2645 
2646 static int ublk_get_queue_numa_node(struct ublk_device *ub, int q_id)
2647 {
2648 	unsigned int cpu;
2649 
2650 	/* Find first CPU mapped to this queue */
2651 	for_each_possible_cpu(cpu) {
2652 		if (ub->tag_set.map[HCTX_TYPE_DEFAULT].mq_map[cpu] == q_id)
2653 			return cpu_to_node(cpu);
2654 	}
2655 
2656 	return NUMA_NO_NODE;
2657 }
2658 
2659 static int ublk_init_queue(struct ublk_device *ub, int q_id)
2660 {
2661 	int depth = ub->dev_info.queue_depth;
2662 	gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO;
2663 	struct ublk_queue *ubq;
2664 	struct page *page;
2665 	int numa_node;
2666 	int size;
2667 
2668 	/* Determine NUMA node based on queue's CPU affinity */
2669 	numa_node = ublk_get_queue_numa_node(ub, q_id);
2670 
2671 	/* Allocate queue structure on local NUMA node */
2672 	ubq = kvzalloc_node(struct_size(ubq, ios, depth), GFP_KERNEL,
2673 			    numa_node);
2674 	if (!ubq)
2675 		return -ENOMEM;
2676 
2677 	spin_lock_init(&ubq->cancel_lock);
2678 	ubq->flags = ub->dev_info.flags;
2679 	ubq->q_id = q_id;
2680 	ubq->q_depth = depth;
2681 	size = ublk_queue_cmd_buf_size(ub);
2682 
2683 	/* Allocate I/O command buffer on local NUMA node */
2684 	page = alloc_pages_node(numa_node, gfp_flags, get_order(size));
2685 	if (!page) {
2686 		kvfree(ubq);
2687 		return -ENOMEM;
2688 	}
2689 	ubq->io_cmd_buf = page_address(page);
2690 
2691 	ub->queues[q_id] = ubq;
2692 	ubq->dev = ub;
2693 	return 0;
2694 }
2695 
2696 static void ublk_deinit_queues(struct ublk_device *ub)
2697 {
2698 	int i;
2699 
2700 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
2701 		ublk_deinit_queue(ub, i);
2702 }
2703 
2704 static int ublk_init_queues(struct ublk_device *ub)
2705 {
2706 	int i, ret;
2707 
2708 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++) {
2709 		ret = ublk_init_queue(ub, i);
2710 		if (ret)
2711 			goto fail;
2712 	}
2713 
2714 	init_completion(&ub->completion);
2715 	return 0;
2716 
2717  fail:
2718 	ublk_deinit_queues(ub);
2719 	return ret;
2720 }
2721 
2722 static int ublk_alloc_dev_number(struct ublk_device *ub, int idx)
2723 {
2724 	int i = idx;
2725 	int err;
2726 
2727 	spin_lock(&ublk_idr_lock);
2728 	/* allocate id, if @id >= 0, we're requesting that specific id */
2729 	if (i >= 0) {
2730 		err = idr_alloc(&ublk_index_idr, ub, i, i + 1, GFP_NOWAIT);
2731 		if (err == -ENOSPC)
2732 			err = -EEXIST;
2733 	} else {
2734 		err = idr_alloc(&ublk_index_idr, ub, 0, UBLK_MAX_UBLKS,
2735 				GFP_NOWAIT);
2736 	}
2737 	spin_unlock(&ublk_idr_lock);
2738 
2739 	if (err >= 0)
2740 		ub->ub_number = err;
2741 
2742 	return err;
2743 }
2744 
2745 static void ublk_free_dev_number(struct ublk_device *ub)
2746 {
2747 	spin_lock(&ublk_idr_lock);
2748 	idr_remove(&ublk_index_idr, ub->ub_number);
2749 	wake_up_all(&ublk_idr_wq);
2750 	spin_unlock(&ublk_idr_lock);
2751 }
2752 
2753 static void ublk_cdev_rel(struct device *dev)
2754 {
2755 	struct ublk_device *ub = container_of(dev, struct ublk_device, cdev_dev);
2756 
2757 	blk_mq_free_tag_set(&ub->tag_set);
2758 	ublk_deinit_queues(ub);
2759 	ublk_free_dev_number(ub);
2760 	mutex_destroy(&ub->mutex);
2761 	mutex_destroy(&ub->cancel_mutex);
2762 	kfree(ub);
2763 }
2764 
2765 static int ublk_add_chdev(struct ublk_device *ub)
2766 {
2767 	struct device *dev = &ub->cdev_dev;
2768 	int minor = ub->ub_number;
2769 	int ret;
2770 
2771 	dev->parent = ublk_misc.this_device;
2772 	dev->devt = MKDEV(MAJOR(ublk_chr_devt), minor);
2773 	dev->class = &ublk_chr_class;
2774 	dev->release = ublk_cdev_rel;
2775 	device_initialize(dev);
2776 
2777 	ret = dev_set_name(dev, "ublkc%d", minor);
2778 	if (ret)
2779 		goto fail;
2780 
2781 	cdev_init(&ub->cdev, &ublk_ch_fops);
2782 	ret = cdev_device_add(&ub->cdev, dev);
2783 	if (ret)
2784 		goto fail;
2785 
2786 	if (ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV)
2787 		unprivileged_ublks_added++;
2788 	return 0;
2789  fail:
2790 	put_device(dev);
2791 	return ret;
2792 }
2793 
2794 /* align max io buffer size with PAGE_SIZE */
2795 static void ublk_align_max_io_size(struct ublk_device *ub)
2796 {
2797 	unsigned int max_io_bytes = ub->dev_info.max_io_buf_bytes;
2798 
2799 	ub->dev_info.max_io_buf_bytes =
2800 		round_down(max_io_bytes, PAGE_SIZE);
2801 }
2802 
2803 static int ublk_add_tag_set(struct ublk_device *ub)
2804 {
2805 	ub->tag_set.ops = &ublk_mq_ops;
2806 	ub->tag_set.nr_hw_queues = ub->dev_info.nr_hw_queues;
2807 	ub->tag_set.queue_depth = ub->dev_info.queue_depth;
2808 	ub->tag_set.numa_node = NUMA_NO_NODE;
2809 	ub->tag_set.driver_data = ub;
2810 	return blk_mq_alloc_tag_set(&ub->tag_set);
2811 }
2812 
2813 static void ublk_remove(struct ublk_device *ub)
2814 {
2815 	bool unprivileged;
2816 
2817 	ublk_stop_dev(ub);
2818 	cdev_device_del(&ub->cdev, &ub->cdev_dev);
2819 	unprivileged = ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV;
2820 	ublk_put_device(ub);
2821 
2822 	if (unprivileged)
2823 		unprivileged_ublks_added--;
2824 }
2825 
2826 static struct ublk_device *ublk_get_device_from_id(int idx)
2827 {
2828 	struct ublk_device *ub = NULL;
2829 
2830 	if (idx < 0)
2831 		return NULL;
2832 
2833 	spin_lock(&ublk_idr_lock);
2834 	ub = idr_find(&ublk_index_idr, idx);
2835 	if (ub)
2836 		ub = ublk_get_device(ub);
2837 	spin_unlock(&ublk_idr_lock);
2838 
2839 	return ub;
2840 }
2841 
2842 static int ublk_ctrl_start_dev(struct ublk_device *ub,
2843 		const struct ublksrv_ctrl_cmd *header)
2844 {
2845 	const struct ublk_param_basic *p = &ub->params.basic;
2846 	int ublksrv_pid = (int)header->data[0];
2847 	struct queue_limits lim = {
2848 		.logical_block_size	= 1 << p->logical_bs_shift,
2849 		.physical_block_size	= 1 << p->physical_bs_shift,
2850 		.io_min			= 1 << p->io_min_shift,
2851 		.io_opt			= 1 << p->io_opt_shift,
2852 		.max_hw_sectors		= p->max_sectors,
2853 		.chunk_sectors		= p->chunk_sectors,
2854 		.virt_boundary_mask	= p->virt_boundary_mask,
2855 		.max_segments		= USHRT_MAX,
2856 		.max_segment_size	= UINT_MAX,
2857 		.dma_alignment		= 3,
2858 	};
2859 	struct gendisk *disk;
2860 	int ret = -EINVAL;
2861 
2862 	if (ublksrv_pid <= 0)
2863 		return -EINVAL;
2864 	if (!(ub->params.types & UBLK_PARAM_TYPE_BASIC))
2865 		return -EINVAL;
2866 
2867 	if (ub->params.types & UBLK_PARAM_TYPE_DISCARD) {
2868 		const struct ublk_param_discard *pd = &ub->params.discard;
2869 
2870 		lim.discard_alignment = pd->discard_alignment;
2871 		lim.discard_granularity = pd->discard_granularity;
2872 		lim.max_hw_discard_sectors = pd->max_discard_sectors;
2873 		lim.max_write_zeroes_sectors = pd->max_write_zeroes_sectors;
2874 		lim.max_discard_segments = pd->max_discard_segments;
2875 	}
2876 
2877 	if (ub->params.types & UBLK_PARAM_TYPE_ZONED) {
2878 		const struct ublk_param_zoned *p = &ub->params.zoned;
2879 
2880 		if (!IS_ENABLED(CONFIG_BLK_DEV_ZONED))
2881 			return -EOPNOTSUPP;
2882 
2883 		lim.features |= BLK_FEAT_ZONED;
2884 		lim.max_active_zones = p->max_active_zones;
2885 		lim.max_open_zones =  p->max_open_zones;
2886 		lim.max_hw_zone_append_sectors = p->max_zone_append_sectors;
2887 	}
2888 
2889 	if (ub->params.basic.attrs & UBLK_ATTR_VOLATILE_CACHE) {
2890 		lim.features |= BLK_FEAT_WRITE_CACHE;
2891 		if (ub->params.basic.attrs & UBLK_ATTR_FUA)
2892 			lim.features |= BLK_FEAT_FUA;
2893 	}
2894 
2895 	if (ub->params.basic.attrs & UBLK_ATTR_ROTATIONAL)
2896 		lim.features |= BLK_FEAT_ROTATIONAL;
2897 
2898 	if (ub->params.types & UBLK_PARAM_TYPE_DMA_ALIGN)
2899 		lim.dma_alignment = ub->params.dma.alignment;
2900 
2901 	if (ub->params.types & UBLK_PARAM_TYPE_SEGMENT) {
2902 		lim.seg_boundary_mask = ub->params.seg.seg_boundary_mask;
2903 		lim.max_segment_size = ub->params.seg.max_segment_size;
2904 		lim.max_segments = ub->params.seg.max_segments;
2905 	}
2906 
2907 	if (wait_for_completion_interruptible(&ub->completion) != 0)
2908 		return -EINTR;
2909 
2910 	if (ub->ublksrv_tgid != ublksrv_pid)
2911 		return -EINVAL;
2912 
2913 	mutex_lock(&ub->mutex);
2914 	if (ub->dev_info.state == UBLK_S_DEV_LIVE ||
2915 	    test_bit(UB_STATE_USED, &ub->state)) {
2916 		ret = -EEXIST;
2917 		goto out_unlock;
2918 	}
2919 
2920 	disk = blk_mq_alloc_disk(&ub->tag_set, &lim, NULL);
2921 	if (IS_ERR(disk)) {
2922 		ret = PTR_ERR(disk);
2923 		goto out_unlock;
2924 	}
2925 	sprintf(disk->disk_name, "ublkb%d", ub->ub_number);
2926 	disk->fops = &ub_fops;
2927 	disk->private_data = ub;
2928 
2929 	ub->dev_info.ublksrv_pid = ublksrv_pid;
2930 	ub->ub_disk = disk;
2931 
2932 	ublk_apply_params(ub);
2933 
2934 	/* don't probe partitions if any daemon task is un-trusted */
2935 	if (ub->unprivileged_daemons)
2936 		set_bit(GD_SUPPRESS_PART_SCAN, &disk->state);
2937 
2938 	ublk_get_device(ub);
2939 	ub->dev_info.state = UBLK_S_DEV_LIVE;
2940 
2941 	if (ublk_dev_is_zoned(ub)) {
2942 		ret = ublk_revalidate_disk_zones(ub);
2943 		if (ret)
2944 			goto out_put_cdev;
2945 	}
2946 
2947 	ret = add_disk(disk);
2948 	if (ret)
2949 		goto out_put_cdev;
2950 
2951 	set_bit(UB_STATE_USED, &ub->state);
2952 
2953 out_put_cdev:
2954 	if (ret) {
2955 		ublk_detach_disk(ub);
2956 		ublk_put_device(ub);
2957 	}
2958 	if (ret)
2959 		put_disk(disk);
2960 out_unlock:
2961 	mutex_unlock(&ub->mutex);
2962 	return ret;
2963 }
2964 
2965 static int ublk_ctrl_get_queue_affinity(struct ublk_device *ub,
2966 		const struct ublksrv_ctrl_cmd *header)
2967 {
2968 	void __user *argp = (void __user *)(unsigned long)header->addr;
2969 	cpumask_var_t cpumask;
2970 	unsigned long queue;
2971 	unsigned int retlen;
2972 	unsigned int i;
2973 	int ret;
2974 
2975 	if (header->len * BITS_PER_BYTE < nr_cpu_ids)
2976 		return -EINVAL;
2977 	if (header->len & (sizeof(unsigned long)-1))
2978 		return -EINVAL;
2979 	if (!header->addr)
2980 		return -EINVAL;
2981 
2982 	queue = header->data[0];
2983 	if (queue >= ub->dev_info.nr_hw_queues)
2984 		return -EINVAL;
2985 
2986 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
2987 		return -ENOMEM;
2988 
2989 	for_each_possible_cpu(i) {
2990 		if (ub->tag_set.map[HCTX_TYPE_DEFAULT].mq_map[i] == queue)
2991 			cpumask_set_cpu(i, cpumask);
2992 	}
2993 
2994 	ret = -EFAULT;
2995 	retlen = min_t(unsigned short, header->len, cpumask_size());
2996 	if (copy_to_user(argp, cpumask, retlen))
2997 		goto out_free_cpumask;
2998 	if (retlen != header->len &&
2999 	    clear_user(argp + retlen, header->len - retlen))
3000 		goto out_free_cpumask;
3001 
3002 	ret = 0;
3003 out_free_cpumask:
3004 	free_cpumask_var(cpumask);
3005 	return ret;
3006 }
3007 
3008 static inline void ublk_dump_dev_info(struct ublksrv_ctrl_dev_info *info)
3009 {
3010 	pr_devel("%s: dev id %d flags %llx\n", __func__,
3011 			info->dev_id, info->flags);
3012 	pr_devel("\t nr_hw_queues %d queue_depth %d\n",
3013 			info->nr_hw_queues, info->queue_depth);
3014 }
3015 
3016 static int ublk_ctrl_add_dev(const struct ublksrv_ctrl_cmd *header)
3017 {
3018 	void __user *argp = (void __user *)(unsigned long)header->addr;
3019 	struct ublksrv_ctrl_dev_info info;
3020 	struct ublk_device *ub;
3021 	int ret = -EINVAL;
3022 
3023 	if (header->len < sizeof(info) || !header->addr)
3024 		return -EINVAL;
3025 	if (header->queue_id != (u16)-1) {
3026 		pr_warn("%s: queue_id is wrong %x\n",
3027 			__func__, header->queue_id);
3028 		return -EINVAL;
3029 	}
3030 
3031 	if (copy_from_user(&info, argp, sizeof(info)))
3032 		return -EFAULT;
3033 
3034 	if (info.queue_depth > UBLK_MAX_QUEUE_DEPTH || !info.queue_depth ||
3035 	    info.nr_hw_queues > UBLK_MAX_NR_QUEUES || !info.nr_hw_queues)
3036 		return -EINVAL;
3037 
3038 	if (capable(CAP_SYS_ADMIN))
3039 		info.flags &= ~UBLK_F_UNPRIVILEGED_DEV;
3040 	else if (!(info.flags & UBLK_F_UNPRIVILEGED_DEV))
3041 		return -EPERM;
3042 
3043 	/* forbid nonsense combinations of recovery flags */
3044 	switch (info.flags & UBLK_F_ALL_RECOVERY_FLAGS) {
3045 	case 0:
3046 	case UBLK_F_USER_RECOVERY:
3047 	case (UBLK_F_USER_RECOVERY | UBLK_F_USER_RECOVERY_REISSUE):
3048 	case (UBLK_F_USER_RECOVERY | UBLK_F_USER_RECOVERY_FAIL_IO):
3049 		break;
3050 	default:
3051 		pr_warn("%s: invalid recovery flags %llx\n", __func__,
3052 			info.flags & UBLK_F_ALL_RECOVERY_FLAGS);
3053 		return -EINVAL;
3054 	}
3055 
3056 	if ((info.flags & UBLK_F_QUIESCE) && !(info.flags & UBLK_F_USER_RECOVERY)) {
3057 		pr_warn("UBLK_F_QUIESCE requires UBLK_F_USER_RECOVERY\n");
3058 		return -EINVAL;
3059 	}
3060 
3061 	/*
3062 	 * unprivileged device can't be trusted, but RECOVERY and
3063 	 * RECOVERY_REISSUE still may hang error handling, so can't
3064 	 * support recovery features for unprivileged ublk now
3065 	 *
3066 	 * TODO: provide forward progress for RECOVERY handler, so that
3067 	 * unprivileged device can benefit from it
3068 	 */
3069 	if (info.flags & UBLK_F_UNPRIVILEGED_DEV) {
3070 		info.flags &= ~(UBLK_F_USER_RECOVERY_REISSUE |
3071 				UBLK_F_USER_RECOVERY);
3072 
3073 		/*
3074 		 * For USER_COPY, we depends on userspace to fill request
3075 		 * buffer by pwrite() to ublk char device, which can't be
3076 		 * used for unprivileged device
3077 		 *
3078 		 * Same with zero copy or auto buffer register.
3079 		 */
3080 		if (info.flags & (UBLK_F_USER_COPY | UBLK_F_SUPPORT_ZERO_COPY |
3081 					UBLK_F_AUTO_BUF_REG))
3082 			return -EINVAL;
3083 	}
3084 
3085 	/* the created device is always owned by current user */
3086 	ublk_store_owner_uid_gid(&info.owner_uid, &info.owner_gid);
3087 
3088 	if (header->dev_id != info.dev_id) {
3089 		pr_warn("%s: dev id not match %u %u\n",
3090 			__func__, header->dev_id, info.dev_id);
3091 		return -EINVAL;
3092 	}
3093 
3094 	if (header->dev_id != U32_MAX && header->dev_id >= UBLK_MAX_UBLKS) {
3095 		pr_warn("%s: dev id is too large. Max supported is %d\n",
3096 			__func__, UBLK_MAX_UBLKS - 1);
3097 		return -EINVAL;
3098 	}
3099 
3100 	ublk_dump_dev_info(&info);
3101 
3102 	ret = mutex_lock_killable(&ublk_ctl_mutex);
3103 	if (ret)
3104 		return ret;
3105 
3106 	ret = -EACCES;
3107 	if ((info.flags & UBLK_F_UNPRIVILEGED_DEV) &&
3108 	    unprivileged_ublks_added >= unprivileged_ublks_max)
3109 		goto out_unlock;
3110 
3111 	ret = -ENOMEM;
3112 	ub = kzalloc(struct_size(ub, queues, info.nr_hw_queues), GFP_KERNEL);
3113 	if (!ub)
3114 		goto out_unlock;
3115 	mutex_init(&ub->mutex);
3116 	spin_lock_init(&ub->lock);
3117 	mutex_init(&ub->cancel_mutex);
3118 
3119 	ret = ublk_alloc_dev_number(ub, header->dev_id);
3120 	if (ret < 0)
3121 		goto out_free_ub;
3122 
3123 	memcpy(&ub->dev_info, &info, sizeof(info));
3124 
3125 	/* update device id */
3126 	ub->dev_info.dev_id = ub->ub_number;
3127 
3128 	/*
3129 	 * 64bit flags will be copied back to userspace as feature
3130 	 * negotiation result, so have to clear flags which driver
3131 	 * doesn't support yet, then userspace can get correct flags
3132 	 * (features) to handle.
3133 	 */
3134 	ub->dev_info.flags &= UBLK_F_ALL;
3135 
3136 	ub->dev_info.flags |= UBLK_F_CMD_IOCTL_ENCODE |
3137 		UBLK_F_URING_CMD_COMP_IN_TASK |
3138 		UBLK_F_PER_IO_DAEMON |
3139 		UBLK_F_BUF_REG_OFF_DAEMON;
3140 
3141 	/* GET_DATA isn't needed any more with USER_COPY or ZERO COPY */
3142 	if (ub->dev_info.flags & (UBLK_F_USER_COPY | UBLK_F_SUPPORT_ZERO_COPY |
3143 				UBLK_F_AUTO_BUF_REG))
3144 		ub->dev_info.flags &= ~UBLK_F_NEED_GET_DATA;
3145 
3146 	/*
3147 	 * Zoned storage support requires reuse `ublksrv_io_cmd->addr` for
3148 	 * returning write_append_lba, which is only allowed in case of
3149 	 * user copy or zero copy
3150 	 */
3151 	if (ublk_dev_is_zoned(ub) &&
3152 	    (!IS_ENABLED(CONFIG_BLK_DEV_ZONED) || !(ub->dev_info.flags &
3153 	     (UBLK_F_USER_COPY | UBLK_F_SUPPORT_ZERO_COPY)))) {
3154 		ret = -EINVAL;
3155 		goto out_free_dev_number;
3156 	}
3157 
3158 	ub->dev_info.nr_hw_queues = min_t(unsigned int,
3159 			ub->dev_info.nr_hw_queues, nr_cpu_ids);
3160 	ublk_align_max_io_size(ub);
3161 
3162 	ret = ublk_add_tag_set(ub);
3163 	if (ret)
3164 		goto out_free_dev_number;
3165 
3166 	ret = ublk_init_queues(ub);
3167 	if (ret)
3168 		goto out_free_tag_set;
3169 
3170 	ret = -EFAULT;
3171 	if (copy_to_user(argp, &ub->dev_info, sizeof(info)))
3172 		goto out_deinit_queues;
3173 
3174 	/*
3175 	 * Add the char dev so that ublksrv daemon can be setup.
3176 	 * ublk_add_chdev() will cleanup everything if it fails.
3177 	 */
3178 	ret = ublk_add_chdev(ub);
3179 	goto out_unlock;
3180 
3181 out_deinit_queues:
3182 	ublk_deinit_queues(ub);
3183 out_free_tag_set:
3184 	blk_mq_free_tag_set(&ub->tag_set);
3185 out_free_dev_number:
3186 	ublk_free_dev_number(ub);
3187 out_free_ub:
3188 	mutex_destroy(&ub->mutex);
3189 	mutex_destroy(&ub->cancel_mutex);
3190 	kfree(ub);
3191 out_unlock:
3192 	mutex_unlock(&ublk_ctl_mutex);
3193 	return ret;
3194 }
3195 
3196 static inline bool ublk_idr_freed(int id)
3197 {
3198 	void *ptr;
3199 
3200 	spin_lock(&ublk_idr_lock);
3201 	ptr = idr_find(&ublk_index_idr, id);
3202 	spin_unlock(&ublk_idr_lock);
3203 
3204 	return ptr == NULL;
3205 }
3206 
3207 static int ublk_ctrl_del_dev(struct ublk_device **p_ub, bool wait)
3208 {
3209 	struct ublk_device *ub = *p_ub;
3210 	int idx = ub->ub_number;
3211 	int ret;
3212 
3213 	ret = mutex_lock_killable(&ublk_ctl_mutex);
3214 	if (ret)
3215 		return ret;
3216 
3217 	if (!test_bit(UB_STATE_DELETED, &ub->state)) {
3218 		ublk_remove(ub);
3219 		set_bit(UB_STATE_DELETED, &ub->state);
3220 	}
3221 
3222 	/* Mark the reference as consumed */
3223 	*p_ub = NULL;
3224 	ublk_put_device(ub);
3225 	mutex_unlock(&ublk_ctl_mutex);
3226 
3227 	/*
3228 	 * Wait until the idr is removed, then it can be reused after
3229 	 * DEL_DEV command is returned.
3230 	 *
3231 	 * If we returns because of user interrupt, future delete command
3232 	 * may come:
3233 	 *
3234 	 * - the device number isn't freed, this device won't or needn't
3235 	 *   be deleted again, since UB_STATE_DELETED is set, and device
3236 	 *   will be released after the last reference is dropped
3237 	 *
3238 	 * - the device number is freed already, we will not find this
3239 	 *   device via ublk_get_device_from_id()
3240 	 */
3241 	if (wait && wait_event_interruptible(ublk_idr_wq, ublk_idr_freed(idx)))
3242 		return -EINTR;
3243 	return 0;
3244 }
3245 
3246 static inline void ublk_ctrl_cmd_dump(struct io_uring_cmd *cmd)
3247 {
3248 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
3249 
3250 	pr_devel("%s: cmd_op %x, dev id %d qid %d data %llx buf %llx len %u\n",
3251 			__func__, cmd->cmd_op, header->dev_id, header->queue_id,
3252 			header->data[0], header->addr, header->len);
3253 }
3254 
3255 static int ublk_ctrl_stop_dev(struct ublk_device *ub)
3256 {
3257 	ublk_stop_dev(ub);
3258 	return 0;
3259 }
3260 
3261 static int ublk_ctrl_get_dev_info(struct ublk_device *ub,
3262 		const struct ublksrv_ctrl_cmd *header)
3263 {
3264 	void __user *argp = (void __user *)(unsigned long)header->addr;
3265 
3266 	if (header->len < sizeof(struct ublksrv_ctrl_dev_info) || !header->addr)
3267 		return -EINVAL;
3268 
3269 	if (copy_to_user(argp, &ub->dev_info, sizeof(ub->dev_info)))
3270 		return -EFAULT;
3271 
3272 	return 0;
3273 }
3274 
3275 /* TYPE_DEVT is readonly, so fill it up before returning to userspace */
3276 static void ublk_ctrl_fill_params_devt(struct ublk_device *ub)
3277 {
3278 	ub->params.devt.char_major = MAJOR(ub->cdev_dev.devt);
3279 	ub->params.devt.char_minor = MINOR(ub->cdev_dev.devt);
3280 
3281 	if (ub->ub_disk) {
3282 		ub->params.devt.disk_major = MAJOR(disk_devt(ub->ub_disk));
3283 		ub->params.devt.disk_minor = MINOR(disk_devt(ub->ub_disk));
3284 	} else {
3285 		ub->params.devt.disk_major = 0;
3286 		ub->params.devt.disk_minor = 0;
3287 	}
3288 	ub->params.types |= UBLK_PARAM_TYPE_DEVT;
3289 }
3290 
3291 static int ublk_ctrl_get_params(struct ublk_device *ub,
3292 		const struct ublksrv_ctrl_cmd *header)
3293 {
3294 	void __user *argp = (void __user *)(unsigned long)header->addr;
3295 	struct ublk_params_header ph;
3296 	int ret;
3297 
3298 	if (header->len <= sizeof(ph) || !header->addr)
3299 		return -EINVAL;
3300 
3301 	if (copy_from_user(&ph, argp, sizeof(ph)))
3302 		return -EFAULT;
3303 
3304 	if (ph.len > header->len || !ph.len)
3305 		return -EINVAL;
3306 
3307 	if (ph.len > sizeof(struct ublk_params))
3308 		ph.len = sizeof(struct ublk_params);
3309 
3310 	mutex_lock(&ub->mutex);
3311 	ublk_ctrl_fill_params_devt(ub);
3312 	if (copy_to_user(argp, &ub->params, ph.len))
3313 		ret = -EFAULT;
3314 	else
3315 		ret = 0;
3316 	mutex_unlock(&ub->mutex);
3317 
3318 	return ret;
3319 }
3320 
3321 static int ublk_ctrl_set_params(struct ublk_device *ub,
3322 		const struct ublksrv_ctrl_cmd *header)
3323 {
3324 	void __user *argp = (void __user *)(unsigned long)header->addr;
3325 	struct ublk_params_header ph;
3326 	int ret = -EFAULT;
3327 
3328 	if (header->len <= sizeof(ph) || !header->addr)
3329 		return -EINVAL;
3330 
3331 	if (copy_from_user(&ph, argp, sizeof(ph)))
3332 		return -EFAULT;
3333 
3334 	if (ph.len > header->len || !ph.len || !ph.types)
3335 		return -EINVAL;
3336 
3337 	if (ph.len > sizeof(struct ublk_params))
3338 		ph.len = sizeof(struct ublk_params);
3339 
3340 	mutex_lock(&ub->mutex);
3341 	if (test_bit(UB_STATE_USED, &ub->state)) {
3342 		/*
3343 		 * Parameters can only be changed when device hasn't
3344 		 * been started yet
3345 		 */
3346 		ret = -EACCES;
3347 	} else if (copy_from_user(&ub->params, argp, ph.len)) {
3348 		ret = -EFAULT;
3349 	} else {
3350 		/* clear all we don't support yet */
3351 		ub->params.types &= UBLK_PARAM_TYPE_ALL;
3352 		ret = ublk_validate_params(ub);
3353 		if (ret)
3354 			ub->params.types = 0;
3355 	}
3356 	mutex_unlock(&ub->mutex);
3357 
3358 	return ret;
3359 }
3360 
3361 static int ublk_ctrl_start_recovery(struct ublk_device *ub,
3362 		const struct ublksrv_ctrl_cmd *header)
3363 {
3364 	int ret = -EINVAL;
3365 
3366 	mutex_lock(&ub->mutex);
3367 	if (ublk_nosrv_should_stop_dev(ub))
3368 		goto out_unlock;
3369 	/*
3370 	 * START_RECOVERY is only allowd after:
3371 	 *
3372 	 * (1) UB_STATE_OPEN is not set, which means the dying process is exited
3373 	 *     and related io_uring ctx is freed so file struct of /dev/ublkcX is
3374 	 *     released.
3375 	 *
3376 	 * and one of the following holds
3377 	 *
3378 	 * (2) UBLK_S_DEV_QUIESCED is set, which means the quiesce_work:
3379 	 *     (a)has quiesced request queue
3380 	 *     (b)has requeued every inflight rqs whose io_flags is ACTIVE
3381 	 *     (c)has requeued/aborted every inflight rqs whose io_flags is NOT ACTIVE
3382 	 *     (d)has completed/camceled all ioucmds owned by ther dying process
3383 	 *
3384 	 * (3) UBLK_S_DEV_FAIL_IO is set, which means the queue is not
3385 	 *     quiesced, but all I/O is being immediately errored
3386 	 */
3387 	if (test_bit(UB_STATE_OPEN, &ub->state) || !ublk_dev_in_recoverable_state(ub)) {
3388 		ret = -EBUSY;
3389 		goto out_unlock;
3390 	}
3391 	pr_devel("%s: start recovery for dev id %d.\n", __func__, header->dev_id);
3392 	init_completion(&ub->completion);
3393 	ret = 0;
3394  out_unlock:
3395 	mutex_unlock(&ub->mutex);
3396 	return ret;
3397 }
3398 
3399 static int ublk_ctrl_end_recovery(struct ublk_device *ub,
3400 		const struct ublksrv_ctrl_cmd *header)
3401 {
3402 	int ublksrv_pid = (int)header->data[0];
3403 	int ret = -EINVAL;
3404 
3405 	pr_devel("%s: Waiting for all FETCH_REQs, dev id %d...\n", __func__,
3406 		 header->dev_id);
3407 
3408 	if (wait_for_completion_interruptible(&ub->completion))
3409 		return -EINTR;
3410 
3411 	pr_devel("%s: All FETCH_REQs received, dev id %d\n", __func__,
3412 		 header->dev_id);
3413 
3414 	if (ub->ublksrv_tgid != ublksrv_pid)
3415 		return -EINVAL;
3416 
3417 	mutex_lock(&ub->mutex);
3418 	if (ublk_nosrv_should_stop_dev(ub))
3419 		goto out_unlock;
3420 
3421 	if (!ublk_dev_in_recoverable_state(ub)) {
3422 		ret = -EBUSY;
3423 		goto out_unlock;
3424 	}
3425 	ub->dev_info.ublksrv_pid = ublksrv_pid;
3426 	ub->dev_info.state = UBLK_S_DEV_LIVE;
3427 	pr_devel("%s: new ublksrv_pid %d, dev id %d\n",
3428 			__func__, ublksrv_pid, header->dev_id);
3429 	blk_mq_kick_requeue_list(ub->ub_disk->queue);
3430 	ret = 0;
3431  out_unlock:
3432 	mutex_unlock(&ub->mutex);
3433 	return ret;
3434 }
3435 
3436 static int ublk_ctrl_get_features(const struct ublksrv_ctrl_cmd *header)
3437 {
3438 	void __user *argp = (void __user *)(unsigned long)header->addr;
3439 	u64 features = UBLK_F_ALL;
3440 
3441 	if (header->len != UBLK_FEATURES_LEN || !header->addr)
3442 		return -EINVAL;
3443 
3444 	if (copy_to_user(argp, &features, UBLK_FEATURES_LEN))
3445 		return -EFAULT;
3446 
3447 	return 0;
3448 }
3449 
3450 static void ublk_ctrl_set_size(struct ublk_device *ub, const struct ublksrv_ctrl_cmd *header)
3451 {
3452 	struct ublk_param_basic *p = &ub->params.basic;
3453 	u64 new_size = header->data[0];
3454 
3455 	mutex_lock(&ub->mutex);
3456 	p->dev_sectors = new_size;
3457 	set_capacity_and_notify(ub->ub_disk, p->dev_sectors);
3458 	mutex_unlock(&ub->mutex);
3459 }
3460 
3461 struct count_busy {
3462 	const struct ublk_queue *ubq;
3463 	unsigned int nr_busy;
3464 };
3465 
3466 static bool ublk_count_busy_req(struct request *rq, void *data)
3467 {
3468 	struct count_busy *idle = data;
3469 
3470 	if (!blk_mq_request_started(rq) && rq->mq_hctx->driver_data == idle->ubq)
3471 		idle->nr_busy += 1;
3472 	return true;
3473 }
3474 
3475 /* uring_cmd is guaranteed to be active if the associated request is idle */
3476 static bool ubq_has_idle_io(const struct ublk_queue *ubq)
3477 {
3478 	struct count_busy data = {
3479 		.ubq = ubq,
3480 	};
3481 
3482 	blk_mq_tagset_busy_iter(&ubq->dev->tag_set, ublk_count_busy_req, &data);
3483 	return data.nr_busy < ubq->q_depth;
3484 }
3485 
3486 /* Wait until each hw queue has at least one idle IO */
3487 static int ublk_wait_for_idle_io(struct ublk_device *ub,
3488 				 unsigned int timeout_ms)
3489 {
3490 	unsigned int elapsed = 0;
3491 	int ret;
3492 
3493 	while (elapsed < timeout_ms && !signal_pending(current)) {
3494 		unsigned int queues_cancelable = 0;
3495 		int i;
3496 
3497 		for (i = 0; i < ub->dev_info.nr_hw_queues; i++) {
3498 			struct ublk_queue *ubq = ublk_get_queue(ub, i);
3499 
3500 			queues_cancelable += !!ubq_has_idle_io(ubq);
3501 		}
3502 
3503 		/*
3504 		 * Each queue needs at least one active command for
3505 		 * notifying ublk server
3506 		 */
3507 		if (queues_cancelable == ub->dev_info.nr_hw_queues)
3508 			break;
3509 
3510 		msleep(UBLK_REQUEUE_DELAY_MS);
3511 		elapsed += UBLK_REQUEUE_DELAY_MS;
3512 	}
3513 
3514 	if (signal_pending(current))
3515 		ret = -EINTR;
3516 	else if (elapsed >= timeout_ms)
3517 		ret = -EBUSY;
3518 	else
3519 		ret = 0;
3520 
3521 	return ret;
3522 }
3523 
3524 static int ublk_ctrl_quiesce_dev(struct ublk_device *ub,
3525 				 const struct ublksrv_ctrl_cmd *header)
3526 {
3527 	/* zero means wait forever */
3528 	u64 timeout_ms = header->data[0];
3529 	struct gendisk *disk;
3530 	int ret = -ENODEV;
3531 
3532 	if (!(ub->dev_info.flags & UBLK_F_QUIESCE))
3533 		return -EOPNOTSUPP;
3534 
3535 	mutex_lock(&ub->mutex);
3536 	disk = ublk_get_disk(ub);
3537 	if (!disk)
3538 		goto unlock;
3539 	if (ub->dev_info.state == UBLK_S_DEV_DEAD)
3540 		goto put_disk;
3541 
3542 	ret = 0;
3543 	/* already in expected state */
3544 	if (ub->dev_info.state != UBLK_S_DEV_LIVE)
3545 		goto put_disk;
3546 
3547 	/* Mark the device as canceling */
3548 	mutex_lock(&ub->cancel_mutex);
3549 	blk_mq_quiesce_queue(disk->queue);
3550 	ublk_set_canceling(ub, true);
3551 	blk_mq_unquiesce_queue(disk->queue);
3552 	mutex_unlock(&ub->cancel_mutex);
3553 
3554 	if (!timeout_ms)
3555 		timeout_ms = UINT_MAX;
3556 	ret = ublk_wait_for_idle_io(ub, timeout_ms);
3557 
3558 put_disk:
3559 	ublk_put_disk(disk);
3560 unlock:
3561 	mutex_unlock(&ub->mutex);
3562 
3563 	/* Cancel pending uring_cmd */
3564 	if (!ret)
3565 		ublk_cancel_dev(ub);
3566 	return ret;
3567 }
3568 
3569 /*
3570  * All control commands are sent via /dev/ublk-control, so we have to check
3571  * the destination device's permission
3572  */
3573 static int ublk_char_dev_permission(struct ublk_device *ub,
3574 		const char *dev_path, int mask)
3575 {
3576 	int err;
3577 	struct path path;
3578 	struct kstat stat;
3579 
3580 	err = kern_path(dev_path, LOOKUP_FOLLOW, &path);
3581 	if (err)
3582 		return err;
3583 
3584 	err = vfs_getattr(&path, &stat, STATX_TYPE, AT_STATX_SYNC_AS_STAT);
3585 	if (err)
3586 		goto exit;
3587 
3588 	err = -EPERM;
3589 	if (stat.rdev != ub->cdev_dev.devt || !S_ISCHR(stat.mode))
3590 		goto exit;
3591 
3592 	err = inode_permission(&nop_mnt_idmap,
3593 			d_backing_inode(path.dentry), mask);
3594 exit:
3595 	path_put(&path);
3596 	return err;
3597 }
3598 
3599 static int ublk_ctrl_uring_cmd_permission(struct ublk_device *ub,
3600 		struct io_uring_cmd *cmd)
3601 {
3602 	struct ublksrv_ctrl_cmd *header = (struct ublksrv_ctrl_cmd *)io_uring_sqe_cmd(cmd->sqe);
3603 	bool unprivileged = ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV;
3604 	void __user *argp = (void __user *)(unsigned long)header->addr;
3605 	char *dev_path = NULL;
3606 	int ret = 0;
3607 	int mask;
3608 
3609 	if (!unprivileged) {
3610 		if (!capable(CAP_SYS_ADMIN))
3611 			return -EPERM;
3612 		/*
3613 		 * The new added command of UBLK_CMD_GET_DEV_INFO2 includes
3614 		 * char_dev_path in payload too, since userspace may not
3615 		 * know if the specified device is created as unprivileged
3616 		 * mode.
3617 		 */
3618 		if (_IOC_NR(cmd->cmd_op) != UBLK_CMD_GET_DEV_INFO2)
3619 			return 0;
3620 	}
3621 
3622 	/*
3623 	 * User has to provide the char device path for unprivileged ublk
3624 	 *
3625 	 * header->addr always points to the dev path buffer, and
3626 	 * header->dev_path_len records length of dev path buffer.
3627 	 */
3628 	if (!header->dev_path_len || header->dev_path_len > PATH_MAX)
3629 		return -EINVAL;
3630 
3631 	if (header->len < header->dev_path_len)
3632 		return -EINVAL;
3633 
3634 	dev_path = memdup_user_nul(argp, header->dev_path_len);
3635 	if (IS_ERR(dev_path))
3636 		return PTR_ERR(dev_path);
3637 
3638 	ret = -EINVAL;
3639 	switch (_IOC_NR(cmd->cmd_op)) {
3640 	case UBLK_CMD_GET_DEV_INFO:
3641 	case UBLK_CMD_GET_DEV_INFO2:
3642 	case UBLK_CMD_GET_QUEUE_AFFINITY:
3643 	case UBLK_CMD_GET_PARAMS:
3644 	case (_IOC_NR(UBLK_U_CMD_GET_FEATURES)):
3645 		mask = MAY_READ;
3646 		break;
3647 	case UBLK_CMD_START_DEV:
3648 	case UBLK_CMD_STOP_DEV:
3649 	case UBLK_CMD_ADD_DEV:
3650 	case UBLK_CMD_DEL_DEV:
3651 	case UBLK_CMD_SET_PARAMS:
3652 	case UBLK_CMD_START_USER_RECOVERY:
3653 	case UBLK_CMD_END_USER_RECOVERY:
3654 	case UBLK_CMD_UPDATE_SIZE:
3655 	case UBLK_CMD_QUIESCE_DEV:
3656 		mask = MAY_READ | MAY_WRITE;
3657 		break;
3658 	default:
3659 		goto exit;
3660 	}
3661 
3662 	ret = ublk_char_dev_permission(ub, dev_path, mask);
3663 	if (!ret) {
3664 		header->len -= header->dev_path_len;
3665 		header->addr += header->dev_path_len;
3666 	}
3667 	pr_devel("%s: dev id %d cmd_op %x uid %d gid %d path %s ret %d\n",
3668 			__func__, ub->ub_number, cmd->cmd_op,
3669 			ub->dev_info.owner_uid, ub->dev_info.owner_gid,
3670 			dev_path, ret);
3671 exit:
3672 	kfree(dev_path);
3673 	return ret;
3674 }
3675 
3676 static int ublk_ctrl_uring_cmd(struct io_uring_cmd *cmd,
3677 		unsigned int issue_flags)
3678 {
3679 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
3680 	struct ublk_device *ub = NULL;
3681 	u32 cmd_op = cmd->cmd_op;
3682 	int ret = -EINVAL;
3683 
3684 	if (issue_flags & IO_URING_F_NONBLOCK)
3685 		return -EAGAIN;
3686 
3687 	ublk_ctrl_cmd_dump(cmd);
3688 
3689 	if (!(issue_flags & IO_URING_F_SQE128))
3690 		goto out;
3691 
3692 	ret = ublk_check_cmd_op(cmd_op);
3693 	if (ret)
3694 		goto out;
3695 
3696 	if (cmd_op == UBLK_U_CMD_GET_FEATURES) {
3697 		ret = ublk_ctrl_get_features(header);
3698 		goto out;
3699 	}
3700 
3701 	if (_IOC_NR(cmd_op) != UBLK_CMD_ADD_DEV) {
3702 		ret = -ENODEV;
3703 		ub = ublk_get_device_from_id(header->dev_id);
3704 		if (!ub)
3705 			goto out;
3706 
3707 		ret = ublk_ctrl_uring_cmd_permission(ub, cmd);
3708 		if (ret)
3709 			goto put_dev;
3710 	}
3711 
3712 	switch (_IOC_NR(cmd_op)) {
3713 	case UBLK_CMD_START_DEV:
3714 		ret = ublk_ctrl_start_dev(ub, header);
3715 		break;
3716 	case UBLK_CMD_STOP_DEV:
3717 		ret = ublk_ctrl_stop_dev(ub);
3718 		break;
3719 	case UBLK_CMD_GET_DEV_INFO:
3720 	case UBLK_CMD_GET_DEV_INFO2:
3721 		ret = ublk_ctrl_get_dev_info(ub, header);
3722 		break;
3723 	case UBLK_CMD_ADD_DEV:
3724 		ret = ublk_ctrl_add_dev(header);
3725 		break;
3726 	case UBLK_CMD_DEL_DEV:
3727 		ret = ublk_ctrl_del_dev(&ub, true);
3728 		break;
3729 	case UBLK_CMD_DEL_DEV_ASYNC:
3730 		ret = ublk_ctrl_del_dev(&ub, false);
3731 		break;
3732 	case UBLK_CMD_GET_QUEUE_AFFINITY:
3733 		ret = ublk_ctrl_get_queue_affinity(ub, header);
3734 		break;
3735 	case UBLK_CMD_GET_PARAMS:
3736 		ret = ublk_ctrl_get_params(ub, header);
3737 		break;
3738 	case UBLK_CMD_SET_PARAMS:
3739 		ret = ublk_ctrl_set_params(ub, header);
3740 		break;
3741 	case UBLK_CMD_START_USER_RECOVERY:
3742 		ret = ublk_ctrl_start_recovery(ub, header);
3743 		break;
3744 	case UBLK_CMD_END_USER_RECOVERY:
3745 		ret = ublk_ctrl_end_recovery(ub, header);
3746 		break;
3747 	case UBLK_CMD_UPDATE_SIZE:
3748 		ublk_ctrl_set_size(ub, header);
3749 		ret = 0;
3750 		break;
3751 	case UBLK_CMD_QUIESCE_DEV:
3752 		ret = ublk_ctrl_quiesce_dev(ub, header);
3753 		break;
3754 	default:
3755 		ret = -EOPNOTSUPP;
3756 		break;
3757 	}
3758 
3759  put_dev:
3760 	if (ub)
3761 		ublk_put_device(ub);
3762  out:
3763 	pr_devel("%s: cmd done ret %d cmd_op %x, dev id %d qid %d\n",
3764 			__func__, ret, cmd->cmd_op, header->dev_id, header->queue_id);
3765 	return ret;
3766 }
3767 
3768 static const struct file_operations ublk_ctl_fops = {
3769 	.open		= nonseekable_open,
3770 	.uring_cmd      = ublk_ctrl_uring_cmd,
3771 	.owner		= THIS_MODULE,
3772 	.llseek		= noop_llseek,
3773 };
3774 
3775 static struct miscdevice ublk_misc = {
3776 	.minor		= MISC_DYNAMIC_MINOR,
3777 	.name		= "ublk-control",
3778 	.fops		= &ublk_ctl_fops,
3779 };
3780 
3781 static int __init ublk_init(void)
3782 {
3783 	int ret;
3784 
3785 	BUILD_BUG_ON((u64)UBLKSRV_IO_BUF_OFFSET +
3786 			UBLKSRV_IO_BUF_TOTAL_SIZE < UBLKSRV_IO_BUF_OFFSET);
3787 	BUILD_BUG_ON(sizeof(struct ublk_auto_buf_reg) != 8);
3788 
3789 	init_waitqueue_head(&ublk_idr_wq);
3790 
3791 	ret = misc_register(&ublk_misc);
3792 	if (ret)
3793 		return ret;
3794 
3795 	ret = alloc_chrdev_region(&ublk_chr_devt, 0, UBLK_MINORS, "ublk-char");
3796 	if (ret)
3797 		goto unregister_mis;
3798 
3799 	ret = class_register(&ublk_chr_class);
3800 	if (ret)
3801 		goto free_chrdev_region;
3802 
3803 	return 0;
3804 
3805 free_chrdev_region:
3806 	unregister_chrdev_region(ublk_chr_devt, UBLK_MINORS);
3807 unregister_mis:
3808 	misc_deregister(&ublk_misc);
3809 	return ret;
3810 }
3811 
3812 static void __exit ublk_exit(void)
3813 {
3814 	struct ublk_device *ub;
3815 	int id;
3816 
3817 	idr_for_each_entry(&ublk_index_idr, ub, id)
3818 		ublk_remove(ub);
3819 
3820 	class_unregister(&ublk_chr_class);
3821 	misc_deregister(&ublk_misc);
3822 
3823 	idr_destroy(&ublk_index_idr);
3824 	unregister_chrdev_region(ublk_chr_devt, UBLK_MINORS);
3825 }
3826 
3827 module_init(ublk_init);
3828 module_exit(ublk_exit);
3829 
3830 static int ublk_set_max_unprivileged_ublks(const char *buf,
3831 					   const struct kernel_param *kp)
3832 {
3833 	return param_set_uint_minmax(buf, kp, 0, UBLK_MAX_UBLKS);
3834 }
3835 
3836 static int ublk_get_max_unprivileged_ublks(char *buf,
3837 					   const struct kernel_param *kp)
3838 {
3839 	return sysfs_emit(buf, "%u\n", unprivileged_ublks_max);
3840 }
3841 
3842 static const struct kernel_param_ops ublk_max_unprivileged_ublks_ops = {
3843 	.set = ublk_set_max_unprivileged_ublks,
3844 	.get = ublk_get_max_unprivileged_ublks,
3845 };
3846 
3847 module_param_cb(ublks_max, &ublk_max_unprivileged_ublks_ops,
3848 		&unprivileged_ublks_max, 0644);
3849 MODULE_PARM_DESC(ublks_max, "max number of unprivileged ublk devices allowed to add(default: 64)");
3850 
3851 MODULE_AUTHOR("Ming Lei <ming.lei@redhat.com>");
3852 MODULE_DESCRIPTION("Userspace block device");
3853 MODULE_LICENSE("GPL");
3854