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