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