xref: /linux/drivers/block/ublk_drv.c (revision b23545529c21737dd7939e86b6f649f06480796d)
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/wait_bit.h>
23 #include <linux/blkdev.h>
24 #include <linux/init.h>
25 #include <linux/swap.h>
26 #include <linux/slab.h>
27 #include <linux/compat.h>
28 #include <linux/mutex.h>
29 #include <linux/writeback.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 <linux/kfifo.h>
48 #include <linux/blk-integrity.h>
49 #include <linux/maple_tree.h>
50 #include <linux/xarray.h>
51 #include <uapi/linux/fs.h>
52 #include <uapi/linux/ublk_cmd.h>
53 
54 #define UBLK_MINORS		(1U << MINORBITS)
55 
56 #define UBLK_INVALID_BUF_IDX 	((u16)-1)
57 
58 /* private ioctl command mirror */
59 #define UBLK_CMD_DEL_DEV_ASYNC	_IOC_NR(UBLK_U_CMD_DEL_DEV_ASYNC)
60 #define UBLK_CMD_UPDATE_SIZE	_IOC_NR(UBLK_U_CMD_UPDATE_SIZE)
61 #define UBLK_CMD_QUIESCE_DEV	_IOC_NR(UBLK_U_CMD_QUIESCE_DEV)
62 #define UBLK_CMD_TRY_STOP_DEV	_IOC_NR(UBLK_U_CMD_TRY_STOP_DEV)
63 #define UBLK_CMD_REG_BUF	_IOC_NR(UBLK_U_CMD_REG_BUF)
64 #define UBLK_CMD_UNREG_BUF	_IOC_NR(UBLK_U_CMD_UNREG_BUF)
65 
66 /* Default max shmem buffer size: 4GB (may be increased in future) */
67 #define UBLK_SHMEM_BUF_SIZE_MAX	(1ULL << 32)
68 
69 #define UBLK_IO_REGISTER_IO_BUF		_IOC_NR(UBLK_U_IO_REGISTER_IO_BUF)
70 #define UBLK_IO_UNREGISTER_IO_BUF	_IOC_NR(UBLK_U_IO_UNREGISTER_IO_BUF)
71 
72 /* All UBLK_F_* have to be included into UBLK_F_ALL */
73 #define UBLK_F_ALL (UBLK_F_SUPPORT_ZERO_COPY \
74 		| UBLK_F_URING_CMD_COMP_IN_TASK \
75 		| UBLK_F_NEED_GET_DATA \
76 		| UBLK_F_USER_RECOVERY \
77 		| UBLK_F_USER_RECOVERY_REISSUE \
78 		| UBLK_F_UNPRIVILEGED_DEV \
79 		| UBLK_F_CMD_IOCTL_ENCODE \
80 		| UBLK_F_USER_COPY \
81 		| UBLK_F_ZONED \
82 		| UBLK_F_USER_RECOVERY_FAIL_IO \
83 		| UBLK_F_UPDATE_SIZE \
84 		| UBLK_F_AUTO_BUF_REG \
85 		| UBLK_F_QUIESCE \
86 		| UBLK_F_PER_IO_DAEMON \
87 		| UBLK_F_BUF_REG_OFF_DAEMON \
88 		| (IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY) ? UBLK_F_INTEGRITY : 0) \
89 		| UBLK_F_SAFE_STOP_DEV \
90 		| UBLK_F_BATCH_IO \
91 		| UBLK_F_NO_AUTO_PART_SCAN \
92 		| UBLK_F_SHMEM_ZC \
93 		| UBLK_F_IO_DESC_SIZE)
94 
95 #define UBLK_F_ALL_RECOVERY_FLAGS (UBLK_F_USER_RECOVERY \
96 		| UBLK_F_USER_RECOVERY_REISSUE \
97 		| UBLK_F_USER_RECOVERY_FAIL_IO)
98 
99 /* All UBLK_PARAM_TYPE_* should be included here */
100 #define UBLK_PARAM_TYPE_ALL                                \
101 	(UBLK_PARAM_TYPE_BASIC | UBLK_PARAM_TYPE_DISCARD | \
102 	 UBLK_PARAM_TYPE_DEVT | UBLK_PARAM_TYPE_ZONED |    \
103 	 UBLK_PARAM_TYPE_DMA_ALIGN | UBLK_PARAM_TYPE_SEGMENT | \
104 	 UBLK_PARAM_TYPE_INTEGRITY)
105 
106 #define UBLK_BATCH_F_ALL  \
107 	(UBLK_BATCH_F_HAS_ZONE_LBA | \
108 	 UBLK_BATCH_F_HAS_BUF_ADDR | \
109 	 UBLK_BATCH_F_AUTO_BUF_REG_FALLBACK)
110 
111 #define UBLK_MAX_IO_DESC_SIZE 256
112 
113 /* ublk batch fetch uring_cmd */
114 struct ublk_batch_fetch_cmd {
115 	struct list_head node;
116 	struct io_uring_cmd *cmd;
117 	unsigned short buf_group;
118 };
119 
120 struct ublk_uring_cmd_pdu {
121 	/*
122 	 * Store requests in same batch temporarily for queuing them to
123 	 * daemon context.
124 	 *
125 	 * It should have been stored to request payload, but we do want
126 	 * to avoid extra pre-allocation, and uring_cmd payload is always
127 	 * free for us
128 	 */
129 	union {
130 		struct request *req;
131 		struct request *req_list;
132 	};
133 
134 	/*
135 	 * The following two are valid in this cmd whole lifetime, and
136 	 * setup in ublk uring_cmd handler
137 	 */
138 	struct ublk_queue *ubq;
139 
140 	union {
141 		u16 tag;
142 		struct ublk_batch_fetch_cmd *fcmd; /* batch io only */
143 	};
144 };
145 
146 struct ublk_batch_io_data {
147 	struct ublk_device *ub;
148 	struct io_uring_cmd *cmd;
149 	struct ublk_batch_io header;
150 	unsigned int issue_flags;
151 	struct io_comp_batch *iob;
152 };
153 
154 /*
155  * io command is active: sqe cmd is received, and its cqe isn't done
156  *
157  * If the flag is set, the io command is owned by ublk driver, and waited
158  * for incoming blk-mq request from the ublk block device.
159  *
160  * If the flag is cleared, the io command will be completed, and owned by
161  * ublk server.
162  */
163 #define UBLK_IO_FLAG_ACTIVE	0x01
164 
165 /*
166  * IO command is completed via cqe, and it is being handled by ublksrv, and
167  * not committed yet
168  *
169  * Basically exclusively with UBLK_IO_FLAG_ACTIVE, so can be served for
170  * cross verification
171  */
172 #define UBLK_IO_FLAG_OWNED_BY_SRV 0x02
173 
174 /*
175  * UBLK_IO_FLAG_NEED_GET_DATA is set because IO command requires
176  * get data buffer address from ublksrv.
177  *
178  * Then, bio data could be copied into this data buffer for a WRITE request
179  * after the IO command is issued again and UBLK_IO_FLAG_NEED_GET_DATA is unset.
180  */
181 #define UBLK_IO_FLAG_NEED_GET_DATA 0x08
182 
183 /*
184  * request buffer is registered automatically, so we have to unregister it
185  * before completing this request.
186  *
187  * io_uring will unregister buffer automatically for us during exiting.
188  */
189 #define UBLK_IO_FLAG_AUTO_BUF_REG 	0x10
190 
191 /* atomic RW with ubq->cancel_lock */
192 #define UBLK_IO_FLAG_CANCELED	0x80000000
193 
194 /*
195  * Initialize refcount to a large number to include any registered buffers.
196  * UBLK_IO_COMMIT_AND_FETCH_REQ will release these references minus those for
197  * any buffers registered on the io daemon task.
198  */
199 #define UBLK_REFCOUNT_INIT (REFCOUNT_MAX / 2)
200 
201 /* used for UBLK_F_BATCH_IO only */
202 #define UBLK_BATCH_IO_UNUSED_TAG	((unsigned short)-1)
203 
204 union ublk_io_buf {
205 	__u64	addr;
206 	struct ublk_auto_buf_reg auto_reg;
207 };
208 
209 struct ublk_io {
210 	union ublk_io_buf buf;
211 	unsigned int flags;
212 	int res;
213 
214 	union {
215 		/* valid if UBLK_IO_FLAG_ACTIVE is set */
216 		struct io_uring_cmd *cmd;
217 		/* valid if UBLK_IO_FLAG_OWNED_BY_SRV is set */
218 		struct request *req;
219 	};
220 
221 	struct task_struct *task;
222 
223 	/*
224 	 * The number of uses of this I/O by the ublk server
225 	 * if user copy or zero copy are enabled:
226 	 * - UBLK_REFCOUNT_INIT from dispatch to the server
227 	 *   until UBLK_IO_COMMIT_AND_FETCH_REQ
228 	 * - 1 for each inflight ublk_ch_{read,write}_iter() call not on task
229 	 * - 1 for each io_uring registered buffer not registered on task
230 	 * The I/O can only be completed once all references are dropped.
231 	 * User copy and buffer registration operations are only permitted
232 	 * if the reference count is nonzero.
233 	 */
234 	refcount_t ref;
235 	/* Count of buffers registered on task and not yet unregistered */
236 	unsigned task_registered_buffers;
237 
238 	void *buf_ctx_handle;
239 	spinlock_t lock;
240 } ____cacheline_aligned_in_smp;
241 
242 struct ublk_queue {
243 	u16 q_id;
244 	u16 q_depth;
245 	u16 io_desc_size;
246 
247 	unsigned long flags;
248 	struct ublksrv_io_desc *io_cmd_buf;
249 
250 	bool force_abort;
251 	bool canceling;
252 	bool fail_io; /* copy of dev->state == UBLK_S_DEV_FAIL_IO */
253 	spinlock_t		cancel_lock;
254 	struct ublk_device *dev;
255 	u16 nr_io_ready;
256 
257 	/*
258 	 * For supporting UBLK_F_BATCH_IO only.
259 	 *
260 	 * Inflight ublk request tag is saved in this fifo
261 	 *
262 	 * There are multiple writer from ublk_queue_rq() or ublk_queue_rqs(),
263 	 * so lock is required for storing request tag to fifo
264 	 *
265 	 * Make sure just one reader for fetching request from task work
266 	 * function to ublk server, so no need to grab the lock in reader
267 	 * side.
268 	 *
269 	 * Batch I/O State Management:
270 	 *
271 	 * The batch I/O system uses implicit state management based on the
272 	 * combination of three key variables below.
273 	 *
274 	 * - IDLE: list_empty(&fcmd_head) && !active_fcmd
275 	 *   No fetch commands available, events queue in evts_fifo
276 	 *
277 	 * - READY: !list_empty(&fcmd_head) && !active_fcmd
278 	 *   Fetch commands available but none processing events
279 	 *
280 	 * - ACTIVE: active_fcmd
281 	 *   One fetch command actively processing events from evts_fifo
282 	 *
283 	 * Key Invariants:
284 	 * - At most one active_fcmd at any time (single reader)
285 	 * - active_fcmd is always from fcmd_head list when non-NULL
286 	 * - evts_fifo can be read locklessly by the single active reader
287 	 * - All state transitions require evts_lock protection
288 	 * - Multiple writers to evts_fifo require lock protection
289 	 */
290 	struct {
291 		DECLARE_KFIFO_PTR(evts_fifo, unsigned short);
292 		spinlock_t evts_lock;
293 
294 		/* List of fetch commands available to process events */
295 		struct list_head fcmd_head;
296 
297 		/* Currently active fetch command (NULL = none active) */
298 		struct ublk_batch_fetch_cmd  *active_fcmd;
299 	}____cacheline_aligned_in_smp;
300 
301 	struct ublk_io ios[] __counted_by(q_depth);
302 };
303 
304 /* Maple tree value: maps a PFN range to buffer location */
305 struct ublk_buf_range {
306 	unsigned short buf_index;
307 	unsigned short flags;
308 	unsigned int base_offset;	/* byte offset within buffer */
309 };
310 
311 struct ublk_device {
312 	struct gendisk		*ub_disk;
313 
314 	struct ublksrv_ctrl_dev_info	dev_info;
315 
316 	struct blk_mq_tag_set	tag_set;
317 
318 	struct cdev		cdev;
319 	struct device		cdev_dev;
320 
321 #define UB_STATE_OPEN		0
322 #define UB_STATE_USED		1
323 #define UB_STATE_DELETED	2
324 /* STOP_DEV canceled the server's commands, until its release */
325 #define UB_STATE_STOPPING	3
326 	unsigned long		state;
327 	int			ub_number;
328 
329 	struct mutex		mutex;
330 
331 	spinlock_t		lock;
332 	struct mm_struct	*mm;
333 
334 	struct ublk_params	params;
335 
336 	u16			nr_queue_ready;
337 	bool 			unprivileged_daemons;
338 	struct mutex cancel_mutex;
339 	/* the open /dev/ublkcN, protected by cancel_mutex */
340 	struct file *ch_file;
341 	/*
342 	 * A cancel started in this FETCH round. Set by ublk_set_canceling(),
343 	 * cleared only by ublk_reset_ch_dev() when a new round starts. While
344 	 * it is set, no queue clears its ->canceling.
345 	 */
346 	bool canceling;
347 	pid_t 	ublksrv_tgid;
348 	struct delayed_work	exit_work;
349 	struct work_struct	partition_scan_work;
350 
351 	bool			block_open; /* protected by open_mutex */
352 
353 	/* shared memory zero copy */
354 	struct maple_tree	buf_tree;
355 	struct ida		buf_ida;
356 
357 	struct ublk_queue       *queues[];
358 };
359 
360 /* header of ublk_params */
361 struct ublk_params_header {
362 	__u32	len;
363 	__u32	types;
364 };
365 
366 static void ublk_io_release(void *priv);
367 static void ublk_stop_dev_unlocked(struct ublk_device *ub);
368 static bool ublk_try_buf_match(struct ublk_device *ub, struct request *rq,
369 				  u32 *buf_idx, u32 *buf_off);
370 static void ublk_buf_cleanup(struct ublk_device *ub);
371 static void ublk_abort_queue(struct ublk_device *ub, struct ublk_queue *ubq);
372 static inline struct request *__ublk_check_and_get_req(struct ublk_device *ub,
373 		u16 q_id, u16 tag, struct ublk_io *io);
374 static void ublk_batch_dispatch(struct ublk_queue *ubq,
375 				const struct ublk_batch_io_data *data,
376 				struct ublk_batch_fetch_cmd *fcmd);
377 
378 static inline bool ublk_dev_support_batch_io(const struct ublk_device *ub)
379 {
380 	return ub->dev_info.flags & UBLK_F_BATCH_IO;
381 }
382 
383 static inline bool ublk_support_batch_io(const struct ublk_queue *ubq)
384 {
385 	return ubq->flags & UBLK_F_BATCH_IO;
386 }
387 
388 static inline void ublk_io_lock(struct ublk_io *io)
389 {
390 	spin_lock(&io->lock);
391 }
392 
393 static inline void ublk_io_unlock(struct ublk_io *io)
394 {
395 	spin_unlock(&io->lock);
396 }
397 
398 /* Initialize the event queue */
399 static inline int ublk_io_evts_init(struct ublk_queue *q, unsigned int size,
400 				    int numa_node)
401 {
402 	spin_lock_init(&q->evts_lock);
403 	return kfifo_alloc_node(&q->evts_fifo, size, GFP_KERNEL, numa_node);
404 }
405 
406 /* Check if event queue is empty */
407 static inline bool ublk_io_evts_empty(const struct ublk_queue *q)
408 {
409 	return kfifo_is_empty(&q->evts_fifo);
410 }
411 
412 static inline void ublk_io_evts_deinit(struct ublk_queue *q)
413 {
414 	WARN_ON_ONCE(!kfifo_is_empty(&q->evts_fifo));
415 	kfifo_free(&q->evts_fifo);
416 }
417 
418 static inline struct ublksrv_io_desc *
419 ublk_get_iod(const struct ublk_queue *ubq, u16 tag)
420 {
421 	return (void *)ubq->io_cmd_buf + tag * (size_t)ubq->io_desc_size;
422 }
423 
424 static inline bool ublk_support_zero_copy(const struct ublk_queue *ubq)
425 {
426 	return ubq->flags & UBLK_F_SUPPORT_ZERO_COPY;
427 }
428 
429 static inline bool ublk_dev_support_zero_copy(const struct ublk_device *ub)
430 {
431 	return ub->dev_info.flags & UBLK_F_SUPPORT_ZERO_COPY;
432 }
433 
434 static inline bool ublk_support_shmem_zc(const struct ublk_queue *ubq)
435 {
436 	return ubq->flags & UBLK_F_SHMEM_ZC;
437 }
438 
439 static inline bool ublk_iod_is_shmem_zc(const struct ublk_queue *ubq, u16 tag)
440 {
441 	return ublk_get_iod(ubq, tag)->op_flags & UBLK_IO_F_SHMEM_ZC;
442 }
443 
444 static inline bool ublk_dev_support_shmem_zc(const struct ublk_device *ub)
445 {
446 	return ub->dev_info.flags & UBLK_F_SHMEM_ZC;
447 }
448 
449 static inline bool ublk_support_auto_buf_reg(const struct ublk_queue *ubq)
450 {
451 	return ubq->flags & UBLK_F_AUTO_BUF_REG;
452 }
453 
454 static inline bool ublk_dev_support_auto_buf_reg(const struct ublk_device *ub)
455 {
456 	return ub->dev_info.flags & UBLK_F_AUTO_BUF_REG;
457 }
458 
459 static inline bool ublk_support_user_copy(const struct ublk_queue *ubq)
460 {
461 	return ubq->flags & UBLK_F_USER_COPY;
462 }
463 
464 static inline bool ublk_dev_support_user_copy(const struct ublk_device *ub)
465 {
466 	return ub->dev_info.flags & UBLK_F_USER_COPY;
467 }
468 
469 static inline bool ublk_dev_is_zoned(const struct ublk_device *ub)
470 {
471 	return ub->dev_info.flags & UBLK_F_ZONED;
472 }
473 
474 static inline bool ublk_queue_is_zoned(const struct ublk_queue *ubq)
475 {
476 	return ubq->flags & UBLK_F_ZONED;
477 }
478 
479 static inline bool ublk_dev_support_integrity(const struct ublk_device *ub)
480 {
481 	return ub->dev_info.flags & UBLK_F_INTEGRITY;
482 }
483 
484 static inline unsigned int ublk_req_build_flags(struct request *req)
485 {
486 	unsigned flags = 0;
487 
488 	if (req->cmd_flags & REQ_FAILFAST_DEV)
489 		flags |= UBLK_IO_F_FAILFAST_DEV;
490 
491 	if (req->cmd_flags & REQ_FAILFAST_TRANSPORT)
492 		flags |= UBLK_IO_F_FAILFAST_TRANSPORT;
493 
494 	if (req->cmd_flags & REQ_FAILFAST_DRIVER)
495 		flags |= UBLK_IO_F_FAILFAST_DRIVER;
496 
497 	if (req->cmd_flags & REQ_META)
498 		flags |= UBLK_IO_F_META;
499 
500 	if (req->cmd_flags & REQ_FUA)
501 		flags |= UBLK_IO_F_FUA;
502 
503 	if (req->cmd_flags & REQ_NOUNMAP)
504 		flags |= UBLK_IO_F_NOUNMAP;
505 
506 	if (req->cmd_flags & REQ_SWAP)
507 		flags |= UBLK_IO_F_SWAP;
508 
509 	if (blk_integrity_rq(req))
510 		flags |= UBLK_IO_F_INTEGRITY;
511 
512 	return flags;
513 }
514 
515 static void ublk_init_iod(struct ublk_queue *ubq, struct request *req,
516 			  uint8_t ublk_op, uint32_t nr_sectors,
517 			  uint64_t start_sector)
518 {
519 	struct ublksrv_io_desc *iod = ublk_get_iod(ubq, req->tag);
520 	struct ublk_io *io = &ubq->ios[req->tag];
521 
522 	iod->op_flags = ublk_op | ublk_req_build_flags(req);
523 	iod->nr_sectors = nr_sectors;
524 	iod->start_sector = start_sector;
525 
526 	/* Try shmem zero-copy match before setting addr */
527 	if (ublk_support_shmem_zc(ubq) && blk_rq_has_data(req)) {
528 		u32 buf_idx, buf_off;
529 
530 		if (ublk_try_buf_match(ubq->dev, req, &buf_idx, &buf_off)) {
531 			iod->op_flags |= UBLK_IO_F_SHMEM_ZC;
532 			iod->addr = ublk_shmem_zc_addr(buf_idx, buf_off);
533 			return;
534 		}
535 	}
536 
537 	iod->addr = io->buf.addr;
538 }
539 
540 #ifdef CONFIG_BLK_DEV_ZONED
541 
542 struct ublk_zoned_report_desc {
543 	__u64 sector;
544 	__u32 nr_zones;
545 };
546 
547 static DEFINE_XARRAY(ublk_zoned_report_descs);
548 
549 static int ublk_zoned_insert_report_desc(const struct request *req,
550 		struct ublk_zoned_report_desc *desc)
551 {
552 	return xa_insert(&ublk_zoned_report_descs, (unsigned long)req,
553 			    desc, GFP_KERNEL);
554 }
555 
556 static struct ublk_zoned_report_desc *ublk_zoned_erase_report_desc(
557 		const struct request *req)
558 {
559 	return xa_erase(&ublk_zoned_report_descs, (unsigned long)req);
560 }
561 
562 static struct ublk_zoned_report_desc *ublk_zoned_get_report_desc(
563 		const struct request *req)
564 {
565 	return xa_load(&ublk_zoned_report_descs, (unsigned long)req);
566 }
567 
568 static int ublk_get_nr_zones(const struct ublk_device *ub)
569 {
570 	const struct ublk_param_basic *p = &ub->params.basic;
571 
572 	/* Zone size is a power of 2 */
573 	return p->dev_sectors >> ilog2(p->chunk_sectors);
574 }
575 
576 static int ublk_revalidate_disk_zones(struct ublk_device *ub)
577 {
578 	return blk_revalidate_disk_zones(ub->ub_disk);
579 }
580 
581 static int ublk_dev_param_zoned_validate(const struct ublk_device *ub)
582 {
583 	const struct ublk_param_zoned *p = &ub->params.zoned;
584 	int nr_zones;
585 
586 	if (!ublk_dev_is_zoned(ub))
587 		return -EINVAL;
588 
589 	if (!p->max_zone_append_sectors)
590 		return -EINVAL;
591 
592 	nr_zones = ublk_get_nr_zones(ub);
593 
594 	if (p->max_active_zones > nr_zones)
595 		return -EINVAL;
596 
597 	if (p->max_open_zones > nr_zones)
598 		return -EINVAL;
599 
600 	return 0;
601 }
602 
603 static void ublk_dev_param_zoned_apply(struct ublk_device *ub)
604 {
605 	ub->ub_disk->nr_zones = ublk_get_nr_zones(ub);
606 }
607 
608 /* Based on virtblk_alloc_report_buffer */
609 static void *ublk_alloc_report_buffer(struct ublk_device *ublk,
610 				      unsigned int nr_zones, size_t *buflen)
611 {
612 	struct request_queue *q = ublk->ub_disk->queue;
613 	size_t bufsize;
614 	void *buf;
615 
616 	nr_zones = min_t(unsigned int, nr_zones,
617 			 ublk->ub_disk->nr_zones);
618 
619 	bufsize = nr_zones * sizeof(struct blk_zone);
620 	bufsize =
621 		min_t(size_t, bufsize, queue_max_hw_sectors(q) << SECTOR_SHIFT);
622 
623 	while (bufsize >= sizeof(struct blk_zone)) {
624 		buf = kvmalloc(bufsize, GFP_KERNEL | __GFP_NORETRY);
625 		if (buf) {
626 			*buflen = bufsize;
627 			return buf;
628 		}
629 		bufsize >>= 1;
630 	}
631 
632 	*buflen = 0;
633 	return NULL;
634 }
635 
636 static int ublk_report_zones(struct gendisk *disk, sector_t sector,
637 		      unsigned int nr_zones, struct blk_report_zones_args *args)
638 {
639 	struct ublk_device *ub = disk->private_data;
640 	unsigned int zone_size_sectors = disk->queue->limits.chunk_sectors;
641 	unsigned int first_zone = sector >> ilog2(zone_size_sectors);
642 	unsigned int done_zones = 0;
643 	unsigned int max_zones_per_request;
644 	int ret;
645 	struct blk_zone *buffer;
646 	size_t buffer_length;
647 
648 	nr_zones = min_t(unsigned int, ub->ub_disk->nr_zones - first_zone,
649 			 nr_zones);
650 
651 	buffer = ublk_alloc_report_buffer(ub, nr_zones, &buffer_length);
652 	if (!buffer)
653 		return -ENOMEM;
654 
655 	max_zones_per_request = buffer_length / sizeof(struct blk_zone);
656 
657 	while (done_zones < nr_zones) {
658 		unsigned int remaining_zones = nr_zones - done_zones;
659 		unsigned int zones_in_request =
660 			min_t(unsigned int, remaining_zones, max_zones_per_request);
661 		struct request *req;
662 		struct ublk_zoned_report_desc desc;
663 		blk_status_t status;
664 
665 		memset(buffer, 0, buffer_length);
666 
667 		req = blk_mq_alloc_request(disk->queue, REQ_OP_DRV_IN, 0);
668 		if (IS_ERR(req)) {
669 			ret = PTR_ERR(req);
670 			goto out;
671 		}
672 
673 		desc.sector = sector;
674 		desc.nr_zones = zones_in_request;
675 		ret = ublk_zoned_insert_report_desc(req, &desc);
676 		if (ret)
677 			goto free_req;
678 
679 		ret = blk_rq_map_kern(req, buffer, buffer_length, GFP_KERNEL);
680 		if (ret)
681 			goto erase_desc;
682 
683 		status = blk_execute_rq(req, 0);
684 		ret = blk_status_to_errno(status);
685 erase_desc:
686 		ublk_zoned_erase_report_desc(req);
687 free_req:
688 		blk_mq_free_request(req);
689 		if (ret)
690 			goto out;
691 
692 		for (unsigned int i = 0; i < zones_in_request; i++) {
693 			struct blk_zone *zone = buffer + i;
694 
695 			/* A zero length zone means no more zones in this response */
696 			if (!zone->len)
697 				break;
698 
699 			ret = disk_report_zone(disk, zone, done_zones, args);
700 			if (ret)
701 				goto out;
702 
703 			done_zones++;
704 			sector += zone_size_sectors;
705 
706 		}
707 	}
708 
709 	ret = done_zones;
710 
711 out:
712 	kvfree(buffer);
713 	return ret;
714 }
715 
716 static bool ublk_validate_req_zoned(const struct request *req)
717 {
718 	switch (req_op(req)) {
719 	case REQ_OP_ZONE_OPEN:
720 	case REQ_OP_ZONE_CLOSE:
721 	case REQ_OP_ZONE_FINISH:
722 	case REQ_OP_ZONE_RESET:
723 	case REQ_OP_ZONE_APPEND:
724 	case REQ_OP_ZONE_RESET_ALL:
725 		return true;
726 	case REQ_OP_DRV_IN:
727 		return !!ublk_zoned_get_report_desc(req);
728 	default:
729 		return false;
730 	}
731 }
732 
733 static void ublk_setup_iod_zoned(struct ublk_queue *ubq, struct request *req)
734 {
735 	struct ublk_zoned_report_desc *desc;
736 	u32 ublk_op;
737 
738 	switch (req_op(req)) {
739 	case REQ_OP_ZONE_OPEN:
740 		ublk_op = UBLK_IO_OP_ZONE_OPEN;
741 		break;
742 	case REQ_OP_ZONE_CLOSE:
743 		ublk_op = UBLK_IO_OP_ZONE_CLOSE;
744 		break;
745 	case REQ_OP_ZONE_FINISH:
746 		ublk_op = UBLK_IO_OP_ZONE_FINISH;
747 		break;
748 	case REQ_OP_ZONE_RESET:
749 		ublk_op = UBLK_IO_OP_ZONE_RESET;
750 		break;
751 	case REQ_OP_ZONE_APPEND:
752 		ublk_op = UBLK_IO_OP_ZONE_APPEND;
753 		break;
754 	case REQ_OP_ZONE_RESET_ALL:
755 		ublk_op = UBLK_IO_OP_ZONE_RESET_ALL;
756 		break;
757 	case REQ_OP_DRV_IN:
758 		desc = ublk_zoned_get_report_desc(req);
759 		ublk_init_iod(ubq, req, UBLK_IO_OP_REPORT_ZONES, desc->nr_zones,
760 			      desc->sector);
761 		return;
762 	default:
763 		WARN_ON_ONCE(1);
764 		return;
765 	}
766 
767 	ublk_init_iod(ubq, req, ublk_op, blk_rq_sectors(req), blk_rq_pos(req));
768 }
769 
770 #else
771 
772 #define ublk_report_zones (NULL)
773 
774 static int ublk_dev_param_zoned_validate(const struct ublk_device *ub)
775 {
776 	return -EOPNOTSUPP;
777 }
778 
779 static void ublk_dev_param_zoned_apply(struct ublk_device *ub)
780 {
781 }
782 
783 static int ublk_revalidate_disk_zones(struct ublk_device *ub)
784 {
785 	return 0;
786 }
787 
788 static bool ublk_validate_req_zoned(const struct request *req)
789 {
790 	return false;
791 }
792 
793 static void ublk_setup_iod_zoned(struct ublk_queue *ubq, struct request *req)
794 {
795 	WARN_ON_ONCE(1);
796 }
797 
798 #endif
799 
800 static inline void __ublk_complete_rq(struct request *req, struct ublk_io *io,
801 				      bool need_map, struct io_comp_batch *iob);
802 
803 static dev_t ublk_chr_devt;
804 static const struct class ublk_chr_class = {
805 	.name = "ublk-char",
806 };
807 
808 static DEFINE_IDR(ublk_index_idr);
809 static DEFINE_SPINLOCK(ublk_idr_lock);
810 static wait_queue_head_t ublk_idr_wq;	/* wait until one idr is freed */
811 
812 static DEFINE_MUTEX(ublk_ctl_mutex);
813 
814 static struct ublk_batch_fetch_cmd *
815 ublk_batch_alloc_fcmd(struct io_uring_cmd *cmd)
816 {
817 	struct ublk_batch_fetch_cmd *fcmd = kzalloc_obj(*fcmd, GFP_NOIO);
818 
819 	if (fcmd) {
820 		fcmd->cmd = cmd;
821 		fcmd->buf_group = READ_ONCE(cmd->sqe->buf_index);
822 		/* a cancel may look at it before it is linked */
823 		INIT_LIST_HEAD(&fcmd->node);
824 	}
825 	return fcmd;
826 }
827 
828 static void ublk_batch_free_fcmd(struct ublk_batch_fetch_cmd *fcmd)
829 {
830 	kfree(fcmd);
831 }
832 
833 static void __ublk_release_fcmd(struct ublk_queue *ubq)
834 {
835 	WRITE_ONCE(ubq->active_fcmd, NULL);
836 }
837 
838 /*
839  * Nothing can move on, so clear ->active_fcmd, and the caller should stop
840  * dispatching
841  */
842 static void ublk_batch_deinit_fetch_buf(struct ublk_queue *ubq,
843 					const struct ublk_batch_io_data *data,
844 					struct ublk_batch_fetch_cmd *fcmd,
845 					int res)
846 {
847 	spin_lock(&ubq->evts_lock);
848 	list_del_init(&fcmd->node);
849 	WARN_ON_ONCE(fcmd != ubq->active_fcmd);
850 	__ublk_release_fcmd(ubq);
851 	spin_unlock(&ubq->evts_lock);
852 
853 	io_uring_cmd_done(fcmd->cmd, res, data->issue_flags);
854 	ublk_batch_free_fcmd(fcmd);
855 }
856 
857 static int ublk_batch_fetch_post_cqe(struct ublk_batch_fetch_cmd *fcmd,
858 				     struct io_br_sel *sel,
859 				     unsigned int issue_flags)
860 {
861 	if (io_uring_mshot_cmd_post_cqe(fcmd->cmd, sel, issue_flags))
862 		return -ENOBUFS;
863 	return 0;
864 }
865 
866 static ssize_t ublk_batch_copy_io_tags(struct ublk_batch_fetch_cmd *fcmd,
867 				       void __user *buf, const u16 *tag_buf,
868 				       unsigned int len)
869 {
870 	if (copy_to_user(buf, tag_buf, len))
871 		return -EFAULT;
872 	return len;
873 }
874 
875 #define UBLK_MAX_UBLKS UBLK_MINORS
876 
877 /*
878  * Max unprivileged ublk devices allowed to add
879  *
880  * It can be extended to one per-user limit in future or even controlled
881  * by cgroup.
882  */
883 static unsigned int unprivileged_ublks_max = 64;
884 static unsigned int unprivileged_ublks_added; /* protected by ublk_ctl_mutex */
885 
886 static struct miscdevice ublk_misc;
887 
888 static inline u16 ublk_pos_to_hwq(loff_t pos)
889 {
890 	return ((pos - UBLKSRV_IO_BUF_OFFSET) >> UBLK_QID_OFF) &
891 		UBLK_QID_BITS_MASK;
892 }
893 
894 static inline unsigned ublk_pos_to_buf_off(loff_t pos)
895 {
896 	return (pos - UBLKSRV_IO_BUF_OFFSET) & UBLK_IO_BUF_BITS_MASK;
897 }
898 
899 static inline u16 ublk_pos_to_tag(loff_t pos)
900 {
901 	return ((pos - UBLKSRV_IO_BUF_OFFSET) >> UBLK_TAG_OFF) &
902 		UBLK_TAG_BITS_MASK;
903 }
904 
905 static void ublk_dev_param_basic_apply(struct ublk_device *ub)
906 {
907 	const struct ublk_param_basic *p = &ub->params.basic;
908 
909 	if (p->attrs & UBLK_ATTR_READ_ONLY)
910 		set_disk_ro(ub->ub_disk, true);
911 
912 	set_capacity(ub->ub_disk, p->dev_sectors);
913 }
914 
915 static int ublk_integrity_flags(u32 flags)
916 {
917 	int ret_flags = BLK_SPLIT_INTERVAL_CAPABLE;
918 
919 	if (flags & LBMD_PI_CAP_INTEGRITY) {
920 		flags &= ~LBMD_PI_CAP_INTEGRITY;
921 		ret_flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
922 	}
923 	if (flags & LBMD_PI_CAP_REFTAG) {
924 		flags &= ~LBMD_PI_CAP_REFTAG;
925 		ret_flags |= BLK_INTEGRITY_REF_TAG;
926 	}
927 	return flags ? -EINVAL : ret_flags;
928 }
929 
930 static int ublk_integrity_pi_tuple_size(u8 csum_type)
931 {
932 	switch (csum_type) {
933 	case LBMD_PI_CSUM_NONE:
934 		return 0;
935 	case LBMD_PI_CSUM_IP:
936 	case LBMD_PI_CSUM_CRC16_T10DIF:
937 		return 8;
938 	case LBMD_PI_CSUM_CRC64_NVME:
939 		return 16;
940 	default:
941 		return -EINVAL;
942 	}
943 }
944 
945 static enum blk_integrity_checksum ublk_integrity_csum_type(u8 csum_type)
946 {
947 	switch (csum_type) {
948 	case LBMD_PI_CSUM_NONE:
949 		return BLK_INTEGRITY_CSUM_NONE;
950 	case LBMD_PI_CSUM_IP:
951 		return BLK_INTEGRITY_CSUM_IP;
952 	case LBMD_PI_CSUM_CRC16_T10DIF:
953 		return BLK_INTEGRITY_CSUM_CRC;
954 	case LBMD_PI_CSUM_CRC64_NVME:
955 		return BLK_INTEGRITY_CSUM_CRC64;
956 	default:
957 		WARN_ON_ONCE(1);
958 		return BLK_INTEGRITY_CSUM_NONE;
959 	}
960 }
961 
962 static int ublk_validate_params(const struct ublk_device *ub)
963 {
964 	/* basic param is the only one which must be set */
965 	if (ub->params.types & UBLK_PARAM_TYPE_BASIC) {
966 		const struct ublk_param_basic *p = &ub->params.basic;
967 
968 		if (p->logical_bs_shift > PAGE_SHIFT || p->logical_bs_shift < 9)
969 			return -EINVAL;
970 
971 		/*
972 		 * 256M is a reasonable upper bound for physical block size,
973 		 * io_min and io_opt; it aligns with the maximum physical
974 		 * block size possible in NVMe.
975 		 */
976 		if (p->physical_bs_shift > ilog2(SZ_256M))
977 			return -EINVAL;
978 
979 		if (p->io_min_shift > ilog2(SZ_256M))
980 			return -EINVAL;
981 
982 		if (p->io_opt_shift > ilog2(SZ_256M))
983 			return -EINVAL;
984 
985 		if (p->logical_bs_shift > p->physical_bs_shift)
986 			return -EINVAL;
987 
988 		if (p->max_sectors > (ub->dev_info.max_io_buf_bytes >> 9))
989 			return -EINVAL;
990 
991 		if (p->max_sectors < PAGE_SECTORS)
992 			return -EINVAL;
993 
994 		if (ublk_dev_is_zoned(ub) && !is_power_of_2(p->chunk_sectors))
995 			return -EINVAL;
996 	} else
997 		return -EINVAL;
998 
999 	if (ub->params.types & UBLK_PARAM_TYPE_DISCARD) {
1000 		const struct ublk_param_discard *p = &ub->params.discard;
1001 
1002 		/* So far, only support single segment discard */
1003 		if (p->max_discard_sectors && p->max_discard_segments != 1)
1004 			return -EINVAL;
1005 
1006 		if (!p->discard_granularity)
1007 			return -EINVAL;
1008 	}
1009 
1010 	/* dev_t is read-only */
1011 	if (ub->params.types & UBLK_PARAM_TYPE_DEVT)
1012 		return -EINVAL;
1013 
1014 	if (ub->params.types & UBLK_PARAM_TYPE_ZONED)
1015 		return ublk_dev_param_zoned_validate(ub);
1016 	else if (ublk_dev_is_zoned(ub))
1017 		return -EINVAL;
1018 
1019 	if (ub->params.types & UBLK_PARAM_TYPE_DMA_ALIGN) {
1020 		const struct ublk_param_dma_align *p = &ub->params.dma;
1021 
1022 		if (p->alignment >= PAGE_SIZE)
1023 			return -EINVAL;
1024 
1025 		if (!is_power_of_2(p->alignment + 1))
1026 			return -EINVAL;
1027 	}
1028 
1029 	if (ub->params.types & UBLK_PARAM_TYPE_SEGMENT) {
1030 		const struct ublk_param_segment *p = &ub->params.seg;
1031 
1032 		if (!is_power_of_2(p->seg_boundary_mask + 1))
1033 			return -EINVAL;
1034 
1035 		if (p->seg_boundary_mask + 1 < UBLK_MIN_SEGMENT_SIZE)
1036 			return -EINVAL;
1037 		if (p->max_segment_size < UBLK_MIN_SEGMENT_SIZE)
1038 			return -EINVAL;
1039 	}
1040 
1041 	if (ub->params.types & UBLK_PARAM_TYPE_INTEGRITY) {
1042 		const struct ublk_param_integrity *p = &ub->params.integrity;
1043 		int pi_tuple_size = ublk_integrity_pi_tuple_size(p->csum_type);
1044 		int flags = ublk_integrity_flags(p->flags);
1045 
1046 		if (!ublk_dev_support_integrity(ub))
1047 			return -EINVAL;
1048 		if (flags < 0)
1049 			return flags;
1050 		if (pi_tuple_size < 0)
1051 			return pi_tuple_size;
1052 		if (!p->metadata_size)
1053 			return -EINVAL;
1054 		if (p->csum_type == LBMD_PI_CSUM_NONE &&
1055 		    p->flags & LBMD_PI_CAP_REFTAG)
1056 			return -EINVAL;
1057 		if (p->pi_offset + pi_tuple_size > p->metadata_size)
1058 			return -EINVAL;
1059 		if (p->interval_exp < SECTOR_SHIFT ||
1060 		    p->interval_exp > ub->params.basic.logical_bs_shift)
1061 			return -EINVAL;
1062 	}
1063 
1064 	return 0;
1065 }
1066 
1067 static void ublk_apply_params(struct ublk_device *ub)
1068 {
1069 	ublk_dev_param_basic_apply(ub);
1070 
1071 	if (ub->params.types & UBLK_PARAM_TYPE_ZONED)
1072 		ublk_dev_param_zoned_apply(ub);
1073 }
1074 
1075 static inline bool ublk_need_map_io(const struct ublk_queue *ubq)
1076 {
1077 	return !ublk_support_user_copy(ubq) && !ublk_support_zero_copy(ubq) &&
1078 		!ublk_support_auto_buf_reg(ubq);
1079 }
1080 
1081 static inline bool ublk_dev_need_map_io(const struct ublk_device *ub)
1082 {
1083 	return !ublk_dev_support_user_copy(ub) &&
1084 	       !ublk_dev_support_zero_copy(ub) &&
1085 	       !ublk_dev_support_auto_buf_reg(ub);
1086 }
1087 
1088 static inline bool ublk_need_req_ref(const struct ublk_queue *ubq)
1089 {
1090 	/*
1091 	 * read()/write() is involved in user copy, so request reference
1092 	 * has to be grabbed
1093 	 *
1094 	 * for zero copy, request buffer need to be registered to io_uring
1095 	 * buffer table, so reference is needed
1096 	 *
1097 	 * For auto buffer register, ublk server still may issue
1098 	 * UBLK_IO_COMMIT_AND_FETCH_REQ before one registered buffer is used up,
1099 	 * so reference is required too.
1100 	 */
1101 	return ublk_support_user_copy(ubq) || ublk_support_zero_copy(ubq) ||
1102 		ublk_support_auto_buf_reg(ubq);
1103 }
1104 
1105 static inline bool ublk_dev_need_req_ref(const struct ublk_device *ub)
1106 {
1107 	return ublk_dev_support_user_copy(ub) ||
1108 	       ublk_dev_support_zero_copy(ub) ||
1109 	       ublk_dev_support_auto_buf_reg(ub);
1110 }
1111 
1112 /*
1113  * ublk IO Reference Counting Design
1114  * ==================================
1115  *
1116  * For user-copy and zero-copy modes, ublk uses a split reference model with
1117  * two counters that together track IO lifetime:
1118  *
1119  *   - io->ref: refcount for off-task buffer registrations and user-copy ops
1120  *   - io->task_registered_buffers: count of buffers registered on the IO task
1121  *
1122  * Key Invariant:
1123  * --------------
1124  * When IO is dispatched to the ublk server (UBLK_IO_FLAG_OWNED_BY_SRV set),
1125  * the sum (io->ref + io->task_registered_buffers) must equal UBLK_REFCOUNT_INIT
1126  * when no active references exist. After IO completion, both counters become
1127  * zero. For I/Os not currently dispatched to the ublk server, both ref and
1128  * task_registered_buffers are 0.
1129  *
1130  * This invariant is checked by ublk_check_and_reset_active_ref() during daemon
1131  * exit to determine if all references have been released.
1132  *
1133  * Why Split Counters:
1134  * -------------------
1135  * Buffers registered on the IO daemon task can use the lightweight
1136  * task_registered_buffers counter (simple increment/decrement) instead of
1137  * atomic refcount operations. The ublk_io_release() callback checks if
1138  * current == io->task to decide which counter to update.
1139  *
1140  * This optimization only applies before IO completion. At completion,
1141  * ublk_sub_req_ref() collapses task_registered_buffers into the atomic ref.
1142  * After that, all subsequent buffer unregistrations must use the atomic ref
1143  * since they may be releasing the last reference.
1144  *
1145  * Reference Lifecycle:
1146  * --------------------
1147  * 1. ublk_init_req_ref(): Sets io->ref = UBLK_REFCOUNT_INIT at IO dispatch
1148  *
1149  * 2. During IO processing:
1150  *    - On-task buffer reg: task_registered_buffers++ (no ref change)
1151  *    - Off-task buffer reg: ref++ via ublk_get_req_ref()
1152  *    - Buffer unregister callback (ublk_io_release):
1153  *      * If on-task: task_registered_buffers--
1154  *      * If off-task: ref-- via ublk_put_req_ref()
1155  *
1156  * 3. ublk_sub_req_ref() at IO completion:
1157  *    - Computes: sub_refs = UBLK_REFCOUNT_INIT - task_registered_buffers
1158  *    - Subtracts sub_refs from ref and zeroes task_registered_buffers
1159  *    - This effectively collapses task_registered_buffers into the atomic ref,
1160  *      accounting for the initial UBLK_REFCOUNT_INIT minus any on-task
1161  *      buffers that were already counted
1162  *
1163  * Example (zero-copy, register on-task, unregister off-task):
1164  *   - Dispatch: ref = UBLK_REFCOUNT_INIT, task_registered_buffers = 0
1165  *   - Register buffer on-task: task_registered_buffers = 1
1166  *   - Unregister off-task: ref-- (UBLK_REFCOUNT_INIT - 1), task_registered_buffers stays 1
1167  *   - Completion via ublk_sub_req_ref():
1168  *     sub_refs = UBLK_REFCOUNT_INIT - 1,
1169  *     ref = (UBLK_REFCOUNT_INIT - 1) - (UBLK_REFCOUNT_INIT - 1) = 0
1170  *
1171  * Example (auto buffer registration):
1172  *   Auto buffer registration sets task_registered_buffers = 1 at dispatch.
1173  *
1174  *   - Dispatch: ref = UBLK_REFCOUNT_INIT, task_registered_buffers = 1
1175  *   - Buffer unregister: task_registered_buffers-- (becomes 0)
1176  *   - Completion via ublk_sub_req_ref():
1177  *     sub_refs = UBLK_REFCOUNT_INIT - 0, ref becomes 0
1178  *
1179  * Example (zero-copy, ublk server killed):
1180  *   When daemon is killed, io_uring cleanup unregisters buffers off-task.
1181  *   ublk_check_and_reset_active_ref() waits for the invariant to hold.
1182  *
1183  *   - Dispatch: ref = UBLK_REFCOUNT_INIT, task_registered_buffers = 0
1184  *   - Register buffer on-task: task_registered_buffers = 1
1185  *   - Daemon killed, io_uring cleanup unregisters buffer (off-task):
1186  *     ref-- (UBLK_REFCOUNT_INIT - 1), task_registered_buffers stays 1
1187  *   - Daemon exit check: sum = (UBLK_REFCOUNT_INIT - 1) + 1 = UBLK_REFCOUNT_INIT
1188  *   - Sum equals UBLK_REFCOUNT_INIT, then both two counters are zeroed by
1189  *     ublk_check_and_reset_active_ref(), so ublk_abort_queue() can proceed
1190  *     and abort pending requests
1191  *
1192  * Batch IO Special Case:
1193  * ----------------------
1194  * In batch IO mode, io->task is NULL. This means ublk_io_release() always
1195  * takes the off-task path (ublk_put_req_ref), decrementing io->ref. The
1196  * task_registered_buffers counter still tracks registered buffers for the
1197  * invariant check, even though the callback doesn't decrement it.
1198  *
1199  * Note: updating task_registered_buffers is protected by io->lock.
1200  */
1201 static inline void ublk_init_req_ref(const struct ublk_queue *ubq,
1202 		struct ublk_io *io)
1203 {
1204 	if (ublk_need_req_ref(ubq))
1205 		refcount_set(&io->ref, UBLK_REFCOUNT_INIT);
1206 }
1207 
1208 static inline bool ublk_get_req_ref(struct ublk_io *io)
1209 {
1210 	return refcount_inc_not_zero(&io->ref);
1211 }
1212 
1213 static inline void ublk_put_req_ref(struct ublk_io *io, struct request *req)
1214 {
1215 	if (!refcount_dec_and_test(&io->ref))
1216 		return;
1217 
1218 	/* ublk_need_map_io() and ublk_need_req_ref() are mutually exclusive */
1219 	__ublk_complete_rq(req, io, false, NULL);
1220 }
1221 
1222 static inline bool ublk_sub_req_ref(struct ublk_io *io)
1223 {
1224 	unsigned sub_refs = UBLK_REFCOUNT_INIT - io->task_registered_buffers;
1225 
1226 	io->task_registered_buffers = 0;
1227 	return refcount_sub_and_test(sub_refs, &io->ref);
1228 }
1229 
1230 static inline bool ublk_need_get_data(const struct ublk_queue *ubq)
1231 {
1232 	return ubq->flags & UBLK_F_NEED_GET_DATA;
1233 }
1234 
1235 static inline bool ublk_dev_need_get_data(const struct ublk_device *ub)
1236 {
1237 	return ub->dev_info.flags & UBLK_F_NEED_GET_DATA;
1238 }
1239 
1240 /* Called in slow path only, keep it noinline for trace purpose */
1241 static noinline struct ublk_device *ublk_get_device(struct ublk_device *ub)
1242 {
1243 	if (kobject_get_unless_zero(&ub->cdev_dev.kobj))
1244 		return ub;
1245 	return NULL;
1246 }
1247 
1248 /* Called in slow path only, keep it noinline for trace purpose */
1249 static noinline void ublk_put_device(struct ublk_device *ub)
1250 {
1251 	put_device(&ub->cdev_dev);
1252 }
1253 
1254 static inline struct ublk_queue *ublk_get_queue(struct ublk_device *dev,
1255 		u16 qid)
1256 {
1257 	return dev->queues[qid];
1258 }
1259 
1260 static inline struct ublksrv_io_desc *
1261 ublk_queue_cmd_buf(struct ublk_device *ub, u16 q_id)
1262 {
1263 	return ublk_get_queue(ub, q_id)->io_cmd_buf;
1264 }
1265 
1266 static inline size_t __ublk_queue_cmd_buf_size(const struct ublk_device *ub,
1267 					       u16 depth)
1268 {
1269 	return round_up(depth * (size_t)ub->dev_info.io_desc_size, PAGE_SIZE);
1270 }
1271 
1272 static inline size_t ublk_queue_cmd_buf_size(const struct ublk_device *ub)
1273 {
1274 	return __ublk_queue_cmd_buf_size(ub, ub->dev_info.queue_depth);
1275 }
1276 
1277 static size_t ublk_max_cmd_buf_size(const struct ublk_device *ub)
1278 {
1279 	return __ublk_queue_cmd_buf_size(ub, UBLK_MAX_QUEUE_DEPTH);
1280 }
1281 
1282 /*
1283  * Should I/O outstanding to the ublk server when it exits be reissued?
1284  * If not, outstanding I/O will get errors.
1285  */
1286 static inline bool ublk_nosrv_should_reissue_outstanding(struct ublk_device *ub)
1287 {
1288 	return (ub->dev_info.flags & UBLK_F_USER_RECOVERY) &&
1289 	       (ub->dev_info.flags & UBLK_F_USER_RECOVERY_REISSUE);
1290 }
1291 
1292 /*
1293  * Should I/O issued while there is no ublk server queue? If not, I/O
1294  * issued while there is no ublk server will get errors.
1295  */
1296 static inline bool ublk_nosrv_dev_should_queue_io(struct ublk_device *ub)
1297 {
1298 	return (ub->dev_info.flags & UBLK_F_USER_RECOVERY) &&
1299 	       !(ub->dev_info.flags & UBLK_F_USER_RECOVERY_FAIL_IO);
1300 }
1301 
1302 /*
1303  * Same as ublk_nosrv_dev_should_queue_io, but uses a queue-local copy
1304  * of the device flags for smaller cache footprint - better for fast
1305  * paths.
1306  */
1307 static inline bool ublk_nosrv_should_queue_io(struct ublk_queue *ubq)
1308 {
1309 	return (ubq->flags & UBLK_F_USER_RECOVERY) &&
1310 	       !(ubq->flags & UBLK_F_USER_RECOVERY_FAIL_IO);
1311 }
1312 
1313 /*
1314  * Should ublk devices be stopped (i.e. no recovery possible) when the
1315  * ublk server exits? If not, devices can be used again by a future
1316  * incarnation of a ublk server via the start_recovery/end_recovery
1317  * commands.
1318  */
1319 static inline bool ublk_nosrv_should_stop_dev(struct ublk_device *ub)
1320 {
1321 	return !(ub->dev_info.flags & UBLK_F_USER_RECOVERY);
1322 }
1323 
1324 static inline bool ublk_dev_in_recoverable_state(struct ublk_device *ub)
1325 {
1326 	return ub->dev_info.state == UBLK_S_DEV_QUIESCED ||
1327 	       ub->dev_info.state == UBLK_S_DEV_FAIL_IO;
1328 }
1329 
1330 static void ublk_free_disk(struct gendisk *disk)
1331 {
1332 	struct ublk_device *ub = disk->private_data;
1333 
1334 	clear_bit(UB_STATE_USED, &ub->state);
1335 	ublk_put_device(ub);
1336 }
1337 
1338 static void ublk_store_owner_uid_gid(unsigned int *owner_uid,
1339 		unsigned int *owner_gid)
1340 {
1341 	kuid_t uid;
1342 	kgid_t gid;
1343 
1344 	current_uid_gid(&uid, &gid);
1345 
1346 	*owner_uid = from_kuid(&init_user_ns, uid);
1347 	*owner_gid = from_kgid(&init_user_ns, gid);
1348 }
1349 
1350 static int ublk_open(struct gendisk *disk, blk_mode_t mode)
1351 {
1352 	struct ublk_device *ub = disk->private_data;
1353 
1354 	if (capable(CAP_SYS_ADMIN))
1355 		return 0;
1356 
1357 	/*
1358 	 * If it is one unprivileged device, only owner can open
1359 	 * the disk. Otherwise it could be one trap made by one
1360 	 * evil user who grants this disk's privileges to other
1361 	 * users deliberately.
1362 	 *
1363 	 * This way is reasonable too given anyone can create
1364 	 * unprivileged device, and no need other's grant.
1365 	 */
1366 	if (ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV) {
1367 		unsigned int curr_uid, curr_gid;
1368 
1369 		ublk_store_owner_uid_gid(&curr_uid, &curr_gid);
1370 
1371 		if (curr_uid != ub->dev_info.owner_uid || curr_gid !=
1372 				ub->dev_info.owner_gid)
1373 			return -EPERM;
1374 	}
1375 
1376 	if (ub->block_open)
1377 		return -ENXIO;
1378 
1379 	return 0;
1380 }
1381 
1382 static const struct block_device_operations ub_fops = {
1383 	.owner =	THIS_MODULE,
1384 	.open =		ublk_open,
1385 	.free_disk =	ublk_free_disk,
1386 	.report_zones =	ublk_report_zones,
1387 };
1388 
1389 static bool ublk_copy_user_bvec(const struct bio_vec *bv, unsigned *offset,
1390 				struct iov_iter *uiter, int dir, size_t *done)
1391 {
1392 	unsigned len;
1393 	void *bv_buf;
1394 	size_t copied;
1395 
1396 	if (*offset >= bv->bv_len) {
1397 		*offset -= bv->bv_len;
1398 		return true;
1399 	}
1400 
1401 	len = bv->bv_len - *offset;
1402 	bv_buf = kmap_local_page(bv->bv_page) + bv->bv_offset + *offset;
1403 	/*
1404 	 * Bio pages may originate from slab caches without a usercopy region
1405 	 * (e.g. jbd2 frozen metadata buffers).  This is the same data that
1406 	 * the loop driver writes to its backing file — no exposure risk.
1407 	 * The bvec length is always trusted, so the size check in
1408 	 * check_copy_size() is not needed either.  Use the unchecked
1409 	 * helpers to avoid false positives on slab pages.
1410 	 */
1411 	if (dir == ITER_DEST)
1412 		copied = _copy_to_iter(bv_buf, len, uiter);
1413 	else
1414 		copied = _copy_from_iter(bv_buf, len, uiter);
1415 
1416 	kunmap_local(bv_buf);
1417 
1418 	*done += copied;
1419 	if (copied < len)
1420 		return false;
1421 
1422 	*offset = 0;
1423 	return true;
1424 }
1425 
1426 /*
1427  * Copy data between request pages and io_iter, and 'offset'
1428  * is the start point of linear offset of request.
1429  */
1430 static size_t ublk_copy_user_pages(const struct request *req,
1431 		unsigned offset, struct iov_iter *uiter, int dir)
1432 {
1433 	struct req_iterator iter;
1434 	struct bio_vec bv;
1435 	size_t done = 0;
1436 
1437 	rq_for_each_segment(bv, req, iter) {
1438 		if (!ublk_copy_user_bvec(&bv, &offset, uiter, dir, &done))
1439 			break;
1440 	}
1441 	return done;
1442 }
1443 
1444 #ifdef CONFIG_BLK_DEV_INTEGRITY
1445 static size_t ublk_copy_user_integrity(const struct request *req,
1446 		unsigned offset, struct iov_iter *uiter, int dir)
1447 {
1448 	size_t done = 0;
1449 	struct bio *bio = req->bio;
1450 	struct bvec_iter iter;
1451 	struct bio_vec iv;
1452 
1453 	if (!blk_integrity_rq(req))
1454 		return 0;
1455 
1456 	bio_for_each_integrity_vec(iv, bio, iter) {
1457 		if (!ublk_copy_user_bvec(&iv, &offset, uiter, dir, &done))
1458 			break;
1459 	}
1460 
1461 	return done;
1462 }
1463 #else /* #ifdef CONFIG_BLK_DEV_INTEGRITY */
1464 static size_t ublk_copy_user_integrity(const struct request *req,
1465 		unsigned offset, struct iov_iter *uiter, int dir)
1466 {
1467 	return 0;
1468 }
1469 #endif /* #ifdef CONFIG_BLK_DEV_INTEGRITY */
1470 
1471 static inline bool ublk_need_map_req(const struct request *req)
1472 {
1473 	return blk_rq_has_data(req) && req_op(req) == REQ_OP_WRITE;
1474 }
1475 
1476 static inline bool ublk_need_unmap_req(const struct request *req)
1477 {
1478 	return blk_rq_has_data(req) &&
1479 	       (req_op(req) == REQ_OP_READ || req_op(req) == REQ_OP_DRV_IN);
1480 }
1481 
1482 static unsigned int ublk_map_io(const struct request *req,
1483 				const struct ublk_io *io)
1484 {
1485 	struct iov_iter iter;
1486 	const int dir = ITER_DEST;
1487 
1488 	if (import_ubuf(dir, u64_to_user_ptr(io->buf.addr), blk_rq_bytes(req),
1489 			&iter) < 0)
1490 		return 0;
1491 
1492 	return ublk_copy_user_pages(req, 0, &iter, dir);
1493 }
1494 
1495 static unsigned int ublk_unmap_io(const struct request *req,
1496 		const struct ublk_io *io)
1497 {
1498 	struct iov_iter iter;
1499 	const int dir = ITER_SOURCE;
1500 
1501 	if (import_ubuf(dir, u64_to_user_ptr(io->buf.addr), io->res, &iter) < 0)
1502 		return 0;
1503 
1504 	return ublk_copy_user_pages(req, 0, &iter, dir);
1505 }
1506 
1507 static bool ublk_validate_req(const struct ublk_queue *ubq,
1508 			      const struct request *req)
1509 {
1510 	switch (req_op(req)) {
1511 	case REQ_OP_READ:
1512 	case REQ_OP_WRITE:
1513 	case REQ_OP_FLUSH:
1514 	case REQ_OP_DISCARD:
1515 	case REQ_OP_WRITE_ZEROES:
1516 		return true;
1517 	default:
1518 		return ublk_queue_is_zoned(ubq) && ublk_validate_req_zoned(req);
1519 	}
1520 }
1521 
1522 static void ublk_setup_iod(struct ublk_queue *ubq, struct request *req)
1523 {
1524 	u32 ublk_op;
1525 
1526 	switch (req_op(req)) {
1527 	case REQ_OP_READ:
1528 		ublk_op = UBLK_IO_OP_READ;
1529 		break;
1530 	case REQ_OP_WRITE:
1531 		ublk_op = UBLK_IO_OP_WRITE;
1532 		break;
1533 	case REQ_OP_FLUSH:
1534 		ublk_op = UBLK_IO_OP_FLUSH;
1535 		break;
1536 	case REQ_OP_DISCARD:
1537 		ublk_op = UBLK_IO_OP_DISCARD;
1538 		break;
1539 	case REQ_OP_WRITE_ZEROES:
1540 		ublk_op = UBLK_IO_OP_WRITE_ZEROES;
1541 		break;
1542 	default:
1543 		ublk_setup_iod_zoned(ubq, req);
1544 		return;
1545 	}
1546 
1547 	ublk_init_iod(ubq, req, ublk_op, blk_rq_sectors(req), blk_rq_pos(req));
1548 }
1549 
1550 static inline struct ublk_uring_cmd_pdu *ublk_get_uring_cmd_pdu(
1551 		struct io_uring_cmd *ioucmd)
1552 {
1553 	return io_uring_cmd_to_pdu(ioucmd, struct ublk_uring_cmd_pdu);
1554 }
1555 
1556 static void ublk_end_request(struct request *req, blk_status_t error)
1557 {
1558 	local_bh_disable();
1559 	blk_mq_end_request(req, error);
1560 	local_bh_enable();
1561 }
1562 
1563 /* todo: handle partial completion */
1564 static inline void __ublk_complete_rq(struct request *req, struct ublk_io *io,
1565 				      bool need_map, struct io_comp_batch *iob)
1566 {
1567 	unsigned int unmapped_bytes;
1568 	blk_status_t res = BLK_STS_OK;
1569 	bool requeue;
1570 
1571 	/* failed read IO if nothing is read */
1572 	if (!io->res && req_op(req) == REQ_OP_READ)
1573 		io->res = -EIO;
1574 
1575 	if (io->res < 0) {
1576 		res = errno_to_blk_status(io->res);
1577 		goto exit;
1578 	}
1579 
1580 	/* shmem zero copy: no data to unmap, pages already shared */
1581 	if (!need_map || !ublk_need_unmap_req(req) ||
1582 	    ublk_iod_is_shmem_zc(req->mq_hctx->driver_data, req->tag))
1583 		goto exit;
1584 
1585 	/* for READ request, writing data in iod->addr to rq buffers */
1586 	unmapped_bytes = ublk_unmap_io(req, io);
1587 
1588 	/*
1589 	 * Extremely impossible since we got data filled in just before
1590 	 *
1591 	 * Re-read simply for this unlikely case.
1592 	 */
1593 	if (unlikely(unmapped_bytes < io->res)) {
1594 		if (unlikely(!unmapped_bytes)) {
1595 			res = BLK_STS_IOERR;
1596 			goto exit;
1597 		}
1598 
1599 		io->res = unmapped_bytes;
1600 	}
1601 
1602 	/*
1603 	 * Run bio->bi_end_io() with softirqs disabled. If the final fput
1604 	 * happens off this path, then that will prevent ublk's blkdev_release()
1605 	 * from being called on current's task work, see fput() implementation.
1606 	 *
1607 	 * Otherwise, ublk server may not provide forward progress in case of
1608 	 * reading the partition table from bdev_open() with disk->open_mutex
1609 	 * held, and causes dead lock as we could already be holding
1610 	 * disk->open_mutex here.
1611 	 *
1612 	 * Preferably we would not be doing IO with a mutex held that is also
1613 	 * used for release, but this work-around will suffice for now.
1614 	 */
1615 	local_bh_disable();
1616 	requeue = blk_update_request(req, BLK_STS_OK, io->res);
1617 	local_bh_enable();
1618 	if (requeue)
1619 		blk_mq_requeue_request(req, true);
1620 	else if (likely(!blk_should_fake_timeout(req->q))) {
1621 		if (blk_mq_add_to_batch(req, iob, false, blk_mq_end_request_batch))
1622 			return;
1623 		__blk_mq_end_request(req, BLK_STS_OK);
1624 	}
1625 
1626 	return;
1627 exit:
1628 	ublk_end_request(req, res);
1629 }
1630 
1631 static struct io_uring_cmd *__ublk_prep_compl_io_cmd(struct ublk_io *io,
1632 						     struct request *req)
1633 {
1634 	/* read cmd first because req will overwrite it */
1635 	struct io_uring_cmd *cmd = io->cmd;
1636 
1637 	/* mark this cmd owned by ublksrv */
1638 	io->flags |= UBLK_IO_FLAG_OWNED_BY_SRV;
1639 
1640 	/*
1641 	 * clear ACTIVE since we are done with this sqe/cmd slot
1642 	 * We can only accept io cmd in case of being not active.
1643 	 */
1644 	io->flags &= ~UBLK_IO_FLAG_ACTIVE;
1645 
1646 	io->req = req;
1647 	return cmd;
1648 }
1649 
1650 static void ublk_complete_io_cmd(struct ublk_io *io, struct request *req,
1651 				 int res, unsigned issue_flags)
1652 {
1653 	struct io_uring_cmd *cmd = __ublk_prep_compl_io_cmd(io, req);
1654 
1655 	/* tell ublksrv one io request is coming */
1656 	io_uring_cmd_done(cmd, res, issue_flags);
1657 }
1658 
1659 #define UBLK_REQUEUE_DELAY_MS	3
1660 
1661 static inline void __ublk_abort_rq(struct ublk_queue *ubq,
1662 		struct request *rq)
1663 {
1664 	/* We cannot process this rq so just requeue it. */
1665 	if (ublk_nosrv_dev_should_queue_io(ubq->dev))
1666 		blk_mq_requeue_request(rq, false);
1667 	else
1668 		ublk_end_request(rq, BLK_STS_IOERR);
1669 }
1670 
1671 static void
1672 ublk_auto_buf_reg_fallback(const struct ublk_queue *ubq, u16 tag)
1673 {
1674 	struct ublksrv_io_desc *iod = ublk_get_iod(ubq, tag);
1675 
1676 	iod->op_flags |= UBLK_IO_F_NEED_REG_BUF;
1677 }
1678 
1679 enum auto_buf_reg_res {
1680 	AUTO_BUF_REG_FAIL,
1681 	AUTO_BUF_REG_FALLBACK,
1682 	AUTO_BUF_REG_OK,
1683 };
1684 
1685 /*
1686  * Setup io state after auto buffer registration.
1687  *
1688  * Must be called after ublk_auto_buf_register() is done.
1689  * Caller must hold io->lock in batch context.
1690  */
1691 static void ublk_auto_buf_io_setup(const struct ublk_queue *ubq,
1692 				   struct request *req, struct ublk_io *io,
1693 				   struct io_uring_cmd *cmd,
1694 				   enum auto_buf_reg_res res)
1695 {
1696 	if (res == AUTO_BUF_REG_OK) {
1697 		io->task_registered_buffers = 1;
1698 		io->buf_ctx_handle = io_uring_cmd_ctx_handle(cmd);
1699 		io->flags |= UBLK_IO_FLAG_AUTO_BUF_REG;
1700 	}
1701 	ublk_init_req_ref(ubq, io);
1702 	__ublk_prep_compl_io_cmd(io, req);
1703 }
1704 
1705 /* Register request bvec to io_uring for auto buffer registration. */
1706 static enum auto_buf_reg_res
1707 ublk_auto_buf_register(const struct ublk_queue *ubq, struct request *req,
1708 		       struct ublk_io *io, struct io_uring_cmd *cmd,
1709 		       unsigned int issue_flags)
1710 {
1711 	int ret;
1712 
1713 	ret = io_buffer_register_request(cmd, req, ublk_io_release,
1714 					 io->buf.auto_reg.index, issue_flags);
1715 	if (ret) {
1716 		if (io->buf.auto_reg.flags & UBLK_AUTO_BUF_REG_FALLBACK) {
1717 			ublk_auto_buf_reg_fallback(ubq, req->tag);
1718 			return AUTO_BUF_REG_FALLBACK;
1719 		}
1720 		ublk_end_request(req, BLK_STS_IOERR);
1721 		return AUTO_BUF_REG_FAIL;
1722 	}
1723 
1724 	return AUTO_BUF_REG_OK;
1725 }
1726 
1727 /*
1728  * Dispatch IO to userspace with auto buffer registration.
1729  *
1730  * Only called in non-batch context from task work, io->lock not held.
1731  */
1732 static void ublk_auto_buf_dispatch(const struct ublk_queue *ubq,
1733 				   struct request *req, struct ublk_io *io,
1734 				   struct io_uring_cmd *cmd,
1735 				   unsigned int issue_flags)
1736 {
1737 	enum auto_buf_reg_res res = ublk_auto_buf_register(ubq, req, io, cmd,
1738 			issue_flags);
1739 
1740 	if (res != AUTO_BUF_REG_FAIL) {
1741 		ublk_auto_buf_io_setup(ubq, req, io, cmd, res);
1742 		io_uring_cmd_done(cmd, UBLK_IO_RES_OK, issue_flags);
1743 	}
1744 }
1745 
1746 static bool ublk_start_io(const struct ublk_queue *ubq, struct request *req,
1747 			  struct ublk_io *io)
1748 {
1749 	unsigned mapped_bytes;
1750 
1751 	/* shmem zero copy: skip data copy, pages already shared */
1752 	if (!ublk_need_map_io(ubq) || !ublk_need_map_req(req) ||
1753 	    ublk_iod_is_shmem_zc(ubq, req->tag))
1754 		return true;
1755 
1756 	mapped_bytes = ublk_map_io(req, io);
1757 
1758 	/* partially mapped, update io descriptor */
1759 	if (unlikely(mapped_bytes != blk_rq_bytes(req))) {
1760 		/*
1761 		 * Nothing mapped, retry until we succeed.
1762 		 *
1763 		 * We may never succeed in mapping any bytes here because
1764 		 * of OOM. TODO: reserve one buffer with single page pinned
1765 		 * for providing forward progress guarantee.
1766 		 */
1767 		if (unlikely(!mapped_bytes)) {
1768 			blk_mq_requeue_request(req, false);
1769 			blk_mq_delay_kick_requeue_list(req->q,
1770 					UBLK_REQUEUE_DELAY_MS);
1771 			return false;
1772 		}
1773 
1774 		ublk_get_iod(ubq, req->tag)->nr_sectors =
1775 			mapped_bytes >> 9;
1776 	}
1777 
1778 	return true;
1779 }
1780 
1781 static void ublk_dispatch_req(struct ublk_queue *ubq, struct request *req)
1782 {
1783 	unsigned int issue_flags = IO_URING_CMD_TASK_WORK_ISSUE_FLAGS;
1784 	u16 tag = req->tag;
1785 	struct ublk_io *io = &ubq->ios[tag];
1786 
1787 	ublk_setup_iod(ubq, req);
1788 	pr_devel("%s: complete: qid %d tag %d io_flags %x addr %llx\n",
1789 			__func__, ubq->q_id, req->tag, io->flags,
1790 			ublk_get_iod(ubq, req->tag)->addr);
1791 
1792 	/*
1793 	 * Task is exiting if either:
1794 	 *
1795 	 * (1) current != io->task.
1796 	 * io_uring_cmd_complete_in_task() tries to run task_work
1797 	 * in a workqueue if cmd's task is PF_EXITING.
1798 	 *
1799 	 * (2) current->flags & PF_EXITING.
1800 	 */
1801 	if (unlikely(current != io->task || current->flags & PF_EXITING)) {
1802 		__ublk_abort_rq(ubq, req);
1803 		return;
1804 	}
1805 
1806 	if (ublk_need_get_data(ubq) && ublk_need_map_req(req)) {
1807 		/*
1808 		 * We have not handled UBLK_IO_NEED_GET_DATA command yet,
1809 		 * so immediately pass UBLK_IO_RES_NEED_GET_DATA to ublksrv
1810 		 * and notify it.
1811 		 */
1812 		io->flags |= UBLK_IO_FLAG_NEED_GET_DATA;
1813 		pr_devel("%s: need get data. qid %d tag %d io_flags %x\n",
1814 				__func__, ubq->q_id, req->tag, io->flags);
1815 		ublk_complete_io_cmd(io, req, UBLK_IO_RES_NEED_GET_DATA,
1816 				     issue_flags);
1817 		return;
1818 	}
1819 
1820 	if (!ublk_start_io(ubq, req, io))
1821 		return;
1822 
1823 	if (ublk_support_auto_buf_reg(ubq) && blk_rq_has_data(req)) {
1824 		ublk_auto_buf_dispatch(ubq, req, io, io->cmd, issue_flags);
1825 	} else {
1826 		ublk_init_req_ref(ubq, io);
1827 		ublk_complete_io_cmd(io, req, UBLK_IO_RES_OK, issue_flags);
1828 	}
1829 }
1830 
1831 static bool __ublk_batch_prep_dispatch(struct ublk_queue *ubq,
1832 				       const struct ublk_batch_io_data *data,
1833 				       unsigned short tag)
1834 {
1835 	struct ublk_device *ub = data->ub;
1836 	struct ublk_io *io = &ubq->ios[tag];
1837 	struct request *req = blk_mq_tag_to_rq(ub->tag_set.tags[ubq->q_id], tag);
1838 	enum auto_buf_reg_res res = AUTO_BUF_REG_FALLBACK;
1839 	struct io_uring_cmd *cmd = data->cmd;
1840 
1841 	ublk_setup_iod(ubq, req);
1842 	if (!ublk_start_io(ubq, req, io))
1843 		return false;
1844 
1845 	if (ublk_support_auto_buf_reg(ubq) && blk_rq_has_data(req)) {
1846 		res = ublk_auto_buf_register(ubq, req, io, cmd,
1847 				data->issue_flags);
1848 
1849 		if (res == AUTO_BUF_REG_FAIL)
1850 			return false;
1851 	}
1852 
1853 	ublk_io_lock(io);
1854 	ublk_auto_buf_io_setup(ubq, req, io, cmd, res);
1855 	ublk_io_unlock(io);
1856 
1857 	return true;
1858 }
1859 
1860 static bool ublk_batch_prep_dispatch(struct ublk_queue *ubq,
1861 				     const struct ublk_batch_io_data *data,
1862 				     unsigned short *tag_buf,
1863 				     unsigned int len)
1864 {
1865 	bool has_unused = false;
1866 	unsigned int i;
1867 
1868 	for (i = 0; i < len; i++) {
1869 		unsigned short tag = tag_buf[i];
1870 
1871 		if (!__ublk_batch_prep_dispatch(ubq, data, tag)) {
1872 			tag_buf[i] = UBLK_BATCH_IO_UNUSED_TAG;
1873 			has_unused = true;
1874 		}
1875 	}
1876 
1877 	return has_unused;
1878 }
1879 
1880 /*
1881  * Filter out UBLK_BATCH_IO_UNUSED_TAG entries from tag_buf.
1882  * Returns the new length after filtering.
1883  */
1884 static noinline unsigned int ublk_filter_unused_tags(unsigned short *tag_buf,
1885 					    unsigned int len)
1886 {
1887 	unsigned int i, j;
1888 
1889 	for (i = 0, j = 0; i < len; i++) {
1890 		if (tag_buf[i] != UBLK_BATCH_IO_UNUSED_TAG) {
1891 			if (i != j)
1892 				tag_buf[j] = tag_buf[i];
1893 			j++;
1894 		}
1895 	}
1896 
1897 	return j;
1898 }
1899 
1900 static noinline void ublk_batch_dispatch_fail(struct ublk_queue *ubq,
1901 		const struct ublk_batch_io_data *data,
1902 		unsigned short *tag_buf, size_t len, int ret)
1903 {
1904 	int i, res;
1905 
1906 	/*
1907 	 * Undo prep state for all IOs since userspace never received them.
1908 	 * This restores IOs to pre-prepared state so they can be cleanly
1909 	 * re-prepared when tags are pulled from FIFO again.
1910 	 */
1911 	for (i = 0; i < len; i++) {
1912 		struct ublk_io *io = &ubq->ios[tag_buf[i]];
1913 		int index = -1;
1914 
1915 		ublk_io_lock(io);
1916 		if (io->flags & UBLK_IO_FLAG_AUTO_BUF_REG)
1917 			index = io->buf.auto_reg.index;
1918 		io->flags &= ~(UBLK_IO_FLAG_OWNED_BY_SRV | UBLK_IO_FLAG_AUTO_BUF_REG);
1919 		io->flags |= UBLK_IO_FLAG_ACTIVE;
1920 		ublk_io_unlock(io);
1921 
1922 		if (index != -1)
1923 			io_buffer_unregister(data->cmd, index,
1924 					data->issue_flags);
1925 	}
1926 
1927 	res = kfifo_in_spinlocked_noirqsave(&ubq->evts_fifo,
1928 		tag_buf, len, &ubq->evts_lock);
1929 
1930 	pr_warn_ratelimited("%s: copy tags or post CQE failure, move back "
1931 			"tags(%d %zu) ret %d\n", __func__, res, len,
1932 			ret);
1933 }
1934 
1935 #define MAX_NR_TAG 128
1936 static int __ublk_batch_dispatch(struct ublk_queue *ubq,
1937 				 const struct ublk_batch_io_data *data,
1938 				 struct ublk_batch_fetch_cmd *fcmd)
1939 {
1940 	const unsigned int tag_sz = sizeof(unsigned short);
1941 	unsigned short tag_buf[MAX_NR_TAG];
1942 	struct io_br_sel sel;
1943 	size_t len = 0;
1944 	bool needs_filter;
1945 	int ret;
1946 
1947 	WARN_ON_ONCE(data->cmd != fcmd->cmd);
1948 
1949 	sel = io_uring_cmd_buffer_select(fcmd->cmd, fcmd->buf_group, &len,
1950 					 data->issue_flags);
1951 	if (sel.val < 0)
1952 		return sel.val;
1953 	if (!sel.addr)
1954 		return -ENOBUFS;
1955 
1956 	/* single reader needn't lock and sizeof(kfifo element) is 2 bytes */
1957 	len = min(len, sizeof(tag_buf)) / tag_sz;
1958 	len = kfifo_out(&ubq->evts_fifo, tag_buf, len);
1959 
1960 	needs_filter = ublk_batch_prep_dispatch(ubq, data, tag_buf, len);
1961 	/* Filter out unused tags before posting to userspace */
1962 	if (unlikely(needs_filter)) {
1963 		int new_len = ublk_filter_unused_tags(tag_buf, len);
1964 
1965 		/* return actual length if all are failed or requeued */
1966 		if (!new_len) {
1967 			/* release the selected buffer */
1968 			sel.val = 0;
1969 			WARN_ON_ONCE(!io_uring_mshot_cmd_post_cqe(fcmd->cmd,
1970 						&sel, data->issue_flags));
1971 			return len;
1972 		}
1973 		len = new_len;
1974 	}
1975 
1976 	sel.val = ublk_batch_copy_io_tags(fcmd, sel.addr, tag_buf, len * tag_sz);
1977 	ret = ublk_batch_fetch_post_cqe(fcmd, &sel, data->issue_flags);
1978 	if (unlikely(ret < 0))
1979 		ublk_batch_dispatch_fail(ubq, data, tag_buf, len, ret);
1980 	return ret;
1981 }
1982 
1983 static struct ublk_batch_fetch_cmd *__ublk_acquire_fcmd(
1984 		struct ublk_queue *ubq)
1985 {
1986 	struct ublk_batch_fetch_cmd *fcmd;
1987 
1988 	lockdep_assert_held(&ubq->evts_lock);
1989 
1990 	/*
1991 	 * Ordering updating ubq->evts_fifo and checking ubq->active_fcmd.
1992 	 *
1993 	 * The pair is the smp_mb() in ublk_batch_dispatch().
1994 	 *
1995 	 * If ubq->active_fcmd is observed as non-NULL, the new added tags
1996 	 * can be visisible in ublk_batch_dispatch() with the barrier pairing.
1997 	 */
1998 	smp_mb();
1999 	if (READ_ONCE(ubq->active_fcmd)) {
2000 		fcmd = NULL;
2001 	} else {
2002 		fcmd = list_first_entry_or_null(&ubq->fcmd_head,
2003 				struct ublk_batch_fetch_cmd, node);
2004 		WRITE_ONCE(ubq->active_fcmd, fcmd);
2005 	}
2006 	return fcmd;
2007 }
2008 
2009 static void ublk_batch_tw_cb(struct io_tw_req tw_req, io_tw_token_t tw)
2010 {
2011 	unsigned int issue_flags = IO_URING_CMD_TASK_WORK_ISSUE_FLAGS;
2012 	struct io_uring_cmd *cmd = io_uring_cmd_from_tw(tw_req);
2013 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
2014 	struct ublk_batch_fetch_cmd *fcmd = pdu->fcmd;
2015 	struct ublk_batch_io_data data = {
2016 		.ub = pdu->ubq->dev,
2017 		.cmd = fcmd->cmd,
2018 		.issue_flags = issue_flags,
2019 	};
2020 
2021 	WARN_ON_ONCE(pdu->ubq->active_fcmd != fcmd);
2022 
2023 	ublk_batch_dispatch(pdu->ubq, &data, fcmd);
2024 }
2025 
2026 static void
2027 ublk_batch_dispatch(struct ublk_queue *ubq,
2028 		    const struct ublk_batch_io_data *data,
2029 		    struct ublk_batch_fetch_cmd *fcmd)
2030 {
2031 	struct ublk_batch_fetch_cmd *new_fcmd;
2032 	unsigned tried = 0;
2033 	int ret = 0;
2034 
2035 again:
2036 	while (!ublk_io_evts_empty(ubq)) {
2037 		ret = __ublk_batch_dispatch(ubq, data, fcmd);
2038 		if (ret <= 0)
2039 			break;
2040 	}
2041 
2042 	if (ret < 0) {
2043 		ublk_batch_deinit_fetch_buf(ubq, data, fcmd, ret);
2044 		return;
2045 	}
2046 
2047 	__ublk_release_fcmd(ubq);
2048 	/*
2049 	 * Order clearing ubq->active_fcmd from __ublk_release_fcmd() and
2050 	 * checking ubq->evts_fifo.
2051 	 *
2052 	 * The pair is the smp_mb() in __ublk_acquire_fcmd().
2053 	 */
2054 	smp_mb();
2055 	if (likely(ublk_io_evts_empty(ubq)))
2056 		return;
2057 
2058 	spin_lock(&ubq->evts_lock);
2059 	new_fcmd = __ublk_acquire_fcmd(ubq);
2060 	spin_unlock(&ubq->evts_lock);
2061 
2062 	if (!new_fcmd)
2063 		return;
2064 
2065 	/* Avoid lockup by allowing to handle at most 32 batches */
2066 	if (new_fcmd == fcmd && tried++ < 32)
2067 		goto again;
2068 
2069 	io_uring_cmd_complete_in_task(new_fcmd->cmd, ublk_batch_tw_cb);
2070 }
2071 
2072 static void ublk_cmd_tw_cb(struct io_tw_req tw_req, io_tw_token_t tw)
2073 {
2074 	struct io_uring_cmd *cmd = io_uring_cmd_from_tw(tw_req);
2075 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
2076 	struct ublk_queue *ubq = pdu->ubq;
2077 
2078 	ublk_dispatch_req(ubq, pdu->req);
2079 }
2080 
2081 static void ublk_batch_queue_cmd(struct ublk_queue *ubq, struct request *rq, bool last)
2082 {
2083 	unsigned short tag = rq->tag;
2084 	struct ublk_batch_fetch_cmd *fcmd = NULL;
2085 
2086 	spin_lock(&ubq->evts_lock);
2087 	kfifo_put(&ubq->evts_fifo, tag);
2088 	if (last)
2089 		fcmd = __ublk_acquire_fcmd(ubq);
2090 	spin_unlock(&ubq->evts_lock);
2091 
2092 	if (fcmd)
2093 		io_uring_cmd_complete_in_task(fcmd->cmd, ublk_batch_tw_cb);
2094 }
2095 
2096 static void ublk_queue_cmd(struct ublk_queue *ubq, struct request *rq)
2097 {
2098 	struct io_uring_cmd *cmd = ubq->ios[rq->tag].cmd;
2099 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
2100 
2101 	pdu->req = rq;
2102 	io_uring_cmd_complete_in_task(cmd, ublk_cmd_tw_cb);
2103 }
2104 
2105 static void ublk_cmd_list_tw_cb(struct io_tw_req tw_req, io_tw_token_t tw)
2106 {
2107 	struct io_uring_cmd *cmd = io_uring_cmd_from_tw(tw_req);
2108 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
2109 	struct request *rq = pdu->req_list;
2110 	struct request *next;
2111 
2112 	do {
2113 		next = rq->rq_next;
2114 		rq->rq_next = NULL;
2115 		ublk_dispatch_req(rq->mq_hctx->driver_data, rq);
2116 		rq = next;
2117 	} while (rq);
2118 }
2119 
2120 static void ublk_queue_cmd_list(struct ublk_io *io, struct rq_list *l)
2121 {
2122 	struct io_uring_cmd *cmd = io->cmd;
2123 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
2124 
2125 	pdu->req_list = rq_list_peek(l);
2126 	rq_list_init(l);
2127 	io_uring_cmd_complete_in_task(cmd, ublk_cmd_list_tw_cb);
2128 }
2129 
2130 static enum blk_eh_timer_return ublk_timeout(struct request *rq)
2131 {
2132 	struct ublk_queue *ubq = rq->mq_hctx->driver_data;
2133 	pid_t tgid = ubq->dev->ublksrv_tgid;
2134 	struct task_struct *p;
2135 	struct pid *pid;
2136 
2137 	if (!(ubq->flags & UBLK_F_UNPRIVILEGED_DEV))
2138 		return BLK_EH_RESET_TIMER;
2139 
2140 	if (unlikely(!tgid))
2141 		return BLK_EH_RESET_TIMER;
2142 
2143 	rcu_read_lock();
2144 	pid = find_vpid(tgid);
2145 	p = pid_task(pid, PIDTYPE_PID);
2146 	if (p)
2147 		send_sig(SIGKILL, p, 0);
2148 	rcu_read_unlock();
2149 	return BLK_EH_DONE;
2150 }
2151 
2152 static blk_status_t ublk_prep_req(struct ublk_queue *ubq, struct request *rq,
2153 				  bool check_cancel)
2154 {
2155 	if (unlikely(READ_ONCE(ubq->fail_io)))
2156 		return BLK_STS_TARGET;
2157 
2158 	/* With recovery feature enabled, force_abort is set in
2159 	 * ublk_stop_dev() before calling del_gendisk(). We have to
2160 	 * abort all requeued and new rqs here to let del_gendisk()
2161 	 * move on. Besides, we cannot not call io_uring_cmd_complete_in_task()
2162 	 * to avoid UAF on io_uring ctx.
2163 	 *
2164 	 * Note: force_abort is guaranteed to be seen because it is set
2165 	 * before request queue is unqiuesced.
2166 	 */
2167 	if (ublk_nosrv_should_queue_io(ubq) &&
2168 	    unlikely(READ_ONCE(ubq->force_abort)))
2169 		return BLK_STS_IOERR;
2170 
2171 	if (check_cancel && unlikely(ubq->canceling))
2172 		return BLK_STS_IOERR;
2173 
2174 	/* fill iod to slot in io cmd buffer */
2175 	if (unlikely(!ublk_validate_req(ubq, rq)))
2176 		return BLK_STS_IOERR;
2177 
2178 	blk_mq_start_request(rq);
2179 	return BLK_STS_OK;
2180 }
2181 
2182 /*
2183  * Common helper for queue_rq that handles request preparation and
2184  * cancellation checks. Returns status and sets should_queue to indicate
2185  * whether the caller should proceed with queuing the request.
2186  */
2187 static inline blk_status_t __ublk_queue_rq_common(struct ublk_queue *ubq,
2188 						   struct request *rq,
2189 						   bool *should_queue)
2190 {
2191 	blk_status_t res;
2192 
2193 	res = ublk_prep_req(ubq, rq, false);
2194 	if (res != BLK_STS_OK) {
2195 		*should_queue = false;
2196 		return res;
2197 	}
2198 
2199 	/*
2200 	 * ->canceling has to be handled after ->force_abort and ->fail_io
2201 	 * is dealt with, otherwise this request may not be failed in case
2202 	 * of recovery, and cause hang when deleting disk
2203 	 */
2204 	if (unlikely(ubq->canceling)) {
2205 		*should_queue = false;
2206 		__ublk_abort_rq(ubq, rq);
2207 		return BLK_STS_OK;
2208 	}
2209 
2210 	*should_queue = true;
2211 	return BLK_STS_OK;
2212 }
2213 
2214 static blk_status_t ublk_queue_rq(struct blk_mq_hw_ctx *hctx,
2215 		const struct blk_mq_queue_data *bd)
2216 {
2217 	struct ublk_queue *ubq = hctx->driver_data;
2218 	struct request *rq = bd->rq;
2219 	bool should_queue;
2220 	blk_status_t res;
2221 
2222 	res = __ublk_queue_rq_common(ubq, rq, &should_queue);
2223 	if (!should_queue)
2224 		return res;
2225 
2226 	ublk_queue_cmd(ubq, rq);
2227 	return BLK_STS_OK;
2228 }
2229 
2230 static blk_status_t ublk_batch_queue_rq(struct blk_mq_hw_ctx *hctx,
2231 		const struct blk_mq_queue_data *bd)
2232 {
2233 	struct ublk_queue *ubq = hctx->driver_data;
2234 	struct request *rq = bd->rq;
2235 	bool should_queue;
2236 	blk_status_t res;
2237 
2238 	res = __ublk_queue_rq_common(ubq, rq, &should_queue);
2239 	if (!should_queue)
2240 		return res;
2241 
2242 	ublk_batch_queue_cmd(ubq, rq, bd->last);
2243 	return BLK_STS_OK;
2244 }
2245 
2246 static inline bool ublk_belong_to_same_batch(const struct ublk_io *io,
2247 					     const struct ublk_io *io2)
2248 {
2249 	return (io_uring_cmd_ctx_handle(io->cmd) ==
2250 		io_uring_cmd_ctx_handle(io2->cmd)) &&
2251 		(io->task == io2->task);
2252 }
2253 
2254 static void ublk_commit_rqs(struct blk_mq_hw_ctx *hctx)
2255 {
2256 	struct ublk_queue *ubq = hctx->driver_data;
2257 	struct ublk_batch_fetch_cmd *fcmd;
2258 
2259 	spin_lock(&ubq->evts_lock);
2260 	fcmd = __ublk_acquire_fcmd(ubq);
2261 	spin_unlock(&ubq->evts_lock);
2262 
2263 	if (fcmd)
2264 		io_uring_cmd_complete_in_task(fcmd->cmd, ublk_batch_tw_cb);
2265 }
2266 
2267 static void ublk_queue_rqs(struct rq_list *rqlist)
2268 {
2269 	struct rq_list requeue_list = { };
2270 	struct rq_list submit_list = { };
2271 	struct ublk_io *io = NULL;
2272 	struct request *req;
2273 
2274 	while ((req = rq_list_pop(rqlist))) {
2275 		struct ublk_queue *this_q = req->mq_hctx->driver_data;
2276 		struct ublk_io *this_io = &this_q->ios[req->tag];
2277 
2278 		if (ublk_prep_req(this_q, req, true) != BLK_STS_OK) {
2279 			rq_list_add_tail(&requeue_list, req);
2280 			continue;
2281 		}
2282 
2283 		if (io && !ublk_belong_to_same_batch(io, this_io) &&
2284 				!rq_list_empty(&submit_list))
2285 			ublk_queue_cmd_list(io, &submit_list);
2286 		io = this_io;
2287 		rq_list_add_tail(&submit_list, req);
2288 	}
2289 
2290 	if (!rq_list_empty(&submit_list))
2291 		ublk_queue_cmd_list(io, &submit_list);
2292 	*rqlist = requeue_list;
2293 }
2294 
2295 static void ublk_batch_queue_cmd_list(struct ublk_queue *ubq, struct rq_list *l)
2296 {
2297 	unsigned short tags[MAX_NR_TAG];
2298 	struct ublk_batch_fetch_cmd *fcmd;
2299 	struct request *rq;
2300 	unsigned cnt = 0;
2301 
2302 	spin_lock(&ubq->evts_lock);
2303 	rq_list_for_each(l, rq) {
2304 		tags[cnt++] = (unsigned short)rq->tag;
2305 		if (cnt >= MAX_NR_TAG) {
2306 			kfifo_in(&ubq->evts_fifo, tags, cnt);
2307 			cnt = 0;
2308 		}
2309 	}
2310 	if (cnt)
2311 		kfifo_in(&ubq->evts_fifo, tags, cnt);
2312 	fcmd = __ublk_acquire_fcmd(ubq);
2313 	spin_unlock(&ubq->evts_lock);
2314 
2315 	rq_list_init(l);
2316 	if (fcmd)
2317 		io_uring_cmd_complete_in_task(fcmd->cmd, ublk_batch_tw_cb);
2318 }
2319 
2320 static void ublk_batch_queue_rqs(struct rq_list *rqlist)
2321 {
2322 	struct rq_list requeue_list = { };
2323 	struct rq_list submit_list = { };
2324 	struct ublk_queue *ubq = NULL;
2325 	struct request *req;
2326 
2327 	while ((req = rq_list_pop(rqlist))) {
2328 		struct ublk_queue *this_q = req->mq_hctx->driver_data;
2329 
2330 		if (ublk_prep_req(this_q, req, true) != BLK_STS_OK) {
2331 			rq_list_add_tail(&requeue_list, req);
2332 			continue;
2333 		}
2334 
2335 		if (ubq && this_q != ubq && !rq_list_empty(&submit_list))
2336 			ublk_batch_queue_cmd_list(ubq, &submit_list);
2337 		ubq = this_q;
2338 		rq_list_add_tail(&submit_list, req);
2339 	}
2340 
2341 	if (!rq_list_empty(&submit_list))
2342 		ublk_batch_queue_cmd_list(ubq, &submit_list);
2343 	*rqlist = requeue_list;
2344 }
2345 
2346 static int ublk_init_hctx(struct blk_mq_hw_ctx *hctx, void *driver_data,
2347 		unsigned int hctx_idx)
2348 {
2349 	struct ublk_device *ub = driver_data;
2350 	struct ublk_queue *ubq = ublk_get_queue(ub, hctx->queue_num);
2351 
2352 	hctx->driver_data = ubq;
2353 	return 0;
2354 }
2355 
2356 static const struct blk_mq_ops ublk_mq_ops = {
2357 	.queue_rq       = ublk_queue_rq,
2358 	.queue_rqs      = ublk_queue_rqs,
2359 	.init_hctx	= ublk_init_hctx,
2360 	.timeout	= ublk_timeout,
2361 };
2362 
2363 static const struct blk_mq_ops ublk_batch_mq_ops = {
2364 	.commit_rqs	= ublk_commit_rqs,
2365 	.queue_rq       = ublk_batch_queue_rq,
2366 	.queue_rqs      = ublk_batch_queue_rqs,
2367 	.init_hctx	= ublk_init_hctx,
2368 	.timeout	= ublk_timeout,
2369 };
2370 
2371 static void ublk_queue_reinit(struct ublk_device *ub, struct ublk_queue *ubq)
2372 {
2373 	u16 i;
2374 
2375 	ubq->nr_io_ready = 0;
2376 
2377 	for (i = 0; i < ubq->q_depth; i++) {
2378 		struct ublk_io *io = &ubq->ios[i];
2379 
2380 		/*
2381 		 * UBLK_IO_FLAG_CANCELED is kept for avoiding to touch
2382 		 * io->cmd
2383 		 */
2384 		io->flags &= UBLK_IO_FLAG_CANCELED;
2385 		io->cmd = NULL;
2386 		io->buf.addr = 0;
2387 
2388 		/*
2389 		 * old task is PF_EXITING, put it now
2390 		 *
2391 		 * It could be NULL in case of closing one quiesced
2392 		 * device.
2393 		 */
2394 		if (io->task) {
2395 			put_task_struct(io->task);
2396 			io->task = NULL;
2397 		}
2398 
2399 		WARN_ON_ONCE(refcount_read(&io->ref));
2400 		WARN_ON_ONCE(io->task_registered_buffers);
2401 	}
2402 }
2403 
2404 static int ublk_ch_open(struct inode *inode, struct file *filp)
2405 {
2406 	struct ublk_device *ub = container_of(inode->i_cdev,
2407 			struct ublk_device, cdev);
2408 
2409 	if (test_and_set_bit(UB_STATE_OPEN, &ub->state))
2410 		return -EBUSY;
2411 	filp->private_data = ub;
2412 	ub->ublksrv_tgid = current->tgid;
2413 	mutex_lock(&ub->cancel_mutex);
2414 	ub->ch_file = filp;
2415 	mutex_unlock(&ub->cancel_mutex);
2416 	return 0;
2417 }
2418 
2419 static void ublk_reset_ch_dev(struct ublk_device *ub)
2420 {
2421 	u16 i;
2422 
2423 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++) {
2424 		struct ublk_queue *ubq = ublk_get_queue(ub, i);
2425 
2426 		/* Sync with ublk_cancel_cmd() */
2427 		spin_lock(&ubq->cancel_lock);
2428 		ublk_queue_reinit(ub, ubq);
2429 		spin_unlock(&ubq->cancel_lock);
2430 	}
2431 
2432 	/* a new FETCH round starts, the queues stay canceling until ready */
2433 	mutex_lock(&ub->cancel_mutex);
2434 	ub->canceling = false;
2435 	mutex_unlock(&ub->cancel_mutex);
2436 
2437 	/* set to NULL, otherwise new tasks cannot mmap io_cmd_buf */
2438 	ub->mm = NULL;
2439 	ub->nr_queue_ready = 0;
2440 	ub->unprivileged_daemons = false;
2441 	ub->ublksrv_tgid = -1;
2442 	clear_bit(UB_STATE_STOPPING, &ub->state);
2443 }
2444 
2445 static struct gendisk *ublk_get_disk(struct ublk_device *ub)
2446 {
2447 	struct gendisk *disk;
2448 
2449 	spin_lock(&ub->lock);
2450 	disk = ub->ub_disk;
2451 	if (disk)
2452 		get_device(disk_to_dev(disk));
2453 	spin_unlock(&ub->lock);
2454 
2455 	return disk;
2456 }
2457 
2458 static void ublk_put_disk(struct gendisk *disk)
2459 {
2460 	if (disk)
2461 		put_device(disk_to_dev(disk));
2462 }
2463 
2464 static void ublk_partition_scan_work(struct work_struct *work)
2465 {
2466 	struct ublk_device *ub =
2467 		container_of(work, struct ublk_device, partition_scan_work);
2468 	/* Hold disk reference to prevent UAF during concurrent teardown */
2469 	struct gendisk *disk = ublk_get_disk(ub);
2470 
2471 	if (!disk)
2472 		return;
2473 
2474 	if (WARN_ON_ONCE(!test_and_clear_bit(GD_SUPPRESS_PART_SCAN,
2475 					     &disk->state)))
2476 		goto out;
2477 
2478 	mutex_lock(&disk->open_mutex);
2479 	bdev_disk_changed(disk, false);
2480 	mutex_unlock(&disk->open_mutex);
2481 out:
2482 	ublk_put_disk(disk);
2483 }
2484 
2485 /*
2486  * Use this function to ensure that ->canceling is consistently set for
2487  * the device and all queues. Do not set these flags directly.
2488  *
2489  * Caller must ensure that:
2490  * - cancel_mutex is held. This ensures that there is no concurrent
2491  *   access to ub->canceling and no concurrent writes to ubq->canceling.
2492  * - there are no concurrent reads of ubq->canceling from the queue_rq
2493  *   path. This can be done by quiescing the queue, or through other
2494  *   means.
2495  */
2496 static void ublk_set_canceling(struct ublk_device *ub, bool canceling)
2497 	__must_hold(&ub->cancel_mutex)
2498 {
2499 	u16 i;
2500 
2501 	ub->canceling = canceling;
2502 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
2503 		ublk_get_queue(ub, i)->canceling = canceling;
2504 }
2505 
2506 static bool ublk_check_and_reset_active_ref(struct ublk_device *ub)
2507 {
2508 	u16 i, j;
2509 
2510 	if (!ublk_dev_need_req_ref(ub))
2511 		return false;
2512 
2513 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++) {
2514 		struct ublk_queue *ubq = ublk_get_queue(ub, i);
2515 
2516 		for (j = 0; j < ubq->q_depth; j++) {
2517 			struct ublk_io *io = &ubq->ios[j];
2518 			unsigned int refs = refcount_read(&io->ref) +
2519 				io->task_registered_buffers;
2520 
2521 			/*
2522 			 * UBLK_REFCOUNT_INIT or zero means no active
2523 			 * reference
2524 			 */
2525 			if (refs != UBLK_REFCOUNT_INIT && refs != 0)
2526 				return true;
2527 
2528 			/* reset to zero if the io hasn't active references */
2529 			refcount_set(&io->ref, 0);
2530 			io->task_registered_buffers = 0;
2531 		}
2532 	}
2533 	return false;
2534 }
2535 
2536 static void ublk_ch_release_work_fn(struct work_struct *work)
2537 {
2538 	struct ublk_device *ub =
2539 		container_of(work, struct ublk_device, exit_work.work);
2540 	struct gendisk *disk;
2541 	u16 i;
2542 
2543 	/*
2544 	 * For zero-copy and auto buffer register modes, I/O references
2545 	 * might not be dropped naturally when the daemon is killed, but
2546 	 * io_uring guarantees that registered bvec kernel buffers are
2547 	 * unregistered finally when freeing io_uring context, then the
2548 	 * active references are dropped.
2549 	 *
2550 	 * Wait until active references are dropped for avoiding use-after-free
2551 	 *
2552 	 * registered buffer may be unregistered in io_ring's release hander,
2553 	 * so have to wait by scheduling work function for avoiding the two
2554 	 * file release dependency.
2555 	 */
2556 	if (ublk_check_and_reset_active_ref(ub)) {
2557 		schedule_delayed_work(&ub->exit_work, 1);
2558 		return;
2559 	}
2560 
2561 	/*
2562 	 * No disk: the device isn't live, or it has been removed already.
2563 	 * There are no requests to abort, but the round still has to be
2564 	 * reset, so that a new server can fetch and start the device.
2565 	 */
2566 	disk = ublk_get_disk(ub);
2567 	if (!disk) {
2568 		mutex_lock(&ub->mutex);
2569 		goto reset;
2570 	}
2571 
2572 	/*
2573 	 * All uring_cmd are done now, so abort any request outstanding to
2574 	 * the ublk server
2575 	 *
2576 	 * This can be done in lockless way because ublk server has been
2577 	 * gone
2578 	 *
2579 	 * More importantly, we have to provide forward progress guarantee
2580 	 * without holding ub->mutex, otherwise control task grabbing
2581 	 * ub->mutex triggers deadlock
2582 	 *
2583 	 * All requests may be inflight, so ->canceling may not be set, set
2584 	 * it now.
2585 	 */
2586 	mutex_lock(&ub->cancel_mutex);
2587 	ublk_set_canceling(ub, true);
2588 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
2589 		ublk_abort_queue(ub, ublk_get_queue(ub, i));
2590 	mutex_unlock(&ub->cancel_mutex);
2591 	blk_mq_kick_requeue_list(disk->queue);
2592 
2593 	/*
2594 	 * All infligh requests have been completed or requeued and any new
2595 	 * request will be failed or requeued via `->canceling` now, so it is
2596 	 * fine to grab ub->mutex now.
2597 	 */
2598 	mutex_lock(&ub->mutex);
2599 
2600 	/* double check after grabbing lock */
2601 	if (!ub->ub_disk)
2602 		goto reset;
2603 
2604 	/*
2605 	 * Transition the device to the nosrv state. What exactly this
2606 	 * means depends on the recovery flags
2607 	 */
2608 	if (ublk_nosrv_should_stop_dev(ub)) {
2609 		/*
2610 		 * Allow any pending/future I/O to pass through quickly
2611 		 * with an error. This is needed because del_gendisk
2612 		 * waits for all pending I/O to complete
2613 		 */
2614 		for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
2615 			WRITE_ONCE(ublk_get_queue(ub, i)->force_abort, true);
2616 
2617 		ublk_stop_dev_unlocked(ub);
2618 	} else {
2619 		if (ublk_nosrv_dev_should_queue_io(ub)) {
2620 			/* ->canceling is set and all requests are aborted */
2621 			ub->dev_info.state = UBLK_S_DEV_QUIESCED;
2622 		} else {
2623 			ub->dev_info.state = UBLK_S_DEV_FAIL_IO;
2624 			for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
2625 				WRITE_ONCE(ublk_get_queue(ub, i)->fail_io, true);
2626 		}
2627 	}
2628 reset:
2629 	/*
2630 	 * All uring_cmd has been done now, reset device & ubq. Under
2631 	 * ub->mutex, so START_DEV sees the round either ready or reset.
2632 	 */
2633 	ublk_reset_ch_dev(ub);
2634 	mutex_unlock(&ub->mutex);
2635 	ublk_put_disk(disk);
2636 	clear_bit(UB_STATE_OPEN, &ub->state);
2637 
2638 	/* put the reference grabbed in ublk_ch_release() */
2639 	ublk_put_device(ub);
2640 	module_put(THIS_MODULE);
2641 }
2642 
2643 static int ublk_ch_release(struct inode *inode, struct file *filp)
2644 {
2645 	struct ublk_device *ub = filp->private_data;
2646 
2647 	mutex_lock(&ub->cancel_mutex);
2648 	ub->ch_file = NULL;
2649 	mutex_unlock(&ub->cancel_mutex);
2650 	/*
2651 	 * Grab ublk device reference, so it won't be gone until we are
2652 	 * really released from work function.
2653 	 */
2654 	ublk_get_device(ub);
2655 
2656 	/* Keep the worker's callback and final device release code resident. */
2657 	__module_get(THIS_MODULE);
2658 	INIT_DELAYED_WORK(&ub->exit_work, ublk_ch_release_work_fn);
2659 	schedule_delayed_work(&ub->exit_work, 0);
2660 	return 0;
2661 }
2662 
2663 /* map pre-allocated per-queue cmd buffer to ublksrv daemon */
2664 static int ublk_ch_mmap(struct file *filp, struct vm_area_struct *vma)
2665 {
2666 	struct ublk_device *ub = filp->private_data;
2667 	size_t sz = vma->vm_end - vma->vm_start;
2668 	size_t max_sz = ublk_max_cmd_buf_size(ub);
2669 	unsigned long pfn, end, phys_off = vma->vm_pgoff << PAGE_SHIFT;
2670 	int ret = 0;
2671 	u16 q_id;
2672 
2673 	spin_lock(&ub->lock);
2674 	if (!ub->mm)
2675 		ub->mm = current->mm;
2676 	if (current->mm != ub->mm)
2677 		ret = -EINVAL;
2678 	spin_unlock(&ub->lock);
2679 
2680 	if (ret)
2681 		return ret;
2682 
2683 	if (vma->vm_flags & VM_WRITE)
2684 		return -EPERM;
2685 
2686 	/*
2687 	 * The per-queue command buffer is kernel-written ABI; prevent
2688 	 * the daemon from upgrading to writable via mprotect().
2689 	 */
2690 	vm_flags_clear(vma, VM_MAYWRITE);
2691 
2692 	end = UBLKSRV_CMD_BUF_OFFSET + ub->dev_info.nr_hw_queues * max_sz;
2693 	if (phys_off < UBLKSRV_CMD_BUF_OFFSET || phys_off >= end)
2694 		return -EINVAL;
2695 
2696 	q_id = (phys_off - UBLKSRV_CMD_BUF_OFFSET) / max_sz;
2697 	pr_devel("%s: qid %d, pid %d, addr %lx pg_off %lx sz %lu\n",
2698 			__func__, q_id, current->pid, vma->vm_start,
2699 			phys_off, (unsigned long)sz);
2700 
2701 	if (sz != ublk_queue_cmd_buf_size(ub))
2702 		return -EINVAL;
2703 
2704 	pfn = virt_to_phys(ublk_queue_cmd_buf(ub, q_id)) >> PAGE_SHIFT;
2705 	return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
2706 }
2707 
2708 static void __ublk_fail_req(struct ublk_device *ub, struct ublk_io *io,
2709 		struct request *req)
2710 {
2711 	WARN_ON_ONCE(!ublk_dev_support_batch_io(ub) &&
2712 			io->flags & UBLK_IO_FLAG_ACTIVE);
2713 
2714 	if (ublk_nosrv_should_reissue_outstanding(ub))
2715 		blk_mq_requeue_request(req, false);
2716 	else {
2717 		io->res = -EIO;
2718 		__ublk_complete_rq(req, io, ublk_dev_need_map_io(ub), NULL);
2719 	}
2720 }
2721 
2722 /*
2723  * Request tag may just be filled to event kfifo, not get chance to
2724  * dispatch, abort these requests too
2725  */
2726 static void ublk_abort_batch_queue(struct ublk_device *ub,
2727 				   struct ublk_queue *ubq)
2728 {
2729 	unsigned short tag;
2730 
2731 	while (kfifo_out(&ubq->evts_fifo, &tag, 1)) {
2732 		struct request *req = blk_mq_tag_to_rq(
2733 				ub->tag_set.tags[ubq->q_id], tag);
2734 
2735 		if (!WARN_ON_ONCE(!req || !blk_mq_request_started(req)))
2736 			__ublk_fail_req(ub, &ubq->ios[tag], req);
2737 	}
2738 }
2739 
2740 /*
2741  * Called from ublk char device release handler, when any uring_cmd is
2742  * done, meantime request queue is "quiesced" since all inflight requests
2743  * can't be completed because ublk server is dead.
2744  *
2745  * So no one can hold our request IO reference any more, simply ignore the
2746  * reference, and complete the request immediately
2747  */
2748 static void ublk_abort_queue(struct ublk_device *ub, struct ublk_queue *ubq)
2749 {
2750 	u16 i;
2751 
2752 	for (i = 0; i < ubq->q_depth; i++) {
2753 		struct ublk_io *io = &ubq->ios[i];
2754 
2755 		if (io->flags & UBLK_IO_FLAG_OWNED_BY_SRV)
2756 			__ublk_fail_req(ub, io, io->req);
2757 	}
2758 
2759 	if (ublk_support_batch_io(ubq))
2760 		ublk_abort_batch_queue(ub, ubq);
2761 }
2762 
2763 static void ublk_start_cancel(struct ublk_device *ub)
2764 {
2765 	struct gendisk *disk;
2766 
2767 	/* sync with ublk_ctrl_start_dev() publishing the disk */
2768 	mutex_lock(&ub->cancel_mutex);
2769 	disk = ublk_get_disk(ub);
2770 	if (ub->canceling)
2771 		goto out;
2772 
2773 	if (disk) {
2774 		/*
2775 		 * Quiesce to serialize with ublk_queue_rq(), ensuring
2776 		 * ubq->canceling is visible when the queue resumes.
2777 		 */
2778 		blk_mq_quiesce_queue(disk->queue);
2779 		ublk_set_canceling(ub, true);
2780 		blk_mq_unquiesce_queue(disk->queue);
2781 	} else {
2782 		/*
2783 		 * Disk not yet allocated by ublk_ctrl_start_dev(), so
2784 		 * there is no request queue and ublk_queue_rq() cannot
2785 		 * be running.  Just set the flag; if start_dev proceeds
2786 		 * later, new I/O will see canceling and be aborted.
2787 		 */
2788 		ublk_set_canceling(ub, true);
2789 	}
2790 out:
2791 	mutex_unlock(&ub->cancel_mutex);
2792 	ublk_put_disk(disk);
2793 }
2794 
2795 static void ublk_cancel_cmd(struct ublk_queue *ubq, u16 tag,
2796 		unsigned int issue_flags)
2797 {
2798 	struct ublk_io *io = &ubq->ios[tag];
2799 	struct ublk_device *ub = ubq->dev;
2800 	struct io_uring_cmd *cmd = NULL;
2801 	struct request *req;
2802 	bool done;
2803 
2804 	if (!(io->flags & UBLK_IO_FLAG_ACTIVE))
2805 		return;
2806 
2807 	/*
2808 	 * Don't try to cancel this command if the request is started for
2809 	 * avoiding race between io_uring_cmd_done() and
2810 	 * io_uring_cmd_complete_in_task().
2811 	 *
2812 	 * Either the started request will be aborted via __ublk_abort_rq(),
2813 	 * then this uring_cmd is canceled next time, or it will be done in
2814 	 * task work function ublk_dispatch_req() because io_uring guarantees
2815 	 * that ublk_dispatch_req() is always called
2816 	 */
2817 	req = blk_mq_tag_to_rq(ub->tag_set.tags[ubq->q_id], tag);
2818 	if (req && blk_mq_request_started(req) && req->tag == tag)
2819 		return;
2820 
2821 	spin_lock(&ubq->cancel_lock);
2822 	done = !!(io->flags & UBLK_IO_FLAG_CANCELED);
2823 	if (!done) {
2824 		io->flags |= UBLK_IO_FLAG_CANCELED;
2825 		/* dependency ordered against smp_wmb() in ublk_prep_cancel() */
2826 		cmd = READ_ONCE(io->cmd);
2827 		io->cmd = NULL;
2828 	}
2829 	spin_unlock(&ubq->cancel_lock);
2830 
2831 	if (!done && cmd)
2832 		io_uring_cmd_done(cmd, UBLK_IO_RES_ABORT, issue_flags);
2833 }
2834 
2835 /*
2836  * Cancel a batch fetch command if it hasn't been claimed by another path.
2837  *
2838  * An fcmd can only be cancelled if:
2839  * 1. It's not the active_fcmd (which is currently being processed)
2840  * 2. It's still on the list (!list_empty check) - once removed from the list,
2841  *    the fcmd is considered claimed and will be freed by whoever removed it
2842  *
2843  * Use list_del_init() so subsequent list_empty() checks work correctly.
2844  */
2845 static void ublk_batch_cancel_cmd(struct ublk_queue *ubq,
2846 				  struct ublk_batch_fetch_cmd *fcmd,
2847 				  unsigned int issue_flags)
2848 {
2849 	bool done;
2850 
2851 	spin_lock(&ubq->evts_lock);
2852 	done = (READ_ONCE(ubq->active_fcmd) != fcmd) && !list_empty(&fcmd->node);
2853 	if (done)
2854 		list_del_init(&fcmd->node);
2855 	spin_unlock(&ubq->evts_lock);
2856 
2857 	if (done) {
2858 		io_uring_cmd_done(fcmd->cmd, UBLK_IO_RES_ABORT, issue_flags);
2859 		ublk_batch_free_fcmd(fcmd);
2860 	}
2861 }
2862 
2863 static void ublk_batch_cancel_queue(struct ublk_queue *ubq)
2864 {
2865 	struct ublk_batch_fetch_cmd *fcmd;
2866 	LIST_HEAD(fcmd_list);
2867 
2868 	spin_lock(&ubq->evts_lock);
2869 	ubq->force_abort = true;
2870 	list_splice_init(&ubq->fcmd_head, &fcmd_list);
2871 	fcmd = READ_ONCE(ubq->active_fcmd);
2872 	if (fcmd)
2873 		list_move(&fcmd->node, &ubq->fcmd_head);
2874 	spin_unlock(&ubq->evts_lock);
2875 
2876 	while (!list_empty(&fcmd_list)) {
2877 		fcmd = list_first_entry(&fcmd_list,
2878 				struct ublk_batch_fetch_cmd, node);
2879 		ublk_batch_cancel_cmd(ubq, fcmd, IO_URING_F_UNLOCKED);
2880 	}
2881 }
2882 
2883 static void ublk_batch_cancel_fn(struct io_uring_cmd *cmd,
2884 				 unsigned int issue_flags)
2885 {
2886 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
2887 	struct ublk_batch_fetch_cmd *fcmd = pdu->fcmd;
2888 	struct ublk_queue *ubq = pdu->ubq;
2889 
2890 	ublk_start_cancel(ubq->dev);
2891 
2892 	ublk_batch_cancel_cmd(ubq, fcmd, issue_flags);
2893 }
2894 
2895 /*
2896  * The ublk char device won't be closed when calling cancel fn, so both
2897  * ublk device and queue are guaranteed to be live
2898  *
2899  * Two-stage cancel:
2900  *
2901  * - make every active uring_cmd done in ->cancel_fn()
2902  *
2903  * - aborting inflight ublk IO requests in ublk char device release handler,
2904  *   which depends on 1st stage because device can only be closed iff all
2905  *   uring_cmd are done
2906  *
2907  * Do _not_ try to acquire ub->mutex before all inflight requests are
2908  * aborted, otherwise deadlock may be caused.
2909  */
2910 static void ublk_uring_cmd_cancel_fn(struct io_uring_cmd *cmd,
2911 		unsigned int issue_flags)
2912 {
2913 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
2914 	struct ublk_queue *ubq = pdu->ubq;
2915 	struct io_uring_cmd *cur;
2916 	struct task_struct *task;
2917 	struct ublk_io *io;
2918 
2919 	if (WARN_ON_ONCE(!ubq))
2920 		return;
2921 
2922 	if (WARN_ON_ONCE(pdu->tag >= ubq->q_depth))
2923 		return;
2924 
2925 	task = io_uring_cmd_get_task(cmd);
2926 	io = &ubq->ios[pdu->tag];
2927 	if (WARN_ON_ONCE(task && task != io->task))
2928 		return;
2929 
2930 	ublk_start_cancel(ubq->dev);
2931 
2932 	/* NULL if a cancel from the control path took it meanwhile */
2933 	cur = READ_ONCE(io->cmd);
2934 	WARN_ON_ONCE(cur && cur != cmd);
2935 	ublk_cancel_cmd(ubq, pdu->tag, issue_flags);
2936 }
2937 
2938 static inline bool ublk_queue_ready(const struct ublk_queue *ubq)
2939 {
2940 	return ubq->nr_io_ready == ubq->q_depth;
2941 }
2942 
2943 static inline bool ublk_dev_ready(const struct ublk_device *ub)
2944 {
2945 	return ub->nr_queue_ready == ub->dev_info.nr_hw_queues;
2946 }
2947 
2948 static void ublk_cancel_queue(struct ublk_queue *ubq)
2949 {
2950 	u16 i;
2951 
2952 	if (ublk_support_batch_io(ubq)) {
2953 		ublk_batch_cancel_queue(ubq);
2954 		return;
2955 	}
2956 
2957 	for (i = 0; i < ubq->q_depth; i++)
2958 		ublk_cancel_cmd(ubq, i, IO_URING_F_UNLOCKED);
2959 }
2960 
2961 /* Cancel all pending commands, must be called after del_gendisk() returns */
2962 static void ublk_cancel_dev(struct ublk_device *ub)
2963 {
2964 	u16 i;
2965 
2966 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
2967 		ublk_cancel_queue(ublk_get_queue(ub, i));
2968 }
2969 
2970 static bool ublk_check_inflight_rq(struct request *rq, void *data)
2971 {
2972 	bool *idle = data;
2973 
2974 	if (blk_mq_request_started(rq)) {
2975 		*idle = false;
2976 		return false;
2977 	}
2978 	return true;
2979 }
2980 
2981 static void ublk_wait_tagset_rqs_idle(struct ublk_device *ub)
2982 {
2983 	bool idle;
2984 
2985 	WARN_ON_ONCE(!blk_queue_quiesced(ub->ub_disk->queue));
2986 	while (true) {
2987 		idle = true;
2988 		blk_mq_tagset_busy_iter(&ub->tag_set,
2989 				ublk_check_inflight_rq, &idle);
2990 		if (idle)
2991 			break;
2992 		msleep(UBLK_REQUEUE_DELAY_MS);
2993 	}
2994 }
2995 
2996 static void ublk_force_abort_dev(struct ublk_device *ub)
2997 {
2998 	u16 i;
2999 
3000 	pr_devel("%s: force abort ub: dev_id %d state %s\n",
3001 			__func__, ub->dev_info.dev_id,
3002 			ub->dev_info.state == UBLK_S_DEV_LIVE ?
3003 			"LIVE" : "QUIESCED");
3004 	blk_mq_quiesce_queue(ub->ub_disk->queue);
3005 	if (ub->dev_info.state == UBLK_S_DEV_LIVE)
3006 		ublk_wait_tagset_rqs_idle(ub);
3007 
3008 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
3009 		ublk_get_queue(ub, i)->force_abort = true;
3010 	blk_mq_unquiesce_queue(ub->ub_disk->queue);
3011 	/* We may have requeued some rqs in ublk_quiesce_queue() */
3012 	blk_mq_kick_requeue_list(ub->ub_disk->queue);
3013 }
3014 
3015 static struct gendisk *ublk_detach_disk(struct ublk_device *ub)
3016 {
3017 	struct gendisk *disk;
3018 
3019 	/* Sync with ublk_abort_queue() by holding the lock */
3020 	spin_lock(&ub->lock);
3021 	disk = ub->ub_disk;
3022 	ub->dev_info.state = UBLK_S_DEV_DEAD;
3023 	ub->dev_info.ublksrv_pid = -1;
3024 	ub->ub_disk = NULL;
3025 	spin_unlock(&ub->lock);
3026 
3027 	return disk;
3028 }
3029 
3030 static void ublk_stop_dev_unlocked(struct ublk_device *ub)
3031 	__must_hold(&ub->mutex)
3032 {
3033 	struct gendisk *disk;
3034 
3035 	if (ub->dev_info.state == UBLK_S_DEV_DEAD)
3036 		return;
3037 
3038 	if (ublk_nosrv_dev_should_queue_io(ub))
3039 		ublk_force_abort_dev(ub);
3040 	del_gendisk(ub->ub_disk);
3041 	disk = ublk_detach_disk(ub);
3042 	put_disk(disk);
3043 }
3044 
3045 static struct file *ublk_get_ch_file(struct ublk_device *ub)
3046 {
3047 	struct file *file;
3048 
3049 	mutex_lock(&ub->cancel_mutex);
3050 	file = ub->ch_file;
3051 	if (file && !file_ref_get(&file->f_ref))
3052 		file = NULL;
3053 	mutex_unlock(&ub->cancel_mutex);
3054 	return file;
3055 }
3056 
3057 static void ublk_stop_dev(struct ublk_device *ub)
3058 {
3059 	struct file *file;
3060 
3061 	/*
3062 	 * FETCH, PREP and START_DEV take ub->mutex. If a server has
3063 	 * /dev/ublkcN open, set STOPPING, which turns it away, and hold a
3064 	 * reference on the file: the server's release, whose reset clears
3065 	 * STOPPING and lets a new server attach, can't run before we drop it.
3066 	 * So the cancel can run after the unlock and only meets this server's
3067 	 * commands; it has to: io_uring_cmd_done() may take uring_lock, under
3068 	 * which FETCH takes ub->mutex.
3069 	 */
3070 	mutex_lock(&ub->mutex);
3071 	ublk_stop_dev_unlocked(ub);
3072 	cancel_work_sync(&ub->partition_scan_work);
3073 	file = ublk_get_ch_file(ub);
3074 	if (file) {
3075 		/*
3076 		 * The server has to close /dev/ublkcN before this device can
3077 		 * be started again: the reset in its release clears STOPPING.
3078 		 */
3079 		set_bit(UB_STATE_STOPPING, &ub->state);
3080 		/* for wake_up_var() below, see wake_up_bit() */
3081 		smp_mb__after_atomic();
3082 	}
3083 	mutex_unlock(&ub->mutex);
3084 
3085 	/* no server: nothing to cancel */
3086 	if (!file)
3087 		return;
3088 
3089 	/* wake a START_DEV waiting for the device to get ready */
3090 	wake_up_var(&ub->nr_queue_ready);
3091 	ublk_cancel_dev(ub);
3092 	__fput_sync(file);
3093 }
3094 
3095 static void ublk_reset_io_flags(struct ublk_queue *ubq, struct ublk_io *io)
3096 {
3097 	/* UBLK_IO_FLAG_CANCELED can be cleared now */
3098 	spin_lock(&ubq->cancel_lock);
3099 	io->flags &= ~UBLK_IO_FLAG_CANCELED;
3100 	spin_unlock(&ubq->cancel_lock);
3101 }
3102 
3103 /* reset per-queue io flags */
3104 static void ublk_queue_reset_io_flags(struct ublk_device *ub,
3105 				      struct ublk_queue *ubq)
3106 {
3107 	/*
3108 	 * A cancel in this FETCH round took a command which still counts as
3109 	 * ready, so the queue has to stay canceling. ub->canceling is set
3110 	 * under cancel_mutex before any command is taken: either we see it
3111 	 * here, or the cancel marks this queue again later.
3112 	 */
3113 	mutex_lock(&ub->cancel_mutex);
3114 	if (!ub->canceling)
3115 		ubq->canceling = false;
3116 	mutex_unlock(&ub->cancel_mutex);
3117 	ubq->fail_io = false;
3118 	ubq->force_abort = false;
3119 }
3120 
3121 /* device can only be started after all IOs are ready */
3122 static void ublk_mark_io_ready(struct ublk_device *ub, u16 q_id,
3123 	struct ublk_io *io)
3124 	__must_hold(&ub->mutex)
3125 {
3126 	struct ublk_queue *ubq = ublk_get_queue(ub, q_id);
3127 
3128 	if (!ub->unprivileged_daemons && !capable(CAP_SYS_ADMIN))
3129 		ub->unprivileged_daemons = true;
3130 
3131 	ubq->nr_io_ready++;
3132 	ublk_reset_io_flags(ubq, io);
3133 
3134 	/* Check if this specific queue is now fully ready */
3135 	if (ublk_queue_ready(ubq)) {
3136 		ub->nr_queue_ready++;
3137 
3138 		/*
3139 		 * Reset queue flags as soon as this queue is ready. Unless
3140 		 * this round saw a cancel, this clears the canceling flag,
3141 		 * allowing batch FETCH commands to succeed during recovery
3142 		 * without waiting for all queues.
3143 		 */
3144 		ublk_queue_reset_io_flags(ub, ubq);
3145 	}
3146 
3147 	/* All queues ready - wake ublk_dev_ready() waiters */
3148 	if (ublk_dev_ready(ub))
3149 		wake_up_var(&ub->nr_queue_ready);
3150 }
3151 
3152 static inline int ublk_check_cmd_op(u32 cmd_op)
3153 {
3154 	u32 ioc_type = _IOC_TYPE(cmd_op);
3155 
3156 	if (!IS_ENABLED(CONFIG_BLKDEV_UBLK_LEGACY_OPCODES) && ioc_type != 'u')
3157 		return -EOPNOTSUPP;
3158 
3159 	if (ioc_type != 'u' && ioc_type != 0)
3160 		return -EOPNOTSUPP;
3161 
3162 	return 0;
3163 }
3164 
3165 /* Must run before ublk_fill_io_cmd() / __ublk_fetch(). */
3166 static inline int ublk_validate_io_buf(const struct ublk_device *ub,
3167 				       struct io_uring_cmd *cmd,
3168 				       struct ublk_auto_buf_reg *buf)
3169 {
3170 	if (!ublk_dev_support_auto_buf_reg(ub))
3171 		return 0;
3172 
3173 	*buf = ublk_sqe_addr_to_auto_buf_reg(READ_ONCE(cmd->sqe->addr));
3174 	if (buf->reserved0 || buf->reserved1)
3175 		return -EINVAL;
3176 	if (buf->flags & ~UBLK_AUTO_BUF_REG_F_MASK)
3177 		return -EINVAL;
3178 	return 0;
3179 }
3180 
3181 static void ublk_clear_auto_buf_reg(struct ublk_io *io,
3182 				    struct io_uring_cmd *cmd,
3183 				    u16 *buf_idx)
3184 {
3185 	if (io->flags & UBLK_IO_FLAG_AUTO_BUF_REG) {
3186 		io->flags &= ~UBLK_IO_FLAG_AUTO_BUF_REG;
3187 
3188 		/*
3189 		 * `UBLK_F_AUTO_BUF_REG` only works iff `UBLK_IO_FETCH_REQ`
3190 		 * and `UBLK_IO_COMMIT_AND_FETCH_REQ` are issued from same
3191 		 * `io_ring_ctx`.
3192 		 *
3193 		 * If this uring_cmd's io_ring_ctx isn't same with the
3194 		 * one for registering the buffer, it is ublk server's
3195 		 * responsibility for unregistering the buffer, otherwise
3196 		 * this ublk request gets stuck.
3197 		 */
3198 		if (buf_idx &&
3199 		    io->buf_ctx_handle == io_uring_cmd_ctx_handle(cmd))
3200 			*buf_idx = io->buf.auto_reg.index;
3201 	}
3202 }
3203 
3204 static inline void ublk_apply_io_buf(const struct ublk_device *ub,
3205 				     struct ublk_io *io,
3206 				     struct io_uring_cmd *cmd,
3207 				     unsigned long buf_addr,
3208 				     const struct ublk_auto_buf_reg *auto_buf,
3209 				     u16 *buf_idx)
3210 {
3211 	if (ublk_dev_support_auto_buf_reg(ub)) {
3212 		ublk_clear_auto_buf_reg(io, cmd, buf_idx);
3213 		io->buf.auto_reg = *auto_buf;
3214 	} else {
3215 		io->buf.addr = buf_addr;
3216 	}
3217 }
3218 
3219 /* Once we return, `io->req` can't be used any more */
3220 static inline struct request *
3221 ublk_fill_io_cmd(struct ublk_io *io, struct io_uring_cmd *cmd)
3222 {
3223 	struct request *req = io->req;
3224 
3225 	io->cmd = cmd;
3226 	io->flags |= UBLK_IO_FLAG_ACTIVE;
3227 	/* now this cmd slot is owned by ublk driver */
3228 	io->flags &= ~UBLK_IO_FLAG_OWNED_BY_SRV;
3229 
3230 	return req;
3231 }
3232 
3233 /*
3234  * Call before ublk_fill_io_cmd() publishes @cmd in io->cmd: a control-path
3235  * cancel may complete any command found there, and io_uring_cmd_done() only
3236  * takes it off the cancelable list if it is marked already. The handlers
3237  * hold uring_lock, so marking takes no lock.
3238  */
3239 static inline void ublk_prep_cancel(struct io_uring_cmd *cmd,
3240 				    unsigned int issue_flags,
3241 				    struct ublk_queue *ubq, u16 tag)
3242 {
3243 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
3244 
3245 	/*
3246 	 * Safe to refer to @ubq since ublk_queue won't be died until its
3247 	 * commands are completed
3248 	 */
3249 	pdu->ubq = ubq;
3250 	pdu->tag = tag;
3251 	io_uring_cmd_mark_cancelable(cmd, issue_flags);
3252 	/* pairs with the cancel loading cmd from io->cmd, then cmd->flags */
3253 	smp_wmb();
3254 }
3255 
3256 static void ublk_io_release(void *priv)
3257 {
3258 	struct request *rq = priv;
3259 	struct ublk_queue *ubq = rq->mq_hctx->driver_data;
3260 	struct ublk_io *io = &ubq->ios[rq->tag];
3261 
3262 	/*
3263 	 * task_registered_buffers may be 0 if buffers were registered off task
3264 	 * but unregistered on task. Or after UBLK_IO_COMMIT_AND_FETCH_REQ.
3265 	 */
3266 	if (current == io->task && io->task_registered_buffers)
3267 		io->task_registered_buffers--;
3268 	else
3269 		ublk_put_req_ref(io, rq);
3270 }
3271 
3272 static int ublk_register_io_buf(struct io_uring_cmd *cmd,
3273 				struct ublk_device *ub,
3274 				u16 q_id, u16 tag,
3275 				struct ublk_io *io,
3276 				unsigned int index, unsigned int issue_flags)
3277 {
3278 	struct request *req;
3279 	int ret;
3280 
3281 	if (!ublk_dev_support_zero_copy(ub))
3282 		return -EINVAL;
3283 
3284 	req = __ublk_check_and_get_req(ub, q_id, tag, io);
3285 	if (!req)
3286 		return -EINVAL;
3287 
3288 	ret = io_buffer_register_request(cmd, req, ublk_io_release, index,
3289 					 issue_flags);
3290 	if (ret) {
3291 		ublk_put_req_ref(io, req);
3292 		return ret;
3293 	}
3294 
3295 	return 0;
3296 }
3297 
3298 static int
3299 ublk_daemon_register_io_buf(struct io_uring_cmd *cmd,
3300 			    struct ublk_device *ub,
3301 			    u16 q_id, u16 tag, struct ublk_io *io,
3302 			    unsigned index, unsigned issue_flags)
3303 {
3304 	unsigned new_registered_buffers;
3305 	struct request *req = io->req;
3306 	int ret;
3307 
3308 	/*
3309 	 * Ensure there are still references for ublk_sub_req_ref() to release.
3310 	 * If not, fall back on the thread-safe buffer registration.
3311 	 */
3312 	new_registered_buffers = io->task_registered_buffers + 1;
3313 	if (unlikely(new_registered_buffers >= UBLK_REFCOUNT_INIT))
3314 		return ublk_register_io_buf(cmd, ub, q_id, tag, io, index,
3315 					    issue_flags);
3316 
3317 	if (!ublk_dev_support_zero_copy(ub) || !blk_rq_has_data(req))
3318 		return -EINVAL;
3319 
3320 	ret = io_buffer_register_request(cmd, req, ublk_io_release, index,
3321 					 issue_flags);
3322 	if (ret)
3323 		return ret;
3324 
3325 	io->task_registered_buffers = new_registered_buffers;
3326 	return 0;
3327 }
3328 
3329 static int ublk_unregister_io_buf(struct io_uring_cmd *cmd,
3330 				  const struct ublk_device *ub,
3331 				  unsigned int index, unsigned int issue_flags)
3332 {
3333 	if (!(ub->dev_info.flags & UBLK_F_SUPPORT_ZERO_COPY))
3334 		return -EINVAL;
3335 
3336 	return io_buffer_unregister(cmd, index, issue_flags);
3337 }
3338 
3339 static int ublk_check_fetch_buf(const struct ublk_device *ub, __u64 buf_addr)
3340 {
3341 	if (ublk_dev_need_map_io(ub)) {
3342 		/*
3343 		 * FETCH_RQ has to provide IO buffer if NEED GET
3344 		 * DATA is not enabled
3345 		 */
3346 		if (!buf_addr && !ublk_dev_need_get_data(ub))
3347 			return -EINVAL;
3348 	} else if (buf_addr) {
3349 		/* User copy requires addr to be unset */
3350 		return -EINVAL;
3351 	}
3352 	return 0;
3353 }
3354 
3355 static int __ublk_fetch(struct io_uring_cmd *cmd, struct ublk_device *ub,
3356 			struct ublk_io *io, u16 q_id)
3357 {
3358 	if (test_bit(UB_STATE_STOPPING, &ub->state))
3359 		return UBLK_IO_RES_ABORT;
3360 
3361 	/* UBLK_IO_FETCH_REQ is only allowed before dev is setup */
3362 	if (ublk_dev_ready(ub))
3363 		return -EBUSY;
3364 
3365 	/* allow each command to be FETCHed at most once */
3366 	if (io->flags & UBLK_IO_FLAG_ACTIVE)
3367 		return -EINVAL;
3368 
3369 	WARN_ON_ONCE(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV);
3370 
3371 	ublk_fill_io_cmd(io, cmd);
3372 
3373 	if (ublk_dev_support_batch_io(ub))
3374 		WRITE_ONCE(io->task, NULL);
3375 	else
3376 		WRITE_ONCE(io->task, get_task_struct(current));
3377 
3378 	return 0;
3379 }
3380 
3381 static int ublk_fetch(struct io_uring_cmd *cmd, struct ublk_device *ub,
3382 		      struct ublk_io *io, __u64 buf_addr, u16 q_id)
3383 {
3384 	struct ublk_auto_buf_reg auto_buf;
3385 	int ret;
3386 
3387 	/*
3388 	 * When handling FETCH command for setting up ublk uring queue,
3389 	 * ub->mutex is the innermost lock, and we won't block for handling
3390 	 * FETCH, so it is fine even for IO_URING_F_NONBLOCK.
3391 	 */
3392 	mutex_lock(&ub->mutex);
3393 	ret = ublk_validate_io_buf(ub, cmd, &auto_buf);
3394 	if (!ret)
3395 		ret = __ublk_fetch(cmd, ub, io, q_id);
3396 	if (!ret) {
3397 		ublk_apply_io_buf(ub, io, cmd, buf_addr, &auto_buf, NULL);
3398 		ublk_mark_io_ready(ub, q_id, io);
3399 	}
3400 	mutex_unlock(&ub->mutex);
3401 	return ret;
3402 }
3403 
3404 static int ublk_check_commit_and_fetch(const struct ublk_device *ub,
3405 				       struct ublk_io *io, __u64 buf_addr)
3406 {
3407 	struct request *req = io->req;
3408 
3409 	if (ublk_dev_need_map_io(ub)) {
3410 		/*
3411 		 * COMMIT_AND_FETCH_REQ has to provide IO buffer if
3412 		 * NEED GET DATA is not enabled or it is Read IO.
3413 		 */
3414 		if (!buf_addr && (!ublk_dev_need_get_data(ub) ||
3415 					req_op(req) == REQ_OP_READ))
3416 			return -EINVAL;
3417 	} else if (req_op(req) != REQ_OP_ZONE_APPEND && buf_addr) {
3418 		/*
3419 		 * User copy requires addr to be unset when command is
3420 		 * not zone append
3421 		 */
3422 		return -EINVAL;
3423 	}
3424 
3425 	return 0;
3426 }
3427 
3428 static bool ublk_need_complete_req(const struct ublk_device *ub,
3429 				   struct ublk_io *io)
3430 {
3431 	if (ublk_dev_need_req_ref(ub))
3432 		return ublk_sub_req_ref(io);
3433 	return true;
3434 }
3435 
3436 static bool ublk_get_data(const struct ublk_queue *ubq, struct ublk_io *io,
3437 			  struct request *req)
3438 {
3439 	/*
3440 	 * We have handled UBLK_IO_NEED_GET_DATA command,
3441 	 * so clear UBLK_IO_FLAG_NEED_GET_DATA now and just
3442 	 * do the copy work.
3443 	 */
3444 	io->flags &= ~UBLK_IO_FLAG_NEED_GET_DATA;
3445 	/* update iod->addr because ublksrv may have passed a new io buffer */
3446 	ublk_get_iod(ubq, req->tag)->addr = io->buf.addr;
3447 	pr_devel("%s: update iod->addr: qid %d tag %d io_flags %x addr %llx\n",
3448 			__func__, ubq->q_id, req->tag, io->flags,
3449 			ublk_get_iod(ubq, req->tag)->addr);
3450 
3451 	return ublk_start_io(ubq, req, io);
3452 }
3453 
3454 static int ublk_ch_uring_cmd_local(struct io_uring_cmd *cmd,
3455 		unsigned int issue_flags)
3456 {
3457 	/* May point to userspace-mapped memory */
3458 	const struct ublksrv_io_cmd *ub_src = io_uring_sqe_cmd(cmd->sqe,
3459 							       struct ublksrv_io_cmd);
3460 	u16 buf_idx = UBLK_INVALID_BUF_IDX;
3461 	struct ublk_device *ub = cmd->file->private_data;
3462 	struct ublk_queue *ubq;
3463 	struct ublk_io *io = NULL;
3464 	u32 cmd_op = cmd->cmd_op;
3465 	u16 q_id = READ_ONCE(ub_src->q_id);
3466 	u16 tag = READ_ONCE(ub_src->tag);
3467 	s32 result = READ_ONCE(ub_src->result);
3468 	u64 addr = READ_ONCE(ub_src->addr); /* unioned with zone_append_lba */
3469 	struct request *req;
3470 	int ret;
3471 	bool compl;
3472 
3473 	WARN_ON_ONCE(issue_flags & IO_URING_F_UNLOCKED);
3474 
3475 	pr_devel("%s: received: cmd op %d queue %d tag %d result %d\n",
3476 			__func__, cmd->cmd_op, q_id, tag, result);
3477 
3478 	ret = ublk_check_cmd_op(cmd_op);
3479 	if (ret)
3480 		goto out;
3481 
3482 	/*
3483 	 * io_buffer_unregister() doesn't access the ubq or io,
3484 	 * so no need to validate the q_id, tag, or task
3485 	 */
3486 	if (_IOC_NR(cmd_op) == UBLK_IO_UNREGISTER_IO_BUF)
3487 		return ublk_unregister_io_buf(cmd, ub, addr, issue_flags);
3488 
3489 	ret = -EINVAL;
3490 	if (q_id >= ub->dev_info.nr_hw_queues)
3491 		goto out;
3492 
3493 	ubq = ublk_get_queue(ub, q_id);
3494 
3495 	if (tag >= ub->dev_info.queue_depth)
3496 		goto out;
3497 
3498 	io = &ubq->ios[tag];
3499 	/* UBLK_IO_FETCH_REQ can be handled on any task, which sets io->task */
3500 	if (unlikely(_IOC_NR(cmd_op) == UBLK_IO_FETCH_REQ)) {
3501 		ret = ublk_check_fetch_buf(ub, addr);
3502 		if (ret)
3503 			goto out;
3504 		/* before ublk_fetch() publishes io->cmd, see ublk_prep_cancel() */
3505 		ublk_prep_cancel(cmd, issue_flags, ubq, tag);
3506 		ret = ublk_fetch(cmd, ub, io, addr, q_id);
3507 		if (ret)
3508 			goto out_done;
3509 		return -EIOCBQUEUED;
3510 	}
3511 
3512 	if (READ_ONCE(io->task) != current) {
3513 		/*
3514 		 * ublk_register_io_buf() accesses only the io's refcount,
3515 		 * so can be handled on any task
3516 		 */
3517 		if (_IOC_NR(cmd_op) == UBLK_IO_REGISTER_IO_BUF)
3518 			return ublk_register_io_buf(cmd, ub, q_id, tag, io,
3519 						    addr, issue_flags);
3520 
3521 		goto out;
3522 	}
3523 
3524 	/* there is pending io cmd, something must be wrong */
3525 	if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV)) {
3526 		ret = -EBUSY;
3527 		goto out;
3528 	}
3529 
3530 	/*
3531 	 * ensure that the user issues UBLK_IO_NEED_GET_DATA
3532 	 * iff the driver have set the UBLK_IO_FLAG_NEED_GET_DATA.
3533 	 */
3534 	if ((!!(io->flags & UBLK_IO_FLAG_NEED_GET_DATA))
3535 			^ (_IOC_NR(cmd_op) == UBLK_IO_NEED_GET_DATA))
3536 		goto out;
3537 
3538 	switch (_IOC_NR(cmd_op)) {
3539 	case UBLK_IO_REGISTER_IO_BUF:
3540 		return ublk_daemon_register_io_buf(cmd, ub, q_id, tag, io, addr,
3541 						   issue_flags);
3542 	case UBLK_IO_COMMIT_AND_FETCH_REQ: {
3543 		struct ublk_auto_buf_reg auto_buf;
3544 
3545 		ret = ublk_check_commit_and_fetch(ub, io, addr);
3546 		if (ret)
3547 			goto out;
3548 		ret = ublk_validate_io_buf(ub, cmd, &auto_buf);
3549 		if (ret)
3550 			goto out;
3551 		io->res = result;
3552 		ublk_prep_cancel(cmd, issue_flags, ubq, tag);
3553 		req = ublk_fill_io_cmd(io, cmd);
3554 		ublk_apply_io_buf(ub, io, cmd, addr, &auto_buf, &buf_idx);
3555 		if (buf_idx != UBLK_INVALID_BUF_IDX)
3556 			io_buffer_unregister(cmd, buf_idx, issue_flags);
3557 		compl = ublk_need_complete_req(ub, io);
3558 
3559 		if (req_op(req) == REQ_OP_ZONE_APPEND)
3560 			req->__sector = addr;
3561 		if (compl)
3562 			__ublk_complete_rq(req, io, ublk_dev_need_map_io(ub), NULL);
3563 		break;
3564 	}
3565 	case UBLK_IO_NEED_GET_DATA:
3566 		/*
3567 		 * ublk_get_data() may fail and fallback to requeue, so keep
3568 		 * uring_cmd active first and prepare for handling new requeued
3569 		 * request
3570 		 */
3571 		ublk_prep_cancel(cmd, issue_flags, ubq, tag);
3572 		req = ublk_fill_io_cmd(io, cmd);
3573 		io->buf.addr = addr;
3574 		if (likely(ublk_get_data(ubq, io, req))) {
3575 			__ublk_prep_compl_io_cmd(io, req);
3576 			ret = UBLK_IO_RES_OK;
3577 			goto out_done;
3578 		}
3579 		break;
3580 	default:
3581 		goto out;
3582 	}
3583 	return -EIOCBQUEUED;
3584 
3585  out_done:
3586 	/* marked cancelable: complete through io_uring_cmd_done() */
3587 	io_uring_cmd_done(cmd, ret, issue_flags);
3588 	return -EIOCBQUEUED;
3589  out:
3590 	pr_devel("%s: complete: cmd op %d, tag %d ret %x io_flags %x\n",
3591 			__func__, cmd_op, tag, ret, io ? io->flags : 0);
3592 	return ret;
3593 }
3594 
3595 static inline struct request *__ublk_check_and_get_req(struct ublk_device *ub,
3596 		u16 q_id, u16 tag, struct ublk_io *io)
3597 {
3598 	struct request *req;
3599 
3600 	/*
3601 	 * can't use io->req in case of concurrent UBLK_IO_COMMIT_AND_FETCH_REQ,
3602 	 * which would overwrite it with io->cmd
3603 	 */
3604 	req = blk_mq_tag_to_rq(ub->tag_set.tags[q_id], tag);
3605 	if (!req)
3606 		return NULL;
3607 
3608 	if (!ublk_get_req_ref(io))
3609 		return NULL;
3610 
3611 	if (unlikely(!blk_mq_request_started(req) || req->tag != tag))
3612 		goto fail_put;
3613 
3614 	if (!blk_rq_has_data(req))
3615 		goto fail_put;
3616 
3617 	return req;
3618 fail_put:
3619 	ublk_put_req_ref(io, req);
3620 	return NULL;
3621 }
3622 
3623 static void ublk_ch_uring_cmd_cb(struct io_tw_req tw_req, io_tw_token_t tw)
3624 {
3625 	unsigned int issue_flags = IO_URING_CMD_TASK_WORK_ISSUE_FLAGS;
3626 	struct io_uring_cmd *cmd = io_uring_cmd_from_tw(tw_req);
3627 	int ret = -ECANCELED;
3628 
3629 	if (!tw.cancel)
3630 		ret = ublk_ch_uring_cmd_local(cmd, issue_flags);
3631 	if (ret != -EIOCBQUEUED)
3632 		io_uring_cmd_done(cmd, ret, issue_flags);
3633 }
3634 
3635 static int ublk_ch_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags)
3636 {
3637 	if (unlikely(issue_flags & IO_URING_F_CANCEL)) {
3638 		ublk_uring_cmd_cancel_fn(cmd, issue_flags);
3639 		return 0;
3640 	}
3641 
3642 	/* well-implemented server won't run into unlocked */
3643 	if (unlikely(issue_flags & IO_URING_F_UNLOCKED)) {
3644 		io_uring_cmd_complete_in_task(cmd, ublk_ch_uring_cmd_cb);
3645 		return -EIOCBQUEUED;
3646 	}
3647 
3648 	return ublk_ch_uring_cmd_local(cmd, issue_flags);
3649 }
3650 
3651 static inline __u64 ublk_batch_buf_addr(const struct ublk_batch_io *uc,
3652 					const struct ublk_elem_header *elem)
3653 {
3654 	const void *buf = elem;
3655 
3656 	if (uc->flags & UBLK_BATCH_F_HAS_BUF_ADDR)
3657 		return *(const __u64 *)(buf + sizeof(*elem));
3658 	return 0;
3659 }
3660 
3661 static inline __u64 ublk_batch_zone_lba(const struct ublk_batch_io *uc,
3662 					const struct ublk_elem_header *elem)
3663 {
3664 	const void *buf = elem;
3665 
3666 	if (uc->flags & UBLK_BATCH_F_HAS_ZONE_LBA)
3667 		return *(const __u64 *)(buf + sizeof(*elem) +
3668 				8 * !!(uc->flags & UBLK_BATCH_F_HAS_BUF_ADDR));
3669 	return -1;
3670 }
3671 
3672 static struct ublk_auto_buf_reg
3673 ublk_batch_auto_buf_reg(const struct ublk_batch_io *uc,
3674 			const struct ublk_elem_header *elem)
3675 {
3676 	struct ublk_auto_buf_reg reg = {
3677 		.index = elem->buf_index,
3678 		.flags = (uc->flags & UBLK_BATCH_F_AUTO_BUF_REG_FALLBACK) ?
3679 			UBLK_AUTO_BUF_REG_FALLBACK : 0,
3680 	};
3681 
3682 	return reg;
3683 }
3684 
3685 /*
3686  * 48 can hold any type of buffer element(8, 16 and 24 bytes) because
3687  * it is the least common multiple(LCM) of 8, 16 and 24
3688  */
3689 #define UBLK_CMD_BATCH_TMP_BUF_SZ  (48 * 10)
3690 struct ublk_batch_io_iter {
3691 	void __user *uaddr;
3692 	const u8 *kaddr;
3693 	unsigned done, total;
3694 	unsigned char elem_bytes;
3695 	/* copy to this buffer from user space */
3696 	unsigned char buf[UBLK_CMD_BATCH_TMP_BUF_SZ];
3697 };
3698 
3699 static inline int
3700 __ublk_walk_cmd_buf(struct ublk_queue *ubq,
3701 		    struct ublk_batch_io_iter *iter,
3702 		    const struct ublk_batch_io_data *data,
3703 		    unsigned bytes,
3704 		    int (*cb)(struct ublk_queue *q,
3705 			    const struct ublk_batch_io_data *data,
3706 			    const struct ublk_elem_header *elem))
3707 {
3708 	unsigned int i;
3709 	int ret = 0;
3710 
3711 	for (i = 0; i < bytes; i += iter->elem_bytes) {
3712 		const struct ublk_elem_header *elem =
3713 			(const struct ublk_elem_header *)&iter->buf[i];
3714 
3715 		if (unlikely(elem->tag >= data->ub->dev_info.queue_depth)) {
3716 			ret = -EINVAL;
3717 			break;
3718 		}
3719 
3720 		ret = cb(ubq, data, elem);
3721 		if (unlikely(ret))
3722 			break;
3723 	}
3724 
3725 	iter->done += i;
3726 	return ret;
3727 }
3728 
3729 static int ublk_walk_cmd_buf(struct ublk_batch_io_iter *iter,
3730 			     const struct ublk_batch_io_data *data,
3731 			     int (*cb)(struct ublk_queue *q,
3732 				     const struct ublk_batch_io_data *data,
3733 				     const struct ublk_elem_header *elem))
3734 {
3735 	struct ublk_queue *ubq = ublk_get_queue(data->ub, data->header.q_id);
3736 	int ret = 0;
3737 
3738 	while (iter->done < iter->total) {
3739 		unsigned int len = min(sizeof(iter->buf), iter->total - iter->done);
3740 
3741 		if (iter->kaddr) {
3742 			memcpy(iter->buf, iter->kaddr + iter->done, len);
3743 		} else if (copy_from_user(iter->buf, iter->uaddr + iter->done,
3744 				  len)) {
3745 			pr_warn("ublk%d: read batch cmd buffer failed\n",
3746 					data->ub->dev_info.dev_id);
3747 			return -EFAULT;
3748 		}
3749 
3750 		ret = __ublk_walk_cmd_buf(ubq, iter, data, len, cb);
3751 		if (ret)
3752 			return ret;
3753 	}
3754 	return 0;
3755 }
3756 
3757 static int ublk_batch_unprep_io(struct ublk_queue *ubq,
3758 				const struct ublk_batch_io_data *data,
3759 				const struct ublk_elem_header *elem)
3760 {
3761 	struct ublk_io *io = &ubq->ios[elem->tag];
3762 
3763 	/*
3764 	 * If queue was ready before this decrement, it won't be anymore,
3765 	 * so we need to decrement the queue ready count and restore the
3766 	 * canceling flag to prevent new requests from being queued.
3767 	 */
3768 	if (ublk_queue_ready(ubq)) {
3769 		data->ub->nr_queue_ready--;
3770 		spin_lock(&ubq->cancel_lock);
3771 		ubq->canceling = true;
3772 		spin_unlock(&ubq->cancel_lock);
3773 	}
3774 	ubq->nr_io_ready--;
3775 
3776 	ublk_io_lock(io);
3777 	io->flags = 0;
3778 	ublk_io_unlock(io);
3779 	return 0;
3780 }
3781 
3782 static void ublk_batch_revert_prep_cmd(struct ublk_batch_io_iter *iter,
3783 				       const struct ublk_batch_io_data *data)
3784 {
3785 	int ret;
3786 
3787 	/* Re-process only what we've already processed, starting from beginning */
3788 	iter->total = iter->done;
3789 	iter->done = 0;
3790 
3791 	ret = ublk_walk_cmd_buf(iter, data, ublk_batch_unprep_io);
3792 	WARN_ON_ONCE(ret);
3793 }
3794 
3795 static int ublk_batch_prep_io(struct ublk_queue *ubq,
3796 			      const struct ublk_batch_io_data *data,
3797 			      const struct ublk_elem_header *elem)
3798 {
3799 	struct ublk_io *io = &ubq->ios[elem->tag];
3800 	const struct ublk_batch_io *uc = &data->header;
3801 	union ublk_io_buf buf = { 0 };
3802 	int ret;
3803 
3804 	if (ublk_dev_support_auto_buf_reg(data->ub))
3805 		buf.auto_reg = ublk_batch_auto_buf_reg(uc, elem);
3806 	else if (ublk_dev_need_map_io(data->ub)) {
3807 		buf.addr = ublk_batch_buf_addr(uc, elem);
3808 
3809 		ret = ublk_check_fetch_buf(data->ub, buf.addr);
3810 		if (ret)
3811 			return ret;
3812 	}
3813 
3814 	ublk_io_lock(io);
3815 	ret = __ublk_fetch(data->cmd, data->ub, io, ubq->q_id);
3816 	if (!ret)
3817 		io->buf = buf;
3818 	ublk_io_unlock(io);
3819 
3820 	if (!ret)
3821 		ublk_mark_io_ready(data->ub, ubq->q_id, io);
3822 
3823 	return ret;
3824 }
3825 
3826 static int ublk_handle_batch_prep_cmd(const struct ublk_batch_io_data *data)
3827 {
3828 	const struct ublk_batch_io *uc = &data->header;
3829 	struct io_uring_cmd *cmd = data->cmd;
3830 	struct ublk_batch_io_iter iter = {
3831 		.uaddr = u64_to_user_ptr(READ_ONCE(cmd->sqe->addr)),
3832 		.total = uc->nr_elem * uc->elem_bytes,
3833 		.elem_bytes = uc->elem_bytes,
3834 	};
3835 	void *cmd_buf;
3836 	int ret;
3837 
3838 	cmd_buf = vmemdup_user(iter.uaddr, iter.total);
3839 	if (IS_ERR(cmd_buf))
3840 		return PTR_ERR(cmd_buf);
3841 	iter.kaddr = cmd_buf;
3842 
3843 	mutex_lock(&data->ub->mutex);
3844 	ret = ublk_walk_cmd_buf(&iter, data, ublk_batch_prep_io);
3845 
3846 	if (ret && iter.done)
3847 		ublk_batch_revert_prep_cmd(&iter, data);
3848 	mutex_unlock(&data->ub->mutex);
3849 	kvfree(cmd_buf);
3850 	return ret;
3851 }
3852 
3853 static int ublk_batch_commit_io_check(const struct ublk_queue *ubq,
3854 				      struct ublk_io *io,
3855 				      union ublk_io_buf *buf)
3856 {
3857 	if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV))
3858 		return -EBUSY;
3859 
3860 	/* BATCH_IO doesn't support UBLK_F_NEED_GET_DATA */
3861 	if (ublk_need_map_io(ubq) && !buf->addr)
3862 		return -EINVAL;
3863 	return 0;
3864 }
3865 
3866 static int ublk_batch_commit_io(struct ublk_queue *ubq,
3867 				const struct ublk_batch_io_data *data,
3868 				const struct ublk_elem_header *elem)
3869 {
3870 	struct ublk_io *io = &ubq->ios[elem->tag];
3871 	const struct ublk_batch_io *uc = &data->header;
3872 	u16 buf_idx = UBLK_INVALID_BUF_IDX;
3873 	union ublk_io_buf buf = { 0 };
3874 	struct request *req = NULL;
3875 	bool auto_reg = false;
3876 	bool compl = false;
3877 	int ret;
3878 
3879 	if (ublk_dev_support_auto_buf_reg(data->ub)) {
3880 		buf.auto_reg = ublk_batch_auto_buf_reg(uc, elem);
3881 		auto_reg = true;
3882 	} else if (ublk_dev_need_map_io(data->ub))
3883 		buf.addr = ublk_batch_buf_addr(uc, elem);
3884 
3885 	ublk_io_lock(io);
3886 	ret = ublk_batch_commit_io_check(ubq, io, &buf);
3887 	if (!ret) {
3888 		io->res = elem->result;
3889 		req = ublk_fill_io_cmd(io, data->cmd);
3890 
3891 		if (auto_reg)
3892 			ublk_clear_auto_buf_reg(io, data->cmd, &buf_idx);
3893 		io->buf = buf;
3894 		compl = ublk_need_complete_req(data->ub, io);
3895 	}
3896 	ublk_io_unlock(io);
3897 
3898 	if (unlikely(ret)) {
3899 		pr_warn_ratelimited("%s: dev %u queue %u io %u: commit failure %d\n",
3900 			__func__, data->ub->dev_info.dev_id, ubq->q_id,
3901 			elem->tag, ret);
3902 		return ret;
3903 	}
3904 
3905 	if (buf_idx != UBLK_INVALID_BUF_IDX)
3906 		io_buffer_unregister(data->cmd, buf_idx, data->issue_flags);
3907 	if (req_op(req) == REQ_OP_ZONE_APPEND)
3908 		req->__sector = ublk_batch_zone_lba(uc, elem);
3909 	if (compl)
3910 		__ublk_complete_rq(req, io, ublk_dev_need_map_io(data->ub), data->iob);
3911 	return 0;
3912 }
3913 
3914 static int ublk_handle_batch_commit_cmd(struct ublk_batch_io_data *data)
3915 {
3916 	const struct ublk_batch_io *uc = &data->header;
3917 	struct io_uring_cmd *cmd = data->cmd;
3918 	struct ublk_batch_io_iter iter = {
3919 		.uaddr = u64_to_user_ptr(READ_ONCE(cmd->sqe->addr)),
3920 		.total = uc->nr_elem * uc->elem_bytes,
3921 		.elem_bytes = uc->elem_bytes,
3922 	};
3923 	DEFINE_IO_COMP_BATCH(iob);
3924 	int ret;
3925 
3926 	data->iob = &iob;
3927 	ret = ublk_walk_cmd_buf(&iter, data, ublk_batch_commit_io);
3928 
3929 	if (iob.complete)
3930 		iob.complete(&iob);
3931 
3932 	return iter.done == 0 ? ret : iter.done;
3933 }
3934 
3935 static int ublk_check_batch_cmd_flags(const struct ublk_batch_io *uc)
3936 {
3937 	unsigned elem_bytes = sizeof(struct ublk_elem_header);
3938 
3939 	if (uc->flags & ~UBLK_BATCH_F_ALL)
3940 		return -EINVAL;
3941 
3942 	/* UBLK_BATCH_F_AUTO_BUF_REG_FALLBACK requires buffer index */
3943 	if ((uc->flags & UBLK_BATCH_F_AUTO_BUF_REG_FALLBACK) &&
3944 			(uc->flags & UBLK_BATCH_F_HAS_BUF_ADDR))
3945 		return -EINVAL;
3946 
3947 	elem_bytes += (uc->flags & UBLK_BATCH_F_HAS_ZONE_LBA ? sizeof(u64) : 0) +
3948 		(uc->flags & UBLK_BATCH_F_HAS_BUF_ADDR ? sizeof(u64) : 0);
3949 	if (uc->elem_bytes != elem_bytes)
3950 		return -EINVAL;
3951 	return 0;
3952 }
3953 
3954 static int ublk_check_batch_cmd(const struct ublk_batch_io_data *data)
3955 {
3956 	const struct ublk_batch_io *uc = &data->header;
3957 
3958 	if (uc->q_id >= data->ub->dev_info.nr_hw_queues)
3959 		return -EINVAL;
3960 
3961 	if (uc->nr_elem > data->ub->dev_info.queue_depth)
3962 		return -E2BIG;
3963 
3964 	if ((uc->flags & UBLK_BATCH_F_HAS_ZONE_LBA) &&
3965 			!ublk_dev_is_zoned(data->ub))
3966 		return -EINVAL;
3967 
3968 	if ((uc->flags & UBLK_BATCH_F_HAS_BUF_ADDR) &&
3969 			!ublk_dev_need_map_io(data->ub))
3970 		return -EINVAL;
3971 
3972 	if ((uc->flags & UBLK_BATCH_F_AUTO_BUF_REG_FALLBACK) &&
3973 			!ublk_dev_support_auto_buf_reg(data->ub))
3974 		return -EINVAL;
3975 
3976 	return ublk_check_batch_cmd_flags(uc);
3977 }
3978 
3979 static int ublk_batch_attach(struct ublk_queue *ubq,
3980 			     struct ublk_batch_io_data *data,
3981 			     struct ublk_batch_fetch_cmd *fcmd)
3982 {
3983 	struct ublk_batch_fetch_cmd *new_fcmd = NULL;
3984 	bool free = false;
3985 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(data->cmd);
3986 
3987 	/*
3988 	 * Mark it cancelable before linking it into fcmd_head, where a cancel
3989 	 * from the control path can take and complete it: see
3990 	 * ublk_prep_cancel(). evts_lock orders the mark before the link.
3991 	 */
3992 	pdu->ubq = ubq;
3993 	pdu->fcmd = fcmd;
3994 	io_uring_cmd_mark_cancelable(fcmd->cmd, data->issue_flags);
3995 
3996 	spin_lock(&ubq->evts_lock);
3997 	if (unlikely(ubq->force_abort || ubq->canceling)) {
3998 		free = true;
3999 	} else {
4000 		list_add_tail(&fcmd->node, &ubq->fcmd_head);
4001 		new_fcmd = __ublk_acquire_fcmd(ubq);
4002 	}
4003 	spin_unlock(&ubq->evts_lock);
4004 
4005 	if (unlikely(free)) {
4006 		/* off the cancelable list first, then nothing can see fcmd */
4007 		io_uring_cmd_done(data->cmd, -ENODEV, data->issue_flags);
4008 		ublk_batch_free_fcmd(fcmd);
4009 		return -EIOCBQUEUED;
4010 	}
4011 
4012 	if (!new_fcmd)
4013 		goto out;
4014 
4015 	/*
4016 	 * If the two fetch commands are originated from same io_ring_ctx,
4017 	 * run batch dispatch directly. Otherwise, schedule task work for
4018 	 * doing it.
4019 	 *
4020 	 * Use data->cmd, not fcmd->cmd: once fcmd is linked and not active,
4021 	 * a cancel from the control path may complete and free it.
4022 	 */
4023 	if (io_uring_cmd_ctx_handle(new_fcmd->cmd) ==
4024 			io_uring_cmd_ctx_handle(data->cmd)) {
4025 		data->cmd = new_fcmd->cmd;
4026 		ublk_batch_dispatch(ubq, data, new_fcmd);
4027 	} else {
4028 		io_uring_cmd_complete_in_task(new_fcmd->cmd,
4029 				ublk_batch_tw_cb);
4030 	}
4031 out:
4032 	return -EIOCBQUEUED;
4033 }
4034 
4035 static int ublk_handle_batch_fetch_cmd(struct ublk_batch_io_data *data)
4036 {
4037 	struct ublk_queue *ubq = ublk_get_queue(data->ub, data->header.q_id);
4038 	struct ublk_batch_fetch_cmd *fcmd = ublk_batch_alloc_fcmd(data->cmd);
4039 
4040 	if (!fcmd)
4041 		return -ENOMEM;
4042 
4043 	return ublk_batch_attach(ubq, data, fcmd);
4044 }
4045 
4046 static int ublk_validate_batch_fetch_cmd(struct ublk_batch_io_data *data)
4047 {
4048 	const struct ublk_batch_io *uc = &data->header;
4049 
4050 	if (uc->q_id >= data->ub->dev_info.nr_hw_queues)
4051 		return -EINVAL;
4052 
4053 	if (!(data->cmd->flags & IORING_URING_CMD_MULTISHOT))
4054 		return -EINVAL;
4055 
4056 	if (uc->elem_bytes != sizeof(__u16))
4057 		return -EINVAL;
4058 
4059 	if (uc->flags != 0)
4060 		return -EINVAL;
4061 
4062 	return 0;
4063 }
4064 
4065 static int ublk_handle_non_batch_cmd(struct io_uring_cmd *cmd,
4066 				     unsigned int issue_flags)
4067 {
4068 	const struct ublksrv_io_cmd *ub_cmd = io_uring_sqe_cmd(cmd->sqe,
4069 							       struct ublksrv_io_cmd);
4070 	struct ublk_device *ub = cmd->file->private_data;
4071 	u16 tag = READ_ONCE(ub_cmd->tag);
4072 	u16 q_id = READ_ONCE(ub_cmd->q_id);
4073 	unsigned index = READ_ONCE(ub_cmd->addr);
4074 	struct ublk_queue *ubq;
4075 	struct ublk_io *io;
4076 
4077 	if (cmd->cmd_op == UBLK_U_IO_UNREGISTER_IO_BUF)
4078 		return ublk_unregister_io_buf(cmd, ub, index, issue_flags);
4079 
4080 	if (q_id >= ub->dev_info.nr_hw_queues)
4081 		return -EINVAL;
4082 
4083 	if (tag >= ub->dev_info.queue_depth)
4084 		return -EINVAL;
4085 
4086 	if (cmd->cmd_op != UBLK_U_IO_REGISTER_IO_BUF)
4087 		return -EOPNOTSUPP;
4088 
4089 	ubq = ublk_get_queue(ub, q_id);
4090 	io = &ubq->ios[tag];
4091 	return ublk_register_io_buf(cmd, ub, q_id, tag, io, index,
4092 			issue_flags);
4093 }
4094 
4095 static int ublk_ch_batch_io_uring_cmd(struct io_uring_cmd *cmd,
4096 				       unsigned int issue_flags)
4097 {
4098 	const struct ublk_batch_io *uc = io_uring_sqe_cmd(cmd->sqe,
4099 							  struct ublk_batch_io);
4100 	struct ublk_device *ub = cmd->file->private_data;
4101 	struct ublk_batch_io_data data = {
4102 		.ub  = ub,
4103 		.cmd = cmd,
4104 		.header = (struct ublk_batch_io) {
4105 			.q_id = READ_ONCE(uc->q_id),
4106 			.flags = READ_ONCE(uc->flags),
4107 			.nr_elem = READ_ONCE(uc->nr_elem),
4108 			.elem_bytes = READ_ONCE(uc->elem_bytes),
4109 		},
4110 		.issue_flags = issue_flags,
4111 	};
4112 	u32 cmd_op = cmd->cmd_op;
4113 	int ret = -EINVAL;
4114 
4115 	if (unlikely(issue_flags & IO_URING_F_CANCEL)) {
4116 		ublk_batch_cancel_fn(cmd, issue_flags);
4117 		return 0;
4118 	}
4119 
4120 	switch (cmd_op) {
4121 	case UBLK_U_IO_PREP_IO_CMDS:
4122 		ret = ublk_check_batch_cmd(&data);
4123 		if (ret)
4124 			goto out;
4125 		ret = ublk_handle_batch_prep_cmd(&data);
4126 		break;
4127 	case UBLK_U_IO_COMMIT_IO_CMDS:
4128 		ret = ublk_check_batch_cmd(&data);
4129 		if (ret)
4130 			goto out;
4131 		ret = ublk_handle_batch_commit_cmd(&data);
4132 		break;
4133 	case UBLK_U_IO_FETCH_IO_CMDS:
4134 		ret = ublk_validate_batch_fetch_cmd(&data);
4135 		if (ret)
4136 			goto out;
4137 		ret = ublk_handle_batch_fetch_cmd(&data);
4138 		break;
4139 	default:
4140 		ret = ublk_handle_non_batch_cmd(cmd, issue_flags);
4141 		break;
4142 	}
4143 out:
4144 	return ret;
4145 }
4146 
4147 static inline bool ublk_check_ubuf_dir(const struct request *req,
4148 		int ubuf_dir)
4149 {
4150 	/* copy ubuf to request pages */
4151 	if ((req_op(req) == REQ_OP_READ || req_op(req) == REQ_OP_DRV_IN) &&
4152 	    ubuf_dir == ITER_SOURCE)
4153 		return true;
4154 
4155 	/* copy request pages to ubuf */
4156 	if ((req_op(req) == REQ_OP_WRITE ||
4157 	     req_op(req) == REQ_OP_ZONE_APPEND) &&
4158 	    ubuf_dir == ITER_DEST)
4159 		return true;
4160 
4161 	return false;
4162 }
4163 
4164 static ssize_t
4165 ublk_user_copy(struct kiocb *iocb, struct iov_iter *iter, int dir)
4166 {
4167 	struct ublk_device *ub = iocb->ki_filp->private_data;
4168 	struct ublk_queue *ubq;
4169 	struct request *req;
4170 	struct ublk_io *io;
4171 	unsigned data_len;
4172 	bool is_integrity;
4173 	bool on_daemon;
4174 	size_t buf_off;
4175 	u16 tag, q_id;
4176 	ssize_t ret;
4177 
4178 	if (!user_backed_iter(iter))
4179 		return -EACCES;
4180 
4181 	if (ub->dev_info.state == UBLK_S_DEV_DEAD)
4182 		return -EACCES;
4183 
4184 	tag = ublk_pos_to_tag(iocb->ki_pos);
4185 	q_id = ublk_pos_to_hwq(iocb->ki_pos);
4186 	buf_off = ublk_pos_to_buf_off(iocb->ki_pos);
4187 	is_integrity = !!(iocb->ki_pos & UBLKSRV_IO_INTEGRITY_FLAG);
4188 
4189 	if (unlikely(!ublk_dev_support_integrity(ub) && is_integrity))
4190 		return -EINVAL;
4191 
4192 	if (q_id >= ub->dev_info.nr_hw_queues)
4193 		return -EINVAL;
4194 
4195 	ubq = ublk_get_queue(ub, q_id);
4196 	if (!ublk_dev_support_user_copy(ub))
4197 		return -EACCES;
4198 
4199 	if (tag >= ub->dev_info.queue_depth)
4200 		return -EINVAL;
4201 
4202 	io = &ubq->ios[tag];
4203 	on_daemon = current == READ_ONCE(io->task);
4204 	if (on_daemon) {
4205 		/* On daemon, io can't be completed concurrently, so skip ref */
4206 		if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV))
4207 			return -EINVAL;
4208 
4209 		req = io->req;
4210 		if (!blk_rq_has_data(req))
4211 			return -EINVAL;
4212 	} else {
4213 		req = __ublk_check_and_get_req(ub, q_id, tag, io);
4214 		if (!req)
4215 			return -EINVAL;
4216 	}
4217 
4218 	if (is_integrity) {
4219 		struct blk_integrity *bi = &req->q->limits.integrity;
4220 
4221 		data_len = bio_integrity_bytes(bi, blk_rq_sectors(req));
4222 	} else {
4223 		data_len = blk_rq_bytes(req);
4224 	}
4225 	if (buf_off > data_len) {
4226 		ret = -EINVAL;
4227 		goto out;
4228 	}
4229 
4230 	if (!ublk_check_ubuf_dir(req, dir)) {
4231 		ret = -EACCES;
4232 		goto out;
4233 	}
4234 
4235 	if (is_integrity)
4236 		ret = ublk_copy_user_integrity(req, buf_off, iter, dir);
4237 	else
4238 		ret = ublk_copy_user_pages(req, buf_off, iter, dir);
4239 
4240 out:
4241 	if (!on_daemon)
4242 		ublk_put_req_ref(io, req);
4243 	return ret;
4244 }
4245 
4246 static ssize_t ublk_ch_read_iter(struct kiocb *iocb, struct iov_iter *to)
4247 {
4248 	return ublk_user_copy(iocb, to, ITER_DEST);
4249 }
4250 
4251 static ssize_t ublk_ch_write_iter(struct kiocb *iocb, struct iov_iter *from)
4252 {
4253 	return ublk_user_copy(iocb, from, ITER_SOURCE);
4254 }
4255 
4256 static const struct file_operations ublk_ch_fops = {
4257 	.owner = THIS_MODULE,
4258 	.open = ublk_ch_open,
4259 	.release = ublk_ch_release,
4260 	.read_iter = ublk_ch_read_iter,
4261 	.write_iter = ublk_ch_write_iter,
4262 	.uring_cmd = ublk_ch_uring_cmd,
4263 	.mmap = ublk_ch_mmap,
4264 };
4265 
4266 static const struct file_operations ublk_ch_batch_io_fops = {
4267 	.owner = THIS_MODULE,
4268 	.open = ublk_ch_open,
4269 	.release = ublk_ch_release,
4270 	.read_iter = ublk_ch_read_iter,
4271 	.write_iter = ublk_ch_write_iter,
4272 	.uring_cmd = ublk_ch_batch_io_uring_cmd,
4273 	.mmap = ublk_ch_mmap,
4274 };
4275 
4276 static void __ublk_deinit_queue(struct ublk_device *ub, struct ublk_queue *ubq)
4277 {
4278 	size_t size;
4279 	u16 i;
4280 
4281 	size = ublk_queue_cmd_buf_size(ub);
4282 
4283 	for (i = 0; i < ubq->q_depth; i++) {
4284 		struct ublk_io *io = &ubq->ios[i];
4285 		if (io->task)
4286 			put_task_struct(io->task);
4287 		WARN_ON_ONCE(refcount_read(&io->ref));
4288 		WARN_ON_ONCE(io->task_registered_buffers);
4289 	}
4290 
4291 	if (ubq->io_cmd_buf)
4292 		free_pages((unsigned long)ubq->io_cmd_buf, get_order(size));
4293 
4294 	if (ublk_dev_support_batch_io(ub))
4295 		ublk_io_evts_deinit(ubq);
4296 
4297 	kvfree(ubq);
4298 }
4299 
4300 static void ublk_deinit_queue(struct ublk_device *ub, u16 q_id)
4301 {
4302 	struct ublk_queue *ubq = ub->queues[q_id];
4303 
4304 	if (!ubq)
4305 		return;
4306 
4307 	__ublk_deinit_queue(ub, ubq);
4308 	ub->queues[q_id] = NULL;
4309 }
4310 
4311 static int ublk_get_queue_numa_node(struct ublk_device *ub, u16 q_id)
4312 {
4313 	unsigned int cpu;
4314 
4315 	/* Find first CPU mapped to this queue */
4316 	for_each_possible_cpu(cpu) {
4317 		if (ub->tag_set.map[HCTX_TYPE_DEFAULT].mq_map[cpu] == q_id)
4318 			return cpu_to_node(cpu);
4319 	}
4320 
4321 	return NUMA_NO_NODE;
4322 }
4323 
4324 static int ublk_init_queue(struct ublk_device *ub, u16 q_id)
4325 {
4326 	u16 depth = ub->dev_info.queue_depth;
4327 	gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO;
4328 	struct ublk_queue *ubq;
4329 	struct page *page;
4330 	int numa_node;
4331 	size_t size;
4332 	int ret;
4333 	u16 i;
4334 
4335 	/* Determine NUMA node based on queue's CPU affinity */
4336 	numa_node = ublk_get_queue_numa_node(ub, q_id);
4337 
4338 	/* Allocate queue structure on local NUMA node */
4339 	ubq = kvzalloc_node(struct_size(ubq, ios, depth), GFP_KERNEL,
4340 			    numa_node);
4341 	if (!ubq)
4342 		return -ENOMEM;
4343 
4344 	spin_lock_init(&ubq->cancel_lock);
4345 	ubq->flags = ub->dev_info.flags;
4346 	ubq->q_id = q_id;
4347 	ubq->q_depth = depth;
4348 	size = ublk_queue_cmd_buf_size(ub);
4349 
4350 	/* Allocate I/O command buffer on local NUMA node */
4351 	page = alloc_pages_node(numa_node, gfp_flags, get_order(size));
4352 	if (!page) {
4353 		kvfree(ubq);
4354 		return -ENOMEM;
4355 	}
4356 	ubq->io_cmd_buf = page_address(page);
4357 	ubq->io_desc_size = ub->dev_info.io_desc_size;
4358 
4359 	for (i = 0; i < ubq->q_depth; i++)
4360 		spin_lock_init(&ubq->ios[i].lock);
4361 
4362 	if (ublk_dev_support_batch_io(ub)) {
4363 		ret = ublk_io_evts_init(ubq, ubq->q_depth, numa_node);
4364 		if (ret)
4365 			goto fail;
4366 		INIT_LIST_HEAD(&ubq->fcmd_head);
4367 	}
4368 	ub->queues[q_id] = ubq;
4369 	ubq->dev = ub;
4370 
4371 	return 0;
4372 fail:
4373 	__ublk_deinit_queue(ub, ubq);
4374 	return ret;
4375 }
4376 
4377 static void ublk_deinit_queues(struct ublk_device *ub)
4378 {
4379 	u16 i;
4380 
4381 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
4382 		ublk_deinit_queue(ub, i);
4383 }
4384 
4385 static int ublk_init_queues(struct ublk_device *ub)
4386 {
4387 	int ret;
4388 	u16 i;
4389 
4390 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++) {
4391 		ret = ublk_init_queue(ub, i);
4392 		if (ret)
4393 			goto fail;
4394 	}
4395 
4396 	return 0;
4397 
4398  fail:
4399 	ublk_deinit_queues(ub);
4400 	return ret;
4401 }
4402 
4403 static int ublk_alloc_dev_number(struct ublk_device *ub, int idx)
4404 {
4405 	int i = idx;
4406 	int err;
4407 
4408 	spin_lock(&ublk_idr_lock);
4409 	/* allocate id, if @id >= 0, we're requesting that specific id */
4410 	if (i >= 0) {
4411 		err = idr_alloc(&ublk_index_idr, ub, i, i + 1, GFP_NOWAIT);
4412 		if (err == -ENOSPC)
4413 			err = -EEXIST;
4414 	} else {
4415 		err = idr_alloc(&ublk_index_idr, ub, 0, UBLK_MAX_UBLKS,
4416 				GFP_NOWAIT);
4417 	}
4418 	spin_unlock(&ublk_idr_lock);
4419 
4420 	if (err >= 0)
4421 		ub->ub_number = err;
4422 
4423 	return err;
4424 }
4425 
4426 static void ublk_free_dev_number(struct ublk_device *ub)
4427 {
4428 	spin_lock(&ublk_idr_lock);
4429 	idr_remove(&ublk_index_idr, ub->ub_number);
4430 	wake_up_all(&ublk_idr_wq);
4431 	spin_unlock(&ublk_idr_lock);
4432 }
4433 
4434 static void ublk_cdev_rel(struct device *dev)
4435 {
4436 	struct ublk_device *ub = container_of(dev, struct ublk_device, cdev_dev);
4437 
4438 	ublk_buf_cleanup(ub);
4439 	blk_mq_free_tag_set(&ub->tag_set);
4440 	ublk_deinit_queues(ub);
4441 	ublk_free_dev_number(ub);
4442 	mutex_destroy(&ub->mutex);
4443 	mutex_destroy(&ub->cancel_mutex);
4444 	kfree(ub);
4445 }
4446 
4447 static int ublk_add_chdev(struct ublk_device *ub)
4448 {
4449 	struct device *dev = &ub->cdev_dev;
4450 	int minor = ub->ub_number;
4451 	int ret;
4452 
4453 	dev->parent = ublk_misc.this_device;
4454 	dev->devt = MKDEV(MAJOR(ublk_chr_devt), minor);
4455 	dev->class = &ublk_chr_class;
4456 	dev->release = ublk_cdev_rel;
4457 	device_initialize(dev);
4458 
4459 	ret = dev_set_name(dev, "ublkc%d", minor);
4460 	if (ret)
4461 		goto fail;
4462 
4463 	if (ublk_dev_support_batch_io(ub))
4464 		cdev_init(&ub->cdev, &ublk_ch_batch_io_fops);
4465 	else
4466 		cdev_init(&ub->cdev, &ublk_ch_fops);
4467 	ret = cdev_device_add(&ub->cdev, dev);
4468 	if (ret)
4469 		goto fail;
4470 
4471 	if (ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV)
4472 		unprivileged_ublks_added++;
4473 	return 0;
4474  fail:
4475 	put_device(dev);
4476 	return ret;
4477 }
4478 
4479 /* align max io buffer size with PAGE_SIZE */
4480 static void ublk_align_max_io_size(struct ublk_device *ub)
4481 {
4482 	unsigned int max_io_bytes = ub->dev_info.max_io_buf_bytes;
4483 
4484 	ub->dev_info.max_io_buf_bytes =
4485 		round_down(max_io_bytes, PAGE_SIZE);
4486 }
4487 
4488 static int ublk_add_tag_set(struct ublk_device *ub)
4489 {
4490 	if (ublk_dev_support_batch_io(ub))
4491 		ub->tag_set.ops = &ublk_batch_mq_ops;
4492 	else
4493 		ub->tag_set.ops = &ublk_mq_ops;
4494 	ub->tag_set.nr_hw_queues = ub->dev_info.nr_hw_queues;
4495 	ub->tag_set.queue_depth = ub->dev_info.queue_depth;
4496 	ub->tag_set.numa_node = NUMA_NO_NODE;
4497 	ub->tag_set.flags = BLK_MQ_F_NO_SCHED_BY_DEFAULT;
4498 	ub->tag_set.driver_data = ub;
4499 	return blk_mq_alloc_tag_set(&ub->tag_set);
4500 }
4501 
4502 static void ublk_remove(struct ublk_device *ub)
4503 {
4504 	bool unprivileged;
4505 
4506 	ublk_stop_dev(ub);
4507 	cdev_device_del(&ub->cdev, &ub->cdev_dev);
4508 	unprivileged = ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV;
4509 	ublk_put_device(ub);
4510 
4511 	if (unprivileged)
4512 		unprivileged_ublks_added--;
4513 }
4514 
4515 static struct ublk_device *ublk_get_device_from_id(int idx)
4516 {
4517 	struct ublk_device *ub = NULL;
4518 
4519 	if (idx < 0)
4520 		return NULL;
4521 
4522 	spin_lock(&ublk_idr_lock);
4523 	ub = idr_find(&ublk_index_idr, idx);
4524 	if (ub)
4525 		ub = ublk_get_device(ub);
4526 	spin_unlock(&ublk_idr_lock);
4527 
4528 	return ub;
4529 }
4530 
4531 static bool ublk_validate_user_pid(struct ublk_device *ub, pid_t ublksrv_pid)
4532 {
4533 	rcu_read_lock();
4534 	ublksrv_pid = pid_nr(find_vpid(ublksrv_pid));
4535 	rcu_read_unlock();
4536 
4537 	return ub->ublksrv_tgid == ublksrv_pid;
4538 }
4539 
4540 static bool ublk_dev_ready_or_stopping(const struct ublk_device *ub)
4541 {
4542 	return ublk_dev_ready(ub) || test_bit(UB_STATE_STOPPING, &ub->state);
4543 }
4544 
4545 /*
4546  * Wait until all queues have fetched their I/O commands, or STOP_DEV set
4547  * UB_STATE_STOPPING, and return with ub->mutex held. The queues stay
4548  * canceling if this round saw a cancel, see ublk_queue_reset_io_flags().
4549  * Ready may regress between wakeup and mutex_lock() (F_BATCH UNPREP,
4550  * daemon death), so re-check it under the mutex and wait again.
4551  */
4552 static int ublk_wait_dev_ready_and_lock(struct ublk_device *ub)
4553 {
4554 	while (true) {
4555 		if (wait_var_event_interruptible(&ub->nr_queue_ready,
4556 						 ublk_dev_ready_or_stopping(ub)))
4557 			return -EINTR;
4558 
4559 		mutex_lock(&ub->mutex);
4560 		if (ublk_dev_ready_or_stopping(ub))
4561 			return 0;
4562 		mutex_unlock(&ub->mutex);
4563 	}
4564 }
4565 
4566 static int ublk_ctrl_start_dev(struct ublk_device *ub,
4567 		const struct ublksrv_ctrl_cmd *header)
4568 {
4569 	const struct ublk_param_basic *p = &ub->params.basic;
4570 	int ublksrv_pid = (int)header->data[0];
4571 	struct queue_limits lim = {
4572 		.logical_block_size	= 1 << p->logical_bs_shift,
4573 		.physical_block_size	= 1 << p->physical_bs_shift,
4574 		.io_min			= 1 << p->io_min_shift,
4575 		.io_opt			= 1 << p->io_opt_shift,
4576 		.max_hw_sectors		= p->max_sectors,
4577 		.chunk_sectors		= p->chunk_sectors,
4578 		.virt_boundary_mask	= p->virt_boundary_mask,
4579 		.max_segments		= USHRT_MAX,
4580 		.max_segment_size	= UINT_MAX,
4581 		.dma_alignment		= 3,
4582 	};
4583 	struct gendisk *disk;
4584 	bool canceled;
4585 	int ret = -EINVAL;
4586 
4587 	if (ublksrv_pid <= 0)
4588 		return -EINVAL;
4589 	if (!(ub->params.types & UBLK_PARAM_TYPE_BASIC))
4590 		return -EINVAL;
4591 
4592 	if (ub->params.types & UBLK_PARAM_TYPE_DISCARD) {
4593 		const struct ublk_param_discard *pd = &ub->params.discard;
4594 
4595 		lim.discard_alignment = pd->discard_alignment;
4596 		lim.discard_granularity = pd->discard_granularity;
4597 		lim.max_hw_discard_sectors = pd->max_discard_sectors;
4598 		lim.max_write_zeroes_sectors = pd->max_write_zeroes_sectors;
4599 		lim.max_discard_segments = pd->max_discard_segments;
4600 	}
4601 
4602 	if (ub->params.types & UBLK_PARAM_TYPE_ZONED) {
4603 		const struct ublk_param_zoned *p = &ub->params.zoned;
4604 
4605 		if (!IS_ENABLED(CONFIG_BLK_DEV_ZONED))
4606 			return -EOPNOTSUPP;
4607 
4608 		lim.features |= BLK_FEAT_ZONED;
4609 		lim.max_active_zones = p->max_active_zones;
4610 		lim.max_open_zones =  p->max_open_zones;
4611 		lim.max_hw_zone_append_sectors = p->max_zone_append_sectors;
4612 	}
4613 
4614 	if (ub->params.basic.attrs & UBLK_ATTR_VOLATILE_CACHE) {
4615 		lim.features |= BLK_FEAT_WRITE_CACHE;
4616 		if (ub->params.basic.attrs & UBLK_ATTR_FUA)
4617 			lim.features |= BLK_FEAT_FUA;
4618 	}
4619 
4620 	if (ub->params.basic.attrs & UBLK_ATTR_ROTATIONAL)
4621 		lim.features |= BLK_FEAT_ROTATIONAL;
4622 
4623 	if (ub->params.types & UBLK_PARAM_TYPE_DMA_ALIGN)
4624 		lim.dma_alignment = ub->params.dma.alignment;
4625 
4626 	if (ub->params.types & UBLK_PARAM_TYPE_SEGMENT) {
4627 		lim.seg_boundary_mask = ub->params.seg.seg_boundary_mask;
4628 		lim.max_segment_size = ub->params.seg.max_segment_size;
4629 		lim.max_segments = ub->params.seg.max_segments;
4630 	}
4631 
4632 	if (ub->params.types & UBLK_PARAM_TYPE_INTEGRITY) {
4633 		const struct ublk_param_integrity *p = &ub->params.integrity;
4634 		int pi_tuple_size = ublk_integrity_pi_tuple_size(p->csum_type);
4635 
4636 		lim.max_integrity_segments =
4637 			p->max_integrity_segments ?: USHRT_MAX;
4638 		lim.integrity = (struct blk_integrity) {
4639 			.flags = ublk_integrity_flags(p->flags),
4640 			.csum_type = ublk_integrity_csum_type(p->csum_type),
4641 			.metadata_size = p->metadata_size,
4642 			.pi_offset = p->pi_offset,
4643 			.interval_exp = p->interval_exp,
4644 			.tag_size = p->tag_size,
4645 			.pi_tuple_size = pi_tuple_size,
4646 		};
4647 	}
4648 
4649 	if (ublk_wait_dev_ready_and_lock(ub))
4650 		return -EINTR;
4651 
4652 	if (!ublk_validate_user_pid(ub, ublksrv_pid)) {
4653 		ret = -EINVAL;
4654 		goto out_unlock;
4655 	}
4656 	if (ub->dev_info.state == UBLK_S_DEV_LIVE ||
4657 	    test_bit(UB_STATE_USED, &ub->state)) {
4658 		ret = -EEXIST;
4659 		goto out_unlock;
4660 	}
4661 	if (test_bit(UB_STATE_STOPPING, &ub->state)) {
4662 		ret = -EBUSY;
4663 		goto out_unlock;
4664 	}
4665 
4666 	disk = blk_mq_alloc_disk(&ub->tag_set, &lim, NULL);
4667 	if (IS_ERR(disk)) {
4668 		ret = PTR_ERR(disk);
4669 		goto out_unlock;
4670 	}
4671 	sprintf(disk->disk_name, "ublkb%d", ub->ub_number);
4672 	disk->fops = &ub_fops;
4673 	disk->private_data = ub;
4674 
4675 	/*
4676 	 * A command of this FETCH round was canceled and can't be fetched
4677 	 * again, don't bring up a disk over it.  Check and publish the disk
4678 	 * in one cancel_mutex section: either this sees ub->canceling, or
4679 	 * ublk_start_cancel() sees the disk and quiesces it before marking
4680 	 * the queues.
4681 	 */
4682 	mutex_lock(&ub->cancel_mutex);
4683 	canceled = ub->canceling;
4684 	if (!canceled)
4685 		ub->ub_disk = disk;
4686 	mutex_unlock(&ub->cancel_mutex);
4687 	if (canceled) {
4688 		put_disk(disk);
4689 		ret = -EBUSY;
4690 		goto out_unlock;
4691 	}
4692 	ub->dev_info.ublksrv_pid = ub->ublksrv_tgid;
4693 
4694 	ublk_apply_params(ub);
4695 
4696 	/*
4697 	 * Suppress partition scan to avoid potential IO hang.
4698 	 *
4699 	 * If ublk server error occurs during partition scan, the IO may
4700 	 * wait while holding ub->mutex, which can deadlock with other
4701 	 * operations that need the mutex. Defer partition scan to async
4702 	 * work.
4703 	 * For unprivileged daemons, keep GD_SUPPRESS_PART_SCAN set
4704 	 * permanently.
4705 	 */
4706 	set_bit(GD_SUPPRESS_PART_SCAN, &disk->state);
4707 
4708 	ublk_get_device(ub);
4709 	ub->dev_info.state = UBLK_S_DEV_LIVE;
4710 
4711 	if (ublk_dev_is_zoned(ub)) {
4712 		ret = ublk_revalidate_disk_zones(ub);
4713 		if (ret)
4714 			goto out_put_cdev;
4715 	}
4716 
4717 	ret = add_disk(disk);
4718 	if (ret)
4719 		goto out_put_cdev;
4720 
4721 	set_bit(UB_STATE_USED, &ub->state);
4722 
4723 	/* Skip partition scan if disabled by user */
4724 	if (ub->dev_info.flags & UBLK_F_NO_AUTO_PART_SCAN) {
4725 		/* Not clear for unprivileged daemons, see comment above */
4726 		if (!ub->unprivileged_daemons)
4727 			clear_bit(GD_SUPPRESS_PART_SCAN, &disk->state);
4728 	} else {
4729 		/* Schedule async partition scan for trusted daemons */
4730 		if (!ub->unprivileged_daemons)
4731 			schedule_work(&ub->partition_scan_work);
4732 	}
4733 
4734 out_put_cdev:
4735 	if (ret) {
4736 		ublk_detach_disk(ub);
4737 		ublk_put_device(ub);
4738 	}
4739 	if (ret)
4740 		put_disk(disk);
4741 out_unlock:
4742 	mutex_unlock(&ub->mutex);
4743 	return ret;
4744 }
4745 
4746 static int ublk_ctrl_get_queue_affinity(struct ublk_device *ub,
4747 		const struct ublksrv_ctrl_cmd *header)
4748 {
4749 	void __user *argp = (void __user *)(unsigned long)header->addr;
4750 	cpumask_var_t cpumask;
4751 	unsigned long queue;
4752 	unsigned int retlen;
4753 	unsigned int i;
4754 	int ret;
4755 
4756 	if (header->len * BITS_PER_BYTE < nr_cpu_ids)
4757 		return -EINVAL;
4758 	if (header->len & (sizeof(unsigned long)-1))
4759 		return -EINVAL;
4760 	if (!header->addr)
4761 		return -EINVAL;
4762 
4763 	queue = header->data[0];
4764 	if (queue >= ub->dev_info.nr_hw_queues)
4765 		return -EINVAL;
4766 
4767 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
4768 		return -ENOMEM;
4769 
4770 	for_each_possible_cpu(i) {
4771 		if (ub->tag_set.map[HCTX_TYPE_DEFAULT].mq_map[i] == queue)
4772 			cpumask_set_cpu(i, cpumask);
4773 	}
4774 
4775 	ret = -EFAULT;
4776 	retlen = min_t(unsigned short, header->len, cpumask_size());
4777 	if (copy_to_user(argp, cpumask, retlen))
4778 		goto out_free_cpumask;
4779 	if (retlen != header->len &&
4780 	    clear_user(argp + retlen, header->len - retlen))
4781 		goto out_free_cpumask;
4782 
4783 	ret = 0;
4784 out_free_cpumask:
4785 	free_cpumask_var(cpumask);
4786 	return ret;
4787 }
4788 
4789 static inline void ublk_dump_dev_info(struct ublksrv_ctrl_dev_info *info)
4790 {
4791 	pr_devel("%s: dev id %d flags %llx\n", __func__,
4792 			info->dev_id, info->flags);
4793 	pr_devel("\t nr_hw_queues %d queue_depth %d\n",
4794 			info->nr_hw_queues, info->queue_depth);
4795 }
4796 
4797 static int ublk_ctrl_add_dev(const struct ublksrv_ctrl_cmd *header)
4798 {
4799 	void __user *argp = (void __user *)(unsigned long)header->addr;
4800 	struct ublksrv_ctrl_dev_info info;
4801 	struct ublk_device *ub;
4802 	int ret = -EINVAL;
4803 
4804 	if (header->len < sizeof(info) || !header->addr)
4805 		return -EINVAL;
4806 	if (header->queue_id != (u16)-1) {
4807 		pr_warn("%s: queue_id is wrong %x\n",
4808 			__func__, header->queue_id);
4809 		return -EINVAL;
4810 	}
4811 
4812 	if (copy_from_user(&info, argp, sizeof(info)))
4813 		return -EFAULT;
4814 
4815 	if (info.queue_depth > UBLK_MAX_QUEUE_DEPTH || !info.queue_depth ||
4816 	    info.nr_hw_queues > UBLK_MAX_NR_QUEUES || !info.nr_hw_queues)
4817 		return -EINVAL;
4818 
4819 	if (capable(CAP_SYS_ADMIN))
4820 		info.flags &= ~UBLK_F_UNPRIVILEGED_DEV;
4821 	else if (!(info.flags & UBLK_F_UNPRIVILEGED_DEV))
4822 		return -EPERM;
4823 
4824 	/* forbid nonsense combinations of recovery flags */
4825 	switch (info.flags & UBLK_F_ALL_RECOVERY_FLAGS) {
4826 	case 0:
4827 	case UBLK_F_USER_RECOVERY:
4828 	case (UBLK_F_USER_RECOVERY | UBLK_F_USER_RECOVERY_REISSUE):
4829 	case (UBLK_F_USER_RECOVERY | UBLK_F_USER_RECOVERY_FAIL_IO):
4830 		break;
4831 	default:
4832 		pr_warn("%s: invalid recovery flags %llx\n", __func__,
4833 			info.flags & UBLK_F_ALL_RECOVERY_FLAGS);
4834 		return -EINVAL;
4835 	}
4836 
4837 	if ((info.flags & UBLK_F_QUIESCE) && !(info.flags & UBLK_F_USER_RECOVERY)) {
4838 		pr_warn("UBLK_F_QUIESCE requires UBLK_F_USER_RECOVERY\n");
4839 		return -EINVAL;
4840 	}
4841 
4842 	/*
4843 	 * unprivileged device can't be trusted, but RECOVERY and
4844 	 * RECOVERY_REISSUE still may hang error handling, so can't
4845 	 * support recovery features for unprivileged ublk now
4846 	 *
4847 	 * TODO: provide forward progress for RECOVERY handler, so that
4848 	 * unprivileged device can benefit from it
4849 	 */
4850 	if (info.flags & UBLK_F_UNPRIVILEGED_DEV) {
4851 		info.flags &= ~(UBLK_F_USER_RECOVERY_REISSUE |
4852 				UBLK_F_USER_RECOVERY);
4853 
4854 		/*
4855 		 * For USER_COPY, we depends on userspace to fill request
4856 		 * buffer by pwrite() to ublk char device, which can't be
4857 		 * used for unprivileged device
4858 		 *
4859 		 * Same with zero copy or auto buffer register.
4860 		 */
4861 		if (info.flags & (UBLK_F_USER_COPY | UBLK_F_SUPPORT_ZERO_COPY |
4862 					UBLK_F_AUTO_BUF_REG))
4863 			return -EINVAL;
4864 	}
4865 
4866 	/* User copy is required to access integrity buffer */
4867 	if (info.flags & UBLK_F_INTEGRITY && !(info.flags & UBLK_F_USER_COPY))
4868 		return -EINVAL;
4869 
4870 	if (info.flags & UBLK_F_IO_DESC_SIZE) {
4871 		if (info.io_desc_size < sizeof(struct ublksrv_io_desc) ||
4872 		    info.io_desc_size % _Alignof(struct ublksrv_io_desc) ||
4873 		    info.io_desc_size > UBLK_MAX_IO_DESC_SIZE)
4874 			return -EINVAL;
4875 	} else {
4876 		info.io_desc_size = sizeof(struct ublksrv_io_desc);
4877 	}
4878 
4879 	/* the created device is always owned by current user */
4880 	ublk_store_owner_uid_gid(&info.owner_uid, &info.owner_gid);
4881 
4882 	if (header->dev_id != info.dev_id) {
4883 		pr_warn("%s: dev id not match %u %u\n",
4884 			__func__, header->dev_id, info.dev_id);
4885 		return -EINVAL;
4886 	}
4887 
4888 	if (header->dev_id != U32_MAX && header->dev_id >= UBLK_MAX_UBLKS) {
4889 		pr_warn("%s: dev id is too large. Max supported is %d\n",
4890 			__func__, UBLK_MAX_UBLKS - 1);
4891 		return -EINVAL;
4892 	}
4893 
4894 	ublk_dump_dev_info(&info);
4895 
4896 	ret = mutex_lock_killable(&ublk_ctl_mutex);
4897 	if (ret)
4898 		return ret;
4899 
4900 	ret = -EACCES;
4901 	if ((info.flags & UBLK_F_UNPRIVILEGED_DEV) &&
4902 	    unprivileged_ublks_added >= unprivileged_ublks_max)
4903 		goto out_unlock;
4904 
4905 	ret = -ENOMEM;
4906 	ub = kzalloc_flex(*ub, queues, info.nr_hw_queues);
4907 	if (!ub)
4908 		goto out_unlock;
4909 	mutex_init(&ub->mutex);
4910 	spin_lock_init(&ub->lock);
4911 	mutex_init(&ub->cancel_mutex);
4912 	mt_init(&ub->buf_tree);
4913 	ida_init(&ub->buf_ida);
4914 	INIT_WORK(&ub->partition_scan_work, ublk_partition_scan_work);
4915 
4916 	ret = ublk_alloc_dev_number(ub, header->dev_id);
4917 	if (ret < 0)
4918 		goto out_free_ub;
4919 
4920 	memcpy(&ub->dev_info, &info, sizeof(info));
4921 
4922 	/* update device id */
4923 	ub->dev_info.dev_id = ub->ub_number;
4924 
4925 	/*
4926 	 * ->state and ->ublksrv_pid are owned by the driver and only read back
4927 	 * by userspace, but they come from the copied-in dev_info, so reset
4928 	 * them. Otherwise a device added with ->state != DEAD looks live while
4929 	 * ->ub_disk is still NULL.
4930 	 */
4931 	ub->dev_info.state = UBLK_S_DEV_DEAD;
4932 	ub->dev_info.ublksrv_pid = -1;
4933 
4934 	/*
4935 	 * 64bit flags will be copied back to userspace as feature
4936 	 * negotiation result, so have to clear flags which driver
4937 	 * doesn't support yet, then userspace can get correct flags
4938 	 * (features) to handle.
4939 	 */
4940 	ub->dev_info.flags &= UBLK_F_ALL;
4941 
4942 	ub->dev_info.flags |= UBLK_F_CMD_IOCTL_ENCODE |
4943 		UBLK_F_URING_CMD_COMP_IN_TASK |
4944 		UBLK_F_PER_IO_DAEMON |
4945 		UBLK_F_BUF_REG_OFF_DAEMON |
4946 		UBLK_F_SAFE_STOP_DEV;
4947 
4948 	/* So far, UBLK_F_PER_IO_DAEMON won't be exposed for BATCH_IO */
4949 	if (ublk_dev_support_batch_io(ub))
4950 		ub->dev_info.flags &= ~UBLK_F_PER_IO_DAEMON;
4951 
4952 	/* GET_DATA isn't needed any more with USER_COPY or ZERO COPY */
4953 	if (ub->dev_info.flags & (UBLK_F_USER_COPY | UBLK_F_SUPPORT_ZERO_COPY |
4954 				UBLK_F_AUTO_BUF_REG))
4955 		ub->dev_info.flags &= ~UBLK_F_NEED_GET_DATA;
4956 
4957 	/* UBLK_F_BATCH_IO doesn't support GET_DATA */
4958 	if (ublk_dev_support_batch_io(ub))
4959 		ub->dev_info.flags &= ~UBLK_F_NEED_GET_DATA;
4960 
4961 	/*
4962 	 * Zoned storage support requires reuse `ublksrv_io_cmd->addr` for
4963 	 * returning write_append_lba, which is only allowed in case of
4964 	 * user copy or zero copy
4965 	 */
4966 	if (ublk_dev_is_zoned(ub) &&
4967 	    (!IS_ENABLED(CONFIG_BLK_DEV_ZONED) || !(ub->dev_info.flags &
4968 	     (UBLK_F_USER_COPY | UBLK_F_SUPPORT_ZERO_COPY)))) {
4969 		ret = -EINVAL;
4970 		goto out_free_dev_number;
4971 	}
4972 
4973 	ub->dev_info.nr_hw_queues = min_t(unsigned int,
4974 			ub->dev_info.nr_hw_queues, nr_cpu_ids);
4975 	ublk_align_max_io_size(ub);
4976 
4977 	ret = ublk_add_tag_set(ub);
4978 	if (ret)
4979 		goto out_free_dev_number;
4980 
4981 	ret = ublk_init_queues(ub);
4982 	if (ret)
4983 		goto out_free_tag_set;
4984 
4985 	ret = -EFAULT;
4986 	if (copy_to_user(argp, &ub->dev_info, sizeof(info)))
4987 		goto out_deinit_queues;
4988 
4989 	/*
4990 	 * Add the char dev so that ublksrv daemon can be setup.
4991 	 * ublk_add_chdev() will cleanup everything if it fails.
4992 	 */
4993 	ret = ublk_add_chdev(ub);
4994 	goto out_unlock;
4995 
4996 out_deinit_queues:
4997 	ublk_deinit_queues(ub);
4998 out_free_tag_set:
4999 	blk_mq_free_tag_set(&ub->tag_set);
5000 out_free_dev_number:
5001 	ublk_free_dev_number(ub);
5002 out_free_ub:
5003 	mutex_destroy(&ub->mutex);
5004 	mutex_destroy(&ub->cancel_mutex);
5005 	kfree(ub);
5006 out_unlock:
5007 	mutex_unlock(&ublk_ctl_mutex);
5008 	return ret;
5009 }
5010 
5011 static inline bool ublk_idr_freed(int id)
5012 {
5013 	void *ptr;
5014 
5015 	spin_lock(&ublk_idr_lock);
5016 	ptr = idr_find(&ublk_index_idr, id);
5017 	spin_unlock(&ublk_idr_lock);
5018 
5019 	return ptr == NULL;
5020 }
5021 
5022 static int ublk_ctrl_del_dev(struct ublk_device **p_ub, bool wait)
5023 {
5024 	struct ublk_device *ub = *p_ub;
5025 	int idx = ub->ub_number;
5026 	int ret;
5027 
5028 	ret = mutex_lock_killable(&ublk_ctl_mutex);
5029 	if (ret)
5030 		return ret;
5031 
5032 	if (!test_bit(UB_STATE_DELETED, &ub->state)) {
5033 		ublk_remove(ub);
5034 		set_bit(UB_STATE_DELETED, &ub->state);
5035 	}
5036 
5037 	mutex_unlock(&ublk_ctl_mutex);
5038 
5039 	/*
5040 	 * Drop the reference outside ublk_ctl_mutex: if it is the last one,
5041 	 * the release frees the tag set, which waits for an SRCU grace period,
5042 	 * and holding the mutex would serialize concurrent deletions on it.
5043 	 */
5044 	*p_ub = NULL;
5045 	ublk_put_device(ub);
5046 
5047 	/*
5048 	 * Wait until the idr is removed, then it can be reused after
5049 	 * DEL_DEV command is returned.
5050 	 *
5051 	 * If we returns because of user interrupt, future delete command
5052 	 * may come:
5053 	 *
5054 	 * - the device number isn't freed, this device won't or needn't
5055 	 *   be deleted again, since UB_STATE_DELETED is set, and device
5056 	 *   will be released after the last reference is dropped
5057 	 *
5058 	 * - the device number is freed already, we will not find this
5059 	 *   device via ublk_get_device_from_id()
5060 	 */
5061 	if (wait && wait_event_interruptible(ublk_idr_wq, ublk_idr_freed(idx)))
5062 		return -EINTR;
5063 	return 0;
5064 }
5065 
5066 static inline void ublk_ctrl_cmd_dump(u32 cmd_op,
5067 				      const struct ublksrv_ctrl_cmd *header)
5068 {
5069 	pr_devel("%s: cmd_op %x, dev id %d qid %d data %llx buf %llx len %u\n",
5070 			__func__, cmd_op, header->dev_id, header->queue_id,
5071 			header->data[0], header->addr, header->len);
5072 }
5073 
5074 static void ublk_ctrl_stop_dev(struct ublk_device *ub)
5075 {
5076 	ublk_stop_dev(ub);
5077 }
5078 
5079 static int ublk_ctrl_try_stop_dev(struct ublk_device *ub)
5080 {
5081 	struct gendisk *disk;
5082 	int ret = 0;
5083 
5084 	disk = ublk_get_disk(ub);
5085 	if (!disk)
5086 		return -ENODEV;
5087 
5088 	mutex_lock(&disk->open_mutex);
5089 	if (disk_openers(disk) > 0) {
5090 		ret = -EBUSY;
5091 		goto unlock;
5092 	}
5093 	ub->block_open = true;
5094 	/* release open_mutex as del_gendisk() will reacquire it */
5095 	mutex_unlock(&disk->open_mutex);
5096 
5097 	ublk_ctrl_stop_dev(ub);
5098 	goto out;
5099 
5100 unlock:
5101 	mutex_unlock(&disk->open_mutex);
5102 out:
5103 	ublk_put_disk(disk);
5104 	return ret;
5105 }
5106 
5107 static int ublk_ctrl_get_dev_info(struct ublk_device *ub,
5108 		const struct ublksrv_ctrl_cmd *header)
5109 {
5110 	struct task_struct *p;
5111 	struct pid *pid;
5112 	struct ublksrv_ctrl_dev_info dev_info;
5113 	pid_t init_ublksrv_tgid = ub->dev_info.ublksrv_pid;
5114 	void __user *argp = (void __user *)(unsigned long)header->addr;
5115 
5116 	if (header->len < sizeof(struct ublksrv_ctrl_dev_info) || !header->addr)
5117 		return -EINVAL;
5118 
5119 	memcpy(&dev_info, &ub->dev_info, sizeof(dev_info));
5120 	dev_info.ublksrv_pid = -1;
5121 
5122 	if (init_ublksrv_tgid > 0) {
5123 		rcu_read_lock();
5124 		pid = find_pid_ns(init_ublksrv_tgid, &init_pid_ns);
5125 		p = pid_task(pid, PIDTYPE_TGID);
5126 		if (p) {
5127 			int vnr = task_tgid_vnr(p);
5128 
5129 			if (vnr)
5130 				dev_info.ublksrv_pid = vnr;
5131 		}
5132 		rcu_read_unlock();
5133 	}
5134 
5135 	if (copy_to_user(argp, &dev_info, sizeof(dev_info)))
5136 		return -EFAULT;
5137 
5138 	return 0;
5139 }
5140 
5141 /* TYPE_DEVT is readonly, so fill it up before returning to userspace */
5142 static void ublk_ctrl_fill_params_devt(struct ublk_device *ub)
5143 {
5144 	ub->params.devt.char_major = MAJOR(ub->cdev_dev.devt);
5145 	ub->params.devt.char_minor = MINOR(ub->cdev_dev.devt);
5146 
5147 	if (ub->ub_disk) {
5148 		ub->params.devt.disk_major = MAJOR(disk_devt(ub->ub_disk));
5149 		ub->params.devt.disk_minor = MINOR(disk_devt(ub->ub_disk));
5150 	} else {
5151 		ub->params.devt.disk_major = 0;
5152 		ub->params.devt.disk_minor = 0;
5153 	}
5154 	ub->params.types |= UBLK_PARAM_TYPE_DEVT;
5155 }
5156 
5157 static int ublk_ctrl_get_params(struct ublk_device *ub,
5158 		const struct ublksrv_ctrl_cmd *header)
5159 {
5160 	void __user *argp = (void __user *)(unsigned long)header->addr;
5161 	struct ublk_params_header ph;
5162 	int ret;
5163 
5164 	if (header->len <= sizeof(ph) || !header->addr)
5165 		return -EINVAL;
5166 
5167 	if (copy_from_user(&ph, argp, sizeof(ph)))
5168 		return -EFAULT;
5169 
5170 	if (ph.len > header->len || !ph.len)
5171 		return -EINVAL;
5172 
5173 	if (ph.len > sizeof(struct ublk_params))
5174 		ph.len = sizeof(struct ublk_params);
5175 
5176 	mutex_lock(&ub->mutex);
5177 	ublk_ctrl_fill_params_devt(ub);
5178 	if (copy_to_user(argp, &ub->params, ph.len))
5179 		ret = -EFAULT;
5180 	else
5181 		ret = 0;
5182 	mutex_unlock(&ub->mutex);
5183 
5184 	return ret;
5185 }
5186 
5187 static int ublk_ctrl_set_params(struct ublk_device *ub,
5188 		const struct ublksrv_ctrl_cmd *header)
5189 {
5190 	void __user *argp = (void __user *)(unsigned long)header->addr;
5191 	struct ublk_params_header ph;
5192 	int ret = -EFAULT;
5193 
5194 	if (header->len <= sizeof(ph) || !header->addr)
5195 		return -EINVAL;
5196 
5197 	if (copy_from_user(&ph, argp, sizeof(ph)))
5198 		return -EFAULT;
5199 
5200 	if (ph.len > header->len || !ph.len || !ph.types)
5201 		return -EINVAL;
5202 
5203 	if (ph.len > sizeof(struct ublk_params))
5204 		ph.len = sizeof(struct ublk_params);
5205 
5206 	mutex_lock(&ub->mutex);
5207 	if (test_bit(UB_STATE_USED, &ub->state)) {
5208 		/*
5209 		 * Parameters can only be changed when device hasn't
5210 		 * been started yet
5211 		 */
5212 		ret = -EACCES;
5213 	} else if (copy_from_user(&ub->params, argp, ph.len)) {
5214 		/* zero out partial copy so no stale params survive */
5215 		memset(&ub->params, 0, sizeof(ub->params));
5216 		ret = -EFAULT;
5217 	} else {
5218 		/* clear all we don't support yet */
5219 		ub->params.types &= UBLK_PARAM_TYPE_ALL;
5220 		ret = ublk_validate_params(ub);
5221 		if (ret)
5222 			memset(&ub->params, 0, sizeof(ub->params));
5223 	}
5224 	mutex_unlock(&ub->mutex);
5225 
5226 	return ret;
5227 }
5228 
5229 static int ublk_ctrl_start_recovery(struct ublk_device *ub)
5230 {
5231 	int ret = -EINVAL;
5232 
5233 	mutex_lock(&ub->mutex);
5234 	if (ublk_nosrv_should_stop_dev(ub))
5235 		goto out_unlock;
5236 	/*
5237 	 * START_RECOVERY is only allowd after:
5238 	 *
5239 	 * (1) UB_STATE_OPEN is not set, which means the dying process is exited
5240 	 *     and related io_uring ctx is freed so file struct of /dev/ublkcX is
5241 	 *     released.
5242 	 *
5243 	 * and one of the following holds
5244 	 *
5245 	 * (2) UBLK_S_DEV_QUIESCED is set, which means the quiesce_work:
5246 	 *     (a)has quiesced request queue
5247 	 *     (b)has requeued every inflight rqs whose io_flags is ACTIVE
5248 	 *     (c)has requeued/aborted every inflight rqs whose io_flags is NOT ACTIVE
5249 	 *     (d)has completed/camceled all ioucmds owned by ther dying process
5250 	 *
5251 	 * (3) UBLK_S_DEV_FAIL_IO is set, which means the queue is not
5252 	 *     quiesced, but all I/O is being immediately errored
5253 	 */
5254 	if (test_bit(UB_STATE_OPEN, &ub->state) || !ublk_dev_in_recoverable_state(ub)) {
5255 		ret = -EBUSY;
5256 		goto out_unlock;
5257 	}
5258 	pr_devel("%s: start recovery for dev id %d\n", __func__, ub->ub_number);
5259 	ret = 0;
5260  out_unlock:
5261 	mutex_unlock(&ub->mutex);
5262 	return ret;
5263 }
5264 
5265 static int ublk_ctrl_end_recovery(struct ublk_device *ub,
5266 		const struct ublksrv_ctrl_cmd *header)
5267 {
5268 	int ublksrv_pid = (int)header->data[0];
5269 	bool canceled;
5270 	int ret = -EINVAL;
5271 
5272 	pr_devel("%s: Waiting for all FETCH_REQs, dev id %d...\n", __func__,
5273 		 header->dev_id);
5274 
5275 	if (ublk_wait_dev_ready_and_lock(ub))
5276 		return -EINTR;
5277 
5278 	pr_devel("%s: All FETCH_REQs received, dev id %d\n", __func__,
5279 		 header->dev_id);
5280 
5281 	if (!ublk_validate_user_pid(ub, ublksrv_pid)) {
5282 		ret = -EINVAL;
5283 		goto out_unlock;
5284 	}
5285 
5286 	if (ublk_nosrv_should_stop_dev(ub))
5287 		goto out_unlock;
5288 
5289 	if (!ublk_dev_in_recoverable_state(ub)) {
5290 		ret = -EBUSY;
5291 		goto out_unlock;
5292 	}
5293 
5294 	/*
5295 	 * As in ublk_ctrl_start_dev(), a canceled command can't be fetched
5296 	 * again.  Best effort: the disk exists here, and a cancel after this
5297 	 * check is the ordinary death of the new server, which
5298 	 * ublk_start_cancel() handles by quiescing and marking.
5299 	 */
5300 	mutex_lock(&ub->cancel_mutex);
5301 	canceled = ub->canceling;
5302 	mutex_unlock(&ub->cancel_mutex);
5303 	if (canceled) {
5304 		ret = -EBUSY;
5305 		goto out_unlock;
5306 	}
5307 	ub->dev_info.ublksrv_pid = ub->ublksrv_tgid;
5308 	ub->dev_info.state = UBLK_S_DEV_LIVE;
5309 	pr_devel("%s: new ublksrv_pid %d, dev id %d\n",
5310 			__func__, ublksrv_pid, header->dev_id);
5311 	blk_mq_kick_requeue_list(ub->ub_disk->queue);
5312 	ret = 0;
5313  out_unlock:
5314 	mutex_unlock(&ub->mutex);
5315 	return ret;
5316 }
5317 
5318 static int ublk_ctrl_get_features(const struct ublksrv_ctrl_cmd *header)
5319 {
5320 	void __user *argp = (void __user *)(unsigned long)header->addr;
5321 	u64 features = UBLK_F_ALL;
5322 
5323 	if (header->len != UBLK_FEATURES_LEN || !header->addr)
5324 		return -EINVAL;
5325 
5326 	if (copy_to_user(argp, &features, UBLK_FEATURES_LEN))
5327 		return -EFAULT;
5328 
5329 	return 0;
5330 }
5331 
5332 static int ublk_ctrl_set_size(struct ublk_device *ub, const struct ublksrv_ctrl_cmd *header)
5333 {
5334 	struct ublk_param_basic *p = &ub->params.basic;
5335 	u64 new_size = header->data[0];
5336 	int ret = 0;
5337 
5338 	mutex_lock(&ub->mutex);
5339 	if (!ub->ub_disk) {
5340 		ret = -ENODEV;
5341 		goto out;
5342 	}
5343 	p->dev_sectors = new_size;
5344 	set_capacity_and_notify(ub->ub_disk, p->dev_sectors);
5345 out:
5346 	mutex_unlock(&ub->mutex);
5347 	return ret;
5348 }
5349 
5350 struct count_busy {
5351 	const struct ublk_queue *ubq;
5352 	u16 nr_busy;
5353 };
5354 
5355 static bool ublk_count_busy_req(struct request *rq, void *data)
5356 {
5357 	struct count_busy *idle = data;
5358 
5359 	if (!blk_mq_request_started(rq) && rq->mq_hctx->driver_data == idle->ubq)
5360 		idle->nr_busy += 1;
5361 	return true;
5362 }
5363 
5364 /* uring_cmd is guaranteed to be active if the associated request is idle */
5365 static bool ubq_has_idle_io(const struct ublk_queue *ubq)
5366 {
5367 	struct count_busy data = {
5368 		.ubq = ubq,
5369 	};
5370 
5371 	blk_mq_tagset_busy_iter(&ubq->dev->tag_set, ublk_count_busy_req, &data);
5372 	return data.nr_busy < ubq->q_depth;
5373 }
5374 
5375 /* Wait until each hw queue has at least one idle IO */
5376 static int ublk_wait_for_idle_io(struct ublk_device *ub,
5377 				 unsigned int timeout_ms)
5378 {
5379 	unsigned int elapsed = 0;
5380 	int ret;
5381 
5382 	/*
5383 	 * For UBLK_F_BATCH_IO ublk server can get notified with existing
5384 	 * or new fetch command, so needn't wait any more
5385 	 */
5386 	if (ublk_dev_support_batch_io(ub))
5387 		return 0;
5388 
5389 	while (elapsed < timeout_ms && !signal_pending(current)) {
5390 		u16 i, queues_cancelable = 0;
5391 
5392 		for (i = 0; i < ub->dev_info.nr_hw_queues; i++) {
5393 			struct ublk_queue *ubq = ublk_get_queue(ub, i);
5394 
5395 			queues_cancelable += !!ubq_has_idle_io(ubq);
5396 		}
5397 
5398 		/*
5399 		 * Each queue needs at least one active command for
5400 		 * notifying ublk server
5401 		 */
5402 		if (queues_cancelable == ub->dev_info.nr_hw_queues)
5403 			break;
5404 
5405 		msleep(UBLK_REQUEUE_DELAY_MS);
5406 		elapsed += UBLK_REQUEUE_DELAY_MS;
5407 	}
5408 
5409 	if (signal_pending(current))
5410 		ret = -EINTR;
5411 	else if (elapsed >= timeout_ms)
5412 		ret = -EBUSY;
5413 	else
5414 		ret = 0;
5415 
5416 	return ret;
5417 }
5418 
5419 static int ublk_ctrl_quiesce_dev(struct ublk_device *ub,
5420 				 const struct ublksrv_ctrl_cmd *header)
5421 {
5422 	/* zero means wait forever */
5423 	u64 timeout_ms = header->data[0];
5424 	struct gendisk *disk;
5425 	int ret = -ENODEV;
5426 
5427 	if (!(ub->dev_info.flags & UBLK_F_QUIESCE))
5428 		return -EOPNOTSUPP;
5429 
5430 	mutex_lock(&ub->mutex);
5431 	disk = ublk_get_disk(ub);
5432 	if (!disk)
5433 		goto unlock;
5434 	if (ub->dev_info.state == UBLK_S_DEV_DEAD)
5435 		goto put_disk;
5436 
5437 	ret = 0;
5438 	/* already in expected state */
5439 	if (ub->dev_info.state != UBLK_S_DEV_LIVE)
5440 		goto put_disk;
5441 
5442 	/* Mark the device as canceling */
5443 	mutex_lock(&ub->cancel_mutex);
5444 	blk_mq_quiesce_queue(disk->queue);
5445 	ublk_set_canceling(ub, true);
5446 	blk_mq_unquiesce_queue(disk->queue);
5447 	mutex_unlock(&ub->cancel_mutex);
5448 
5449 	if (!timeout_ms)
5450 		timeout_ms = UINT_MAX;
5451 	ret = ublk_wait_for_idle_io(ub, timeout_ms);
5452 
5453 put_disk:
5454 	ublk_put_disk(disk);
5455 unlock:
5456 	mutex_unlock(&ub->mutex);
5457 
5458 	/* Cancel pending uring_cmd */
5459 	if (!ret)
5460 		ublk_cancel_dev(ub);
5461 	return ret;
5462 }
5463 
5464 /*
5465  * All control commands are sent via /dev/ublk-control, so we have to check
5466  * the destination device's permission
5467  */
5468 static int ublk_char_dev_permission(struct ublk_device *ub,
5469 		const char *dev_path, int mask)
5470 {
5471 	int err;
5472 	struct path path;
5473 	struct kstat stat;
5474 
5475 	err = kern_path(dev_path, LOOKUP_FOLLOW, &path);
5476 	if (err)
5477 		return err;
5478 
5479 	err = vfs_getattr(&path, &stat, STATX_TYPE, AT_STATX_SYNC_AS_STAT);
5480 	if (err)
5481 		goto exit;
5482 
5483 	err = -EPERM;
5484 	if (stat.rdev != ub->cdev_dev.devt || !S_ISCHR(stat.mode))
5485 		goto exit;
5486 
5487 	err = inode_permission(&nop_mnt_idmap,
5488 			d_backing_inode(path.dentry), mask);
5489 exit:
5490 	path_put(&path);
5491 	return err;
5492 }
5493 
5494 /*
5495  * Lock for maple tree modification: acquire ub->mutex, then freeze queue
5496  * if device is started. If device is not yet started, only mutex is
5497  * needed since no I/O path can access the tree.
5498  *
5499  * This ordering (mutex -> freeze) is safe because ublk_stop_dev_unlocked()
5500  * already holds ub->mutex when calling del_gendisk() which freezes the queue.
5501 */
5502 static unsigned int ublk_lock_buf_tree(struct ublk_device *ub)
5503 {
5504 	unsigned int memflags = 0;
5505 
5506 	mutex_lock(&ub->mutex);
5507 	if (ub->ub_disk)
5508 		memflags = blk_mq_freeze_queue(ub->ub_disk->queue);
5509 
5510 	return memflags;
5511 }
5512 
5513 static void ublk_unlock_buf_tree(struct ublk_device *ub, unsigned int memflags)
5514 {
5515 	if (ub->ub_disk)
5516 		blk_mq_unfreeze_queue(ub->ub_disk->queue, memflags);
5517 	mutex_unlock(&ub->mutex);
5518 }
5519 
5520 /* Erase coalesced PFN ranges from the maple tree matching buf_index */
5521 static void ublk_buf_erase_ranges(struct ublk_device *ub, int buf_index)
5522 {
5523 	MA_STATE(mas, &ub->buf_tree, 0, ULONG_MAX);
5524 	struct ublk_buf_range *range;
5525 
5526 	mas_lock(&mas);
5527 	mas_for_each(&mas, range, ULONG_MAX) {
5528 		if (range->buf_index == buf_index) {
5529 			mas_erase(&mas);
5530 			kfree(range);
5531 		}
5532 	}
5533 	mas_unlock(&mas);
5534 }
5535 
5536 static int __ublk_ctrl_reg_buf(struct ublk_device *ub,
5537 			       struct page **pages, unsigned long nr_pages,
5538 			       int index, unsigned short flags)
5539 {
5540 	unsigned long i;
5541 	int ret;
5542 
5543 	for (i = 0; i < nr_pages; i++) {
5544 		unsigned long pfn = page_to_pfn(pages[i]);
5545 		unsigned long start = i;
5546 		struct ublk_buf_range *range;
5547 
5548 		/* Find run of consecutive PFNs */
5549 		while (i + 1 < nr_pages &&
5550 		       page_to_pfn(pages[i + 1]) == pfn + (i - start) + 1)
5551 			i++;
5552 
5553 		range = kzalloc_obj(*range);
5554 		if (!range) {
5555 			ret = -ENOMEM;
5556 			goto unwind;
5557 		}
5558 		range->buf_index = index;
5559 		range->flags = flags;
5560 		range->base_offset = start << PAGE_SHIFT;
5561 
5562 		ret = mtree_insert_range(&ub->buf_tree, pfn,
5563 					 pfn + (i - start),
5564 					 range, GFP_KERNEL);
5565 		if (ret) {
5566 			kfree(range);
5567 			goto unwind;
5568 		}
5569 	}
5570 	return 0;
5571 
5572 unwind:
5573 	ublk_buf_erase_ranges(ub, index);
5574 	return ret;
5575 }
5576 
5577 /*
5578  * Register a shared memory buffer for zero-copy I/O.
5579  * Pins pages, builds PFN maple tree, freezes/unfreezes the queue
5580  * internally. Returns buffer index (>= 0) on success.
5581  */
5582 static int ublk_ctrl_reg_buf(struct ublk_device *ub,
5583 			     struct ublksrv_ctrl_cmd *header)
5584 {
5585 	void __user *argp = (void __user *)(unsigned long)header->addr;
5586 	struct ublk_shmem_buf_reg buf_reg;
5587 	unsigned long nr_pages;
5588 	struct page **pages = NULL;
5589 	unsigned int gup_flags;
5590 	unsigned int memflags;
5591 	long pinned;
5592 	int index;
5593 	int ret;
5594 
5595 	if (!ublk_dev_support_shmem_zc(ub))
5596 		return -EOPNOTSUPP;
5597 
5598 	memset(&buf_reg, 0, sizeof(buf_reg));
5599 	if (copy_from_user(&buf_reg, argp,
5600 			   min_t(size_t, header->len, sizeof(buf_reg))))
5601 		return -EFAULT;
5602 
5603 	if (buf_reg.flags & ~UBLK_SHMEM_BUF_READ_ONLY)
5604 		return -EINVAL;
5605 
5606 	if (buf_reg.reserved)
5607 		return -EINVAL;
5608 
5609 	if (!buf_reg.len || buf_reg.len > UBLK_SHMEM_BUF_SIZE_MAX ||
5610 	    !PAGE_ALIGNED(buf_reg.len) || !PAGE_ALIGNED(buf_reg.addr))
5611 		return -EINVAL;
5612 
5613 	nr_pages = buf_reg.len >> PAGE_SHIFT;
5614 
5615 	/* Pin pages before any locks (may sleep) */
5616 	pages = kvmalloc_objs(*pages, nr_pages);
5617 	if (!pages)
5618 		return -ENOMEM;
5619 
5620 	gup_flags = FOLL_LONGTERM;
5621 	if (!(buf_reg.flags & UBLK_SHMEM_BUF_READ_ONLY))
5622 		gup_flags |= FOLL_WRITE;
5623 
5624 	pinned = pin_user_pages_fast(buf_reg.addr, nr_pages, gup_flags, pages);
5625 	if (pinned < 0) {
5626 		ret = pinned;
5627 		goto err_free_pages;
5628 	}
5629 	if (pinned != nr_pages) {
5630 		ret = -EFAULT;
5631 		goto err_unpin;
5632 	}
5633 
5634 	memflags = ublk_lock_buf_tree(ub);
5635 
5636 	index = ida_alloc_max(&ub->buf_ida, USHRT_MAX, GFP_KERNEL);
5637 	if (index < 0) {
5638 		ret = index;
5639 		goto err_unlock;
5640 	}
5641 
5642 	ret = __ublk_ctrl_reg_buf(ub, pages, nr_pages, index, buf_reg.flags);
5643 	if (ret) {
5644 		ida_free(&ub->buf_ida, index);
5645 		goto err_unlock;
5646 	}
5647 
5648 	ublk_unlock_buf_tree(ub, memflags);
5649 	kvfree(pages);
5650 	return index;
5651 
5652 err_unlock:
5653 	ublk_unlock_buf_tree(ub, memflags);
5654 err_unpin:
5655 	unpin_user_pages(pages, pinned);
5656 err_free_pages:
5657 	kvfree(pages);
5658 	return ret;
5659 }
5660 
5661 static void ublk_unpin_range_pages(unsigned long base_pfn,
5662 				   unsigned long nr_pages)
5663 {
5664 #define UBLK_UNPIN_BATCH	32
5665 	struct page *pages[UBLK_UNPIN_BATCH];
5666 	unsigned long off;
5667 
5668 	for (off = 0; off < nr_pages; ) {
5669 		unsigned int batch = min_t(unsigned long,
5670 					   nr_pages - off, UBLK_UNPIN_BATCH);
5671 		unsigned int j;
5672 
5673 		for (j = 0; j < batch; j++)
5674 			pages[j] = pfn_to_page(base_pfn + off + j);
5675 		unpin_user_pages(pages, batch);
5676 		off += batch;
5677 	}
5678 }
5679 
5680 /*
5681  * Inner loop: erase up to UBLK_REMOVE_BATCH matching ranges under
5682  * mas_lock, collecting the page ranges in a fixed-size array. Then
5683  * drop the lock and unpin pages + free ranges outside spinlock context.
5684  *
5685  * Returns true if the tree walk completed, false if more ranges remain.
5686  */
5687 #define UBLK_REMOVE_BATCH	64
5688 
5689 struct ublk_unpin_range {
5690 	unsigned long base_pfn;
5691 	unsigned long nr_pages;
5692 };
5693 
5694 static bool __ublk_shmem_remove_ranges(struct ublk_device *ub,
5695 					int buf_index, int *ret)
5696 {
5697 	MA_STATE(mas, &ub->buf_tree, 0, ULONG_MAX);
5698 	struct ublk_buf_range *range;
5699 	struct ublk_unpin_range to_unpin[UBLK_REMOVE_BATCH];
5700 	unsigned int count = 0;
5701 	unsigned int i;
5702 	bool done = false;
5703 
5704 	mas_lock(&mas);
5705 	mas_for_each(&mas, range, ULONG_MAX) {
5706 		if (buf_index >= 0 && range->buf_index != buf_index)
5707 			continue;
5708 
5709 		*ret = 0;
5710 		to_unpin[count].base_pfn = mas.index;
5711 		to_unpin[count].nr_pages = mas.last - mas.index + 1;
5712 		mas_erase(&mas);
5713 		kfree(range);
5714 		if (++count >= UBLK_REMOVE_BATCH)
5715 			goto unlock;
5716 	}
5717 	done = true;
5718 unlock:
5719 	mas_unlock(&mas);
5720 
5721 	for (i = 0; i < count; i++)
5722 		ublk_unpin_range_pages(to_unpin[i].base_pfn,
5723 				       to_unpin[i].nr_pages);
5724 
5725 	return done;
5726 }
5727 
5728 /*
5729  * Remove ranges from the maple tree matching buf_index, unpin pages
5730  * and free range structs. If buf_index < 0, remove all ranges.
5731  * Processes ranges in batches to avoid holding the maple tree spinlock
5732  * across potentially expensive page unpinning.
5733  */
5734 static int ublk_shmem_remove_ranges(struct ublk_device *ub, int buf_index)
5735 {
5736 	int ret = -ENOENT;
5737 
5738 	while (!__ublk_shmem_remove_ranges(ub, buf_index, &ret))
5739 		cond_resched();
5740 	return ret;
5741 }
5742 
5743 static int ublk_ctrl_unreg_buf(struct ublk_device *ub,
5744 			       struct ublksrv_ctrl_cmd *header)
5745 {
5746 	int index = (int)header->data[0];
5747 	unsigned int memflags;
5748 	int ret;
5749 
5750 	if (!ublk_dev_support_shmem_zc(ub))
5751 		return -EOPNOTSUPP;
5752 
5753 	if (index < 0 || index > USHRT_MAX)
5754 		return -EINVAL;
5755 
5756 	memflags = ublk_lock_buf_tree(ub);
5757 
5758 	ret = ublk_shmem_remove_ranges(ub, index);
5759 	if (!ret)
5760 		ida_free(&ub->buf_ida, index);
5761 
5762 	ublk_unlock_buf_tree(ub, memflags);
5763 	return ret;
5764 }
5765 
5766 static void ublk_buf_cleanup(struct ublk_device *ub)
5767 {
5768 	ublk_shmem_remove_ranges(ub, -1);
5769 	mtree_destroy(&ub->buf_tree);
5770 	ida_destroy(&ub->buf_ida);
5771 }
5772 
5773 /* Check if request pages match a registered shared memory buffer */
5774 static bool ublk_try_buf_match(struct ublk_device *ub,
5775 				   struct request *rq,
5776 				   u32 *buf_idx, u32 *buf_off)
5777 {
5778 	struct req_iterator iter;
5779 	struct bio_vec bv;
5780 	int index = -1;
5781 	unsigned long expected_offset = 0;
5782 	bool first = true;
5783 
5784 	guard(rcu)();
5785 
5786 	rq_for_each_bvec(bv, rq, iter) {
5787 		unsigned long pfn = page_to_pfn(bv.bv_page);
5788 		unsigned long end_pfn = pfn +
5789 			((bv.bv_offset + bv.bv_len - 1) >> PAGE_SHIFT);
5790 		struct ublk_buf_range *range;
5791 		unsigned long off;
5792 		MA_STATE(mas, &ub->buf_tree, pfn, pfn);
5793 
5794 		range = mas_walk(&mas);
5795 		if (!range)
5796 			return false;
5797 
5798 		/* verify all pages in this bvec fall within the range */
5799 		if (end_pfn > mas.last)
5800 			return false;
5801 
5802 		off = range->base_offset +
5803 			(pfn - mas.index) * PAGE_SIZE + bv.bv_offset;
5804 
5805 		if (first) {
5806 			/* Read-only buffer can't serve READ (kernel writes) */
5807 			if ((range->flags & UBLK_SHMEM_BUF_READ_ONLY) &&
5808 			    req_op(rq) != REQ_OP_WRITE)
5809 				return false;
5810 			index = range->buf_index;
5811 			expected_offset = off;
5812 			*buf_off = off;
5813 			first = false;
5814 		} else {
5815 			if (range->buf_index != index)
5816 				return false;
5817 			if (off != expected_offset)
5818 				return false;
5819 		}
5820 		expected_offset += bv.bv_len;
5821 	}
5822 
5823 	if (first)
5824 		return false;
5825 
5826 	*buf_idx = index;
5827 	return true;
5828 }
5829 
5830 static int ublk_ctrl_uring_cmd_permission(struct ublk_device *ub,
5831 		u32 cmd_op, struct ublksrv_ctrl_cmd *header)
5832 {
5833 	bool unprivileged = ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV;
5834 	void __user *argp = (void __user *)(unsigned long)header->addr;
5835 	char *dev_path = NULL;
5836 	int ret = 0;
5837 	int mask;
5838 
5839 	if (!unprivileged) {
5840 		if (!capable(CAP_SYS_ADMIN))
5841 			return -EPERM;
5842 		/*
5843 		 * The new added command of UBLK_CMD_GET_DEV_INFO2 includes
5844 		 * char_dev_path in payload too, since userspace may not
5845 		 * know if the specified device is created as unprivileged
5846 		 * mode.
5847 		 */
5848 		if (_IOC_NR(cmd_op) != UBLK_CMD_GET_DEV_INFO2)
5849 			return 0;
5850 	}
5851 
5852 	/*
5853 	 * User has to provide the char device path for unprivileged ublk
5854 	 *
5855 	 * header->addr always points to the dev path buffer, and
5856 	 * header->dev_path_len records length of dev path buffer.
5857 	 */
5858 	if (!header->dev_path_len || header->dev_path_len > PATH_MAX)
5859 		return -EINVAL;
5860 
5861 	if (header->len < header->dev_path_len)
5862 		return -EINVAL;
5863 
5864 	dev_path = memdup_user_nul(argp, header->dev_path_len);
5865 	if (IS_ERR(dev_path))
5866 		return PTR_ERR(dev_path);
5867 
5868 	ret = -EINVAL;
5869 	switch (_IOC_NR(cmd_op)) {
5870 	case UBLK_CMD_GET_DEV_INFO:
5871 	case UBLK_CMD_GET_DEV_INFO2:
5872 	case UBLK_CMD_GET_QUEUE_AFFINITY:
5873 	case UBLK_CMD_GET_PARAMS:
5874 	case (_IOC_NR(UBLK_U_CMD_GET_FEATURES)):
5875 		mask = MAY_READ;
5876 		break;
5877 	case UBLK_CMD_START_DEV:
5878 	case UBLK_CMD_STOP_DEV:
5879 	case UBLK_CMD_ADD_DEV:
5880 	case UBLK_CMD_DEL_DEV:
5881 	case UBLK_CMD_SET_PARAMS:
5882 	case UBLK_CMD_START_USER_RECOVERY:
5883 	case UBLK_CMD_END_USER_RECOVERY:
5884 	case UBLK_CMD_UPDATE_SIZE:
5885 	case UBLK_CMD_QUIESCE_DEV:
5886 	case UBLK_CMD_TRY_STOP_DEV:
5887 	case UBLK_CMD_REG_BUF:
5888 	case UBLK_CMD_UNREG_BUF:
5889 		mask = MAY_READ | MAY_WRITE;
5890 		break;
5891 	default:
5892 		goto exit;
5893 	}
5894 
5895 	ret = ublk_char_dev_permission(ub, dev_path, mask);
5896 	if (!ret) {
5897 		header->len -= header->dev_path_len;
5898 		header->addr += header->dev_path_len;
5899 	}
5900 	pr_devel("%s: dev id %d cmd_op %x uid %d gid %d path %s ret %d\n",
5901 			__func__, ub->ub_number, cmd_op,
5902 			ub->dev_info.owner_uid, ub->dev_info.owner_gid,
5903 			dev_path, ret);
5904 exit:
5905 	kfree(dev_path);
5906 	return ret;
5907 }
5908 
5909 static bool ublk_ctrl_uring_cmd_may_sleep(u32 cmd_op)
5910 {
5911 	switch (_IOC_NR(cmd_op)) {
5912 	case UBLK_CMD_GET_QUEUE_AFFINITY:
5913 	case UBLK_CMD_GET_DEV_INFO:
5914 	case UBLK_CMD_GET_DEV_INFO2:
5915 	case _IOC_NR(UBLK_U_CMD_GET_FEATURES):
5916 		return false;
5917 	default:
5918 		return true;
5919 	}
5920 }
5921 
5922 static int ublk_ctrl_uring_cmd(struct io_uring_cmd *cmd,
5923 		unsigned int issue_flags)
5924 {
5925 	/* May point to userspace-mapped memory */
5926 	const struct ublksrv_ctrl_cmd *ub_src = io_uring_sqe128_cmd(cmd->sqe,
5927 								    struct ublksrv_ctrl_cmd);
5928 	struct ublksrv_ctrl_cmd header;
5929 	struct ublk_device *ub = NULL;
5930 	u32 cmd_op = cmd->cmd_op;
5931 	int ret = -EINVAL;
5932 
5933 	if (ublk_ctrl_uring_cmd_may_sleep(cmd_op) &&
5934 	    issue_flags & IO_URING_F_NONBLOCK)
5935 		return -EAGAIN;
5936 
5937 	if (!(issue_flags & IO_URING_F_SQE128))
5938 		return -EINVAL;
5939 
5940 	header.dev_id = READ_ONCE(ub_src->dev_id);
5941 	header.queue_id = READ_ONCE(ub_src->queue_id);
5942 	header.len = READ_ONCE(ub_src->len);
5943 	header.addr = READ_ONCE(ub_src->addr);
5944 	header.data[0] = READ_ONCE(ub_src->data[0]);
5945 	header.dev_path_len = READ_ONCE(ub_src->dev_path_len);
5946 	ublk_ctrl_cmd_dump(cmd_op, &header);
5947 
5948 	ret = ublk_check_cmd_op(cmd_op);
5949 	if (ret)
5950 		goto out;
5951 
5952 	if (cmd_op == UBLK_U_CMD_GET_FEATURES) {
5953 		ret = ublk_ctrl_get_features(&header);
5954 		goto out;
5955 	}
5956 
5957 	if (_IOC_NR(cmd_op) != UBLK_CMD_ADD_DEV) {
5958 		ret = -ENODEV;
5959 		ub = ublk_get_device_from_id(header.dev_id);
5960 		if (!ub)
5961 			goto out;
5962 
5963 		ret = ublk_ctrl_uring_cmd_permission(ub, cmd_op, &header);
5964 		if (ret)
5965 			goto put_dev;
5966 	}
5967 
5968 	switch (_IOC_NR(cmd_op)) {
5969 	case UBLK_CMD_START_DEV:
5970 		ret = ublk_ctrl_start_dev(ub, &header);
5971 		break;
5972 	case UBLK_CMD_STOP_DEV:
5973 		ublk_ctrl_stop_dev(ub);
5974 		ret = 0;
5975 		break;
5976 	case UBLK_CMD_GET_DEV_INFO:
5977 	case UBLK_CMD_GET_DEV_INFO2:
5978 		ret = ublk_ctrl_get_dev_info(ub, &header);
5979 		break;
5980 	case UBLK_CMD_ADD_DEV:
5981 		ret = ublk_ctrl_add_dev(&header);
5982 		break;
5983 	case UBLK_CMD_DEL_DEV:
5984 		ret = ublk_ctrl_del_dev(&ub, true);
5985 		break;
5986 	case UBLK_CMD_DEL_DEV_ASYNC:
5987 		ret = ublk_ctrl_del_dev(&ub, false);
5988 		break;
5989 	case UBLK_CMD_GET_QUEUE_AFFINITY:
5990 		ret = ublk_ctrl_get_queue_affinity(ub, &header);
5991 		break;
5992 	case UBLK_CMD_GET_PARAMS:
5993 		ret = ublk_ctrl_get_params(ub, &header);
5994 		break;
5995 	case UBLK_CMD_SET_PARAMS:
5996 		ret = ublk_ctrl_set_params(ub, &header);
5997 		break;
5998 	case UBLK_CMD_START_USER_RECOVERY:
5999 		ret = ublk_ctrl_start_recovery(ub);
6000 		break;
6001 	case UBLK_CMD_END_USER_RECOVERY:
6002 		ret = ublk_ctrl_end_recovery(ub, &header);
6003 		break;
6004 	case UBLK_CMD_UPDATE_SIZE:
6005 		ret = ublk_ctrl_set_size(ub, &header);
6006 		break;
6007 	case UBLK_CMD_QUIESCE_DEV:
6008 		ret = ublk_ctrl_quiesce_dev(ub, &header);
6009 		break;
6010 	case UBLK_CMD_TRY_STOP_DEV:
6011 		ret = ublk_ctrl_try_stop_dev(ub);
6012 		break;
6013 	case UBLK_CMD_REG_BUF:
6014 		ret = ublk_ctrl_reg_buf(ub, &header);
6015 		break;
6016 	case UBLK_CMD_UNREG_BUF:
6017 		ret = ublk_ctrl_unreg_buf(ub, &header);
6018 		break;
6019 	default:
6020 		ret = -EOPNOTSUPP;
6021 		break;
6022 	}
6023 
6024  put_dev:
6025 	if (ub)
6026 		ublk_put_device(ub);
6027  out:
6028 	pr_devel("%s: cmd done ret %d cmd_op %x, dev id %d qid %d\n",
6029 			__func__, ret, cmd_op, header.dev_id, header.queue_id);
6030 	return ret;
6031 }
6032 
6033 static const struct file_operations ublk_ctl_fops = {
6034 	.open		= nonseekable_open,
6035 	.uring_cmd      = ublk_ctrl_uring_cmd,
6036 	.owner		= THIS_MODULE,
6037 	.llseek		= noop_llseek,
6038 };
6039 
6040 static struct miscdevice ublk_misc = {
6041 	.minor		= MISC_DYNAMIC_MINOR,
6042 	.name		= "ublk-control",
6043 	.fops		= &ublk_ctl_fops,
6044 };
6045 
6046 static int __init ublk_init(void)
6047 {
6048 	int ret;
6049 
6050 	BUILD_BUG_ON((u64)UBLKSRV_IO_BUF_OFFSET +
6051 			UBLKSRV_IO_BUF_TOTAL_SIZE < UBLKSRV_IO_BUF_OFFSET);
6052 	/*
6053 	 * Ensure UBLKSRV_IO_BUF_OFFSET + UBLKSRV_IO_BUF_TOTAL_SIZE
6054 	 * doesn't overflow into UBLKSRV_IO_INTEGRITY_FLAG
6055 	 */
6056 	BUILD_BUG_ON(UBLKSRV_IO_BUF_OFFSET + UBLKSRV_IO_BUF_TOTAL_SIZE >=
6057 		     UBLKSRV_IO_INTEGRITY_FLAG);
6058 	BUILD_BUG_ON(sizeof(struct ublk_auto_buf_reg) != 8);
6059 
6060 	init_waitqueue_head(&ublk_idr_wq);
6061 
6062 	ret = misc_register(&ublk_misc);
6063 	if (ret)
6064 		return ret;
6065 
6066 	ret = alloc_chrdev_region(&ublk_chr_devt, 0, UBLK_MINORS, "ublk-char");
6067 	if (ret)
6068 		goto unregister_mis;
6069 
6070 	ret = class_register(&ublk_chr_class);
6071 	if (ret)
6072 		goto free_chrdev_region;
6073 
6074 	return 0;
6075 
6076 free_chrdev_region:
6077 	unregister_chrdev_region(ublk_chr_devt, UBLK_MINORS);
6078 unregister_mis:
6079 	misc_deregister(&ublk_misc);
6080 	return ret;
6081 }
6082 
6083 static void __exit ublk_exit(void)
6084 {
6085 	struct ublk_device *ub;
6086 	int id;
6087 
6088 	idr_for_each_entry(&ublk_index_idr, ub, id)
6089 		ublk_remove(ub);
6090 
6091 	class_unregister(&ublk_chr_class);
6092 	misc_deregister(&ublk_misc);
6093 
6094 	idr_destroy(&ublk_index_idr);
6095 	unregister_chrdev_region(ublk_chr_devt, UBLK_MINORS);
6096 }
6097 
6098 module_init(ublk_init);
6099 module_exit(ublk_exit);
6100 
6101 static int ublk_set_max_unprivileged_ublks(const char *buf,
6102 					   const struct kernel_param *kp)
6103 {
6104 	return param_set_uint_minmax(buf, kp, 0, UBLK_MAX_UBLKS);
6105 }
6106 
6107 static int ublk_get_max_unprivileged_ublks(char *buf,
6108 					   const struct kernel_param *kp)
6109 {
6110 	return sysfs_emit(buf, "%u\n", unprivileged_ublks_max);
6111 }
6112 
6113 static const struct kernel_param_ops ublk_max_unprivileged_ublks_ops = {
6114 	.set = ublk_set_max_unprivileged_ublks,
6115 	.get = ublk_get_max_unprivileged_ublks,
6116 };
6117 
6118 module_param_cb(ublks_max, &ublk_max_unprivileged_ublks_ops,
6119 		&unprivileged_ublks_max, 0644);
6120 MODULE_PARM_DESC(ublks_max, "max number of unprivileged ublk devices allowed to add(default: 64)");
6121 
6122 MODULE_AUTHOR("Ming Lei <ming.lei@redhat.com>");
6123 MODULE_DESCRIPTION("Userspace block device");
6124 MODULE_LICENSE("GPL");
6125