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