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