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