xref: /linux/drivers/block/ublk_drv.c (revision 35ef102063fd6f39e045e6d4e92ac04d3d29c0bf)
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_request(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(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 	/*
2657 	 * The per-queue command buffer is kernel-written ABI; prevent
2658 	 * the daemon from upgrading to writable via mprotect().
2659 	 */
2660 	vm_flags_clear(vma, VM_MAYWRITE);
2661 
2662 	end = UBLKSRV_CMD_BUF_OFFSET + ub->dev_info.nr_hw_queues * max_sz;
2663 	if (phys_off < UBLKSRV_CMD_BUF_OFFSET || phys_off >= end)
2664 		return -EINVAL;
2665 
2666 	q_id = (phys_off - UBLKSRV_CMD_BUF_OFFSET) / max_sz;
2667 	pr_devel("%s: qid %d, pid %d, addr %lx pg_off %lx sz %lu\n",
2668 			__func__, q_id, current->pid, vma->vm_start,
2669 			phys_off, (unsigned long)sz);
2670 
2671 	if (sz != ublk_queue_cmd_buf_size(ub))
2672 		return -EINVAL;
2673 
2674 	pfn = virt_to_phys(ublk_queue_cmd_buf(ub, q_id)) >> PAGE_SHIFT;
2675 	return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
2676 }
2677 
2678 static void __ublk_fail_req(struct ublk_device *ub, struct ublk_io *io,
2679 		struct request *req)
2680 {
2681 	WARN_ON_ONCE(!ublk_dev_support_batch_io(ub) &&
2682 			io->flags & UBLK_IO_FLAG_ACTIVE);
2683 
2684 	if (ublk_nosrv_should_reissue_outstanding(ub))
2685 		blk_mq_requeue_request(req, false);
2686 	else {
2687 		io->res = -EIO;
2688 		__ublk_complete_rq(req, io, ublk_dev_need_map_io(ub), NULL);
2689 	}
2690 }
2691 
2692 /*
2693  * Request tag may just be filled to event kfifo, not get chance to
2694  * dispatch, abort these requests too
2695  */
2696 static void ublk_abort_batch_queue(struct ublk_device *ub,
2697 				   struct ublk_queue *ubq)
2698 {
2699 	unsigned short tag;
2700 
2701 	while (kfifo_out(&ubq->evts_fifo, &tag, 1)) {
2702 		struct request *req = blk_mq_tag_to_rq(
2703 				ub->tag_set.tags[ubq->q_id], tag);
2704 
2705 		if (!WARN_ON_ONCE(!req || !blk_mq_request_started(req)))
2706 			__ublk_fail_req(ub, &ubq->ios[tag], req);
2707 	}
2708 }
2709 
2710 /*
2711  * Called from ublk char device release handler, when any uring_cmd is
2712  * done, meantime request queue is "quiesced" since all inflight requests
2713  * can't be completed because ublk server is dead.
2714  *
2715  * So no one can hold our request IO reference any more, simply ignore the
2716  * reference, and complete the request immediately
2717  */
2718 static void ublk_abort_queue(struct ublk_device *ub, struct ublk_queue *ubq)
2719 {
2720 	u16 i;
2721 
2722 	for (i = 0; i < ubq->q_depth; i++) {
2723 		struct ublk_io *io = &ubq->ios[i];
2724 
2725 		if (io->flags & UBLK_IO_FLAG_OWNED_BY_SRV)
2726 			__ublk_fail_req(ub, io, io->req);
2727 	}
2728 
2729 	if (ublk_support_batch_io(ubq))
2730 		ublk_abort_batch_queue(ub, ubq);
2731 }
2732 
2733 static void ublk_start_cancel(struct ublk_device *ub)
2734 {
2735 	struct gendisk *disk = ublk_get_disk(ub);
2736 
2737 	mutex_lock(&ub->cancel_mutex);
2738 	if (ub->canceling)
2739 		goto out;
2740 
2741 	if (disk) {
2742 		/*
2743 		 * Quiesce to serialize with ublk_queue_rq(), ensuring
2744 		 * ubq->canceling is visible when the queue resumes.
2745 		 */
2746 		blk_mq_quiesce_queue(disk->queue);
2747 		ublk_set_canceling(ub, true);
2748 		blk_mq_unquiesce_queue(disk->queue);
2749 	} else {
2750 		/*
2751 		 * Disk not yet allocated by ublk_ctrl_start_dev(), so
2752 		 * there is no request queue and ublk_queue_rq() cannot
2753 		 * be running.  Just set the flag; if start_dev proceeds
2754 		 * later, new I/O will see canceling and be aborted.
2755 		 */
2756 		ublk_set_canceling(ub, true);
2757 	}
2758 out:
2759 	mutex_unlock(&ub->cancel_mutex);
2760 	ublk_put_disk(disk);
2761 }
2762 
2763 static void ublk_cancel_cmd(struct ublk_queue *ubq, u16 tag,
2764 		unsigned int issue_flags)
2765 {
2766 	struct ublk_io *io = &ubq->ios[tag];
2767 	struct ublk_device *ub = ubq->dev;
2768 	struct io_uring_cmd *cmd = NULL;
2769 	struct request *req;
2770 	bool done;
2771 
2772 	if (!(io->flags & UBLK_IO_FLAG_ACTIVE))
2773 		return;
2774 
2775 	/*
2776 	 * Don't try to cancel this command if the request is started for
2777 	 * avoiding race between io_uring_cmd_done() and
2778 	 * io_uring_cmd_complete_in_task().
2779 	 *
2780 	 * Either the started request will be aborted via __ublk_abort_rq(),
2781 	 * then this uring_cmd is canceled next time, or it will be done in
2782 	 * task work function ublk_dispatch_req() because io_uring guarantees
2783 	 * that ublk_dispatch_req() is always called
2784 	 */
2785 	req = blk_mq_tag_to_rq(ub->tag_set.tags[ubq->q_id], tag);
2786 	if (req && blk_mq_request_started(req) && req->tag == tag)
2787 		return;
2788 
2789 	spin_lock(&ubq->cancel_lock);
2790 	done = !!(io->flags & UBLK_IO_FLAG_CANCELED);
2791 	if (!done) {
2792 		io->flags |= UBLK_IO_FLAG_CANCELED;
2793 		cmd = io->cmd;
2794 		io->cmd = NULL;
2795 	}
2796 	spin_unlock(&ubq->cancel_lock);
2797 
2798 	if (!done && cmd)
2799 		io_uring_cmd_done(cmd, UBLK_IO_RES_ABORT, issue_flags);
2800 }
2801 
2802 /*
2803  * Cancel a batch fetch command if it hasn't been claimed by another path.
2804  *
2805  * An fcmd can only be cancelled if:
2806  * 1. It's not the active_fcmd (which is currently being processed)
2807  * 2. It's still on the list (!list_empty check) - once removed from the list,
2808  *    the fcmd is considered claimed and will be freed by whoever removed it
2809  *
2810  * Use list_del_init() so subsequent list_empty() checks work correctly.
2811  */
2812 static void ublk_batch_cancel_cmd(struct ublk_queue *ubq,
2813 				  struct ublk_batch_fetch_cmd *fcmd,
2814 				  unsigned int issue_flags)
2815 {
2816 	bool done;
2817 
2818 	spin_lock(&ubq->evts_lock);
2819 	done = (READ_ONCE(ubq->active_fcmd) != fcmd) && !list_empty(&fcmd->node);
2820 	if (done)
2821 		list_del_init(&fcmd->node);
2822 	spin_unlock(&ubq->evts_lock);
2823 
2824 	if (done) {
2825 		io_uring_cmd_done(fcmd->cmd, UBLK_IO_RES_ABORT, issue_flags);
2826 		ublk_batch_free_fcmd(fcmd);
2827 	}
2828 }
2829 
2830 static void ublk_batch_cancel_queue(struct ublk_queue *ubq)
2831 {
2832 	struct ublk_batch_fetch_cmd *fcmd;
2833 	LIST_HEAD(fcmd_list);
2834 
2835 	spin_lock(&ubq->evts_lock);
2836 	ubq->force_abort = true;
2837 	list_splice_init(&ubq->fcmd_head, &fcmd_list);
2838 	fcmd = READ_ONCE(ubq->active_fcmd);
2839 	if (fcmd)
2840 		list_move(&fcmd->node, &ubq->fcmd_head);
2841 	spin_unlock(&ubq->evts_lock);
2842 
2843 	while (!list_empty(&fcmd_list)) {
2844 		fcmd = list_first_entry(&fcmd_list,
2845 				struct ublk_batch_fetch_cmd, node);
2846 		ublk_batch_cancel_cmd(ubq, fcmd, IO_URING_F_UNLOCKED);
2847 	}
2848 }
2849 
2850 static void ublk_batch_cancel_fn(struct io_uring_cmd *cmd,
2851 				 unsigned int issue_flags)
2852 {
2853 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
2854 	struct ublk_batch_fetch_cmd *fcmd = pdu->fcmd;
2855 	struct ublk_queue *ubq = pdu->ubq;
2856 
2857 	ublk_start_cancel(ubq->dev);
2858 
2859 	ublk_batch_cancel_cmd(ubq, fcmd, issue_flags);
2860 }
2861 
2862 /*
2863  * The ublk char device won't be closed when calling cancel fn, so both
2864  * ublk device and queue are guaranteed to be live
2865  *
2866  * Two-stage cancel:
2867  *
2868  * - make every active uring_cmd done in ->cancel_fn()
2869  *
2870  * - aborting inflight ublk IO requests in ublk char device release handler,
2871  *   which depends on 1st stage because device can only be closed iff all
2872  *   uring_cmd are done
2873  *
2874  * Do _not_ try to acquire ub->mutex before all inflight requests are
2875  * aborted, otherwise deadlock may be caused.
2876  */
2877 static void ublk_uring_cmd_cancel_fn(struct io_uring_cmd *cmd,
2878 		unsigned int issue_flags)
2879 {
2880 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
2881 	struct ublk_queue *ubq = pdu->ubq;
2882 	struct task_struct *task;
2883 	struct ublk_io *io;
2884 
2885 	if (WARN_ON_ONCE(!ubq))
2886 		return;
2887 
2888 	if (WARN_ON_ONCE(pdu->tag >= ubq->q_depth))
2889 		return;
2890 
2891 	task = io_uring_cmd_get_task(cmd);
2892 	io = &ubq->ios[pdu->tag];
2893 	if (WARN_ON_ONCE(task && task != io->task))
2894 		return;
2895 
2896 	ublk_start_cancel(ubq->dev);
2897 
2898 	WARN_ON_ONCE(io->cmd != cmd);
2899 	ublk_cancel_cmd(ubq, pdu->tag, issue_flags);
2900 }
2901 
2902 static inline bool ublk_queue_ready(const struct ublk_queue *ubq)
2903 {
2904 	return ubq->nr_io_ready == ubq->q_depth;
2905 }
2906 
2907 static inline bool ublk_dev_ready(const struct ublk_device *ub)
2908 {
2909 	return ub->nr_queue_ready == ub->dev_info.nr_hw_queues;
2910 }
2911 
2912 static void ublk_cancel_queue(struct ublk_queue *ubq)
2913 {
2914 	u16 i;
2915 
2916 	if (ublk_support_batch_io(ubq)) {
2917 		ublk_batch_cancel_queue(ubq);
2918 		return;
2919 	}
2920 
2921 	for (i = 0; i < ubq->q_depth; i++)
2922 		ublk_cancel_cmd(ubq, i, IO_URING_F_UNLOCKED);
2923 }
2924 
2925 /* Cancel all pending commands, must be called after del_gendisk() returns */
2926 static void ublk_cancel_dev(struct ublk_device *ub)
2927 {
2928 	u16 i;
2929 
2930 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
2931 		ublk_cancel_queue(ublk_get_queue(ub, i));
2932 }
2933 
2934 static bool ublk_check_inflight_rq(struct request *rq, void *data)
2935 {
2936 	bool *idle = data;
2937 
2938 	if (blk_mq_request_started(rq)) {
2939 		*idle = false;
2940 		return false;
2941 	}
2942 	return true;
2943 }
2944 
2945 static void ublk_wait_tagset_rqs_idle(struct ublk_device *ub)
2946 {
2947 	bool idle;
2948 
2949 	WARN_ON_ONCE(!blk_queue_quiesced(ub->ub_disk->queue));
2950 	while (true) {
2951 		idle = true;
2952 		blk_mq_tagset_busy_iter(&ub->tag_set,
2953 				ublk_check_inflight_rq, &idle);
2954 		if (idle)
2955 			break;
2956 		msleep(UBLK_REQUEUE_DELAY_MS);
2957 	}
2958 }
2959 
2960 static void ublk_force_abort_dev(struct ublk_device *ub)
2961 {
2962 	u16 i;
2963 
2964 	pr_devel("%s: force abort ub: dev_id %d state %s\n",
2965 			__func__, ub->dev_info.dev_id,
2966 			ub->dev_info.state == UBLK_S_DEV_LIVE ?
2967 			"LIVE" : "QUIESCED");
2968 	blk_mq_quiesce_queue(ub->ub_disk->queue);
2969 	if (ub->dev_info.state == UBLK_S_DEV_LIVE)
2970 		ublk_wait_tagset_rqs_idle(ub);
2971 
2972 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
2973 		ublk_get_queue(ub, i)->force_abort = true;
2974 	blk_mq_unquiesce_queue(ub->ub_disk->queue);
2975 	/* We may have requeued some rqs in ublk_quiesce_queue() */
2976 	blk_mq_kick_requeue_list(ub->ub_disk->queue);
2977 }
2978 
2979 static struct gendisk *ublk_detach_disk(struct ublk_device *ub)
2980 {
2981 	struct gendisk *disk;
2982 
2983 	/* Sync with ublk_abort_queue() by holding the lock */
2984 	spin_lock(&ub->lock);
2985 	disk = ub->ub_disk;
2986 	ub->dev_info.state = UBLK_S_DEV_DEAD;
2987 	ub->dev_info.ublksrv_pid = -1;
2988 	ub->ub_disk = NULL;
2989 	spin_unlock(&ub->lock);
2990 
2991 	return disk;
2992 }
2993 
2994 static void ublk_stop_dev_unlocked(struct ublk_device *ub)
2995 	__must_hold(&ub->mutex)
2996 {
2997 	struct gendisk *disk;
2998 
2999 	if (ub->dev_info.state == UBLK_S_DEV_DEAD)
3000 		return;
3001 
3002 	if (ublk_nosrv_dev_should_queue_io(ub))
3003 		ublk_force_abort_dev(ub);
3004 	del_gendisk(ub->ub_disk);
3005 	disk = ublk_detach_disk(ub);
3006 	put_disk(disk);
3007 }
3008 
3009 static void ublk_stop_dev(struct ublk_device *ub)
3010 {
3011 	mutex_lock(&ub->mutex);
3012 	ublk_stop_dev_unlocked(ub);
3013 	mutex_unlock(&ub->mutex);
3014 	cancel_work_sync(&ub->partition_scan_work);
3015 	ublk_cancel_dev(ub);
3016 }
3017 
3018 static void ublk_reset_io_flags(struct ublk_queue *ubq, struct ublk_io *io)
3019 {
3020 	/* UBLK_IO_FLAG_CANCELED can be cleared now */
3021 	spin_lock(&ubq->cancel_lock);
3022 	io->flags &= ~UBLK_IO_FLAG_CANCELED;
3023 	spin_unlock(&ubq->cancel_lock);
3024 }
3025 
3026 /* reset per-queue io flags */
3027 static void ublk_queue_reset_io_flags(struct ublk_queue *ubq)
3028 {
3029 	spin_lock(&ubq->cancel_lock);
3030 	ubq->canceling = false;
3031 	spin_unlock(&ubq->cancel_lock);
3032 	ubq->fail_io = false;
3033 	ubq->force_abort = false;
3034 }
3035 
3036 /* device can only be started after all IOs are ready */
3037 static void ublk_mark_io_ready(struct ublk_device *ub, u16 q_id,
3038 	struct ublk_io *io)
3039 	__must_hold(&ub->mutex)
3040 {
3041 	struct ublk_queue *ubq = ublk_get_queue(ub, q_id);
3042 
3043 	if (!ub->unprivileged_daemons && !capable(CAP_SYS_ADMIN))
3044 		ub->unprivileged_daemons = true;
3045 
3046 	ubq->nr_io_ready++;
3047 	ublk_reset_io_flags(ubq, io);
3048 
3049 	/* Check if this specific queue is now fully ready */
3050 	if (ublk_queue_ready(ubq)) {
3051 		ub->nr_queue_ready++;
3052 
3053 		/*
3054 		 * Reset queue flags as soon as this queue is ready.
3055 		 * This clears the canceling flag, allowing batch FETCH commands
3056 		 * to succeed during recovery without waiting for all queues.
3057 		 */
3058 		ublk_queue_reset_io_flags(ubq);
3059 	}
3060 
3061 	/* Check if all queues are ready */
3062 	if (ublk_dev_ready(ub)) {
3063 		/*
3064 		 * All queues ready - clear device-level canceling flag
3065 		 * and wake ublk_dev_ready() waiters.
3066 		 */
3067 		mutex_lock(&ub->cancel_mutex);
3068 		ub->canceling = false;
3069 		mutex_unlock(&ub->cancel_mutex);
3070 		wake_up_var(&ub->nr_queue_ready);
3071 	}
3072 }
3073 
3074 static inline int ublk_check_cmd_op(u32 cmd_op)
3075 {
3076 	u32 ioc_type = _IOC_TYPE(cmd_op);
3077 
3078 	if (!IS_ENABLED(CONFIG_BLKDEV_UBLK_LEGACY_OPCODES) && ioc_type != 'u')
3079 		return -EOPNOTSUPP;
3080 
3081 	if (ioc_type != 'u' && ioc_type != 0)
3082 		return -EOPNOTSUPP;
3083 
3084 	return 0;
3085 }
3086 
3087 /* Must run before ublk_fill_io_cmd() / __ublk_fetch(). */
3088 static inline int ublk_validate_io_buf(const struct ublk_device *ub,
3089 				       struct io_uring_cmd *cmd,
3090 				       struct ublk_auto_buf_reg *buf)
3091 {
3092 	if (!ublk_dev_support_auto_buf_reg(ub))
3093 		return 0;
3094 
3095 	*buf = ublk_sqe_addr_to_auto_buf_reg(READ_ONCE(cmd->sqe->addr));
3096 	if (buf->reserved0 || buf->reserved1)
3097 		return -EINVAL;
3098 	if (buf->flags & ~UBLK_AUTO_BUF_REG_F_MASK)
3099 		return -EINVAL;
3100 	return 0;
3101 }
3102 
3103 static void ublk_clear_auto_buf_reg(struct ublk_io *io,
3104 				    struct io_uring_cmd *cmd,
3105 				    u16 *buf_idx)
3106 {
3107 	if (io->flags & UBLK_IO_FLAG_AUTO_BUF_REG) {
3108 		io->flags &= ~UBLK_IO_FLAG_AUTO_BUF_REG;
3109 
3110 		/*
3111 		 * `UBLK_F_AUTO_BUF_REG` only works iff `UBLK_IO_FETCH_REQ`
3112 		 * and `UBLK_IO_COMMIT_AND_FETCH_REQ` are issued from same
3113 		 * `io_ring_ctx`.
3114 		 *
3115 		 * If this uring_cmd's io_ring_ctx isn't same with the
3116 		 * one for registering the buffer, it is ublk server's
3117 		 * responsibility for unregistering the buffer, otherwise
3118 		 * this ublk request gets stuck.
3119 		 */
3120 		if (buf_idx &&
3121 		    io->buf_ctx_handle == io_uring_cmd_ctx_handle(cmd))
3122 			*buf_idx = io->buf.auto_reg.index;
3123 	}
3124 }
3125 
3126 static inline void ublk_apply_io_buf(const struct ublk_device *ub,
3127 				     struct ublk_io *io,
3128 				     struct io_uring_cmd *cmd,
3129 				     unsigned long buf_addr,
3130 				     const struct ublk_auto_buf_reg *auto_buf,
3131 				     u16 *buf_idx)
3132 {
3133 	if (ublk_dev_support_auto_buf_reg(ub)) {
3134 		ublk_clear_auto_buf_reg(io, cmd, buf_idx);
3135 		io->buf.auto_reg = *auto_buf;
3136 	} else {
3137 		io->buf.addr = buf_addr;
3138 	}
3139 }
3140 
3141 /* Once we return, `io->req` can't be used any more */
3142 static inline struct request *
3143 ublk_fill_io_cmd(struct ublk_io *io, struct io_uring_cmd *cmd)
3144 {
3145 	struct request *req = io->req;
3146 
3147 	io->cmd = cmd;
3148 	io->flags |= UBLK_IO_FLAG_ACTIVE;
3149 	/* now this cmd slot is owned by ublk driver */
3150 	io->flags &= ~UBLK_IO_FLAG_OWNED_BY_SRV;
3151 
3152 	return req;
3153 }
3154 
3155 static inline void ublk_prep_cancel(struct io_uring_cmd *cmd,
3156 				    unsigned int issue_flags,
3157 				    struct ublk_queue *ubq, u16 tag)
3158 {
3159 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
3160 
3161 	/*
3162 	 * Safe to refer to @ubq since ublk_queue won't be died until its
3163 	 * commands are completed
3164 	 */
3165 	pdu->ubq = ubq;
3166 	pdu->tag = tag;
3167 	io_uring_cmd_mark_cancelable(cmd, issue_flags);
3168 }
3169 
3170 static void ublk_io_release(void *priv)
3171 {
3172 	struct request *rq = priv;
3173 	struct ublk_queue *ubq = rq->mq_hctx->driver_data;
3174 	struct ublk_io *io = &ubq->ios[rq->tag];
3175 
3176 	/*
3177 	 * task_registered_buffers may be 0 if buffers were registered off task
3178 	 * but unregistered on task. Or after UBLK_IO_COMMIT_AND_FETCH_REQ.
3179 	 */
3180 	if (current == io->task && io->task_registered_buffers)
3181 		io->task_registered_buffers--;
3182 	else
3183 		ublk_put_req_ref(io, rq);
3184 }
3185 
3186 static int ublk_register_io_buf(struct io_uring_cmd *cmd,
3187 				struct ublk_device *ub,
3188 				u16 q_id, u16 tag,
3189 				struct ublk_io *io,
3190 				unsigned int index, unsigned int issue_flags)
3191 {
3192 	struct request *req;
3193 	int ret;
3194 
3195 	if (!ublk_dev_support_zero_copy(ub))
3196 		return -EINVAL;
3197 
3198 	req = __ublk_check_and_get_req(ub, q_id, tag, io);
3199 	if (!req)
3200 		return -EINVAL;
3201 
3202 	ret = io_buffer_register_request(cmd, req, ublk_io_release, index,
3203 					 issue_flags);
3204 	if (ret) {
3205 		ublk_put_req_ref(io, req);
3206 		return ret;
3207 	}
3208 
3209 	return 0;
3210 }
3211 
3212 static int
3213 ublk_daemon_register_io_buf(struct io_uring_cmd *cmd,
3214 			    struct ublk_device *ub,
3215 			    u16 q_id, u16 tag, struct ublk_io *io,
3216 			    unsigned index, unsigned issue_flags)
3217 {
3218 	unsigned new_registered_buffers;
3219 	struct request *req = io->req;
3220 	int ret;
3221 
3222 	/*
3223 	 * Ensure there are still references for ublk_sub_req_ref() to release.
3224 	 * If not, fall back on the thread-safe buffer registration.
3225 	 */
3226 	new_registered_buffers = io->task_registered_buffers + 1;
3227 	if (unlikely(new_registered_buffers >= UBLK_REFCOUNT_INIT))
3228 		return ublk_register_io_buf(cmd, ub, q_id, tag, io, index,
3229 					    issue_flags);
3230 
3231 	if (!ublk_dev_support_zero_copy(ub) || !blk_rq_has_data(req))
3232 		return -EINVAL;
3233 
3234 	ret = io_buffer_register_request(cmd, req, ublk_io_release, index,
3235 					 issue_flags);
3236 	if (ret)
3237 		return ret;
3238 
3239 	io->task_registered_buffers = new_registered_buffers;
3240 	return 0;
3241 }
3242 
3243 static int ublk_unregister_io_buf(struct io_uring_cmd *cmd,
3244 				  const struct ublk_device *ub,
3245 				  unsigned int index, unsigned int issue_flags)
3246 {
3247 	if (!(ub->dev_info.flags & UBLK_F_SUPPORT_ZERO_COPY))
3248 		return -EINVAL;
3249 
3250 	return io_buffer_unregister(cmd, index, issue_flags);
3251 }
3252 
3253 static int ublk_check_fetch_buf(const struct ublk_device *ub, __u64 buf_addr)
3254 {
3255 	if (ublk_dev_need_map_io(ub)) {
3256 		/*
3257 		 * FETCH_RQ has to provide IO buffer if NEED GET
3258 		 * DATA is not enabled
3259 		 */
3260 		if (!buf_addr && !ublk_dev_need_get_data(ub))
3261 			return -EINVAL;
3262 	} else if (buf_addr) {
3263 		/* User copy requires addr to be unset */
3264 		return -EINVAL;
3265 	}
3266 	return 0;
3267 }
3268 
3269 static int __ublk_fetch(struct io_uring_cmd *cmd, struct ublk_device *ub,
3270 			struct ublk_io *io, u16 q_id)
3271 {
3272 	/* UBLK_IO_FETCH_REQ is only allowed before dev is setup */
3273 	if (ublk_dev_ready(ub))
3274 		return -EBUSY;
3275 
3276 	/* allow each command to be FETCHed at most once */
3277 	if (io->flags & UBLK_IO_FLAG_ACTIVE)
3278 		return -EINVAL;
3279 
3280 	WARN_ON_ONCE(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV);
3281 
3282 	ublk_fill_io_cmd(io, cmd);
3283 
3284 	if (ublk_dev_support_batch_io(ub))
3285 		WRITE_ONCE(io->task, NULL);
3286 	else
3287 		WRITE_ONCE(io->task, get_task_struct(current));
3288 
3289 	return 0;
3290 }
3291 
3292 static int ublk_fetch(struct io_uring_cmd *cmd, struct ublk_device *ub,
3293 		      struct ublk_io *io, __u64 buf_addr, u16 q_id)
3294 {
3295 	struct ublk_auto_buf_reg auto_buf;
3296 	int ret;
3297 
3298 	/*
3299 	 * When handling FETCH command for setting up ublk uring queue,
3300 	 * ub->mutex is the innermost lock, and we won't block for handling
3301 	 * FETCH, so it is fine even for IO_URING_F_NONBLOCK.
3302 	 */
3303 	mutex_lock(&ub->mutex);
3304 	ret = ublk_validate_io_buf(ub, cmd, &auto_buf);
3305 	if (!ret)
3306 		ret = __ublk_fetch(cmd, ub, io, q_id);
3307 	if (!ret) {
3308 		ublk_apply_io_buf(ub, io, cmd, buf_addr, &auto_buf, NULL);
3309 		ublk_mark_io_ready(ub, q_id, io);
3310 	}
3311 	mutex_unlock(&ub->mutex);
3312 	return ret;
3313 }
3314 
3315 static int ublk_check_commit_and_fetch(const struct ublk_device *ub,
3316 				       struct ublk_io *io, __u64 buf_addr)
3317 {
3318 	struct request *req = io->req;
3319 
3320 	if (ublk_dev_need_map_io(ub)) {
3321 		/*
3322 		 * COMMIT_AND_FETCH_REQ has to provide IO buffer if
3323 		 * NEED GET DATA is not enabled or it is Read IO.
3324 		 */
3325 		if (!buf_addr && (!ublk_dev_need_get_data(ub) ||
3326 					req_op(req) == REQ_OP_READ))
3327 			return -EINVAL;
3328 	} else if (req_op(req) != REQ_OP_ZONE_APPEND && buf_addr) {
3329 		/*
3330 		 * User copy requires addr to be unset when command is
3331 		 * not zone append
3332 		 */
3333 		return -EINVAL;
3334 	}
3335 
3336 	return 0;
3337 }
3338 
3339 static bool ublk_need_complete_req(const struct ublk_device *ub,
3340 				   struct ublk_io *io)
3341 {
3342 	if (ublk_dev_need_req_ref(ub))
3343 		return ublk_sub_req_ref(io);
3344 	return true;
3345 }
3346 
3347 static bool ublk_get_data(const struct ublk_queue *ubq, struct ublk_io *io,
3348 			  struct request *req)
3349 {
3350 	/*
3351 	 * We have handled UBLK_IO_NEED_GET_DATA command,
3352 	 * so clear UBLK_IO_FLAG_NEED_GET_DATA now and just
3353 	 * do the copy work.
3354 	 */
3355 	io->flags &= ~UBLK_IO_FLAG_NEED_GET_DATA;
3356 	/* update iod->addr because ublksrv may have passed a new io buffer */
3357 	ublk_get_iod(ubq, req->tag)->addr = io->buf.addr;
3358 	pr_devel("%s: update iod->addr: qid %d tag %d io_flags %x addr %llx\n",
3359 			__func__, ubq->q_id, req->tag, io->flags,
3360 			ublk_get_iod(ubq, req->tag)->addr);
3361 
3362 	return ublk_start_io(ubq, req, io);
3363 }
3364 
3365 static int ublk_ch_uring_cmd_local(struct io_uring_cmd *cmd,
3366 		unsigned int issue_flags)
3367 {
3368 	/* May point to userspace-mapped memory */
3369 	const struct ublksrv_io_cmd *ub_src = io_uring_sqe_cmd(cmd->sqe,
3370 							       struct ublksrv_io_cmd);
3371 	u16 buf_idx = UBLK_INVALID_BUF_IDX;
3372 	struct ublk_device *ub = cmd->file->private_data;
3373 	struct ublk_queue *ubq;
3374 	struct ublk_io *io = NULL;
3375 	u32 cmd_op = cmd->cmd_op;
3376 	u16 q_id = READ_ONCE(ub_src->q_id);
3377 	u16 tag = READ_ONCE(ub_src->tag);
3378 	s32 result = READ_ONCE(ub_src->result);
3379 	u64 addr = READ_ONCE(ub_src->addr); /* unioned with zone_append_lba */
3380 	struct request *req;
3381 	int ret;
3382 	bool compl;
3383 
3384 	WARN_ON_ONCE(issue_flags & IO_URING_F_UNLOCKED);
3385 
3386 	pr_devel("%s: received: cmd op %d queue %d tag %d result %d\n",
3387 			__func__, cmd->cmd_op, q_id, tag, result);
3388 
3389 	ret = ublk_check_cmd_op(cmd_op);
3390 	if (ret)
3391 		goto out;
3392 
3393 	/*
3394 	 * io_buffer_unregister() doesn't access the ubq or io,
3395 	 * so no need to validate the q_id, tag, or task
3396 	 */
3397 	if (_IOC_NR(cmd_op) == UBLK_IO_UNREGISTER_IO_BUF)
3398 		return ublk_unregister_io_buf(cmd, ub, addr, issue_flags);
3399 
3400 	ret = -EINVAL;
3401 	if (q_id >= ub->dev_info.nr_hw_queues)
3402 		goto out;
3403 
3404 	ubq = ublk_get_queue(ub, q_id);
3405 
3406 	if (tag >= ub->dev_info.queue_depth)
3407 		goto out;
3408 
3409 	io = &ubq->ios[tag];
3410 	/* UBLK_IO_FETCH_REQ can be handled on any task, which sets io->task */
3411 	if (unlikely(_IOC_NR(cmd_op) == UBLK_IO_FETCH_REQ)) {
3412 		ret = ublk_check_fetch_buf(ub, addr);
3413 		if (ret)
3414 			goto out;
3415 		ret = ublk_fetch(cmd, ub, io, addr, q_id);
3416 		if (ret)
3417 			goto out;
3418 
3419 		ublk_prep_cancel(cmd, issue_flags, ubq, tag);
3420 		return -EIOCBQUEUED;
3421 	}
3422 
3423 	if (READ_ONCE(io->task) != current) {
3424 		/*
3425 		 * ublk_register_io_buf() accesses only the io's refcount,
3426 		 * so can be handled on any task
3427 		 */
3428 		if (_IOC_NR(cmd_op) == UBLK_IO_REGISTER_IO_BUF)
3429 			return ublk_register_io_buf(cmd, ub, q_id, tag, io,
3430 						    addr, issue_flags);
3431 
3432 		goto out;
3433 	}
3434 
3435 	/* there is pending io cmd, something must be wrong */
3436 	if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV)) {
3437 		ret = -EBUSY;
3438 		goto out;
3439 	}
3440 
3441 	/*
3442 	 * ensure that the user issues UBLK_IO_NEED_GET_DATA
3443 	 * iff the driver have set the UBLK_IO_FLAG_NEED_GET_DATA.
3444 	 */
3445 	if ((!!(io->flags & UBLK_IO_FLAG_NEED_GET_DATA))
3446 			^ (_IOC_NR(cmd_op) == UBLK_IO_NEED_GET_DATA))
3447 		goto out;
3448 
3449 	switch (_IOC_NR(cmd_op)) {
3450 	case UBLK_IO_REGISTER_IO_BUF:
3451 		return ublk_daemon_register_io_buf(cmd, ub, q_id, tag, io, addr,
3452 						   issue_flags);
3453 	case UBLK_IO_COMMIT_AND_FETCH_REQ: {
3454 		struct ublk_auto_buf_reg auto_buf;
3455 
3456 		ret = ublk_check_commit_and_fetch(ub, io, addr);
3457 		if (ret)
3458 			goto out;
3459 		ret = ublk_validate_io_buf(ub, cmd, &auto_buf);
3460 		if (ret)
3461 			goto out;
3462 		io->res = result;
3463 		req = ublk_fill_io_cmd(io, cmd);
3464 		ublk_apply_io_buf(ub, io, cmd, addr, &auto_buf, &buf_idx);
3465 		if (buf_idx != UBLK_INVALID_BUF_IDX)
3466 			io_buffer_unregister(cmd, buf_idx, issue_flags);
3467 		compl = ublk_need_complete_req(ub, io);
3468 
3469 		if (req_op(req) == REQ_OP_ZONE_APPEND)
3470 			req->__sector = addr;
3471 		if (compl)
3472 			__ublk_complete_rq(req, io, ublk_dev_need_map_io(ub), NULL);
3473 		break;
3474 	}
3475 	case UBLK_IO_NEED_GET_DATA:
3476 		/*
3477 		 * ublk_get_data() may fail and fallback to requeue, so keep
3478 		 * uring_cmd active first and prepare for handling new requeued
3479 		 * request
3480 		 */
3481 		req = ublk_fill_io_cmd(io, cmd);
3482 		io->buf.addr = addr;
3483 		if (likely(ublk_get_data(ubq, io, req))) {
3484 			__ublk_prep_compl_io_cmd(io, req);
3485 			return UBLK_IO_RES_OK;
3486 		}
3487 		break;
3488 	default:
3489 		goto out;
3490 	}
3491 	ublk_prep_cancel(cmd, issue_flags, ubq, tag);
3492 	return -EIOCBQUEUED;
3493 
3494  out:
3495 	pr_devel("%s: complete: cmd op %d, tag %d ret %x io_flags %x\n",
3496 			__func__, cmd_op, tag, ret, io ? io->flags : 0);
3497 	return ret;
3498 }
3499 
3500 static inline struct request *__ublk_check_and_get_req(struct ublk_device *ub,
3501 		u16 q_id, u16 tag, struct ublk_io *io)
3502 {
3503 	struct request *req;
3504 
3505 	/*
3506 	 * can't use io->req in case of concurrent UBLK_IO_COMMIT_AND_FETCH_REQ,
3507 	 * which would overwrite it with io->cmd
3508 	 */
3509 	req = blk_mq_tag_to_rq(ub->tag_set.tags[q_id], tag);
3510 	if (!req)
3511 		return NULL;
3512 
3513 	if (!ublk_get_req_ref(io))
3514 		return NULL;
3515 
3516 	if (unlikely(!blk_mq_request_started(req) || req->tag != tag))
3517 		goto fail_put;
3518 
3519 	if (!blk_rq_has_data(req))
3520 		goto fail_put;
3521 
3522 	return req;
3523 fail_put:
3524 	ublk_put_req_ref(io, req);
3525 	return NULL;
3526 }
3527 
3528 static void ublk_ch_uring_cmd_cb(struct io_tw_req tw_req, io_tw_token_t tw)
3529 {
3530 	unsigned int issue_flags = IO_URING_CMD_TASK_WORK_ISSUE_FLAGS;
3531 	struct io_uring_cmd *cmd = io_uring_cmd_from_tw(tw_req);
3532 	int ret = -ECANCELED;
3533 
3534 	if (!tw.cancel)
3535 		ret = ublk_ch_uring_cmd_local(cmd, issue_flags);
3536 	if (ret != -EIOCBQUEUED)
3537 		io_uring_cmd_done(cmd, ret, issue_flags);
3538 }
3539 
3540 static int ublk_ch_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags)
3541 {
3542 	if (unlikely(issue_flags & IO_URING_F_CANCEL)) {
3543 		ublk_uring_cmd_cancel_fn(cmd, issue_flags);
3544 		return 0;
3545 	}
3546 
3547 	/* well-implemented server won't run into unlocked */
3548 	if (unlikely(issue_flags & IO_URING_F_UNLOCKED)) {
3549 		io_uring_cmd_complete_in_task(cmd, ublk_ch_uring_cmd_cb);
3550 		return -EIOCBQUEUED;
3551 	}
3552 
3553 	return ublk_ch_uring_cmd_local(cmd, issue_flags);
3554 }
3555 
3556 static inline __u64 ublk_batch_buf_addr(const struct ublk_batch_io *uc,
3557 					const struct ublk_elem_header *elem)
3558 {
3559 	const void *buf = elem;
3560 
3561 	if (uc->flags & UBLK_BATCH_F_HAS_BUF_ADDR)
3562 		return *(const __u64 *)(buf + sizeof(*elem));
3563 	return 0;
3564 }
3565 
3566 static inline __u64 ublk_batch_zone_lba(const struct ublk_batch_io *uc,
3567 					const struct ublk_elem_header *elem)
3568 {
3569 	const void *buf = elem;
3570 
3571 	if (uc->flags & UBLK_BATCH_F_HAS_ZONE_LBA)
3572 		return *(const __u64 *)(buf + sizeof(*elem) +
3573 				8 * !!(uc->flags & UBLK_BATCH_F_HAS_BUF_ADDR));
3574 	return -1;
3575 }
3576 
3577 static struct ublk_auto_buf_reg
3578 ublk_batch_auto_buf_reg(const struct ublk_batch_io *uc,
3579 			const struct ublk_elem_header *elem)
3580 {
3581 	struct ublk_auto_buf_reg reg = {
3582 		.index = elem->buf_index,
3583 		.flags = (uc->flags & UBLK_BATCH_F_AUTO_BUF_REG_FALLBACK) ?
3584 			UBLK_AUTO_BUF_REG_FALLBACK : 0,
3585 	};
3586 
3587 	return reg;
3588 }
3589 
3590 /*
3591  * 48 can hold any type of buffer element(8, 16 and 24 bytes) because
3592  * it is the least common multiple(LCM) of 8, 16 and 24
3593  */
3594 #define UBLK_CMD_BATCH_TMP_BUF_SZ  (48 * 10)
3595 struct ublk_batch_io_iter {
3596 	void __user *uaddr;
3597 	const u8 *kaddr;
3598 	unsigned done, total;
3599 	unsigned char elem_bytes;
3600 	/* copy to this buffer from user space */
3601 	unsigned char buf[UBLK_CMD_BATCH_TMP_BUF_SZ];
3602 };
3603 
3604 static inline int
3605 __ublk_walk_cmd_buf(struct ublk_queue *ubq,
3606 		    struct ublk_batch_io_iter *iter,
3607 		    const struct ublk_batch_io_data *data,
3608 		    unsigned bytes,
3609 		    int (*cb)(struct ublk_queue *q,
3610 			    const struct ublk_batch_io_data *data,
3611 			    const struct ublk_elem_header *elem))
3612 {
3613 	unsigned int i;
3614 	int ret = 0;
3615 
3616 	for (i = 0; i < bytes; i += iter->elem_bytes) {
3617 		const struct ublk_elem_header *elem =
3618 			(const struct ublk_elem_header *)&iter->buf[i];
3619 
3620 		if (unlikely(elem->tag >= data->ub->dev_info.queue_depth)) {
3621 			ret = -EINVAL;
3622 			break;
3623 		}
3624 
3625 		ret = cb(ubq, data, elem);
3626 		if (unlikely(ret))
3627 			break;
3628 	}
3629 
3630 	iter->done += i;
3631 	return ret;
3632 }
3633 
3634 static int ublk_walk_cmd_buf(struct ublk_batch_io_iter *iter,
3635 			     const struct ublk_batch_io_data *data,
3636 			     int (*cb)(struct ublk_queue *q,
3637 				     const struct ublk_batch_io_data *data,
3638 				     const struct ublk_elem_header *elem))
3639 {
3640 	struct ublk_queue *ubq = ublk_get_queue(data->ub, data->header.q_id);
3641 	int ret = 0;
3642 
3643 	while (iter->done < iter->total) {
3644 		unsigned int len = min(sizeof(iter->buf), iter->total - iter->done);
3645 
3646 		if (iter->kaddr) {
3647 			memcpy(iter->buf, iter->kaddr + iter->done, len);
3648 		} else if (copy_from_user(iter->buf, iter->uaddr + iter->done,
3649 				  len)) {
3650 			pr_warn("ublk%d: read batch cmd buffer failed\n",
3651 					data->ub->dev_info.dev_id);
3652 			return -EFAULT;
3653 		}
3654 
3655 		ret = __ublk_walk_cmd_buf(ubq, iter, data, len, cb);
3656 		if (ret)
3657 			return ret;
3658 	}
3659 	return 0;
3660 }
3661 
3662 static int ublk_batch_unprep_io(struct ublk_queue *ubq,
3663 				const struct ublk_batch_io_data *data,
3664 				const struct ublk_elem_header *elem)
3665 {
3666 	struct ublk_io *io = &ubq->ios[elem->tag];
3667 
3668 	/*
3669 	 * If queue was ready before this decrement, it won't be anymore,
3670 	 * so we need to decrement the queue ready count and restore the
3671 	 * canceling flag to prevent new requests from being queued.
3672 	 */
3673 	if (ublk_queue_ready(ubq)) {
3674 		data->ub->nr_queue_ready--;
3675 		spin_lock(&ubq->cancel_lock);
3676 		ubq->canceling = true;
3677 		spin_unlock(&ubq->cancel_lock);
3678 	}
3679 	ubq->nr_io_ready--;
3680 
3681 	ublk_io_lock(io);
3682 	io->flags = 0;
3683 	ublk_io_unlock(io);
3684 	return 0;
3685 }
3686 
3687 static void ublk_batch_revert_prep_cmd(struct ublk_batch_io_iter *iter,
3688 				       const struct ublk_batch_io_data *data)
3689 {
3690 	int ret;
3691 
3692 	/* Re-process only what we've already processed, starting from beginning */
3693 	iter->total = iter->done;
3694 	iter->done = 0;
3695 
3696 	ret = ublk_walk_cmd_buf(iter, data, ublk_batch_unprep_io);
3697 	WARN_ON_ONCE(ret);
3698 }
3699 
3700 static int ublk_batch_prep_io(struct ublk_queue *ubq,
3701 			      const struct ublk_batch_io_data *data,
3702 			      const struct ublk_elem_header *elem)
3703 {
3704 	struct ublk_io *io = &ubq->ios[elem->tag];
3705 	const struct ublk_batch_io *uc = &data->header;
3706 	union ublk_io_buf buf = { 0 };
3707 	int ret;
3708 
3709 	if (ublk_dev_support_auto_buf_reg(data->ub))
3710 		buf.auto_reg = ublk_batch_auto_buf_reg(uc, elem);
3711 	else if (ublk_dev_need_map_io(data->ub)) {
3712 		buf.addr = ublk_batch_buf_addr(uc, elem);
3713 
3714 		ret = ublk_check_fetch_buf(data->ub, buf.addr);
3715 		if (ret)
3716 			return ret;
3717 	}
3718 
3719 	ublk_io_lock(io);
3720 	ret = __ublk_fetch(data->cmd, data->ub, io, ubq->q_id);
3721 	if (!ret)
3722 		io->buf = buf;
3723 	ublk_io_unlock(io);
3724 
3725 	if (!ret)
3726 		ublk_mark_io_ready(data->ub, ubq->q_id, io);
3727 
3728 	return ret;
3729 }
3730 
3731 static int ublk_handle_batch_prep_cmd(const struct ublk_batch_io_data *data)
3732 {
3733 	const struct ublk_batch_io *uc = &data->header;
3734 	struct io_uring_cmd *cmd = data->cmd;
3735 	struct ublk_batch_io_iter iter = {
3736 		.uaddr = u64_to_user_ptr(READ_ONCE(cmd->sqe->addr)),
3737 		.total = uc->nr_elem * uc->elem_bytes,
3738 		.elem_bytes = uc->elem_bytes,
3739 	};
3740 	void *cmd_buf;
3741 	int ret;
3742 
3743 	cmd_buf = vmemdup_user(iter.uaddr, iter.total);
3744 	if (IS_ERR(cmd_buf))
3745 		return PTR_ERR(cmd_buf);
3746 	iter.kaddr = cmd_buf;
3747 
3748 	mutex_lock(&data->ub->mutex);
3749 	ret = ublk_walk_cmd_buf(&iter, data, ublk_batch_prep_io);
3750 
3751 	if (ret && iter.done)
3752 		ublk_batch_revert_prep_cmd(&iter, data);
3753 	mutex_unlock(&data->ub->mutex);
3754 	kvfree(cmd_buf);
3755 	return ret;
3756 }
3757 
3758 static int ublk_batch_commit_io_check(const struct ublk_queue *ubq,
3759 				      struct ublk_io *io,
3760 				      union ublk_io_buf *buf)
3761 {
3762 	if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV))
3763 		return -EBUSY;
3764 
3765 	/* BATCH_IO doesn't support UBLK_F_NEED_GET_DATA */
3766 	if (ublk_need_map_io(ubq) && !buf->addr)
3767 		return -EINVAL;
3768 	return 0;
3769 }
3770 
3771 static int ublk_batch_commit_io(struct ublk_queue *ubq,
3772 				const struct ublk_batch_io_data *data,
3773 				const struct ublk_elem_header *elem)
3774 {
3775 	struct ublk_io *io = &ubq->ios[elem->tag];
3776 	const struct ublk_batch_io *uc = &data->header;
3777 	u16 buf_idx = UBLK_INVALID_BUF_IDX;
3778 	union ublk_io_buf buf = { 0 };
3779 	struct request *req = NULL;
3780 	bool auto_reg = false;
3781 	bool compl = false;
3782 	int ret;
3783 
3784 	if (ublk_dev_support_auto_buf_reg(data->ub)) {
3785 		buf.auto_reg = ublk_batch_auto_buf_reg(uc, elem);
3786 		auto_reg = true;
3787 	} else if (ublk_dev_need_map_io(data->ub))
3788 		buf.addr = ublk_batch_buf_addr(uc, elem);
3789 
3790 	ublk_io_lock(io);
3791 	ret = ublk_batch_commit_io_check(ubq, io, &buf);
3792 	if (!ret) {
3793 		io->res = elem->result;
3794 		req = ublk_fill_io_cmd(io, data->cmd);
3795 
3796 		if (auto_reg)
3797 			ublk_clear_auto_buf_reg(io, data->cmd, &buf_idx);
3798 		io->buf = buf;
3799 		compl = ublk_need_complete_req(data->ub, io);
3800 	}
3801 	ublk_io_unlock(io);
3802 
3803 	if (unlikely(ret)) {
3804 		pr_warn_ratelimited("%s: dev %u queue %u io %u: commit failure %d\n",
3805 			__func__, data->ub->dev_info.dev_id, ubq->q_id,
3806 			elem->tag, ret);
3807 		return ret;
3808 	}
3809 
3810 	if (buf_idx != UBLK_INVALID_BUF_IDX)
3811 		io_buffer_unregister(data->cmd, buf_idx, data->issue_flags);
3812 	if (req_op(req) == REQ_OP_ZONE_APPEND)
3813 		req->__sector = ublk_batch_zone_lba(uc, elem);
3814 	if (compl)
3815 		__ublk_complete_rq(req, io, ublk_dev_need_map_io(data->ub), data->iob);
3816 	return 0;
3817 }
3818 
3819 static int ublk_handle_batch_commit_cmd(struct ublk_batch_io_data *data)
3820 {
3821 	const struct ublk_batch_io *uc = &data->header;
3822 	struct io_uring_cmd *cmd = data->cmd;
3823 	struct ublk_batch_io_iter iter = {
3824 		.uaddr = u64_to_user_ptr(READ_ONCE(cmd->sqe->addr)),
3825 		.total = uc->nr_elem * uc->elem_bytes,
3826 		.elem_bytes = uc->elem_bytes,
3827 	};
3828 	DEFINE_IO_COMP_BATCH(iob);
3829 	int ret;
3830 
3831 	data->iob = &iob;
3832 	ret = ublk_walk_cmd_buf(&iter, data, ublk_batch_commit_io);
3833 
3834 	if (iob.complete)
3835 		iob.complete(&iob);
3836 
3837 	return iter.done == 0 ? ret : iter.done;
3838 }
3839 
3840 static int ublk_check_batch_cmd_flags(const struct ublk_batch_io *uc)
3841 {
3842 	unsigned elem_bytes = sizeof(struct ublk_elem_header);
3843 
3844 	if (uc->flags & ~UBLK_BATCH_F_ALL)
3845 		return -EINVAL;
3846 
3847 	/* UBLK_BATCH_F_AUTO_BUF_REG_FALLBACK requires buffer index */
3848 	if ((uc->flags & UBLK_BATCH_F_AUTO_BUF_REG_FALLBACK) &&
3849 			(uc->flags & UBLK_BATCH_F_HAS_BUF_ADDR))
3850 		return -EINVAL;
3851 
3852 	elem_bytes += (uc->flags & UBLK_BATCH_F_HAS_ZONE_LBA ? sizeof(u64) : 0) +
3853 		(uc->flags & UBLK_BATCH_F_HAS_BUF_ADDR ? sizeof(u64) : 0);
3854 	if (uc->elem_bytes != elem_bytes)
3855 		return -EINVAL;
3856 	return 0;
3857 }
3858 
3859 static int ublk_check_batch_cmd(const struct ublk_batch_io_data *data)
3860 {
3861 	const struct ublk_batch_io *uc = &data->header;
3862 
3863 	if (uc->q_id >= data->ub->dev_info.nr_hw_queues)
3864 		return -EINVAL;
3865 
3866 	if (uc->nr_elem > data->ub->dev_info.queue_depth)
3867 		return -E2BIG;
3868 
3869 	if ((uc->flags & UBLK_BATCH_F_HAS_ZONE_LBA) &&
3870 			!ublk_dev_is_zoned(data->ub))
3871 		return -EINVAL;
3872 
3873 	if ((uc->flags & UBLK_BATCH_F_HAS_BUF_ADDR) &&
3874 			!ublk_dev_need_map_io(data->ub))
3875 		return -EINVAL;
3876 
3877 	if ((uc->flags & UBLK_BATCH_F_AUTO_BUF_REG_FALLBACK) &&
3878 			!ublk_dev_support_auto_buf_reg(data->ub))
3879 		return -EINVAL;
3880 
3881 	return ublk_check_batch_cmd_flags(uc);
3882 }
3883 
3884 static int ublk_batch_attach(struct ublk_queue *ubq,
3885 			     struct ublk_batch_io_data *data,
3886 			     struct ublk_batch_fetch_cmd *fcmd)
3887 {
3888 	struct ublk_batch_fetch_cmd *new_fcmd = NULL;
3889 	bool free = false;
3890 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(data->cmd);
3891 
3892 	spin_lock(&ubq->evts_lock);
3893 	if (unlikely(ubq->force_abort || ubq->canceling)) {
3894 		free = true;
3895 	} else {
3896 		list_add_tail(&fcmd->node, &ubq->fcmd_head);
3897 		new_fcmd = __ublk_acquire_fcmd(ubq);
3898 	}
3899 	spin_unlock(&ubq->evts_lock);
3900 
3901 	if (unlikely(free)) {
3902 		ublk_batch_free_fcmd(fcmd);
3903 		return -ENODEV;
3904 	}
3905 
3906 	pdu->ubq = ubq;
3907 	pdu->fcmd = fcmd;
3908 	io_uring_cmd_mark_cancelable(fcmd->cmd, data->issue_flags);
3909 
3910 	if (!new_fcmd)
3911 		goto out;
3912 
3913 	/*
3914 	 * If the two fetch commands are originated from same io_ring_ctx,
3915 	 * run batch dispatch directly. Otherwise, schedule task work for
3916 	 * doing it.
3917 	 */
3918 	if (io_uring_cmd_ctx_handle(new_fcmd->cmd) ==
3919 			io_uring_cmd_ctx_handle(fcmd->cmd)) {
3920 		data->cmd = new_fcmd->cmd;
3921 		ublk_batch_dispatch(ubq, data, new_fcmd);
3922 	} else {
3923 		io_uring_cmd_complete_in_task(new_fcmd->cmd,
3924 				ublk_batch_tw_cb);
3925 	}
3926 out:
3927 	return -EIOCBQUEUED;
3928 }
3929 
3930 static int ublk_handle_batch_fetch_cmd(struct ublk_batch_io_data *data)
3931 {
3932 	struct ublk_queue *ubq = ublk_get_queue(data->ub, data->header.q_id);
3933 	struct ublk_batch_fetch_cmd *fcmd = ublk_batch_alloc_fcmd(data->cmd);
3934 
3935 	if (!fcmd)
3936 		return -ENOMEM;
3937 
3938 	return ublk_batch_attach(ubq, data, fcmd);
3939 }
3940 
3941 static int ublk_validate_batch_fetch_cmd(struct ublk_batch_io_data *data)
3942 {
3943 	const struct ublk_batch_io *uc = &data->header;
3944 
3945 	if (uc->q_id >= data->ub->dev_info.nr_hw_queues)
3946 		return -EINVAL;
3947 
3948 	if (!(data->cmd->flags & IORING_URING_CMD_MULTISHOT))
3949 		return -EINVAL;
3950 
3951 	if (uc->elem_bytes != sizeof(__u16))
3952 		return -EINVAL;
3953 
3954 	if (uc->flags != 0)
3955 		return -EINVAL;
3956 
3957 	return 0;
3958 }
3959 
3960 static int ublk_handle_non_batch_cmd(struct io_uring_cmd *cmd,
3961 				     unsigned int issue_flags)
3962 {
3963 	const struct ublksrv_io_cmd *ub_cmd = io_uring_sqe_cmd(cmd->sqe,
3964 							       struct ublksrv_io_cmd);
3965 	struct ublk_device *ub = cmd->file->private_data;
3966 	u16 tag = READ_ONCE(ub_cmd->tag);
3967 	u16 q_id = READ_ONCE(ub_cmd->q_id);
3968 	unsigned index = READ_ONCE(ub_cmd->addr);
3969 	struct ublk_queue *ubq;
3970 	struct ublk_io *io;
3971 
3972 	if (cmd->cmd_op == UBLK_U_IO_UNREGISTER_IO_BUF)
3973 		return ublk_unregister_io_buf(cmd, ub, index, issue_flags);
3974 
3975 	if (q_id >= ub->dev_info.nr_hw_queues)
3976 		return -EINVAL;
3977 
3978 	if (tag >= ub->dev_info.queue_depth)
3979 		return -EINVAL;
3980 
3981 	if (cmd->cmd_op != UBLK_U_IO_REGISTER_IO_BUF)
3982 		return -EOPNOTSUPP;
3983 
3984 	ubq = ublk_get_queue(ub, q_id);
3985 	io = &ubq->ios[tag];
3986 	return ublk_register_io_buf(cmd, ub, q_id, tag, io, index,
3987 			issue_flags);
3988 }
3989 
3990 static int ublk_ch_batch_io_uring_cmd(struct io_uring_cmd *cmd,
3991 				       unsigned int issue_flags)
3992 {
3993 	const struct ublk_batch_io *uc = io_uring_sqe_cmd(cmd->sqe,
3994 							  struct ublk_batch_io);
3995 	struct ublk_device *ub = cmd->file->private_data;
3996 	struct ublk_batch_io_data data = {
3997 		.ub  = ub,
3998 		.cmd = cmd,
3999 		.header = (struct ublk_batch_io) {
4000 			.q_id = READ_ONCE(uc->q_id),
4001 			.flags = READ_ONCE(uc->flags),
4002 			.nr_elem = READ_ONCE(uc->nr_elem),
4003 			.elem_bytes = READ_ONCE(uc->elem_bytes),
4004 		},
4005 		.issue_flags = issue_flags,
4006 	};
4007 	u32 cmd_op = cmd->cmd_op;
4008 	int ret = -EINVAL;
4009 
4010 	if (unlikely(issue_flags & IO_URING_F_CANCEL)) {
4011 		ublk_batch_cancel_fn(cmd, issue_flags);
4012 		return 0;
4013 	}
4014 
4015 	switch (cmd_op) {
4016 	case UBLK_U_IO_PREP_IO_CMDS:
4017 		ret = ublk_check_batch_cmd(&data);
4018 		if (ret)
4019 			goto out;
4020 		ret = ublk_handle_batch_prep_cmd(&data);
4021 		break;
4022 	case UBLK_U_IO_COMMIT_IO_CMDS:
4023 		ret = ublk_check_batch_cmd(&data);
4024 		if (ret)
4025 			goto out;
4026 		ret = ublk_handle_batch_commit_cmd(&data);
4027 		break;
4028 	case UBLK_U_IO_FETCH_IO_CMDS:
4029 		ret = ublk_validate_batch_fetch_cmd(&data);
4030 		if (ret)
4031 			goto out;
4032 		ret = ublk_handle_batch_fetch_cmd(&data);
4033 		break;
4034 	default:
4035 		ret = ublk_handle_non_batch_cmd(cmd, issue_flags);
4036 		break;
4037 	}
4038 out:
4039 	return ret;
4040 }
4041 
4042 static inline bool ublk_check_ubuf_dir(const struct request *req,
4043 		int ubuf_dir)
4044 {
4045 	/* copy ubuf to request pages */
4046 	if ((req_op(req) == REQ_OP_READ || req_op(req) == REQ_OP_DRV_IN) &&
4047 	    ubuf_dir == ITER_SOURCE)
4048 		return true;
4049 
4050 	/* copy request pages to ubuf */
4051 	if ((req_op(req) == REQ_OP_WRITE ||
4052 	     req_op(req) == REQ_OP_ZONE_APPEND) &&
4053 	    ubuf_dir == ITER_DEST)
4054 		return true;
4055 
4056 	return false;
4057 }
4058 
4059 static ssize_t
4060 ublk_user_copy(struct kiocb *iocb, struct iov_iter *iter, int dir)
4061 {
4062 	struct ublk_device *ub = iocb->ki_filp->private_data;
4063 	struct ublk_queue *ubq;
4064 	struct request *req;
4065 	struct ublk_io *io;
4066 	unsigned data_len;
4067 	bool is_integrity;
4068 	bool on_daemon;
4069 	size_t buf_off;
4070 	u16 tag, q_id;
4071 	ssize_t ret;
4072 
4073 	if (!user_backed_iter(iter))
4074 		return -EACCES;
4075 
4076 	if (ub->dev_info.state == UBLK_S_DEV_DEAD)
4077 		return -EACCES;
4078 
4079 	tag = ublk_pos_to_tag(iocb->ki_pos);
4080 	q_id = ublk_pos_to_hwq(iocb->ki_pos);
4081 	buf_off = ublk_pos_to_buf_off(iocb->ki_pos);
4082 	is_integrity = !!(iocb->ki_pos & UBLKSRV_IO_INTEGRITY_FLAG);
4083 
4084 	if (unlikely(!ublk_dev_support_integrity(ub) && is_integrity))
4085 		return -EINVAL;
4086 
4087 	if (q_id >= ub->dev_info.nr_hw_queues)
4088 		return -EINVAL;
4089 
4090 	ubq = ublk_get_queue(ub, q_id);
4091 	if (!ublk_dev_support_user_copy(ub))
4092 		return -EACCES;
4093 
4094 	if (tag >= ub->dev_info.queue_depth)
4095 		return -EINVAL;
4096 
4097 	io = &ubq->ios[tag];
4098 	on_daemon = current == READ_ONCE(io->task);
4099 	if (on_daemon) {
4100 		/* On daemon, io can't be completed concurrently, so skip ref */
4101 		if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV))
4102 			return -EINVAL;
4103 
4104 		req = io->req;
4105 		if (!blk_rq_has_data(req))
4106 			return -EINVAL;
4107 	} else {
4108 		req = __ublk_check_and_get_req(ub, q_id, tag, io);
4109 		if (!req)
4110 			return -EINVAL;
4111 	}
4112 
4113 	if (is_integrity) {
4114 		struct blk_integrity *bi = &req->q->limits.integrity;
4115 
4116 		data_len = bio_integrity_bytes(bi, blk_rq_sectors(req));
4117 	} else {
4118 		data_len = blk_rq_bytes(req);
4119 	}
4120 	if (buf_off > data_len) {
4121 		ret = -EINVAL;
4122 		goto out;
4123 	}
4124 
4125 	if (!ublk_check_ubuf_dir(req, dir)) {
4126 		ret = -EACCES;
4127 		goto out;
4128 	}
4129 
4130 	if (is_integrity)
4131 		ret = ublk_copy_user_integrity(req, buf_off, iter, dir);
4132 	else
4133 		ret = ublk_copy_user_pages(req, buf_off, iter, dir);
4134 
4135 out:
4136 	if (!on_daemon)
4137 		ublk_put_req_ref(io, req);
4138 	return ret;
4139 }
4140 
4141 static ssize_t ublk_ch_read_iter(struct kiocb *iocb, struct iov_iter *to)
4142 {
4143 	return ublk_user_copy(iocb, to, ITER_DEST);
4144 }
4145 
4146 static ssize_t ublk_ch_write_iter(struct kiocb *iocb, struct iov_iter *from)
4147 {
4148 	return ublk_user_copy(iocb, from, ITER_SOURCE);
4149 }
4150 
4151 static const struct file_operations ublk_ch_fops = {
4152 	.owner = THIS_MODULE,
4153 	.open = ublk_ch_open,
4154 	.release = ublk_ch_release,
4155 	.read_iter = ublk_ch_read_iter,
4156 	.write_iter = ublk_ch_write_iter,
4157 	.uring_cmd = ublk_ch_uring_cmd,
4158 	.mmap = ublk_ch_mmap,
4159 };
4160 
4161 static const struct file_operations ublk_ch_batch_io_fops = {
4162 	.owner = THIS_MODULE,
4163 	.open = ublk_ch_open,
4164 	.release = ublk_ch_release,
4165 	.read_iter = ublk_ch_read_iter,
4166 	.write_iter = ublk_ch_write_iter,
4167 	.uring_cmd = ublk_ch_batch_io_uring_cmd,
4168 	.mmap = ublk_ch_mmap,
4169 };
4170 
4171 static void __ublk_deinit_queue(struct ublk_device *ub, struct ublk_queue *ubq)
4172 {
4173 	size_t size;
4174 	u16 i;
4175 
4176 	size = ublk_queue_cmd_buf_size(ub);
4177 
4178 	for (i = 0; i < ubq->q_depth; i++) {
4179 		struct ublk_io *io = &ubq->ios[i];
4180 		if (io->task)
4181 			put_task_struct(io->task);
4182 		WARN_ON_ONCE(refcount_read(&io->ref));
4183 		WARN_ON_ONCE(io->task_registered_buffers);
4184 	}
4185 
4186 	if (ubq->io_cmd_buf)
4187 		free_pages((unsigned long)ubq->io_cmd_buf, get_order(size));
4188 
4189 	if (ublk_dev_support_batch_io(ub))
4190 		ublk_io_evts_deinit(ubq);
4191 
4192 	kvfree(ubq);
4193 }
4194 
4195 static void ublk_deinit_queue(struct ublk_device *ub, u16 q_id)
4196 {
4197 	struct ublk_queue *ubq = ub->queues[q_id];
4198 
4199 	if (!ubq)
4200 		return;
4201 
4202 	__ublk_deinit_queue(ub, ubq);
4203 	ub->queues[q_id] = NULL;
4204 }
4205 
4206 static int ublk_get_queue_numa_node(struct ublk_device *ub, u16 q_id)
4207 {
4208 	unsigned int cpu;
4209 
4210 	/* Find first CPU mapped to this queue */
4211 	for_each_possible_cpu(cpu) {
4212 		if (ub->tag_set.map[HCTX_TYPE_DEFAULT].mq_map[cpu] == q_id)
4213 			return cpu_to_node(cpu);
4214 	}
4215 
4216 	return NUMA_NO_NODE;
4217 }
4218 
4219 static int ublk_init_queue(struct ublk_device *ub, u16 q_id)
4220 {
4221 	u16 depth = ub->dev_info.queue_depth;
4222 	gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO;
4223 	struct ublk_queue *ubq;
4224 	struct page *page;
4225 	int numa_node;
4226 	size_t size;
4227 	int ret;
4228 	u16 i;
4229 
4230 	/* Determine NUMA node based on queue's CPU affinity */
4231 	numa_node = ublk_get_queue_numa_node(ub, q_id);
4232 
4233 	/* Allocate queue structure on local NUMA node */
4234 	ubq = kvzalloc_node(struct_size(ubq, ios, depth), GFP_KERNEL,
4235 			    numa_node);
4236 	if (!ubq)
4237 		return -ENOMEM;
4238 
4239 	spin_lock_init(&ubq->cancel_lock);
4240 	ubq->flags = ub->dev_info.flags;
4241 	ubq->q_id = q_id;
4242 	ubq->q_depth = depth;
4243 	size = ublk_queue_cmd_buf_size(ub);
4244 
4245 	/* Allocate I/O command buffer on local NUMA node */
4246 	page = alloc_pages_node(numa_node, gfp_flags, get_order(size));
4247 	if (!page) {
4248 		kvfree(ubq);
4249 		return -ENOMEM;
4250 	}
4251 	ubq->io_cmd_buf = page_address(page);
4252 	ubq->io_desc_size = ub->dev_info.io_desc_size;
4253 
4254 	for (i = 0; i < ubq->q_depth; i++)
4255 		spin_lock_init(&ubq->ios[i].lock);
4256 
4257 	if (ublk_dev_support_batch_io(ub)) {
4258 		ret = ublk_io_evts_init(ubq, ubq->q_depth, numa_node);
4259 		if (ret)
4260 			goto fail;
4261 		INIT_LIST_HEAD(&ubq->fcmd_head);
4262 	}
4263 	ub->queues[q_id] = ubq;
4264 	ubq->dev = ub;
4265 
4266 	return 0;
4267 fail:
4268 	__ublk_deinit_queue(ub, ubq);
4269 	return ret;
4270 }
4271 
4272 static void ublk_deinit_queues(struct ublk_device *ub)
4273 {
4274 	u16 i;
4275 
4276 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
4277 		ublk_deinit_queue(ub, i);
4278 }
4279 
4280 static int ublk_init_queues(struct ublk_device *ub)
4281 {
4282 	int ret;
4283 	u16 i;
4284 
4285 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++) {
4286 		ret = ublk_init_queue(ub, i);
4287 		if (ret)
4288 			goto fail;
4289 	}
4290 
4291 	return 0;
4292 
4293  fail:
4294 	ublk_deinit_queues(ub);
4295 	return ret;
4296 }
4297 
4298 static int ublk_alloc_dev_number(struct ublk_device *ub, int idx)
4299 {
4300 	int i = idx;
4301 	int err;
4302 
4303 	spin_lock(&ublk_idr_lock);
4304 	/* allocate id, if @id >= 0, we're requesting that specific id */
4305 	if (i >= 0) {
4306 		err = idr_alloc(&ublk_index_idr, ub, i, i + 1, GFP_NOWAIT);
4307 		if (err == -ENOSPC)
4308 			err = -EEXIST;
4309 	} else {
4310 		err = idr_alloc(&ublk_index_idr, ub, 0, UBLK_MAX_UBLKS,
4311 				GFP_NOWAIT);
4312 	}
4313 	spin_unlock(&ublk_idr_lock);
4314 
4315 	if (err >= 0)
4316 		ub->ub_number = err;
4317 
4318 	return err;
4319 }
4320 
4321 static void ublk_free_dev_number(struct ublk_device *ub)
4322 {
4323 	spin_lock(&ublk_idr_lock);
4324 	idr_remove(&ublk_index_idr, ub->ub_number);
4325 	wake_up_all(&ublk_idr_wq);
4326 	spin_unlock(&ublk_idr_lock);
4327 }
4328 
4329 static void ublk_cdev_rel(struct device *dev)
4330 {
4331 	struct ublk_device *ub = container_of(dev, struct ublk_device, cdev_dev);
4332 
4333 	ublk_buf_cleanup(ub);
4334 	blk_mq_free_tag_set(&ub->tag_set);
4335 	ublk_deinit_queues(ub);
4336 	ublk_free_dev_number(ub);
4337 	mutex_destroy(&ub->mutex);
4338 	mutex_destroy(&ub->cancel_mutex);
4339 	kfree(ub);
4340 }
4341 
4342 static int ublk_add_chdev(struct ublk_device *ub)
4343 {
4344 	struct device *dev = &ub->cdev_dev;
4345 	int minor = ub->ub_number;
4346 	int ret;
4347 
4348 	dev->parent = ublk_misc.this_device;
4349 	dev->devt = MKDEV(MAJOR(ublk_chr_devt), minor);
4350 	dev->class = &ublk_chr_class;
4351 	dev->release = ublk_cdev_rel;
4352 	device_initialize(dev);
4353 
4354 	ret = dev_set_name(dev, "ublkc%d", minor);
4355 	if (ret)
4356 		goto fail;
4357 
4358 	if (ublk_dev_support_batch_io(ub))
4359 		cdev_init(&ub->cdev, &ublk_ch_batch_io_fops);
4360 	else
4361 		cdev_init(&ub->cdev, &ublk_ch_fops);
4362 	ret = cdev_device_add(&ub->cdev, dev);
4363 	if (ret)
4364 		goto fail;
4365 
4366 	if (ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV)
4367 		unprivileged_ublks_added++;
4368 	return 0;
4369  fail:
4370 	put_device(dev);
4371 	return ret;
4372 }
4373 
4374 /* align max io buffer size with PAGE_SIZE */
4375 static void ublk_align_max_io_size(struct ublk_device *ub)
4376 {
4377 	unsigned int max_io_bytes = ub->dev_info.max_io_buf_bytes;
4378 
4379 	ub->dev_info.max_io_buf_bytes =
4380 		round_down(max_io_bytes, PAGE_SIZE);
4381 }
4382 
4383 static int ublk_add_tag_set(struct ublk_device *ub)
4384 {
4385 	if (ublk_dev_support_batch_io(ub))
4386 		ub->tag_set.ops = &ublk_batch_mq_ops;
4387 	else
4388 		ub->tag_set.ops = &ublk_mq_ops;
4389 	ub->tag_set.nr_hw_queues = ub->dev_info.nr_hw_queues;
4390 	ub->tag_set.queue_depth = ub->dev_info.queue_depth;
4391 	ub->tag_set.numa_node = NUMA_NO_NODE;
4392 	ub->tag_set.driver_data = ub;
4393 	return blk_mq_alloc_tag_set(&ub->tag_set);
4394 }
4395 
4396 static void ublk_remove(struct ublk_device *ub)
4397 {
4398 	bool unprivileged;
4399 
4400 	ublk_stop_dev(ub);
4401 	cdev_device_del(&ub->cdev, &ub->cdev_dev);
4402 	unprivileged = ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV;
4403 	ublk_put_device(ub);
4404 
4405 	if (unprivileged)
4406 		unprivileged_ublks_added--;
4407 }
4408 
4409 static struct ublk_device *ublk_get_device_from_id(int idx)
4410 {
4411 	struct ublk_device *ub = NULL;
4412 
4413 	if (idx < 0)
4414 		return NULL;
4415 
4416 	spin_lock(&ublk_idr_lock);
4417 	ub = idr_find(&ublk_index_idr, idx);
4418 	if (ub)
4419 		ub = ublk_get_device(ub);
4420 	spin_unlock(&ublk_idr_lock);
4421 
4422 	return ub;
4423 }
4424 
4425 static bool ublk_validate_user_pid(struct ublk_device *ub, pid_t ublksrv_pid)
4426 {
4427 	rcu_read_lock();
4428 	ublksrv_pid = pid_nr(find_vpid(ublksrv_pid));
4429 	rcu_read_unlock();
4430 
4431 	return ub->ublksrv_tgid == ublksrv_pid;
4432 }
4433 
4434 /*
4435  * Wait until all queues have fetched their I/O commands, and return with
4436  * ub->mutex held and readiness guaranteed: then every queue's ->canceling
4437  * is cleared. Ready may regress between wakeup and mutex_lock() (F_BATCH
4438  * UNPREP, daemon death), so re-check it under the mutex and wait again.
4439  */
4440 static int ublk_wait_dev_ready_and_lock(struct ublk_device *ub)
4441 {
4442 	while (true) {
4443 		if (wait_var_event_interruptible(&ub->nr_queue_ready,
4444 						 ublk_dev_ready(ub)))
4445 			return -EINTR;
4446 
4447 		mutex_lock(&ub->mutex);
4448 		if (ublk_dev_ready(ub))
4449 			return 0;
4450 		mutex_unlock(&ub->mutex);
4451 	}
4452 }
4453 
4454 static int ublk_ctrl_start_dev(struct ublk_device *ub,
4455 		const struct ublksrv_ctrl_cmd *header)
4456 {
4457 	const struct ublk_param_basic *p = &ub->params.basic;
4458 	int ublksrv_pid = (int)header->data[0];
4459 	struct queue_limits lim = {
4460 		.logical_block_size	= 1 << p->logical_bs_shift,
4461 		.physical_block_size	= 1 << p->physical_bs_shift,
4462 		.io_min			= 1 << p->io_min_shift,
4463 		.io_opt			= 1 << p->io_opt_shift,
4464 		.max_hw_sectors		= p->max_sectors,
4465 		.chunk_sectors		= p->chunk_sectors,
4466 		.virt_boundary_mask	= p->virt_boundary_mask,
4467 		.max_segments		= USHRT_MAX,
4468 		.max_segment_size	= UINT_MAX,
4469 		.dma_alignment		= 3,
4470 	};
4471 	struct gendisk *disk;
4472 	int ret = -EINVAL;
4473 
4474 	if (ublksrv_pid <= 0)
4475 		return -EINVAL;
4476 	if (!(ub->params.types & UBLK_PARAM_TYPE_BASIC))
4477 		return -EINVAL;
4478 
4479 	if (ub->params.types & UBLK_PARAM_TYPE_DISCARD) {
4480 		const struct ublk_param_discard *pd = &ub->params.discard;
4481 
4482 		lim.discard_alignment = pd->discard_alignment;
4483 		lim.discard_granularity = pd->discard_granularity;
4484 		lim.max_hw_discard_sectors = pd->max_discard_sectors;
4485 		lim.max_write_zeroes_sectors = pd->max_write_zeroes_sectors;
4486 		lim.max_discard_segments = pd->max_discard_segments;
4487 	}
4488 
4489 	if (ub->params.types & UBLK_PARAM_TYPE_ZONED) {
4490 		const struct ublk_param_zoned *p = &ub->params.zoned;
4491 
4492 		if (!IS_ENABLED(CONFIG_BLK_DEV_ZONED))
4493 			return -EOPNOTSUPP;
4494 
4495 		lim.features |= BLK_FEAT_ZONED;
4496 		lim.max_active_zones = p->max_active_zones;
4497 		lim.max_open_zones =  p->max_open_zones;
4498 		lim.max_hw_zone_append_sectors = p->max_zone_append_sectors;
4499 	}
4500 
4501 	if (ub->params.basic.attrs & UBLK_ATTR_VOLATILE_CACHE) {
4502 		lim.features |= BLK_FEAT_WRITE_CACHE;
4503 		if (ub->params.basic.attrs & UBLK_ATTR_FUA)
4504 			lim.features |= BLK_FEAT_FUA;
4505 	}
4506 
4507 	if (ub->params.basic.attrs & UBLK_ATTR_ROTATIONAL)
4508 		lim.features |= BLK_FEAT_ROTATIONAL;
4509 
4510 	if (ub->params.types & UBLK_PARAM_TYPE_DMA_ALIGN)
4511 		lim.dma_alignment = ub->params.dma.alignment;
4512 
4513 	if (ub->params.types & UBLK_PARAM_TYPE_SEGMENT) {
4514 		lim.seg_boundary_mask = ub->params.seg.seg_boundary_mask;
4515 		lim.max_segment_size = ub->params.seg.max_segment_size;
4516 		lim.max_segments = ub->params.seg.max_segments;
4517 	}
4518 
4519 	if (ub->params.types & UBLK_PARAM_TYPE_INTEGRITY) {
4520 		const struct ublk_param_integrity *p = &ub->params.integrity;
4521 		int pi_tuple_size = ublk_integrity_pi_tuple_size(p->csum_type);
4522 
4523 		lim.max_integrity_segments =
4524 			p->max_integrity_segments ?: USHRT_MAX;
4525 		lim.integrity = (struct blk_integrity) {
4526 			.flags = ublk_integrity_flags(p->flags),
4527 			.csum_type = ublk_integrity_csum_type(p->csum_type),
4528 			.metadata_size = p->metadata_size,
4529 			.pi_offset = p->pi_offset,
4530 			.interval_exp = p->interval_exp,
4531 			.tag_size = p->tag_size,
4532 			.pi_tuple_size = pi_tuple_size,
4533 		};
4534 	}
4535 
4536 	if (ublk_wait_dev_ready_and_lock(ub))
4537 		return -EINTR;
4538 
4539 	if (!ublk_validate_user_pid(ub, ublksrv_pid)) {
4540 		ret = -EINVAL;
4541 		goto out_unlock;
4542 	}
4543 	if (ub->dev_info.state == UBLK_S_DEV_LIVE ||
4544 	    test_bit(UB_STATE_USED, &ub->state)) {
4545 		ret = -EEXIST;
4546 		goto out_unlock;
4547 	}
4548 
4549 	disk = blk_mq_alloc_disk(&ub->tag_set, &lim, NULL);
4550 	if (IS_ERR(disk)) {
4551 		ret = PTR_ERR(disk);
4552 		goto out_unlock;
4553 	}
4554 	sprintf(disk->disk_name, "ublkb%d", ub->ub_number);
4555 	disk->fops = &ub_fops;
4556 	disk->private_data = ub;
4557 
4558 	ub->dev_info.ublksrv_pid = ub->ublksrv_tgid;
4559 	ub->ub_disk = disk;
4560 
4561 	ublk_apply_params(ub);
4562 
4563 	/*
4564 	 * Suppress partition scan to avoid potential IO hang.
4565 	 *
4566 	 * If ublk server error occurs during partition scan, the IO may
4567 	 * wait while holding ub->mutex, which can deadlock with other
4568 	 * operations that need the mutex. Defer partition scan to async
4569 	 * work.
4570 	 * For unprivileged daemons, keep GD_SUPPRESS_PART_SCAN set
4571 	 * permanently.
4572 	 */
4573 	set_bit(GD_SUPPRESS_PART_SCAN, &disk->state);
4574 
4575 	ublk_get_device(ub);
4576 	ub->dev_info.state = UBLK_S_DEV_LIVE;
4577 
4578 	if (ublk_dev_is_zoned(ub)) {
4579 		ret = ublk_revalidate_disk_zones(ub);
4580 		if (ret)
4581 			goto out_put_cdev;
4582 	}
4583 
4584 	ret = add_disk(disk);
4585 	if (ret)
4586 		goto out_put_cdev;
4587 
4588 	set_bit(UB_STATE_USED, &ub->state);
4589 
4590 	/* Skip partition scan if disabled by user */
4591 	if (ub->dev_info.flags & UBLK_F_NO_AUTO_PART_SCAN) {
4592 		/* Not clear for unprivileged daemons, see comment above */
4593 		if (!ub->unprivileged_daemons)
4594 			clear_bit(GD_SUPPRESS_PART_SCAN, &disk->state);
4595 	} else {
4596 		/* Schedule async partition scan for trusted daemons */
4597 		if (!ub->unprivileged_daemons)
4598 			schedule_work(&ub->partition_scan_work);
4599 	}
4600 
4601 out_put_cdev:
4602 	if (ret) {
4603 		ublk_detach_disk(ub);
4604 		ublk_put_device(ub);
4605 	}
4606 	if (ret)
4607 		put_disk(disk);
4608 out_unlock:
4609 	mutex_unlock(&ub->mutex);
4610 	return ret;
4611 }
4612 
4613 static int ublk_ctrl_get_queue_affinity(struct ublk_device *ub,
4614 		const struct ublksrv_ctrl_cmd *header)
4615 {
4616 	void __user *argp = (void __user *)(unsigned long)header->addr;
4617 	cpumask_var_t cpumask;
4618 	unsigned long queue;
4619 	unsigned int retlen;
4620 	unsigned int i;
4621 	int ret;
4622 
4623 	if (header->len * BITS_PER_BYTE < nr_cpu_ids)
4624 		return -EINVAL;
4625 	if (header->len & (sizeof(unsigned long)-1))
4626 		return -EINVAL;
4627 	if (!header->addr)
4628 		return -EINVAL;
4629 
4630 	queue = header->data[0];
4631 	if (queue >= ub->dev_info.nr_hw_queues)
4632 		return -EINVAL;
4633 
4634 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
4635 		return -ENOMEM;
4636 
4637 	for_each_possible_cpu(i) {
4638 		if (ub->tag_set.map[HCTX_TYPE_DEFAULT].mq_map[i] == queue)
4639 			cpumask_set_cpu(i, cpumask);
4640 	}
4641 
4642 	ret = -EFAULT;
4643 	retlen = min_t(unsigned short, header->len, cpumask_size());
4644 	if (copy_to_user(argp, cpumask, retlen))
4645 		goto out_free_cpumask;
4646 	if (retlen != header->len &&
4647 	    clear_user(argp + retlen, header->len - retlen))
4648 		goto out_free_cpumask;
4649 
4650 	ret = 0;
4651 out_free_cpumask:
4652 	free_cpumask_var(cpumask);
4653 	return ret;
4654 }
4655 
4656 static inline void ublk_dump_dev_info(struct ublksrv_ctrl_dev_info *info)
4657 {
4658 	pr_devel("%s: dev id %d flags %llx\n", __func__,
4659 			info->dev_id, info->flags);
4660 	pr_devel("\t nr_hw_queues %d queue_depth %d\n",
4661 			info->nr_hw_queues, info->queue_depth);
4662 }
4663 
4664 static int ublk_ctrl_add_dev(const struct ublksrv_ctrl_cmd *header)
4665 {
4666 	void __user *argp = (void __user *)(unsigned long)header->addr;
4667 	struct ublksrv_ctrl_dev_info info;
4668 	struct ublk_device *ub;
4669 	int ret = -EINVAL;
4670 
4671 	if (header->len < sizeof(info) || !header->addr)
4672 		return -EINVAL;
4673 	if (header->queue_id != (u16)-1) {
4674 		pr_warn("%s: queue_id is wrong %x\n",
4675 			__func__, header->queue_id);
4676 		return -EINVAL;
4677 	}
4678 
4679 	if (copy_from_user(&info, argp, sizeof(info)))
4680 		return -EFAULT;
4681 
4682 	if (info.queue_depth > UBLK_MAX_QUEUE_DEPTH || !info.queue_depth ||
4683 	    info.nr_hw_queues > UBLK_MAX_NR_QUEUES || !info.nr_hw_queues)
4684 		return -EINVAL;
4685 
4686 	if (capable(CAP_SYS_ADMIN))
4687 		info.flags &= ~UBLK_F_UNPRIVILEGED_DEV;
4688 	else if (!(info.flags & UBLK_F_UNPRIVILEGED_DEV))
4689 		return -EPERM;
4690 
4691 	/* forbid nonsense combinations of recovery flags */
4692 	switch (info.flags & UBLK_F_ALL_RECOVERY_FLAGS) {
4693 	case 0:
4694 	case UBLK_F_USER_RECOVERY:
4695 	case (UBLK_F_USER_RECOVERY | UBLK_F_USER_RECOVERY_REISSUE):
4696 	case (UBLK_F_USER_RECOVERY | UBLK_F_USER_RECOVERY_FAIL_IO):
4697 		break;
4698 	default:
4699 		pr_warn("%s: invalid recovery flags %llx\n", __func__,
4700 			info.flags & UBLK_F_ALL_RECOVERY_FLAGS);
4701 		return -EINVAL;
4702 	}
4703 
4704 	if ((info.flags & UBLK_F_QUIESCE) && !(info.flags & UBLK_F_USER_RECOVERY)) {
4705 		pr_warn("UBLK_F_QUIESCE requires UBLK_F_USER_RECOVERY\n");
4706 		return -EINVAL;
4707 	}
4708 
4709 	/*
4710 	 * unprivileged device can't be trusted, but RECOVERY and
4711 	 * RECOVERY_REISSUE still may hang error handling, so can't
4712 	 * support recovery features for unprivileged ublk now
4713 	 *
4714 	 * TODO: provide forward progress for RECOVERY handler, so that
4715 	 * unprivileged device can benefit from it
4716 	 */
4717 	if (info.flags & UBLK_F_UNPRIVILEGED_DEV) {
4718 		info.flags &= ~(UBLK_F_USER_RECOVERY_REISSUE |
4719 				UBLK_F_USER_RECOVERY);
4720 
4721 		/*
4722 		 * For USER_COPY, we depends on userspace to fill request
4723 		 * buffer by pwrite() to ublk char device, which can't be
4724 		 * used for unprivileged device
4725 		 *
4726 		 * Same with zero copy or auto buffer register.
4727 		 */
4728 		if (info.flags & (UBLK_F_USER_COPY | UBLK_F_SUPPORT_ZERO_COPY |
4729 					UBLK_F_AUTO_BUF_REG))
4730 			return -EINVAL;
4731 	}
4732 
4733 	/* User copy is required to access integrity buffer */
4734 	if (info.flags & UBLK_F_INTEGRITY && !(info.flags & UBLK_F_USER_COPY))
4735 		return -EINVAL;
4736 
4737 	if (info.flags & UBLK_F_IO_DESC_SIZE) {
4738 		if (info.io_desc_size < sizeof(struct ublksrv_io_desc) ||
4739 		    info.io_desc_size % _Alignof(struct ublksrv_io_desc) ||
4740 		    info.io_desc_size > UBLK_MAX_IO_DESC_SIZE)
4741 			return -EINVAL;
4742 	} else {
4743 		info.io_desc_size = sizeof(struct ublksrv_io_desc);
4744 	}
4745 
4746 	/* the created device is always owned by current user */
4747 	ublk_store_owner_uid_gid(&info.owner_uid, &info.owner_gid);
4748 
4749 	if (header->dev_id != info.dev_id) {
4750 		pr_warn("%s: dev id not match %u %u\n",
4751 			__func__, header->dev_id, info.dev_id);
4752 		return -EINVAL;
4753 	}
4754 
4755 	if (header->dev_id != U32_MAX && header->dev_id >= UBLK_MAX_UBLKS) {
4756 		pr_warn("%s: dev id is too large. Max supported is %d\n",
4757 			__func__, UBLK_MAX_UBLKS - 1);
4758 		return -EINVAL;
4759 	}
4760 
4761 	ublk_dump_dev_info(&info);
4762 
4763 	ret = mutex_lock_killable(&ublk_ctl_mutex);
4764 	if (ret)
4765 		return ret;
4766 
4767 	ret = -EACCES;
4768 	if ((info.flags & UBLK_F_UNPRIVILEGED_DEV) &&
4769 	    unprivileged_ublks_added >= unprivileged_ublks_max)
4770 		goto out_unlock;
4771 
4772 	ret = -ENOMEM;
4773 	ub = kzalloc_flex(*ub, queues, info.nr_hw_queues);
4774 	if (!ub)
4775 		goto out_unlock;
4776 	mutex_init(&ub->mutex);
4777 	spin_lock_init(&ub->lock);
4778 	mutex_init(&ub->cancel_mutex);
4779 	mt_init(&ub->buf_tree);
4780 	ida_init(&ub->buf_ida);
4781 	INIT_WORK(&ub->partition_scan_work, ublk_partition_scan_work);
4782 
4783 	ret = ublk_alloc_dev_number(ub, header->dev_id);
4784 	if (ret < 0)
4785 		goto out_free_ub;
4786 
4787 	memcpy(&ub->dev_info, &info, sizeof(info));
4788 
4789 	/* update device id */
4790 	ub->dev_info.dev_id = ub->ub_number;
4791 
4792 	/*
4793 	 * ->state and ->ublksrv_pid are owned by the driver and only read back
4794 	 * by userspace, but they come from the copied-in dev_info, so reset
4795 	 * them. Otherwise a device added with ->state != DEAD looks live while
4796 	 * ->ub_disk is still NULL.
4797 	 */
4798 	ub->dev_info.state = UBLK_S_DEV_DEAD;
4799 	ub->dev_info.ublksrv_pid = -1;
4800 
4801 	/*
4802 	 * 64bit flags will be copied back to userspace as feature
4803 	 * negotiation result, so have to clear flags which driver
4804 	 * doesn't support yet, then userspace can get correct flags
4805 	 * (features) to handle.
4806 	 */
4807 	ub->dev_info.flags &= UBLK_F_ALL;
4808 
4809 	ub->dev_info.flags |= UBLK_F_CMD_IOCTL_ENCODE |
4810 		UBLK_F_URING_CMD_COMP_IN_TASK |
4811 		UBLK_F_PER_IO_DAEMON |
4812 		UBLK_F_BUF_REG_OFF_DAEMON |
4813 		UBLK_F_SAFE_STOP_DEV;
4814 
4815 	/* So far, UBLK_F_PER_IO_DAEMON won't be exposed for BATCH_IO */
4816 	if (ublk_dev_support_batch_io(ub))
4817 		ub->dev_info.flags &= ~UBLK_F_PER_IO_DAEMON;
4818 
4819 	/* GET_DATA isn't needed any more with USER_COPY or ZERO COPY */
4820 	if (ub->dev_info.flags & (UBLK_F_USER_COPY | UBLK_F_SUPPORT_ZERO_COPY |
4821 				UBLK_F_AUTO_BUF_REG))
4822 		ub->dev_info.flags &= ~UBLK_F_NEED_GET_DATA;
4823 
4824 	/* UBLK_F_BATCH_IO doesn't support GET_DATA */
4825 	if (ublk_dev_support_batch_io(ub))
4826 		ub->dev_info.flags &= ~UBLK_F_NEED_GET_DATA;
4827 
4828 	/*
4829 	 * Zoned storage support requires reuse `ublksrv_io_cmd->addr` for
4830 	 * returning write_append_lba, which is only allowed in case of
4831 	 * user copy or zero copy
4832 	 */
4833 	if (ublk_dev_is_zoned(ub) &&
4834 	    (!IS_ENABLED(CONFIG_BLK_DEV_ZONED) || !(ub->dev_info.flags &
4835 	     (UBLK_F_USER_COPY | UBLK_F_SUPPORT_ZERO_COPY)))) {
4836 		ret = -EINVAL;
4837 		goto out_free_dev_number;
4838 	}
4839 
4840 	ub->dev_info.nr_hw_queues = min_t(unsigned int,
4841 			ub->dev_info.nr_hw_queues, nr_cpu_ids);
4842 	ublk_align_max_io_size(ub);
4843 
4844 	ret = ublk_add_tag_set(ub);
4845 	if (ret)
4846 		goto out_free_dev_number;
4847 
4848 	ret = ublk_init_queues(ub);
4849 	if (ret)
4850 		goto out_free_tag_set;
4851 
4852 	ret = -EFAULT;
4853 	if (copy_to_user(argp, &ub->dev_info, sizeof(info)))
4854 		goto out_deinit_queues;
4855 
4856 	/*
4857 	 * Add the char dev so that ublksrv daemon can be setup.
4858 	 * ublk_add_chdev() will cleanup everything if it fails.
4859 	 */
4860 	ret = ublk_add_chdev(ub);
4861 	goto out_unlock;
4862 
4863 out_deinit_queues:
4864 	ublk_deinit_queues(ub);
4865 out_free_tag_set:
4866 	blk_mq_free_tag_set(&ub->tag_set);
4867 out_free_dev_number:
4868 	ublk_free_dev_number(ub);
4869 out_free_ub:
4870 	mutex_destroy(&ub->mutex);
4871 	mutex_destroy(&ub->cancel_mutex);
4872 	kfree(ub);
4873 out_unlock:
4874 	mutex_unlock(&ublk_ctl_mutex);
4875 	return ret;
4876 }
4877 
4878 static inline bool ublk_idr_freed(int id)
4879 {
4880 	void *ptr;
4881 
4882 	spin_lock(&ublk_idr_lock);
4883 	ptr = idr_find(&ublk_index_idr, id);
4884 	spin_unlock(&ublk_idr_lock);
4885 
4886 	return ptr == NULL;
4887 }
4888 
4889 static int ublk_ctrl_del_dev(struct ublk_device **p_ub, bool wait)
4890 {
4891 	struct ublk_device *ub = *p_ub;
4892 	int idx = ub->ub_number;
4893 	int ret;
4894 
4895 	ret = mutex_lock_killable(&ublk_ctl_mutex);
4896 	if (ret)
4897 		return ret;
4898 
4899 	if (!test_bit(UB_STATE_DELETED, &ub->state)) {
4900 		ublk_remove(ub);
4901 		set_bit(UB_STATE_DELETED, &ub->state);
4902 	}
4903 
4904 	/* Mark the reference as consumed */
4905 	*p_ub = NULL;
4906 	ublk_put_device(ub);
4907 	mutex_unlock(&ublk_ctl_mutex);
4908 
4909 	/*
4910 	 * Wait until the idr is removed, then it can be reused after
4911 	 * DEL_DEV command is returned.
4912 	 *
4913 	 * If we returns because of user interrupt, future delete command
4914 	 * may come:
4915 	 *
4916 	 * - the device number isn't freed, this device won't or needn't
4917 	 *   be deleted again, since UB_STATE_DELETED is set, and device
4918 	 *   will be released after the last reference is dropped
4919 	 *
4920 	 * - the device number is freed already, we will not find this
4921 	 *   device via ublk_get_device_from_id()
4922 	 */
4923 	if (wait && wait_event_interruptible(ublk_idr_wq, ublk_idr_freed(idx)))
4924 		return -EINTR;
4925 	return 0;
4926 }
4927 
4928 static inline void ublk_ctrl_cmd_dump(u32 cmd_op,
4929 				      const struct ublksrv_ctrl_cmd *header)
4930 {
4931 	pr_devel("%s: cmd_op %x, dev id %d qid %d data %llx buf %llx len %u\n",
4932 			__func__, cmd_op, header->dev_id, header->queue_id,
4933 			header->data[0], header->addr, header->len);
4934 }
4935 
4936 static void ublk_ctrl_stop_dev(struct ublk_device *ub)
4937 {
4938 	ublk_stop_dev(ub);
4939 }
4940 
4941 static int ublk_ctrl_try_stop_dev(struct ublk_device *ub)
4942 {
4943 	struct gendisk *disk;
4944 	int ret = 0;
4945 
4946 	disk = ublk_get_disk(ub);
4947 	if (!disk)
4948 		return -ENODEV;
4949 
4950 	mutex_lock(&disk->open_mutex);
4951 	if (disk_openers(disk) > 0) {
4952 		ret = -EBUSY;
4953 		goto unlock;
4954 	}
4955 	ub->block_open = true;
4956 	/* release open_mutex as del_gendisk() will reacquire it */
4957 	mutex_unlock(&disk->open_mutex);
4958 
4959 	ublk_ctrl_stop_dev(ub);
4960 	goto out;
4961 
4962 unlock:
4963 	mutex_unlock(&disk->open_mutex);
4964 out:
4965 	ublk_put_disk(disk);
4966 	return ret;
4967 }
4968 
4969 static int ublk_ctrl_get_dev_info(struct ublk_device *ub,
4970 		const struct ublksrv_ctrl_cmd *header)
4971 {
4972 	struct task_struct *p;
4973 	struct pid *pid;
4974 	struct ublksrv_ctrl_dev_info dev_info;
4975 	pid_t init_ublksrv_tgid = ub->dev_info.ublksrv_pid;
4976 	void __user *argp = (void __user *)(unsigned long)header->addr;
4977 
4978 	if (header->len < sizeof(struct ublksrv_ctrl_dev_info) || !header->addr)
4979 		return -EINVAL;
4980 
4981 	memcpy(&dev_info, &ub->dev_info, sizeof(dev_info));
4982 	dev_info.ublksrv_pid = -1;
4983 
4984 	if (init_ublksrv_tgid > 0) {
4985 		rcu_read_lock();
4986 		pid = find_pid_ns(init_ublksrv_tgid, &init_pid_ns);
4987 		p = pid_task(pid, PIDTYPE_TGID);
4988 		if (p) {
4989 			int vnr = task_tgid_vnr(p);
4990 
4991 			if (vnr)
4992 				dev_info.ublksrv_pid = vnr;
4993 		}
4994 		rcu_read_unlock();
4995 	}
4996 
4997 	if (copy_to_user(argp, &dev_info, sizeof(dev_info)))
4998 		return -EFAULT;
4999 
5000 	return 0;
5001 }
5002 
5003 /* TYPE_DEVT is readonly, so fill it up before returning to userspace */
5004 static void ublk_ctrl_fill_params_devt(struct ublk_device *ub)
5005 {
5006 	ub->params.devt.char_major = MAJOR(ub->cdev_dev.devt);
5007 	ub->params.devt.char_minor = MINOR(ub->cdev_dev.devt);
5008 
5009 	if (ub->ub_disk) {
5010 		ub->params.devt.disk_major = MAJOR(disk_devt(ub->ub_disk));
5011 		ub->params.devt.disk_minor = MINOR(disk_devt(ub->ub_disk));
5012 	} else {
5013 		ub->params.devt.disk_major = 0;
5014 		ub->params.devt.disk_minor = 0;
5015 	}
5016 	ub->params.types |= UBLK_PARAM_TYPE_DEVT;
5017 }
5018 
5019 static int ublk_ctrl_get_params(struct ublk_device *ub,
5020 		const struct ublksrv_ctrl_cmd *header)
5021 {
5022 	void __user *argp = (void __user *)(unsigned long)header->addr;
5023 	struct ublk_params_header ph;
5024 	int ret;
5025 
5026 	if (header->len <= sizeof(ph) || !header->addr)
5027 		return -EINVAL;
5028 
5029 	if (copy_from_user(&ph, argp, sizeof(ph)))
5030 		return -EFAULT;
5031 
5032 	if (ph.len > header->len || !ph.len)
5033 		return -EINVAL;
5034 
5035 	if (ph.len > sizeof(struct ublk_params))
5036 		ph.len = sizeof(struct ublk_params);
5037 
5038 	mutex_lock(&ub->mutex);
5039 	ublk_ctrl_fill_params_devt(ub);
5040 	if (copy_to_user(argp, &ub->params, ph.len))
5041 		ret = -EFAULT;
5042 	else
5043 		ret = 0;
5044 	mutex_unlock(&ub->mutex);
5045 
5046 	return ret;
5047 }
5048 
5049 static int ublk_ctrl_set_params(struct ublk_device *ub,
5050 		const struct ublksrv_ctrl_cmd *header)
5051 {
5052 	void __user *argp = (void __user *)(unsigned long)header->addr;
5053 	struct ublk_params_header ph;
5054 	int ret = -EFAULT;
5055 
5056 	if (header->len <= sizeof(ph) || !header->addr)
5057 		return -EINVAL;
5058 
5059 	if (copy_from_user(&ph, argp, sizeof(ph)))
5060 		return -EFAULT;
5061 
5062 	if (ph.len > header->len || !ph.len || !ph.types)
5063 		return -EINVAL;
5064 
5065 	if (ph.len > sizeof(struct ublk_params))
5066 		ph.len = sizeof(struct ublk_params);
5067 
5068 	mutex_lock(&ub->mutex);
5069 	if (test_bit(UB_STATE_USED, &ub->state)) {
5070 		/*
5071 		 * Parameters can only be changed when device hasn't
5072 		 * been started yet
5073 		 */
5074 		ret = -EACCES;
5075 	} else if (copy_from_user(&ub->params, argp, ph.len)) {
5076 		/* zero out partial copy so no stale params survive */
5077 		memset(&ub->params, 0, sizeof(ub->params));
5078 		ret = -EFAULT;
5079 	} else {
5080 		/* clear all we don't support yet */
5081 		ub->params.types &= UBLK_PARAM_TYPE_ALL;
5082 		ret = ublk_validate_params(ub);
5083 		if (ret)
5084 			memset(&ub->params, 0, sizeof(ub->params));
5085 	}
5086 	mutex_unlock(&ub->mutex);
5087 
5088 	return ret;
5089 }
5090 
5091 static int ublk_ctrl_start_recovery(struct ublk_device *ub)
5092 {
5093 	int ret = -EINVAL;
5094 
5095 	mutex_lock(&ub->mutex);
5096 	if (ublk_nosrv_should_stop_dev(ub))
5097 		goto out_unlock;
5098 	/*
5099 	 * START_RECOVERY is only allowd after:
5100 	 *
5101 	 * (1) UB_STATE_OPEN is not set, which means the dying process is exited
5102 	 *     and related io_uring ctx is freed so file struct of /dev/ublkcX is
5103 	 *     released.
5104 	 *
5105 	 * and one of the following holds
5106 	 *
5107 	 * (2) UBLK_S_DEV_QUIESCED is set, which means the quiesce_work:
5108 	 *     (a)has quiesced request queue
5109 	 *     (b)has requeued every inflight rqs whose io_flags is ACTIVE
5110 	 *     (c)has requeued/aborted every inflight rqs whose io_flags is NOT ACTIVE
5111 	 *     (d)has completed/camceled all ioucmds owned by ther dying process
5112 	 *
5113 	 * (3) UBLK_S_DEV_FAIL_IO is set, which means the queue is not
5114 	 *     quiesced, but all I/O is being immediately errored
5115 	 */
5116 	if (test_bit(UB_STATE_OPEN, &ub->state) || !ublk_dev_in_recoverable_state(ub)) {
5117 		ret = -EBUSY;
5118 		goto out_unlock;
5119 	}
5120 	pr_devel("%s: start recovery for dev id %d\n", __func__, ub->ub_number);
5121 	ret = 0;
5122  out_unlock:
5123 	mutex_unlock(&ub->mutex);
5124 	return ret;
5125 }
5126 
5127 static int ublk_ctrl_end_recovery(struct ublk_device *ub,
5128 		const struct ublksrv_ctrl_cmd *header)
5129 {
5130 	int ublksrv_pid = (int)header->data[0];
5131 	int ret = -EINVAL;
5132 
5133 	pr_devel("%s: Waiting for all FETCH_REQs, dev id %d...\n", __func__,
5134 		 header->dev_id);
5135 
5136 	if (ublk_wait_dev_ready_and_lock(ub))
5137 		return -EINTR;
5138 
5139 	pr_devel("%s: All FETCH_REQs received, dev id %d\n", __func__,
5140 		 header->dev_id);
5141 
5142 	if (!ublk_validate_user_pid(ub, ublksrv_pid)) {
5143 		ret = -EINVAL;
5144 		goto out_unlock;
5145 	}
5146 
5147 	if (ublk_nosrv_should_stop_dev(ub))
5148 		goto out_unlock;
5149 
5150 	if (!ublk_dev_in_recoverable_state(ub)) {
5151 		ret = -EBUSY;
5152 		goto out_unlock;
5153 	}
5154 	ub->dev_info.ublksrv_pid = ub->ublksrv_tgid;
5155 	ub->dev_info.state = UBLK_S_DEV_LIVE;
5156 	pr_devel("%s: new ublksrv_pid %d, dev id %d\n",
5157 			__func__, ublksrv_pid, header->dev_id);
5158 	blk_mq_kick_requeue_list(ub->ub_disk->queue);
5159 	ret = 0;
5160  out_unlock:
5161 	mutex_unlock(&ub->mutex);
5162 	return ret;
5163 }
5164 
5165 static int ublk_ctrl_get_features(const struct ublksrv_ctrl_cmd *header)
5166 {
5167 	void __user *argp = (void __user *)(unsigned long)header->addr;
5168 	u64 features = UBLK_F_ALL;
5169 
5170 	if (header->len != UBLK_FEATURES_LEN || !header->addr)
5171 		return -EINVAL;
5172 
5173 	if (copy_to_user(argp, &features, UBLK_FEATURES_LEN))
5174 		return -EFAULT;
5175 
5176 	return 0;
5177 }
5178 
5179 static int ublk_ctrl_set_size(struct ublk_device *ub, const struct ublksrv_ctrl_cmd *header)
5180 {
5181 	struct ublk_param_basic *p = &ub->params.basic;
5182 	u64 new_size = header->data[0];
5183 	int ret = 0;
5184 
5185 	mutex_lock(&ub->mutex);
5186 	if (!ub->ub_disk) {
5187 		ret = -ENODEV;
5188 		goto out;
5189 	}
5190 	p->dev_sectors = new_size;
5191 	set_capacity_and_notify(ub->ub_disk, p->dev_sectors);
5192 out:
5193 	mutex_unlock(&ub->mutex);
5194 	return ret;
5195 }
5196 
5197 struct count_busy {
5198 	const struct ublk_queue *ubq;
5199 	u16 nr_busy;
5200 };
5201 
5202 static bool ublk_count_busy_req(struct request *rq, void *data)
5203 {
5204 	struct count_busy *idle = data;
5205 
5206 	if (!blk_mq_request_started(rq) && rq->mq_hctx->driver_data == idle->ubq)
5207 		idle->nr_busy += 1;
5208 	return true;
5209 }
5210 
5211 /* uring_cmd is guaranteed to be active if the associated request is idle */
5212 static bool ubq_has_idle_io(const struct ublk_queue *ubq)
5213 {
5214 	struct count_busy data = {
5215 		.ubq = ubq,
5216 	};
5217 
5218 	blk_mq_tagset_busy_iter(&ubq->dev->tag_set, ublk_count_busy_req, &data);
5219 	return data.nr_busy < ubq->q_depth;
5220 }
5221 
5222 /* Wait until each hw queue has at least one idle IO */
5223 static int ublk_wait_for_idle_io(struct ublk_device *ub,
5224 				 unsigned int timeout_ms)
5225 {
5226 	unsigned int elapsed = 0;
5227 	int ret;
5228 
5229 	/*
5230 	 * For UBLK_F_BATCH_IO ublk server can get notified with existing
5231 	 * or new fetch command, so needn't wait any more
5232 	 */
5233 	if (ublk_dev_support_batch_io(ub))
5234 		return 0;
5235 
5236 	while (elapsed < timeout_ms && !signal_pending(current)) {
5237 		u16 i, queues_cancelable = 0;
5238 
5239 		for (i = 0; i < ub->dev_info.nr_hw_queues; i++) {
5240 			struct ublk_queue *ubq = ublk_get_queue(ub, i);
5241 
5242 			queues_cancelable += !!ubq_has_idle_io(ubq);
5243 		}
5244 
5245 		/*
5246 		 * Each queue needs at least one active command for
5247 		 * notifying ublk server
5248 		 */
5249 		if (queues_cancelable == ub->dev_info.nr_hw_queues)
5250 			break;
5251 
5252 		msleep(UBLK_REQUEUE_DELAY_MS);
5253 		elapsed += UBLK_REQUEUE_DELAY_MS;
5254 	}
5255 
5256 	if (signal_pending(current))
5257 		ret = -EINTR;
5258 	else if (elapsed >= timeout_ms)
5259 		ret = -EBUSY;
5260 	else
5261 		ret = 0;
5262 
5263 	return ret;
5264 }
5265 
5266 static int ublk_ctrl_quiesce_dev(struct ublk_device *ub,
5267 				 const struct ublksrv_ctrl_cmd *header)
5268 {
5269 	/* zero means wait forever */
5270 	u64 timeout_ms = header->data[0];
5271 	struct gendisk *disk;
5272 	int ret = -ENODEV;
5273 
5274 	if (!(ub->dev_info.flags & UBLK_F_QUIESCE))
5275 		return -EOPNOTSUPP;
5276 
5277 	mutex_lock(&ub->mutex);
5278 	disk = ublk_get_disk(ub);
5279 	if (!disk)
5280 		goto unlock;
5281 	if (ub->dev_info.state == UBLK_S_DEV_DEAD)
5282 		goto put_disk;
5283 
5284 	ret = 0;
5285 	/* already in expected state */
5286 	if (ub->dev_info.state != UBLK_S_DEV_LIVE)
5287 		goto put_disk;
5288 
5289 	/* Mark the device as canceling */
5290 	mutex_lock(&ub->cancel_mutex);
5291 	blk_mq_quiesce_queue(disk->queue);
5292 	ublk_set_canceling(ub, true);
5293 	blk_mq_unquiesce_queue(disk->queue);
5294 	mutex_unlock(&ub->cancel_mutex);
5295 
5296 	if (!timeout_ms)
5297 		timeout_ms = UINT_MAX;
5298 	ret = ublk_wait_for_idle_io(ub, timeout_ms);
5299 
5300 put_disk:
5301 	ublk_put_disk(disk);
5302 unlock:
5303 	mutex_unlock(&ub->mutex);
5304 
5305 	/* Cancel pending uring_cmd */
5306 	if (!ret)
5307 		ublk_cancel_dev(ub);
5308 	return ret;
5309 }
5310 
5311 /*
5312  * All control commands are sent via /dev/ublk-control, so we have to check
5313  * the destination device's permission
5314  */
5315 static int ublk_char_dev_permission(struct ublk_device *ub,
5316 		const char *dev_path, int mask)
5317 {
5318 	int err;
5319 	struct path path;
5320 	struct kstat stat;
5321 
5322 	err = kern_path(dev_path, LOOKUP_FOLLOW, &path);
5323 	if (err)
5324 		return err;
5325 
5326 	err = vfs_getattr(&path, &stat, STATX_TYPE, AT_STATX_SYNC_AS_STAT);
5327 	if (err)
5328 		goto exit;
5329 
5330 	err = -EPERM;
5331 	if (stat.rdev != ub->cdev_dev.devt || !S_ISCHR(stat.mode))
5332 		goto exit;
5333 
5334 	err = inode_permission(&nop_mnt_idmap,
5335 			d_backing_inode(path.dentry), mask);
5336 exit:
5337 	path_put(&path);
5338 	return err;
5339 }
5340 
5341 /*
5342  * Lock for maple tree modification: acquire ub->mutex, then freeze queue
5343  * if device is started. If device is not yet started, only mutex is
5344  * needed since no I/O path can access the tree.
5345  *
5346  * This ordering (mutex -> freeze) is safe because ublk_stop_dev_unlocked()
5347  * already holds ub->mutex when calling del_gendisk() which freezes the queue.
5348 */
5349 static unsigned int ublk_lock_buf_tree(struct ublk_device *ub)
5350 {
5351 	unsigned int memflags = 0;
5352 
5353 	mutex_lock(&ub->mutex);
5354 	if (ub->ub_disk)
5355 		memflags = blk_mq_freeze_queue(ub->ub_disk->queue);
5356 
5357 	return memflags;
5358 }
5359 
5360 static void ublk_unlock_buf_tree(struct ublk_device *ub, unsigned int memflags)
5361 {
5362 	if (ub->ub_disk)
5363 		blk_mq_unfreeze_queue(ub->ub_disk->queue, memflags);
5364 	mutex_unlock(&ub->mutex);
5365 }
5366 
5367 /* Erase coalesced PFN ranges from the maple tree matching buf_index */
5368 static void ublk_buf_erase_ranges(struct ublk_device *ub, int buf_index)
5369 {
5370 	MA_STATE(mas, &ub->buf_tree, 0, ULONG_MAX);
5371 	struct ublk_buf_range *range;
5372 
5373 	mas_lock(&mas);
5374 	mas_for_each(&mas, range, ULONG_MAX) {
5375 		if (range->buf_index == buf_index) {
5376 			mas_erase(&mas);
5377 			kfree(range);
5378 		}
5379 	}
5380 	mas_unlock(&mas);
5381 }
5382 
5383 static int __ublk_ctrl_reg_buf(struct ublk_device *ub,
5384 			       struct page **pages, unsigned long nr_pages,
5385 			       int index, unsigned short flags)
5386 {
5387 	unsigned long i;
5388 	int ret;
5389 
5390 	for (i = 0; i < nr_pages; i++) {
5391 		unsigned long pfn = page_to_pfn(pages[i]);
5392 		unsigned long start = i;
5393 		struct ublk_buf_range *range;
5394 
5395 		/* Find run of consecutive PFNs */
5396 		while (i + 1 < nr_pages &&
5397 		       page_to_pfn(pages[i + 1]) == pfn + (i - start) + 1)
5398 			i++;
5399 
5400 		range = kzalloc_obj(*range);
5401 		if (!range) {
5402 			ret = -ENOMEM;
5403 			goto unwind;
5404 		}
5405 		range->buf_index = index;
5406 		range->flags = flags;
5407 		range->base_offset = start << PAGE_SHIFT;
5408 
5409 		ret = mtree_insert_range(&ub->buf_tree, pfn,
5410 					 pfn + (i - start),
5411 					 range, GFP_KERNEL);
5412 		if (ret) {
5413 			kfree(range);
5414 			goto unwind;
5415 		}
5416 	}
5417 	return 0;
5418 
5419 unwind:
5420 	ublk_buf_erase_ranges(ub, index);
5421 	return ret;
5422 }
5423 
5424 /*
5425  * Register a shared memory buffer for zero-copy I/O.
5426  * Pins pages, builds PFN maple tree, freezes/unfreezes the queue
5427  * internally. Returns buffer index (>= 0) on success.
5428  */
5429 static int ublk_ctrl_reg_buf(struct ublk_device *ub,
5430 			     struct ublksrv_ctrl_cmd *header)
5431 {
5432 	void __user *argp = (void __user *)(unsigned long)header->addr;
5433 	struct ublk_shmem_buf_reg buf_reg;
5434 	unsigned long nr_pages;
5435 	struct page **pages = NULL;
5436 	unsigned int gup_flags;
5437 	unsigned int memflags;
5438 	long pinned;
5439 	int index;
5440 	int ret;
5441 
5442 	if (!ublk_dev_support_shmem_zc(ub))
5443 		return -EOPNOTSUPP;
5444 
5445 	memset(&buf_reg, 0, sizeof(buf_reg));
5446 	if (copy_from_user(&buf_reg, argp,
5447 			   min_t(size_t, header->len, sizeof(buf_reg))))
5448 		return -EFAULT;
5449 
5450 	if (buf_reg.flags & ~UBLK_SHMEM_BUF_READ_ONLY)
5451 		return -EINVAL;
5452 
5453 	if (buf_reg.reserved)
5454 		return -EINVAL;
5455 
5456 	if (!buf_reg.len || buf_reg.len > UBLK_SHMEM_BUF_SIZE_MAX ||
5457 	    !PAGE_ALIGNED(buf_reg.len) || !PAGE_ALIGNED(buf_reg.addr))
5458 		return -EINVAL;
5459 
5460 	nr_pages = buf_reg.len >> PAGE_SHIFT;
5461 
5462 	/* Pin pages before any locks (may sleep) */
5463 	pages = kvmalloc_objs(*pages, nr_pages);
5464 	if (!pages)
5465 		return -ENOMEM;
5466 
5467 	gup_flags = FOLL_LONGTERM;
5468 	if (!(buf_reg.flags & UBLK_SHMEM_BUF_READ_ONLY))
5469 		gup_flags |= FOLL_WRITE;
5470 
5471 	pinned = pin_user_pages_fast(buf_reg.addr, nr_pages, gup_flags, pages);
5472 	if (pinned < 0) {
5473 		ret = pinned;
5474 		goto err_free_pages;
5475 	}
5476 	if (pinned != nr_pages) {
5477 		ret = -EFAULT;
5478 		goto err_unpin;
5479 	}
5480 
5481 	memflags = ublk_lock_buf_tree(ub);
5482 
5483 	index = ida_alloc_max(&ub->buf_ida, USHRT_MAX, GFP_KERNEL);
5484 	if (index < 0) {
5485 		ret = index;
5486 		goto err_unlock;
5487 	}
5488 
5489 	ret = __ublk_ctrl_reg_buf(ub, pages, nr_pages, index, buf_reg.flags);
5490 	if (ret) {
5491 		ida_free(&ub->buf_ida, index);
5492 		goto err_unlock;
5493 	}
5494 
5495 	ublk_unlock_buf_tree(ub, memflags);
5496 	kvfree(pages);
5497 	return index;
5498 
5499 err_unlock:
5500 	ublk_unlock_buf_tree(ub, memflags);
5501 err_unpin:
5502 	unpin_user_pages(pages, pinned);
5503 err_free_pages:
5504 	kvfree(pages);
5505 	return ret;
5506 }
5507 
5508 static void ublk_unpin_range_pages(unsigned long base_pfn,
5509 				   unsigned long nr_pages)
5510 {
5511 #define UBLK_UNPIN_BATCH	32
5512 	struct page *pages[UBLK_UNPIN_BATCH];
5513 	unsigned long off;
5514 
5515 	for (off = 0; off < nr_pages; ) {
5516 		unsigned int batch = min_t(unsigned long,
5517 					   nr_pages - off, UBLK_UNPIN_BATCH);
5518 		unsigned int j;
5519 
5520 		for (j = 0; j < batch; j++)
5521 			pages[j] = pfn_to_page(base_pfn + off + j);
5522 		unpin_user_pages(pages, batch);
5523 		off += batch;
5524 	}
5525 }
5526 
5527 /*
5528  * Inner loop: erase up to UBLK_REMOVE_BATCH matching ranges under
5529  * mas_lock, collecting the page ranges in a fixed-size array. Then
5530  * drop the lock and unpin pages + free ranges outside spinlock context.
5531  *
5532  * Returns true if the tree walk completed, false if more ranges remain.
5533  */
5534 #define UBLK_REMOVE_BATCH	64
5535 
5536 struct ublk_unpin_range {
5537 	unsigned long base_pfn;
5538 	unsigned long nr_pages;
5539 };
5540 
5541 static bool __ublk_shmem_remove_ranges(struct ublk_device *ub,
5542 					int buf_index, int *ret)
5543 {
5544 	MA_STATE(mas, &ub->buf_tree, 0, ULONG_MAX);
5545 	struct ublk_buf_range *range;
5546 	struct ublk_unpin_range to_unpin[UBLK_REMOVE_BATCH];
5547 	unsigned int count = 0;
5548 	unsigned int i;
5549 	bool done = false;
5550 
5551 	mas_lock(&mas);
5552 	mas_for_each(&mas, range, ULONG_MAX) {
5553 		if (buf_index >= 0 && range->buf_index != buf_index)
5554 			continue;
5555 
5556 		*ret = 0;
5557 		to_unpin[count].base_pfn = mas.index;
5558 		to_unpin[count].nr_pages = mas.last - mas.index + 1;
5559 		mas_erase(&mas);
5560 		kfree(range);
5561 		if (++count >= UBLK_REMOVE_BATCH)
5562 			goto unlock;
5563 	}
5564 	done = true;
5565 unlock:
5566 	mas_unlock(&mas);
5567 
5568 	for (i = 0; i < count; i++)
5569 		ublk_unpin_range_pages(to_unpin[i].base_pfn,
5570 				       to_unpin[i].nr_pages);
5571 
5572 	return done;
5573 }
5574 
5575 /*
5576  * Remove ranges from the maple tree matching buf_index, unpin pages
5577  * and free range structs. If buf_index < 0, remove all ranges.
5578  * Processes ranges in batches to avoid holding the maple tree spinlock
5579  * across potentially expensive page unpinning.
5580  */
5581 static int ublk_shmem_remove_ranges(struct ublk_device *ub, int buf_index)
5582 {
5583 	int ret = -ENOENT;
5584 
5585 	while (!__ublk_shmem_remove_ranges(ub, buf_index, &ret))
5586 		cond_resched();
5587 	return ret;
5588 }
5589 
5590 static int ublk_ctrl_unreg_buf(struct ublk_device *ub,
5591 			       struct ublksrv_ctrl_cmd *header)
5592 {
5593 	int index = (int)header->data[0];
5594 	unsigned int memflags;
5595 	int ret;
5596 
5597 	if (!ublk_dev_support_shmem_zc(ub))
5598 		return -EOPNOTSUPP;
5599 
5600 	if (index < 0 || index > USHRT_MAX)
5601 		return -EINVAL;
5602 
5603 	memflags = ublk_lock_buf_tree(ub);
5604 
5605 	ret = ublk_shmem_remove_ranges(ub, index);
5606 	if (!ret)
5607 		ida_free(&ub->buf_ida, index);
5608 
5609 	ublk_unlock_buf_tree(ub, memflags);
5610 	return ret;
5611 }
5612 
5613 static void ublk_buf_cleanup(struct ublk_device *ub)
5614 {
5615 	ublk_shmem_remove_ranges(ub, -1);
5616 	mtree_destroy(&ub->buf_tree);
5617 	ida_destroy(&ub->buf_ida);
5618 }
5619 
5620 /* Check if request pages match a registered shared memory buffer */
5621 static bool ublk_try_buf_match(struct ublk_device *ub,
5622 				   struct request *rq,
5623 				   u32 *buf_idx, u32 *buf_off)
5624 {
5625 	struct req_iterator iter;
5626 	struct bio_vec bv;
5627 	int index = -1;
5628 	unsigned long expected_offset = 0;
5629 	bool first = true;
5630 
5631 	rq_for_each_bvec(bv, rq, iter) {
5632 		unsigned long pfn = page_to_pfn(bv.bv_page);
5633 		unsigned long end_pfn = pfn +
5634 			((bv.bv_offset + bv.bv_len - 1) >> PAGE_SHIFT);
5635 		struct ublk_buf_range *range;
5636 		unsigned long off;
5637 		MA_STATE(mas, &ub->buf_tree, pfn, pfn);
5638 
5639 		range = mas_walk(&mas);
5640 		if (!range)
5641 			return false;
5642 
5643 		/* verify all pages in this bvec fall within the range */
5644 		if (end_pfn > mas.last)
5645 			return false;
5646 
5647 		off = range->base_offset +
5648 			(pfn - mas.index) * PAGE_SIZE + bv.bv_offset;
5649 
5650 		if (first) {
5651 			/* Read-only buffer can't serve READ (kernel writes) */
5652 			if ((range->flags & UBLK_SHMEM_BUF_READ_ONLY) &&
5653 			    req_op(rq) != REQ_OP_WRITE)
5654 				return false;
5655 			index = range->buf_index;
5656 			expected_offset = off;
5657 			*buf_off = off;
5658 			first = false;
5659 		} else {
5660 			if (range->buf_index != index)
5661 				return false;
5662 			if (off != expected_offset)
5663 				return false;
5664 		}
5665 		expected_offset += bv.bv_len;
5666 	}
5667 
5668 	if (first)
5669 		return false;
5670 
5671 	*buf_idx = index;
5672 	return true;
5673 }
5674 
5675 static int ublk_ctrl_uring_cmd_permission(struct ublk_device *ub,
5676 		u32 cmd_op, struct ublksrv_ctrl_cmd *header)
5677 {
5678 	bool unprivileged = ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV;
5679 	void __user *argp = (void __user *)(unsigned long)header->addr;
5680 	char *dev_path = NULL;
5681 	int ret = 0;
5682 	int mask;
5683 
5684 	if (!unprivileged) {
5685 		if (!capable(CAP_SYS_ADMIN))
5686 			return -EPERM;
5687 		/*
5688 		 * The new added command of UBLK_CMD_GET_DEV_INFO2 includes
5689 		 * char_dev_path in payload too, since userspace may not
5690 		 * know if the specified device is created as unprivileged
5691 		 * mode.
5692 		 */
5693 		if (_IOC_NR(cmd_op) != UBLK_CMD_GET_DEV_INFO2)
5694 			return 0;
5695 	}
5696 
5697 	/*
5698 	 * User has to provide the char device path for unprivileged ublk
5699 	 *
5700 	 * header->addr always points to the dev path buffer, and
5701 	 * header->dev_path_len records length of dev path buffer.
5702 	 */
5703 	if (!header->dev_path_len || header->dev_path_len > PATH_MAX)
5704 		return -EINVAL;
5705 
5706 	if (header->len < header->dev_path_len)
5707 		return -EINVAL;
5708 
5709 	dev_path = memdup_user_nul(argp, header->dev_path_len);
5710 	if (IS_ERR(dev_path))
5711 		return PTR_ERR(dev_path);
5712 
5713 	ret = -EINVAL;
5714 	switch (_IOC_NR(cmd_op)) {
5715 	case UBLK_CMD_GET_DEV_INFO:
5716 	case UBLK_CMD_GET_DEV_INFO2:
5717 	case UBLK_CMD_GET_QUEUE_AFFINITY:
5718 	case UBLK_CMD_GET_PARAMS:
5719 	case (_IOC_NR(UBLK_U_CMD_GET_FEATURES)):
5720 		mask = MAY_READ;
5721 		break;
5722 	case UBLK_CMD_START_DEV:
5723 	case UBLK_CMD_STOP_DEV:
5724 	case UBLK_CMD_ADD_DEV:
5725 	case UBLK_CMD_DEL_DEV:
5726 	case UBLK_CMD_SET_PARAMS:
5727 	case UBLK_CMD_START_USER_RECOVERY:
5728 	case UBLK_CMD_END_USER_RECOVERY:
5729 	case UBLK_CMD_UPDATE_SIZE:
5730 	case UBLK_CMD_QUIESCE_DEV:
5731 	case UBLK_CMD_TRY_STOP_DEV:
5732 	case UBLK_CMD_REG_BUF:
5733 	case UBLK_CMD_UNREG_BUF:
5734 		mask = MAY_READ | MAY_WRITE;
5735 		break;
5736 	default:
5737 		goto exit;
5738 	}
5739 
5740 	ret = ublk_char_dev_permission(ub, dev_path, mask);
5741 	if (!ret) {
5742 		header->len -= header->dev_path_len;
5743 		header->addr += header->dev_path_len;
5744 	}
5745 	pr_devel("%s: dev id %d cmd_op %x uid %d gid %d path %s ret %d\n",
5746 			__func__, ub->ub_number, cmd_op,
5747 			ub->dev_info.owner_uid, ub->dev_info.owner_gid,
5748 			dev_path, ret);
5749 exit:
5750 	kfree(dev_path);
5751 	return ret;
5752 }
5753 
5754 static bool ublk_ctrl_uring_cmd_may_sleep(u32 cmd_op)
5755 {
5756 	switch (_IOC_NR(cmd_op)) {
5757 	case UBLK_CMD_GET_QUEUE_AFFINITY:
5758 	case UBLK_CMD_GET_DEV_INFO:
5759 	case UBLK_CMD_GET_DEV_INFO2:
5760 	case _IOC_NR(UBLK_U_CMD_GET_FEATURES):
5761 		return false;
5762 	default:
5763 		return true;
5764 	}
5765 }
5766 
5767 static int ublk_ctrl_uring_cmd(struct io_uring_cmd *cmd,
5768 		unsigned int issue_flags)
5769 {
5770 	/* May point to userspace-mapped memory */
5771 	const struct ublksrv_ctrl_cmd *ub_src = io_uring_sqe128_cmd(cmd->sqe,
5772 								    struct ublksrv_ctrl_cmd);
5773 	struct ublksrv_ctrl_cmd header;
5774 	struct ublk_device *ub = NULL;
5775 	u32 cmd_op = cmd->cmd_op;
5776 	int ret = -EINVAL;
5777 
5778 	if (ublk_ctrl_uring_cmd_may_sleep(cmd_op) &&
5779 	    issue_flags & IO_URING_F_NONBLOCK)
5780 		return -EAGAIN;
5781 
5782 	if (!(issue_flags & IO_URING_F_SQE128))
5783 		return -EINVAL;
5784 
5785 	header.dev_id = READ_ONCE(ub_src->dev_id);
5786 	header.queue_id = READ_ONCE(ub_src->queue_id);
5787 	header.len = READ_ONCE(ub_src->len);
5788 	header.addr = READ_ONCE(ub_src->addr);
5789 	header.data[0] = READ_ONCE(ub_src->data[0]);
5790 	header.dev_path_len = READ_ONCE(ub_src->dev_path_len);
5791 	ublk_ctrl_cmd_dump(cmd_op, &header);
5792 
5793 	ret = ublk_check_cmd_op(cmd_op);
5794 	if (ret)
5795 		goto out;
5796 
5797 	if (cmd_op == UBLK_U_CMD_GET_FEATURES) {
5798 		ret = ublk_ctrl_get_features(&header);
5799 		goto out;
5800 	}
5801 
5802 	if (_IOC_NR(cmd_op) != UBLK_CMD_ADD_DEV) {
5803 		ret = -ENODEV;
5804 		ub = ublk_get_device_from_id(header.dev_id);
5805 		if (!ub)
5806 			goto out;
5807 
5808 		ret = ublk_ctrl_uring_cmd_permission(ub, cmd_op, &header);
5809 		if (ret)
5810 			goto put_dev;
5811 	}
5812 
5813 	switch (_IOC_NR(cmd_op)) {
5814 	case UBLK_CMD_START_DEV:
5815 		ret = ublk_ctrl_start_dev(ub, &header);
5816 		break;
5817 	case UBLK_CMD_STOP_DEV:
5818 		ublk_ctrl_stop_dev(ub);
5819 		ret = 0;
5820 		break;
5821 	case UBLK_CMD_GET_DEV_INFO:
5822 	case UBLK_CMD_GET_DEV_INFO2:
5823 		ret = ublk_ctrl_get_dev_info(ub, &header);
5824 		break;
5825 	case UBLK_CMD_ADD_DEV:
5826 		ret = ublk_ctrl_add_dev(&header);
5827 		break;
5828 	case UBLK_CMD_DEL_DEV:
5829 		ret = ublk_ctrl_del_dev(&ub, true);
5830 		break;
5831 	case UBLK_CMD_DEL_DEV_ASYNC:
5832 		ret = ublk_ctrl_del_dev(&ub, false);
5833 		break;
5834 	case UBLK_CMD_GET_QUEUE_AFFINITY:
5835 		ret = ublk_ctrl_get_queue_affinity(ub, &header);
5836 		break;
5837 	case UBLK_CMD_GET_PARAMS:
5838 		ret = ublk_ctrl_get_params(ub, &header);
5839 		break;
5840 	case UBLK_CMD_SET_PARAMS:
5841 		ret = ublk_ctrl_set_params(ub, &header);
5842 		break;
5843 	case UBLK_CMD_START_USER_RECOVERY:
5844 		ret = ublk_ctrl_start_recovery(ub);
5845 		break;
5846 	case UBLK_CMD_END_USER_RECOVERY:
5847 		ret = ublk_ctrl_end_recovery(ub, &header);
5848 		break;
5849 	case UBLK_CMD_UPDATE_SIZE:
5850 		ret = ublk_ctrl_set_size(ub, &header);
5851 		break;
5852 	case UBLK_CMD_QUIESCE_DEV:
5853 		ret = ublk_ctrl_quiesce_dev(ub, &header);
5854 		break;
5855 	case UBLK_CMD_TRY_STOP_DEV:
5856 		ret = ublk_ctrl_try_stop_dev(ub);
5857 		break;
5858 	case UBLK_CMD_REG_BUF:
5859 		ret = ublk_ctrl_reg_buf(ub, &header);
5860 		break;
5861 	case UBLK_CMD_UNREG_BUF:
5862 		ret = ublk_ctrl_unreg_buf(ub, &header);
5863 		break;
5864 	default:
5865 		ret = -EOPNOTSUPP;
5866 		break;
5867 	}
5868 
5869  put_dev:
5870 	if (ub)
5871 		ublk_put_device(ub);
5872  out:
5873 	pr_devel("%s: cmd done ret %d cmd_op %x, dev id %d qid %d\n",
5874 			__func__, ret, cmd_op, header.dev_id, header.queue_id);
5875 	return ret;
5876 }
5877 
5878 static const struct file_operations ublk_ctl_fops = {
5879 	.open		= nonseekable_open,
5880 	.uring_cmd      = ublk_ctrl_uring_cmd,
5881 	.owner		= THIS_MODULE,
5882 	.llseek		= noop_llseek,
5883 };
5884 
5885 static struct miscdevice ublk_misc = {
5886 	.minor		= MISC_DYNAMIC_MINOR,
5887 	.name		= "ublk-control",
5888 	.fops		= &ublk_ctl_fops,
5889 };
5890 
5891 static int __init ublk_init(void)
5892 {
5893 	int ret;
5894 
5895 	BUILD_BUG_ON((u64)UBLKSRV_IO_BUF_OFFSET +
5896 			UBLKSRV_IO_BUF_TOTAL_SIZE < UBLKSRV_IO_BUF_OFFSET);
5897 	/*
5898 	 * Ensure UBLKSRV_IO_BUF_OFFSET + UBLKSRV_IO_BUF_TOTAL_SIZE
5899 	 * doesn't overflow into UBLKSRV_IO_INTEGRITY_FLAG
5900 	 */
5901 	BUILD_BUG_ON(UBLKSRV_IO_BUF_OFFSET + UBLKSRV_IO_BUF_TOTAL_SIZE >=
5902 		     UBLKSRV_IO_INTEGRITY_FLAG);
5903 	BUILD_BUG_ON(sizeof(struct ublk_auto_buf_reg) != 8);
5904 
5905 	init_waitqueue_head(&ublk_idr_wq);
5906 
5907 	ret = misc_register(&ublk_misc);
5908 	if (ret)
5909 		return ret;
5910 
5911 	ret = alloc_chrdev_region(&ublk_chr_devt, 0, UBLK_MINORS, "ublk-char");
5912 	if (ret)
5913 		goto unregister_mis;
5914 
5915 	ret = class_register(&ublk_chr_class);
5916 	if (ret)
5917 		goto free_chrdev_region;
5918 
5919 	return 0;
5920 
5921 free_chrdev_region:
5922 	unregister_chrdev_region(ublk_chr_devt, UBLK_MINORS);
5923 unregister_mis:
5924 	misc_deregister(&ublk_misc);
5925 	return ret;
5926 }
5927 
5928 static void __exit ublk_exit(void)
5929 {
5930 	struct ublk_device *ub;
5931 	int id;
5932 
5933 	idr_for_each_entry(&ublk_index_idr, ub, id)
5934 		ublk_remove(ub);
5935 
5936 	class_unregister(&ublk_chr_class);
5937 	misc_deregister(&ublk_misc);
5938 
5939 	idr_destroy(&ublk_index_idr);
5940 	unregister_chrdev_region(ublk_chr_devt, UBLK_MINORS);
5941 }
5942 
5943 module_init(ublk_init);
5944 module_exit(ublk_exit);
5945 
5946 static int ublk_set_max_unprivileged_ublks(const char *buf,
5947 					   const struct kernel_param *kp)
5948 {
5949 	return param_set_uint_minmax(buf, kp, 0, UBLK_MAX_UBLKS);
5950 }
5951 
5952 static int ublk_get_max_unprivileged_ublks(char *buf,
5953 					   const struct kernel_param *kp)
5954 {
5955 	return sysfs_emit(buf, "%u\n", unprivileged_ublks_max);
5956 }
5957 
5958 static const struct kernel_param_ops ublk_max_unprivileged_ublks_ops = {
5959 	.set = ublk_set_max_unprivileged_ublks,
5960 	.get = ublk_get_max_unprivileged_ublks,
5961 };
5962 
5963 module_param_cb(ublks_max, &ublk_max_unprivileged_ublks_ops,
5964 		&unprivileged_ublks_max, 0644);
5965 MODULE_PARM_DESC(ublks_max, "max number of unprivileged ublk devices allowed to add(default: 64)");
5966 
5967 MODULE_AUTHOR("Ming Lei <ming.lei@redhat.com>");
5968 MODULE_DESCRIPTION("Userspace block device");
5969 MODULE_LICENSE("GPL");
5970