xref: /linux/drivers/block/ublk_drv.c (revision 5058a62875e1916e5133a1639f0207ea2148c0bc)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Userspace block device - block device which IO is handled from userspace
4  *
5  * Take full use of io_uring passthrough command for communicating with
6  * ublk userspace daemon(ublksrvd) for handling basic IO request.
7  *
8  * Copyright 2022 Ming Lei <ming.lei@redhat.com>
9  *
10  * (part of code stolen from loop.c)
11  */
12 #include <linux/module.h>
13 #include <linux/moduleparam.h>
14 #include <linux/sched.h>
15 #include <linux/fs.h>
16 #include <linux/pagemap.h>
17 #include <linux/file.h>
18 #include <linux/stat.h>
19 #include <linux/errno.h>
20 #include <linux/major.h>
21 #include <linux/wait.h>
22 #include <linux/blkdev.h>
23 #include <linux/init.h>
24 #include <linux/swap.h>
25 #include <linux/slab.h>
26 #include <linux/compat.h>
27 #include <linux/mutex.h>
28 #include <linux/writeback.h>
29 #include <linux/completion.h>
30 #include <linux/highmem.h>
31 #include <linux/sysfs.h>
32 #include <linux/miscdevice.h>
33 #include <linux/falloc.h>
34 #include <linux/uio.h>
35 #include <linux/ioprio.h>
36 #include <linux/sched/mm.h>
37 #include <linux/uaccess.h>
38 #include <linux/cdev.h>
39 #include <linux/io_uring/cmd.h>
40 #include <linux/blk-mq.h>
41 #include <linux/delay.h>
42 #include <linux/mm.h>
43 #include <asm/page.h>
44 #include <linux/task_work.h>
45 #include <linux/namei.h>
46 #include <linux/kref.h>
47 #include <uapi/linux/ublk_cmd.h>
48 
49 #define UBLK_MINORS		(1U << MINORBITS)
50 
51 #define UBLK_INVALID_BUF_IDX 	((u16)-1)
52 
53 /* private ioctl command mirror */
54 #define UBLK_CMD_DEL_DEV_ASYNC	_IOC_NR(UBLK_U_CMD_DEL_DEV_ASYNC)
55 #define UBLK_CMD_UPDATE_SIZE	_IOC_NR(UBLK_U_CMD_UPDATE_SIZE)
56 #define UBLK_CMD_QUIESCE_DEV	_IOC_NR(UBLK_U_CMD_QUIESCE_DEV)
57 
58 #define UBLK_IO_REGISTER_IO_BUF		_IOC_NR(UBLK_U_IO_REGISTER_IO_BUF)
59 #define UBLK_IO_UNREGISTER_IO_BUF	_IOC_NR(UBLK_U_IO_UNREGISTER_IO_BUF)
60 
61 /* All UBLK_F_* have to be included into UBLK_F_ALL */
62 #define UBLK_F_ALL (UBLK_F_SUPPORT_ZERO_COPY \
63 		| UBLK_F_URING_CMD_COMP_IN_TASK \
64 		| UBLK_F_NEED_GET_DATA \
65 		| UBLK_F_USER_RECOVERY \
66 		| UBLK_F_USER_RECOVERY_REISSUE \
67 		| UBLK_F_UNPRIVILEGED_DEV \
68 		| UBLK_F_CMD_IOCTL_ENCODE \
69 		| UBLK_F_USER_COPY \
70 		| UBLK_F_ZONED \
71 		| UBLK_F_USER_RECOVERY_FAIL_IO \
72 		| UBLK_F_UPDATE_SIZE \
73 		| UBLK_F_AUTO_BUF_REG \
74 		| UBLK_F_QUIESCE \
75 		| UBLK_F_PER_IO_DAEMON \
76 		| UBLK_F_BUF_REG_OFF_DAEMON)
77 
78 #define UBLK_F_ALL_RECOVERY_FLAGS (UBLK_F_USER_RECOVERY \
79 		| UBLK_F_USER_RECOVERY_REISSUE \
80 		| UBLK_F_USER_RECOVERY_FAIL_IO)
81 
82 /* All UBLK_PARAM_TYPE_* should be included here */
83 #define UBLK_PARAM_TYPE_ALL                                \
84 	(UBLK_PARAM_TYPE_BASIC | UBLK_PARAM_TYPE_DISCARD | \
85 	 UBLK_PARAM_TYPE_DEVT | UBLK_PARAM_TYPE_ZONED |    \
86 	 UBLK_PARAM_TYPE_DMA_ALIGN | UBLK_PARAM_TYPE_SEGMENT)
87 
88 struct ublk_uring_cmd_pdu {
89 	/*
90 	 * Store requests in same batch temporarily for queuing them to
91 	 * daemon context.
92 	 *
93 	 * It should have been stored to request payload, but we do want
94 	 * to avoid extra pre-allocation, and uring_cmd payload is always
95 	 * free for us
96 	 */
97 	union {
98 		struct request *req;
99 		struct request *req_list;
100 	};
101 
102 	/*
103 	 * The following two are valid in this cmd whole lifetime, and
104 	 * setup in ublk uring_cmd handler
105 	 */
106 	struct ublk_queue *ubq;
107 
108 	u16 tag;
109 };
110 
111 /*
112  * io command is active: sqe cmd is received, and its cqe isn't done
113  *
114  * If the flag is set, the io command is owned by ublk driver, and waited
115  * for incoming blk-mq request from the ublk block device.
116  *
117  * If the flag is cleared, the io command will be completed, and owned by
118  * ublk server.
119  */
120 #define UBLK_IO_FLAG_ACTIVE	0x01
121 
122 /*
123  * IO command is completed via cqe, and it is being handled by ublksrv, and
124  * not committed yet
125  *
126  * Basically exclusively with UBLK_IO_FLAG_ACTIVE, so can be served for
127  * cross verification
128  */
129 #define UBLK_IO_FLAG_OWNED_BY_SRV 0x02
130 
131 /*
132  * UBLK_IO_FLAG_NEED_GET_DATA is set because IO command requires
133  * get data buffer address from ublksrv.
134  *
135  * Then, bio data could be copied into this data buffer for a WRITE request
136  * after the IO command is issued again and UBLK_IO_FLAG_NEED_GET_DATA is unset.
137  */
138 #define UBLK_IO_FLAG_NEED_GET_DATA 0x08
139 
140 /*
141  * request buffer is registered automatically, so we have to unregister it
142  * before completing this request.
143  *
144  * io_uring will unregister buffer automatically for us during exiting.
145  */
146 #define UBLK_IO_FLAG_AUTO_BUF_REG 	0x10
147 
148 /* atomic RW with ubq->cancel_lock */
149 #define UBLK_IO_FLAG_CANCELED	0x80000000
150 
151 /*
152  * Initialize refcount to a large number to include any registered buffers.
153  * UBLK_IO_COMMIT_AND_FETCH_REQ will release these references minus those for
154  * any buffers registered on the io daemon task.
155  */
156 #define UBLK_REFCOUNT_INIT (REFCOUNT_MAX / 2)
157 
158 struct ublk_io {
159 	/* userspace buffer address from io cmd */
160 	union {
161 		__u64	addr;
162 		struct ublk_auto_buf_reg buf;
163 	};
164 	unsigned int flags;
165 	int res;
166 
167 	union {
168 		/* valid if UBLK_IO_FLAG_ACTIVE is set */
169 		struct io_uring_cmd *cmd;
170 		/* valid if UBLK_IO_FLAG_OWNED_BY_SRV is set */
171 		struct request *req;
172 	};
173 
174 	struct task_struct *task;
175 
176 	/*
177 	 * The number of uses of this I/O by the ublk server
178 	 * if user copy or zero copy are enabled:
179 	 * - UBLK_REFCOUNT_INIT from dispatch to the server
180 	 *   until UBLK_IO_COMMIT_AND_FETCH_REQ
181 	 * - 1 for each inflight ublk_ch_{read,write}_iter() call
182 	 * - 1 for each io_uring registered buffer not registered on task
183 	 * The I/O can only be completed once all references are dropped.
184 	 * User copy and buffer registration operations are only permitted
185 	 * if the reference count is nonzero.
186 	 */
187 	refcount_t ref;
188 	/* Count of buffers registered on task and not yet unregistered */
189 	unsigned task_registered_buffers;
190 
191 	void *buf_ctx_handle;
192 } ____cacheline_aligned_in_smp;
193 
194 struct ublk_queue {
195 	int q_id;
196 	int q_depth;
197 
198 	unsigned long flags;
199 	struct ublksrv_io_desc *io_cmd_buf;
200 
201 	bool force_abort;
202 	bool canceling;
203 	bool fail_io; /* copy of dev->state == UBLK_S_DEV_FAIL_IO */
204 	unsigned short nr_io_ready;	/* how many ios setup */
205 	spinlock_t		cancel_lock;
206 	struct ublk_device *dev;
207 	struct ublk_io ios[];
208 };
209 
210 struct ublk_device {
211 	struct gendisk		*ub_disk;
212 
213 	char	*__queues;
214 
215 	unsigned int	queue_size;
216 	struct ublksrv_ctrl_dev_info	dev_info;
217 
218 	struct blk_mq_tag_set	tag_set;
219 
220 	struct cdev		cdev;
221 	struct device		cdev_dev;
222 
223 #define UB_STATE_OPEN		0
224 #define UB_STATE_USED		1
225 #define UB_STATE_DELETED	2
226 	unsigned long		state;
227 	int			ub_number;
228 
229 	struct mutex		mutex;
230 
231 	spinlock_t		lock;
232 	struct mm_struct	*mm;
233 
234 	struct ublk_params	params;
235 
236 	struct completion	completion;
237 	unsigned int		nr_queues_ready;
238 	bool 			unprivileged_daemons;
239 	struct mutex cancel_mutex;
240 	bool canceling;
241 	pid_t 	ublksrv_tgid;
242 };
243 
244 /* header of ublk_params */
245 struct ublk_params_header {
246 	__u32	len;
247 	__u32	types;
248 };
249 
250 static void ublk_io_release(void *priv);
251 static void ublk_stop_dev_unlocked(struct ublk_device *ub);
252 static void ublk_abort_queue(struct ublk_device *ub, struct ublk_queue *ubq);
253 static inline struct request *__ublk_check_and_get_req(struct ublk_device *ub,
254 		const struct ublk_queue *ubq, struct ublk_io *io,
255 		size_t offset);
256 static inline unsigned int ublk_req_build_flags(struct request *req);
257 
258 static inline struct ublksrv_io_desc *
ublk_get_iod(const struct ublk_queue * ubq,unsigned tag)259 ublk_get_iod(const struct ublk_queue *ubq, unsigned tag)
260 {
261 	return &ubq->io_cmd_buf[tag];
262 }
263 
ublk_dev_is_zoned(const struct ublk_device * ub)264 static inline bool ublk_dev_is_zoned(const struct ublk_device *ub)
265 {
266 	return ub->dev_info.flags & UBLK_F_ZONED;
267 }
268 
ublk_queue_is_zoned(struct ublk_queue * ubq)269 static inline bool ublk_queue_is_zoned(struct ublk_queue *ubq)
270 {
271 	return ubq->flags & UBLK_F_ZONED;
272 }
273 
274 #ifdef CONFIG_BLK_DEV_ZONED
275 
276 struct ublk_zoned_report_desc {
277 	__u64 sector;
278 	__u32 operation;
279 	__u32 nr_zones;
280 };
281 
282 static DEFINE_XARRAY(ublk_zoned_report_descs);
283 
ublk_zoned_insert_report_desc(const struct request * req,struct ublk_zoned_report_desc * desc)284 static int ublk_zoned_insert_report_desc(const struct request *req,
285 		struct ublk_zoned_report_desc *desc)
286 {
287 	return xa_insert(&ublk_zoned_report_descs, (unsigned long)req,
288 			    desc, GFP_KERNEL);
289 }
290 
ublk_zoned_erase_report_desc(const struct request * req)291 static struct ublk_zoned_report_desc *ublk_zoned_erase_report_desc(
292 		const struct request *req)
293 {
294 	return xa_erase(&ublk_zoned_report_descs, (unsigned long)req);
295 }
296 
ublk_zoned_get_report_desc(const struct request * req)297 static struct ublk_zoned_report_desc *ublk_zoned_get_report_desc(
298 		const struct request *req)
299 {
300 	return xa_load(&ublk_zoned_report_descs, (unsigned long)req);
301 }
302 
ublk_get_nr_zones(const struct ublk_device * ub)303 static int ublk_get_nr_zones(const struct ublk_device *ub)
304 {
305 	const struct ublk_param_basic *p = &ub->params.basic;
306 
307 	/* Zone size is a power of 2 */
308 	return p->dev_sectors >> ilog2(p->chunk_sectors);
309 }
310 
ublk_revalidate_disk_zones(struct ublk_device * ub)311 static int ublk_revalidate_disk_zones(struct ublk_device *ub)
312 {
313 	return blk_revalidate_disk_zones(ub->ub_disk);
314 }
315 
ublk_dev_param_zoned_validate(const struct ublk_device * ub)316 static int ublk_dev_param_zoned_validate(const struct ublk_device *ub)
317 {
318 	const struct ublk_param_zoned *p = &ub->params.zoned;
319 	int nr_zones;
320 
321 	if (!ublk_dev_is_zoned(ub))
322 		return -EINVAL;
323 
324 	if (!p->max_zone_append_sectors)
325 		return -EINVAL;
326 
327 	nr_zones = ublk_get_nr_zones(ub);
328 
329 	if (p->max_active_zones > nr_zones)
330 		return -EINVAL;
331 
332 	if (p->max_open_zones > nr_zones)
333 		return -EINVAL;
334 
335 	return 0;
336 }
337 
ublk_dev_param_zoned_apply(struct ublk_device * ub)338 static void ublk_dev_param_zoned_apply(struct ublk_device *ub)
339 {
340 	ub->ub_disk->nr_zones = ublk_get_nr_zones(ub);
341 }
342 
343 /* Based on virtblk_alloc_report_buffer */
ublk_alloc_report_buffer(struct ublk_device * ublk,unsigned int nr_zones,size_t * buflen)344 static void *ublk_alloc_report_buffer(struct ublk_device *ublk,
345 				      unsigned int nr_zones, size_t *buflen)
346 {
347 	struct request_queue *q = ublk->ub_disk->queue;
348 	size_t bufsize;
349 	void *buf;
350 
351 	nr_zones = min_t(unsigned int, nr_zones,
352 			 ublk->ub_disk->nr_zones);
353 
354 	bufsize = nr_zones * sizeof(struct blk_zone);
355 	bufsize =
356 		min_t(size_t, bufsize, queue_max_hw_sectors(q) << SECTOR_SHIFT);
357 
358 	while (bufsize >= sizeof(struct blk_zone)) {
359 		buf = kvmalloc(bufsize, GFP_KERNEL | __GFP_NORETRY);
360 		if (buf) {
361 			*buflen = bufsize;
362 			return buf;
363 		}
364 		bufsize >>= 1;
365 	}
366 
367 	*buflen = 0;
368 	return NULL;
369 }
370 
ublk_report_zones(struct gendisk * disk,sector_t sector,unsigned int nr_zones,report_zones_cb cb,void * data)371 static int ublk_report_zones(struct gendisk *disk, sector_t sector,
372 		      unsigned int nr_zones, report_zones_cb cb, void *data)
373 {
374 	struct ublk_device *ub = disk->private_data;
375 	unsigned int zone_size_sectors = disk->queue->limits.chunk_sectors;
376 	unsigned int first_zone = sector >> ilog2(zone_size_sectors);
377 	unsigned int done_zones = 0;
378 	unsigned int max_zones_per_request;
379 	int ret;
380 	struct blk_zone *buffer;
381 	size_t buffer_length;
382 
383 	nr_zones = min_t(unsigned int, ub->ub_disk->nr_zones - first_zone,
384 			 nr_zones);
385 
386 	buffer = ublk_alloc_report_buffer(ub, nr_zones, &buffer_length);
387 	if (!buffer)
388 		return -ENOMEM;
389 
390 	max_zones_per_request = buffer_length / sizeof(struct blk_zone);
391 
392 	while (done_zones < nr_zones) {
393 		unsigned int remaining_zones = nr_zones - done_zones;
394 		unsigned int zones_in_request =
395 			min_t(unsigned int, remaining_zones, max_zones_per_request);
396 		struct request *req;
397 		struct ublk_zoned_report_desc desc;
398 		blk_status_t status;
399 
400 		memset(buffer, 0, buffer_length);
401 
402 		req = blk_mq_alloc_request(disk->queue, REQ_OP_DRV_IN, 0);
403 		if (IS_ERR(req)) {
404 			ret = PTR_ERR(req);
405 			goto out;
406 		}
407 
408 		desc.operation = UBLK_IO_OP_REPORT_ZONES;
409 		desc.sector = sector;
410 		desc.nr_zones = zones_in_request;
411 		ret = ublk_zoned_insert_report_desc(req, &desc);
412 		if (ret)
413 			goto free_req;
414 
415 		ret = blk_rq_map_kern(req, buffer, buffer_length, GFP_KERNEL);
416 		if (ret)
417 			goto erase_desc;
418 
419 		status = blk_execute_rq(req, 0);
420 		ret = blk_status_to_errno(status);
421 erase_desc:
422 		ublk_zoned_erase_report_desc(req);
423 free_req:
424 		blk_mq_free_request(req);
425 		if (ret)
426 			goto out;
427 
428 		for (unsigned int i = 0; i < zones_in_request; i++) {
429 			struct blk_zone *zone = buffer + i;
430 
431 			/* A zero length zone means no more zones in this response */
432 			if (!zone->len)
433 				break;
434 
435 			ret = cb(zone, i, data);
436 			if (ret)
437 				goto out;
438 
439 			done_zones++;
440 			sector += zone_size_sectors;
441 
442 		}
443 	}
444 
445 	ret = done_zones;
446 
447 out:
448 	kvfree(buffer);
449 	return ret;
450 }
451 
ublk_setup_iod_zoned(struct ublk_queue * ubq,struct request * req)452 static blk_status_t ublk_setup_iod_zoned(struct ublk_queue *ubq,
453 					 struct request *req)
454 {
455 	struct ublksrv_io_desc *iod = ublk_get_iod(ubq, req->tag);
456 	struct ublk_io *io = &ubq->ios[req->tag];
457 	struct ublk_zoned_report_desc *desc;
458 	u32 ublk_op;
459 
460 	switch (req_op(req)) {
461 	case REQ_OP_ZONE_OPEN:
462 		ublk_op = UBLK_IO_OP_ZONE_OPEN;
463 		break;
464 	case REQ_OP_ZONE_CLOSE:
465 		ublk_op = UBLK_IO_OP_ZONE_CLOSE;
466 		break;
467 	case REQ_OP_ZONE_FINISH:
468 		ublk_op = UBLK_IO_OP_ZONE_FINISH;
469 		break;
470 	case REQ_OP_ZONE_RESET:
471 		ublk_op = UBLK_IO_OP_ZONE_RESET;
472 		break;
473 	case REQ_OP_ZONE_APPEND:
474 		ublk_op = UBLK_IO_OP_ZONE_APPEND;
475 		break;
476 	case REQ_OP_ZONE_RESET_ALL:
477 		ublk_op = UBLK_IO_OP_ZONE_RESET_ALL;
478 		break;
479 	case REQ_OP_DRV_IN:
480 		desc = ublk_zoned_get_report_desc(req);
481 		if (!desc)
482 			return BLK_STS_IOERR;
483 		ublk_op = desc->operation;
484 		switch (ublk_op) {
485 		case UBLK_IO_OP_REPORT_ZONES:
486 			iod->op_flags = ublk_op | ublk_req_build_flags(req);
487 			iod->nr_zones = desc->nr_zones;
488 			iod->start_sector = desc->sector;
489 			return BLK_STS_OK;
490 		default:
491 			return BLK_STS_IOERR;
492 		}
493 	case REQ_OP_DRV_OUT:
494 		/* We do not support drv_out */
495 		return BLK_STS_NOTSUPP;
496 	default:
497 		return BLK_STS_IOERR;
498 	}
499 
500 	iod->op_flags = ublk_op | ublk_req_build_flags(req);
501 	iod->nr_sectors = blk_rq_sectors(req);
502 	iod->start_sector = blk_rq_pos(req);
503 	iod->addr = io->addr;
504 
505 	return BLK_STS_OK;
506 }
507 
508 #else
509 
510 #define ublk_report_zones (NULL)
511 
ublk_dev_param_zoned_validate(const struct ublk_device * ub)512 static int ublk_dev_param_zoned_validate(const struct ublk_device *ub)
513 {
514 	return -EOPNOTSUPP;
515 }
516 
ublk_dev_param_zoned_apply(struct ublk_device * ub)517 static void ublk_dev_param_zoned_apply(struct ublk_device *ub)
518 {
519 }
520 
ublk_revalidate_disk_zones(struct ublk_device * ub)521 static int ublk_revalidate_disk_zones(struct ublk_device *ub)
522 {
523 	return 0;
524 }
525 
ublk_setup_iod_zoned(struct ublk_queue * ubq,struct request * req)526 static blk_status_t ublk_setup_iod_zoned(struct ublk_queue *ubq,
527 					 struct request *req)
528 {
529 	return BLK_STS_NOTSUPP;
530 }
531 
532 #endif
533 
534 static inline void __ublk_complete_rq(struct request *req);
535 
536 static dev_t ublk_chr_devt;
537 static const struct class ublk_chr_class = {
538 	.name = "ublk-char",
539 };
540 
541 static DEFINE_IDR(ublk_index_idr);
542 static DEFINE_SPINLOCK(ublk_idr_lock);
543 static wait_queue_head_t ublk_idr_wq;	/* wait until one idr is freed */
544 
545 static DEFINE_MUTEX(ublk_ctl_mutex);
546 
547 
548 #define UBLK_MAX_UBLKS UBLK_MINORS
549 
550 /*
551  * Max unprivileged ublk devices allowed to add
552  *
553  * It can be extended to one per-user limit in future or even controlled
554  * by cgroup.
555  */
556 static unsigned int unprivileged_ublks_max = 64;
557 static unsigned int unprivileged_ublks_added; /* protected by ublk_ctl_mutex */
558 
559 static struct miscdevice ublk_misc;
560 
ublk_pos_to_hwq(loff_t pos)561 static inline unsigned ublk_pos_to_hwq(loff_t pos)
562 {
563 	return ((pos - UBLKSRV_IO_BUF_OFFSET) >> UBLK_QID_OFF) &
564 		UBLK_QID_BITS_MASK;
565 }
566 
ublk_pos_to_buf_off(loff_t pos)567 static inline unsigned ublk_pos_to_buf_off(loff_t pos)
568 {
569 	return (pos - UBLKSRV_IO_BUF_OFFSET) & UBLK_IO_BUF_BITS_MASK;
570 }
571 
ublk_pos_to_tag(loff_t pos)572 static inline unsigned ublk_pos_to_tag(loff_t pos)
573 {
574 	return ((pos - UBLKSRV_IO_BUF_OFFSET) >> UBLK_TAG_OFF) &
575 		UBLK_TAG_BITS_MASK;
576 }
577 
ublk_dev_param_basic_apply(struct ublk_device * ub)578 static void ublk_dev_param_basic_apply(struct ublk_device *ub)
579 {
580 	const struct ublk_param_basic *p = &ub->params.basic;
581 
582 	if (p->attrs & UBLK_ATTR_READ_ONLY)
583 		set_disk_ro(ub->ub_disk, true);
584 
585 	set_capacity(ub->ub_disk, p->dev_sectors);
586 }
587 
ublk_validate_params(const struct ublk_device * ub)588 static int ublk_validate_params(const struct ublk_device *ub)
589 {
590 	/* basic param is the only one which must be set */
591 	if (ub->params.types & UBLK_PARAM_TYPE_BASIC) {
592 		const struct ublk_param_basic *p = &ub->params.basic;
593 
594 		if (p->logical_bs_shift > PAGE_SHIFT || p->logical_bs_shift < 9)
595 			return -EINVAL;
596 
597 		if (p->logical_bs_shift > p->physical_bs_shift)
598 			return -EINVAL;
599 
600 		if (p->max_sectors > (ub->dev_info.max_io_buf_bytes >> 9))
601 			return -EINVAL;
602 
603 		if (ublk_dev_is_zoned(ub) && !p->chunk_sectors)
604 			return -EINVAL;
605 	} else
606 		return -EINVAL;
607 
608 	if (ub->params.types & UBLK_PARAM_TYPE_DISCARD) {
609 		const struct ublk_param_discard *p = &ub->params.discard;
610 
611 		/* So far, only support single segment discard */
612 		if (p->max_discard_sectors && p->max_discard_segments != 1)
613 			return -EINVAL;
614 
615 		if (!p->discard_granularity)
616 			return -EINVAL;
617 	}
618 
619 	/* dev_t is read-only */
620 	if (ub->params.types & UBLK_PARAM_TYPE_DEVT)
621 		return -EINVAL;
622 
623 	if (ub->params.types & UBLK_PARAM_TYPE_ZONED)
624 		return ublk_dev_param_zoned_validate(ub);
625 	else if (ublk_dev_is_zoned(ub))
626 		return -EINVAL;
627 
628 	if (ub->params.types & UBLK_PARAM_TYPE_DMA_ALIGN) {
629 		const struct ublk_param_dma_align *p = &ub->params.dma;
630 
631 		if (p->alignment >= PAGE_SIZE)
632 			return -EINVAL;
633 
634 		if (!is_power_of_2(p->alignment + 1))
635 			return -EINVAL;
636 	}
637 
638 	if (ub->params.types & UBLK_PARAM_TYPE_SEGMENT) {
639 		const struct ublk_param_segment *p = &ub->params.seg;
640 
641 		if (!is_power_of_2(p->seg_boundary_mask + 1))
642 			return -EINVAL;
643 
644 		if (p->seg_boundary_mask + 1 < UBLK_MIN_SEGMENT_SIZE)
645 			return -EINVAL;
646 		if (p->max_segment_size < UBLK_MIN_SEGMENT_SIZE)
647 			return -EINVAL;
648 	}
649 
650 	return 0;
651 }
652 
ublk_apply_params(struct ublk_device * ub)653 static void ublk_apply_params(struct ublk_device *ub)
654 {
655 	ublk_dev_param_basic_apply(ub);
656 
657 	if (ub->params.types & UBLK_PARAM_TYPE_ZONED)
658 		ublk_dev_param_zoned_apply(ub);
659 }
660 
ublk_support_zero_copy(const struct ublk_queue * ubq)661 static inline bool ublk_support_zero_copy(const struct ublk_queue *ubq)
662 {
663 	return ubq->flags & UBLK_F_SUPPORT_ZERO_COPY;
664 }
665 
ublk_support_auto_buf_reg(const struct ublk_queue * ubq)666 static inline bool ublk_support_auto_buf_reg(const struct ublk_queue *ubq)
667 {
668 	return ubq->flags & UBLK_F_AUTO_BUF_REG;
669 }
670 
ublk_support_user_copy(const struct ublk_queue * ubq)671 static inline bool ublk_support_user_copy(const struct ublk_queue *ubq)
672 {
673 	return ubq->flags & UBLK_F_USER_COPY;
674 }
675 
ublk_need_map_io(const struct ublk_queue * ubq)676 static inline bool ublk_need_map_io(const struct ublk_queue *ubq)
677 {
678 	return !ublk_support_user_copy(ubq) && !ublk_support_zero_copy(ubq) &&
679 		!ublk_support_auto_buf_reg(ubq);
680 }
681 
ublk_need_req_ref(const struct ublk_queue * ubq)682 static inline bool ublk_need_req_ref(const struct ublk_queue *ubq)
683 {
684 	/*
685 	 * read()/write() is involved in user copy, so request reference
686 	 * has to be grabbed
687 	 *
688 	 * for zero copy, request buffer need to be registered to io_uring
689 	 * buffer table, so reference is needed
690 	 *
691 	 * For auto buffer register, ublk server still may issue
692 	 * UBLK_IO_COMMIT_AND_FETCH_REQ before one registered buffer is used up,
693 	 * so reference is required too.
694 	 */
695 	return ublk_support_user_copy(ubq) || ublk_support_zero_copy(ubq) ||
696 		ublk_support_auto_buf_reg(ubq);
697 }
698 
ublk_init_req_ref(const struct ublk_queue * ubq,struct ublk_io * io)699 static inline void ublk_init_req_ref(const struct ublk_queue *ubq,
700 		struct ublk_io *io)
701 {
702 	if (ublk_need_req_ref(ubq))
703 		refcount_set(&io->ref, UBLK_REFCOUNT_INIT);
704 }
705 
ublk_get_req_ref(struct ublk_io * io)706 static inline bool ublk_get_req_ref(struct ublk_io *io)
707 {
708 	return refcount_inc_not_zero(&io->ref);
709 }
710 
ublk_put_req_ref(struct ublk_io * io,struct request * req)711 static inline void ublk_put_req_ref(struct ublk_io *io, struct request *req)
712 {
713 	if (refcount_dec_and_test(&io->ref))
714 		__ublk_complete_rq(req);
715 }
716 
ublk_sub_req_ref(struct ublk_io * io)717 static inline bool ublk_sub_req_ref(struct ublk_io *io)
718 {
719 	unsigned sub_refs = UBLK_REFCOUNT_INIT - io->task_registered_buffers;
720 
721 	io->task_registered_buffers = 0;
722 	return refcount_sub_and_test(sub_refs, &io->ref);
723 }
724 
ublk_need_get_data(const struct ublk_queue * ubq)725 static inline bool ublk_need_get_data(const struct ublk_queue *ubq)
726 {
727 	return ubq->flags & UBLK_F_NEED_GET_DATA;
728 }
729 
730 /* Called in slow path only, keep it noinline for trace purpose */
ublk_get_device(struct ublk_device * ub)731 static noinline struct ublk_device *ublk_get_device(struct ublk_device *ub)
732 {
733 	if (kobject_get_unless_zero(&ub->cdev_dev.kobj))
734 		return ub;
735 	return NULL;
736 }
737 
738 /* Called in slow path only, keep it noinline for trace purpose */
ublk_put_device(struct ublk_device * ub)739 static noinline void ublk_put_device(struct ublk_device *ub)
740 {
741 	put_device(&ub->cdev_dev);
742 }
743 
ublk_get_queue(struct ublk_device * dev,int qid)744 static inline struct ublk_queue *ublk_get_queue(struct ublk_device *dev,
745 		int qid)
746 {
747        return (struct ublk_queue *)&(dev->__queues[qid * dev->queue_size]);
748 }
749 
ublk_rq_has_data(const struct request * rq)750 static inline bool ublk_rq_has_data(const struct request *rq)
751 {
752 	return bio_has_data(rq->bio);
753 }
754 
755 static inline struct ublksrv_io_desc *
ublk_queue_cmd_buf(struct ublk_device * ub,int q_id)756 ublk_queue_cmd_buf(struct ublk_device *ub, int q_id)
757 {
758 	return ublk_get_queue(ub, q_id)->io_cmd_buf;
759 }
760 
__ublk_queue_cmd_buf_size(int depth)761 static inline int __ublk_queue_cmd_buf_size(int depth)
762 {
763 	return round_up(depth * sizeof(struct ublksrv_io_desc), PAGE_SIZE);
764 }
765 
ublk_queue_cmd_buf_size(struct ublk_device * ub,int q_id)766 static inline int ublk_queue_cmd_buf_size(struct ublk_device *ub, int q_id)
767 {
768 	struct ublk_queue *ubq = ublk_get_queue(ub, q_id);
769 
770 	return __ublk_queue_cmd_buf_size(ubq->q_depth);
771 }
772 
ublk_max_cmd_buf_size(void)773 static int ublk_max_cmd_buf_size(void)
774 {
775 	return __ublk_queue_cmd_buf_size(UBLK_MAX_QUEUE_DEPTH);
776 }
777 
778 /*
779  * Should I/O outstanding to the ublk server when it exits be reissued?
780  * If not, outstanding I/O will get errors.
781  */
ublk_nosrv_should_reissue_outstanding(struct ublk_device * ub)782 static inline bool ublk_nosrv_should_reissue_outstanding(struct ublk_device *ub)
783 {
784 	return (ub->dev_info.flags & UBLK_F_USER_RECOVERY) &&
785 	       (ub->dev_info.flags & UBLK_F_USER_RECOVERY_REISSUE);
786 }
787 
788 /*
789  * Should I/O issued while there is no ublk server queue? If not, I/O
790  * issued while there is no ublk server will get errors.
791  */
ublk_nosrv_dev_should_queue_io(struct ublk_device * ub)792 static inline bool ublk_nosrv_dev_should_queue_io(struct ublk_device *ub)
793 {
794 	return (ub->dev_info.flags & UBLK_F_USER_RECOVERY) &&
795 	       !(ub->dev_info.flags & UBLK_F_USER_RECOVERY_FAIL_IO);
796 }
797 
798 /*
799  * Same as ublk_nosrv_dev_should_queue_io, but uses a queue-local copy
800  * of the device flags for smaller cache footprint - better for fast
801  * paths.
802  */
ublk_nosrv_should_queue_io(struct ublk_queue * ubq)803 static inline bool ublk_nosrv_should_queue_io(struct ublk_queue *ubq)
804 {
805 	return (ubq->flags & UBLK_F_USER_RECOVERY) &&
806 	       !(ubq->flags & UBLK_F_USER_RECOVERY_FAIL_IO);
807 }
808 
809 /*
810  * Should ublk devices be stopped (i.e. no recovery possible) when the
811  * ublk server exits? If not, devices can be used again by a future
812  * incarnation of a ublk server via the start_recovery/end_recovery
813  * commands.
814  */
ublk_nosrv_should_stop_dev(struct ublk_device * ub)815 static inline bool ublk_nosrv_should_stop_dev(struct ublk_device *ub)
816 {
817 	return !(ub->dev_info.flags & UBLK_F_USER_RECOVERY);
818 }
819 
ublk_dev_in_recoverable_state(struct ublk_device * ub)820 static inline bool ublk_dev_in_recoverable_state(struct ublk_device *ub)
821 {
822 	return ub->dev_info.state == UBLK_S_DEV_QUIESCED ||
823 	       ub->dev_info.state == UBLK_S_DEV_FAIL_IO;
824 }
825 
ublk_free_disk(struct gendisk * disk)826 static void ublk_free_disk(struct gendisk *disk)
827 {
828 	struct ublk_device *ub = disk->private_data;
829 
830 	clear_bit(UB_STATE_USED, &ub->state);
831 	ublk_put_device(ub);
832 }
833 
ublk_store_owner_uid_gid(unsigned int * owner_uid,unsigned int * owner_gid)834 static void ublk_store_owner_uid_gid(unsigned int *owner_uid,
835 		unsigned int *owner_gid)
836 {
837 	kuid_t uid;
838 	kgid_t gid;
839 
840 	current_uid_gid(&uid, &gid);
841 
842 	*owner_uid = from_kuid(&init_user_ns, uid);
843 	*owner_gid = from_kgid(&init_user_ns, gid);
844 }
845 
ublk_open(struct gendisk * disk,blk_mode_t mode)846 static int ublk_open(struct gendisk *disk, blk_mode_t mode)
847 {
848 	struct ublk_device *ub = disk->private_data;
849 
850 	if (capable(CAP_SYS_ADMIN))
851 		return 0;
852 
853 	/*
854 	 * If it is one unprivileged device, only owner can open
855 	 * the disk. Otherwise it could be one trap made by one
856 	 * evil user who grants this disk's privileges to other
857 	 * users deliberately.
858 	 *
859 	 * This way is reasonable too given anyone can create
860 	 * unprivileged device, and no need other's grant.
861 	 */
862 	if (ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV) {
863 		unsigned int curr_uid, curr_gid;
864 
865 		ublk_store_owner_uid_gid(&curr_uid, &curr_gid);
866 
867 		if (curr_uid != ub->dev_info.owner_uid || curr_gid !=
868 				ub->dev_info.owner_gid)
869 			return -EPERM;
870 	}
871 
872 	return 0;
873 }
874 
875 static const struct block_device_operations ub_fops = {
876 	.owner =	THIS_MODULE,
877 	.open =		ublk_open,
878 	.free_disk =	ublk_free_disk,
879 	.report_zones =	ublk_report_zones,
880 };
881 
882 #define UBLK_MAX_PIN_PAGES	32
883 
884 struct ublk_io_iter {
885 	struct page *pages[UBLK_MAX_PIN_PAGES];
886 	struct bio *bio;
887 	struct bvec_iter iter;
888 };
889 
890 /* return how many pages are copied */
ublk_copy_io_pages(struct ublk_io_iter * data,size_t total,size_t pg_off,int dir)891 static void ublk_copy_io_pages(struct ublk_io_iter *data,
892 		size_t total, size_t pg_off, int dir)
893 {
894 	unsigned done = 0;
895 	unsigned pg_idx = 0;
896 
897 	while (done < total) {
898 		struct bio_vec bv = bio_iter_iovec(data->bio, data->iter);
899 		unsigned int bytes = min3(bv.bv_len, (unsigned)total - done,
900 				(unsigned)(PAGE_SIZE - pg_off));
901 		void *bv_buf = bvec_kmap_local(&bv);
902 		void *pg_buf = kmap_local_page(data->pages[pg_idx]);
903 
904 		if (dir == ITER_DEST)
905 			memcpy(pg_buf + pg_off, bv_buf, bytes);
906 		else
907 			memcpy(bv_buf, pg_buf + pg_off, bytes);
908 
909 		kunmap_local(pg_buf);
910 		kunmap_local(bv_buf);
911 
912 		/* advance page array */
913 		pg_off += bytes;
914 		if (pg_off == PAGE_SIZE) {
915 			pg_idx += 1;
916 			pg_off = 0;
917 		}
918 
919 		done += bytes;
920 
921 		/* advance bio */
922 		bio_advance_iter_single(data->bio, &data->iter, bytes);
923 		if (!data->iter.bi_size) {
924 			data->bio = data->bio->bi_next;
925 			if (data->bio == NULL)
926 				break;
927 			data->iter = data->bio->bi_iter;
928 		}
929 	}
930 }
931 
ublk_advance_io_iter(const struct request * req,struct ublk_io_iter * iter,unsigned int offset)932 static bool ublk_advance_io_iter(const struct request *req,
933 		struct ublk_io_iter *iter, unsigned int offset)
934 {
935 	struct bio *bio = req->bio;
936 
937 	for_each_bio(bio) {
938 		if (bio->bi_iter.bi_size > offset) {
939 			iter->bio = bio;
940 			iter->iter = bio->bi_iter;
941 			bio_advance_iter(iter->bio, &iter->iter, offset);
942 			return true;
943 		}
944 		offset -= bio->bi_iter.bi_size;
945 	}
946 	return false;
947 }
948 
949 /*
950  * Copy data between request pages and io_iter, and 'offset'
951  * is the start point of linear offset of request.
952  */
ublk_copy_user_pages(const struct request * req,unsigned offset,struct iov_iter * uiter,int dir)953 static size_t ublk_copy_user_pages(const struct request *req,
954 		unsigned offset, struct iov_iter *uiter, int dir)
955 {
956 	struct ublk_io_iter iter;
957 	size_t done = 0;
958 
959 	if (!ublk_advance_io_iter(req, &iter, offset))
960 		return 0;
961 
962 	while (iov_iter_count(uiter) && iter.bio) {
963 		unsigned nr_pages;
964 		ssize_t len;
965 		size_t off;
966 		int i;
967 
968 		len = iov_iter_get_pages2(uiter, iter.pages,
969 				iov_iter_count(uiter),
970 				UBLK_MAX_PIN_PAGES, &off);
971 		if (len <= 0)
972 			return done;
973 
974 		ublk_copy_io_pages(&iter, len, off, dir);
975 		nr_pages = DIV_ROUND_UP(len + off, PAGE_SIZE);
976 		for (i = 0; i < nr_pages; i++) {
977 			if (dir == ITER_DEST)
978 				set_page_dirty(iter.pages[i]);
979 			put_page(iter.pages[i]);
980 		}
981 		done += len;
982 	}
983 
984 	return done;
985 }
986 
ublk_need_map_req(const struct request * req)987 static inline bool ublk_need_map_req(const struct request *req)
988 {
989 	return ublk_rq_has_data(req) && req_op(req) == REQ_OP_WRITE;
990 }
991 
ublk_need_unmap_req(const struct request * req)992 static inline bool ublk_need_unmap_req(const struct request *req)
993 {
994 	return ublk_rq_has_data(req) &&
995 	       (req_op(req) == REQ_OP_READ || req_op(req) == REQ_OP_DRV_IN);
996 }
997 
ublk_map_io(const struct ublk_queue * ubq,const struct request * req,const struct ublk_io * io)998 static int ublk_map_io(const struct ublk_queue *ubq, const struct request *req,
999 		       const struct ublk_io *io)
1000 {
1001 	const unsigned int rq_bytes = blk_rq_bytes(req);
1002 
1003 	if (!ublk_need_map_io(ubq))
1004 		return rq_bytes;
1005 
1006 	/*
1007 	 * no zero copy, we delay copy WRITE request data into ublksrv
1008 	 * context and the big benefit is that pinning pages in current
1009 	 * context is pretty fast, see ublk_pin_user_pages
1010 	 */
1011 	if (ublk_need_map_req(req)) {
1012 		struct iov_iter iter;
1013 		const int dir = ITER_DEST;
1014 
1015 		import_ubuf(dir, u64_to_user_ptr(io->addr), rq_bytes, &iter);
1016 		return ublk_copy_user_pages(req, 0, &iter, dir);
1017 	}
1018 	return rq_bytes;
1019 }
1020 
ublk_unmap_io(const struct ublk_queue * ubq,const struct request * req,const struct ublk_io * io)1021 static int ublk_unmap_io(const struct ublk_queue *ubq,
1022 		const struct request *req,
1023 		const struct ublk_io *io)
1024 {
1025 	const unsigned int rq_bytes = blk_rq_bytes(req);
1026 
1027 	if (!ublk_need_map_io(ubq))
1028 		return rq_bytes;
1029 
1030 	if (ublk_need_unmap_req(req)) {
1031 		struct iov_iter iter;
1032 		const int dir = ITER_SOURCE;
1033 
1034 		WARN_ON_ONCE(io->res > rq_bytes);
1035 
1036 		import_ubuf(dir, u64_to_user_ptr(io->addr), io->res, &iter);
1037 		return ublk_copy_user_pages(req, 0, &iter, dir);
1038 	}
1039 	return rq_bytes;
1040 }
1041 
ublk_req_build_flags(struct request * req)1042 static inline unsigned int ublk_req_build_flags(struct request *req)
1043 {
1044 	unsigned flags = 0;
1045 
1046 	if (req->cmd_flags & REQ_FAILFAST_DEV)
1047 		flags |= UBLK_IO_F_FAILFAST_DEV;
1048 
1049 	if (req->cmd_flags & REQ_FAILFAST_TRANSPORT)
1050 		flags |= UBLK_IO_F_FAILFAST_TRANSPORT;
1051 
1052 	if (req->cmd_flags & REQ_FAILFAST_DRIVER)
1053 		flags |= UBLK_IO_F_FAILFAST_DRIVER;
1054 
1055 	if (req->cmd_flags & REQ_META)
1056 		flags |= UBLK_IO_F_META;
1057 
1058 	if (req->cmd_flags & REQ_FUA)
1059 		flags |= UBLK_IO_F_FUA;
1060 
1061 	if (req->cmd_flags & REQ_NOUNMAP)
1062 		flags |= UBLK_IO_F_NOUNMAP;
1063 
1064 	if (req->cmd_flags & REQ_SWAP)
1065 		flags |= UBLK_IO_F_SWAP;
1066 
1067 	return flags;
1068 }
1069 
ublk_setup_iod(struct ublk_queue * ubq,struct request * req)1070 static blk_status_t ublk_setup_iod(struct ublk_queue *ubq, struct request *req)
1071 {
1072 	struct ublksrv_io_desc *iod = ublk_get_iod(ubq, req->tag);
1073 	struct ublk_io *io = &ubq->ios[req->tag];
1074 	enum req_op op = req_op(req);
1075 	u32 ublk_op;
1076 
1077 	if (!ublk_queue_is_zoned(ubq) &&
1078 	    (op_is_zone_mgmt(op) || op == REQ_OP_ZONE_APPEND))
1079 		return BLK_STS_IOERR;
1080 
1081 	switch (req_op(req)) {
1082 	case REQ_OP_READ:
1083 		ublk_op = UBLK_IO_OP_READ;
1084 		break;
1085 	case REQ_OP_WRITE:
1086 		ublk_op = UBLK_IO_OP_WRITE;
1087 		break;
1088 	case REQ_OP_FLUSH:
1089 		ublk_op = UBLK_IO_OP_FLUSH;
1090 		break;
1091 	case REQ_OP_DISCARD:
1092 		ublk_op = UBLK_IO_OP_DISCARD;
1093 		break;
1094 	case REQ_OP_WRITE_ZEROES:
1095 		ublk_op = UBLK_IO_OP_WRITE_ZEROES;
1096 		break;
1097 	default:
1098 		if (ublk_queue_is_zoned(ubq))
1099 			return ublk_setup_iod_zoned(ubq, req);
1100 		return BLK_STS_IOERR;
1101 	}
1102 
1103 	/* need to translate since kernel may change */
1104 	iod->op_flags = ublk_op | ublk_req_build_flags(req);
1105 	iod->nr_sectors = blk_rq_sectors(req);
1106 	iod->start_sector = blk_rq_pos(req);
1107 	iod->addr = io->addr;
1108 
1109 	return BLK_STS_OK;
1110 }
1111 
ublk_get_uring_cmd_pdu(struct io_uring_cmd * ioucmd)1112 static inline struct ublk_uring_cmd_pdu *ublk_get_uring_cmd_pdu(
1113 		struct io_uring_cmd *ioucmd)
1114 {
1115 	return io_uring_cmd_to_pdu(ioucmd, struct ublk_uring_cmd_pdu);
1116 }
1117 
1118 /* todo: handle partial completion */
__ublk_complete_rq(struct request * req)1119 static inline void __ublk_complete_rq(struct request *req)
1120 {
1121 	struct ublk_queue *ubq = req->mq_hctx->driver_data;
1122 	struct ublk_io *io = &ubq->ios[req->tag];
1123 	unsigned int unmapped_bytes;
1124 	blk_status_t res = BLK_STS_OK;
1125 
1126 	/* failed read IO if nothing is read */
1127 	if (!io->res && req_op(req) == REQ_OP_READ)
1128 		io->res = -EIO;
1129 
1130 	if (io->res < 0) {
1131 		res = errno_to_blk_status(io->res);
1132 		goto exit;
1133 	}
1134 
1135 	/*
1136 	 * FLUSH, DISCARD or WRITE_ZEROES usually won't return bytes returned, so end them
1137 	 * directly.
1138 	 *
1139 	 * Both the two needn't unmap.
1140 	 */
1141 	if (req_op(req) != REQ_OP_READ && req_op(req) != REQ_OP_WRITE &&
1142 	    req_op(req) != REQ_OP_DRV_IN)
1143 		goto exit;
1144 
1145 	/* for READ request, writing data in iod->addr to rq buffers */
1146 	unmapped_bytes = ublk_unmap_io(ubq, req, io);
1147 
1148 	/*
1149 	 * Extremely impossible since we got data filled in just before
1150 	 *
1151 	 * Re-read simply for this unlikely case.
1152 	 */
1153 	if (unlikely(unmapped_bytes < io->res))
1154 		io->res = unmapped_bytes;
1155 
1156 	if (blk_update_request(req, BLK_STS_OK, io->res))
1157 		blk_mq_requeue_request(req, true);
1158 	else if (likely(!blk_should_fake_timeout(req->q)))
1159 		__blk_mq_end_request(req, BLK_STS_OK);
1160 
1161 	return;
1162 exit:
1163 	blk_mq_end_request(req, res);
1164 }
1165 
__ublk_prep_compl_io_cmd(struct ublk_io * io,struct request * req)1166 static struct io_uring_cmd *__ublk_prep_compl_io_cmd(struct ublk_io *io,
1167 						     struct request *req)
1168 {
1169 	/* read cmd first because req will overwrite it */
1170 	struct io_uring_cmd *cmd = io->cmd;
1171 
1172 	/* mark this cmd owned by ublksrv */
1173 	io->flags |= UBLK_IO_FLAG_OWNED_BY_SRV;
1174 
1175 	/*
1176 	 * clear ACTIVE since we are done with this sqe/cmd slot
1177 	 * We can only accept io cmd in case of being not active.
1178 	 */
1179 	io->flags &= ~UBLK_IO_FLAG_ACTIVE;
1180 
1181 	io->req = req;
1182 	return cmd;
1183 }
1184 
ublk_complete_io_cmd(struct ublk_io * io,struct request * req,int res,unsigned issue_flags)1185 static void ublk_complete_io_cmd(struct ublk_io *io, struct request *req,
1186 				 int res, unsigned issue_flags)
1187 {
1188 	struct io_uring_cmd *cmd = __ublk_prep_compl_io_cmd(io, req);
1189 
1190 	/* tell ublksrv one io request is coming */
1191 	io_uring_cmd_done(cmd, res, 0, issue_flags);
1192 }
1193 
1194 #define UBLK_REQUEUE_DELAY_MS	3
1195 
__ublk_abort_rq(struct ublk_queue * ubq,struct request * rq)1196 static inline void __ublk_abort_rq(struct ublk_queue *ubq,
1197 		struct request *rq)
1198 {
1199 	/* We cannot process this rq so just requeue it. */
1200 	if (ublk_nosrv_dev_should_queue_io(ubq->dev))
1201 		blk_mq_requeue_request(rq, false);
1202 	else
1203 		blk_mq_end_request(rq, BLK_STS_IOERR);
1204 }
1205 
1206 static void
ublk_auto_buf_reg_fallback(const struct ublk_queue * ubq,struct ublk_io * io)1207 ublk_auto_buf_reg_fallback(const struct ublk_queue *ubq, struct ublk_io *io)
1208 {
1209 	unsigned tag = io - ubq->ios;
1210 	struct ublksrv_io_desc *iod = ublk_get_iod(ubq, tag);
1211 
1212 	iod->op_flags |= UBLK_IO_F_NEED_REG_BUF;
1213 }
1214 
ublk_auto_buf_reg(const struct ublk_queue * ubq,struct request * req,struct ublk_io * io,unsigned int issue_flags)1215 static bool ublk_auto_buf_reg(const struct ublk_queue *ubq, struct request *req,
1216 			      struct ublk_io *io, unsigned int issue_flags)
1217 {
1218 	int ret;
1219 
1220 	ret = io_buffer_register_bvec(io->cmd, req, ublk_io_release,
1221 				      io->buf.index, issue_flags);
1222 	if (ret) {
1223 		if (io->buf.flags & UBLK_AUTO_BUF_REG_FALLBACK) {
1224 			ublk_auto_buf_reg_fallback(ubq, io);
1225 			return true;
1226 		}
1227 		blk_mq_end_request(req, BLK_STS_IOERR);
1228 		return false;
1229 	}
1230 
1231 	io->task_registered_buffers = 1;
1232 	io->buf_ctx_handle = io_uring_cmd_ctx_handle(io->cmd);
1233 	io->flags |= UBLK_IO_FLAG_AUTO_BUF_REG;
1234 	return true;
1235 }
1236 
ublk_prep_auto_buf_reg(struct ublk_queue * ubq,struct request * req,struct ublk_io * io,unsigned int issue_flags)1237 static bool ublk_prep_auto_buf_reg(struct ublk_queue *ubq,
1238 				   struct request *req, struct ublk_io *io,
1239 				   unsigned int issue_flags)
1240 {
1241 	ublk_init_req_ref(ubq, io);
1242 	if (ublk_support_auto_buf_reg(ubq) && ublk_rq_has_data(req))
1243 		return ublk_auto_buf_reg(ubq, req, io, issue_flags);
1244 
1245 	return true;
1246 }
1247 
ublk_start_io(const struct ublk_queue * ubq,struct request * req,struct ublk_io * io)1248 static bool ublk_start_io(const struct ublk_queue *ubq, struct request *req,
1249 			  struct ublk_io *io)
1250 {
1251 	unsigned mapped_bytes = ublk_map_io(ubq, req, io);
1252 
1253 	/* partially mapped, update io descriptor */
1254 	if (unlikely(mapped_bytes != blk_rq_bytes(req))) {
1255 		/*
1256 		 * Nothing mapped, retry until we succeed.
1257 		 *
1258 		 * We may never succeed in mapping any bytes here because
1259 		 * of OOM. TODO: reserve one buffer with single page pinned
1260 		 * for providing forward progress guarantee.
1261 		 */
1262 		if (unlikely(!mapped_bytes)) {
1263 			blk_mq_requeue_request(req, false);
1264 			blk_mq_delay_kick_requeue_list(req->q,
1265 					UBLK_REQUEUE_DELAY_MS);
1266 			return false;
1267 		}
1268 
1269 		ublk_get_iod(ubq, req->tag)->nr_sectors =
1270 			mapped_bytes >> 9;
1271 	}
1272 
1273 	return true;
1274 }
1275 
ublk_dispatch_req(struct ublk_queue * ubq,struct request * req,unsigned int issue_flags)1276 static void ublk_dispatch_req(struct ublk_queue *ubq,
1277 			      struct request *req,
1278 			      unsigned int issue_flags)
1279 {
1280 	int tag = req->tag;
1281 	struct ublk_io *io = &ubq->ios[tag];
1282 
1283 	pr_devel("%s: complete: qid %d tag %d io_flags %x addr %llx\n",
1284 			__func__, ubq->q_id, req->tag, io->flags,
1285 			ublk_get_iod(ubq, req->tag)->addr);
1286 
1287 	/*
1288 	 * Task is exiting if either:
1289 	 *
1290 	 * (1) current != io->task.
1291 	 * io_uring_cmd_complete_in_task() tries to run task_work
1292 	 * in a workqueue if cmd's task is PF_EXITING.
1293 	 *
1294 	 * (2) current->flags & PF_EXITING.
1295 	 */
1296 	if (unlikely(current != io->task || current->flags & PF_EXITING)) {
1297 		__ublk_abort_rq(ubq, req);
1298 		return;
1299 	}
1300 
1301 	if (ublk_need_get_data(ubq) && ublk_need_map_req(req)) {
1302 		/*
1303 		 * We have not handled UBLK_IO_NEED_GET_DATA command yet,
1304 		 * so immediately pass UBLK_IO_RES_NEED_GET_DATA to ublksrv
1305 		 * and notify it.
1306 		 */
1307 		io->flags |= UBLK_IO_FLAG_NEED_GET_DATA;
1308 		pr_devel("%s: need get data. qid %d tag %d io_flags %x\n",
1309 				__func__, ubq->q_id, req->tag, io->flags);
1310 		ublk_complete_io_cmd(io, req, UBLK_IO_RES_NEED_GET_DATA,
1311 				     issue_flags);
1312 		return;
1313 	}
1314 
1315 	if (!ublk_start_io(ubq, req, io))
1316 		return;
1317 
1318 	if (ublk_prep_auto_buf_reg(ubq, req, io, issue_flags))
1319 		ublk_complete_io_cmd(io, req, UBLK_IO_RES_OK, issue_flags);
1320 }
1321 
ublk_cmd_tw_cb(struct io_uring_cmd * cmd,unsigned int issue_flags)1322 static void ublk_cmd_tw_cb(struct io_uring_cmd *cmd,
1323 			   unsigned int issue_flags)
1324 {
1325 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
1326 	struct ublk_queue *ubq = pdu->ubq;
1327 
1328 	ublk_dispatch_req(ubq, pdu->req, issue_flags);
1329 }
1330 
ublk_queue_cmd(struct ublk_queue * ubq,struct request * rq)1331 static void ublk_queue_cmd(struct ublk_queue *ubq, struct request *rq)
1332 {
1333 	struct io_uring_cmd *cmd = ubq->ios[rq->tag].cmd;
1334 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
1335 
1336 	pdu->req = rq;
1337 	io_uring_cmd_complete_in_task(cmd, ublk_cmd_tw_cb);
1338 }
1339 
ublk_cmd_list_tw_cb(struct io_uring_cmd * cmd,unsigned int issue_flags)1340 static void ublk_cmd_list_tw_cb(struct io_uring_cmd *cmd,
1341 		unsigned int issue_flags)
1342 {
1343 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
1344 	struct request *rq = pdu->req_list;
1345 	struct request *next;
1346 
1347 	do {
1348 		next = rq->rq_next;
1349 		rq->rq_next = NULL;
1350 		ublk_dispatch_req(rq->mq_hctx->driver_data, rq, issue_flags);
1351 		rq = next;
1352 	} while (rq);
1353 }
1354 
ublk_queue_cmd_list(struct ublk_io * io,struct rq_list * l)1355 static void ublk_queue_cmd_list(struct ublk_io *io, struct rq_list *l)
1356 {
1357 	struct io_uring_cmd *cmd = io->cmd;
1358 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
1359 
1360 	pdu->req_list = rq_list_peek(l);
1361 	rq_list_init(l);
1362 	io_uring_cmd_complete_in_task(cmd, ublk_cmd_list_tw_cb);
1363 }
1364 
ublk_timeout(struct request * rq)1365 static enum blk_eh_timer_return ublk_timeout(struct request *rq)
1366 {
1367 	struct ublk_queue *ubq = rq->mq_hctx->driver_data;
1368 	pid_t tgid = ubq->dev->ublksrv_tgid;
1369 	struct task_struct *p;
1370 	struct pid *pid;
1371 
1372 	if (!(ubq->flags & UBLK_F_UNPRIVILEGED_DEV))
1373 		return BLK_EH_RESET_TIMER;
1374 
1375 	if (unlikely(!tgid))
1376 		return BLK_EH_RESET_TIMER;
1377 
1378 	rcu_read_lock();
1379 	pid = find_vpid(tgid);
1380 	p = pid_task(pid, PIDTYPE_PID);
1381 	if (p)
1382 		send_sig(SIGKILL, p, 0);
1383 	rcu_read_unlock();
1384 	return BLK_EH_DONE;
1385 }
1386 
ublk_prep_req(struct ublk_queue * ubq,struct request * rq,bool check_cancel)1387 static blk_status_t ublk_prep_req(struct ublk_queue *ubq, struct request *rq,
1388 				  bool check_cancel)
1389 {
1390 	blk_status_t res;
1391 
1392 	if (unlikely(READ_ONCE(ubq->fail_io)))
1393 		return BLK_STS_TARGET;
1394 
1395 	/* With recovery feature enabled, force_abort is set in
1396 	 * ublk_stop_dev() before calling del_gendisk(). We have to
1397 	 * abort all requeued and new rqs here to let del_gendisk()
1398 	 * move on. Besides, we cannot not call io_uring_cmd_complete_in_task()
1399 	 * to avoid UAF on io_uring ctx.
1400 	 *
1401 	 * Note: force_abort is guaranteed to be seen because it is set
1402 	 * before request queue is unqiuesced.
1403 	 */
1404 	if (ublk_nosrv_should_queue_io(ubq) &&
1405 	    unlikely(READ_ONCE(ubq->force_abort)))
1406 		return BLK_STS_IOERR;
1407 
1408 	if (check_cancel && unlikely(ubq->canceling))
1409 		return BLK_STS_IOERR;
1410 
1411 	/* fill iod to slot in io cmd buffer */
1412 	res = ublk_setup_iod(ubq, rq);
1413 	if (unlikely(res != BLK_STS_OK))
1414 		return BLK_STS_IOERR;
1415 
1416 	blk_mq_start_request(rq);
1417 	return BLK_STS_OK;
1418 }
1419 
ublk_queue_rq(struct blk_mq_hw_ctx * hctx,const struct blk_mq_queue_data * bd)1420 static blk_status_t ublk_queue_rq(struct blk_mq_hw_ctx *hctx,
1421 		const struct blk_mq_queue_data *bd)
1422 {
1423 	struct ublk_queue *ubq = hctx->driver_data;
1424 	struct request *rq = bd->rq;
1425 	blk_status_t res;
1426 
1427 	res = ublk_prep_req(ubq, rq, false);
1428 	if (res != BLK_STS_OK)
1429 		return res;
1430 
1431 	/*
1432 	 * ->canceling has to be handled after ->force_abort and ->fail_io
1433 	 * is dealt with, otherwise this request may not be failed in case
1434 	 * of recovery, and cause hang when deleting disk
1435 	 */
1436 	if (unlikely(ubq->canceling)) {
1437 		__ublk_abort_rq(ubq, rq);
1438 		return BLK_STS_OK;
1439 	}
1440 
1441 	ublk_queue_cmd(ubq, rq);
1442 	return BLK_STS_OK;
1443 }
1444 
ublk_belong_to_same_batch(const struct ublk_io * io,const struct ublk_io * io2)1445 static inline bool ublk_belong_to_same_batch(const struct ublk_io *io,
1446 					     const struct ublk_io *io2)
1447 {
1448 	return (io_uring_cmd_ctx_handle(io->cmd) ==
1449 		io_uring_cmd_ctx_handle(io2->cmd)) &&
1450 		(io->task == io2->task);
1451 }
1452 
ublk_queue_rqs(struct rq_list * rqlist)1453 static void ublk_queue_rqs(struct rq_list *rqlist)
1454 {
1455 	struct rq_list requeue_list = { };
1456 	struct rq_list submit_list = { };
1457 	struct ublk_io *io = NULL;
1458 	struct request *req;
1459 
1460 	while ((req = rq_list_pop(rqlist))) {
1461 		struct ublk_queue *this_q = req->mq_hctx->driver_data;
1462 		struct ublk_io *this_io = &this_q->ios[req->tag];
1463 
1464 		if (ublk_prep_req(this_q, req, true) != BLK_STS_OK) {
1465 			rq_list_add_tail(&requeue_list, req);
1466 			continue;
1467 		}
1468 
1469 		if (io && !ublk_belong_to_same_batch(io, this_io) &&
1470 				!rq_list_empty(&submit_list))
1471 			ublk_queue_cmd_list(io, &submit_list);
1472 		io = this_io;
1473 		rq_list_add_tail(&submit_list, req);
1474 	}
1475 
1476 	if (!rq_list_empty(&submit_list))
1477 		ublk_queue_cmd_list(io, &submit_list);
1478 	*rqlist = requeue_list;
1479 }
1480 
ublk_init_hctx(struct blk_mq_hw_ctx * hctx,void * driver_data,unsigned int hctx_idx)1481 static int ublk_init_hctx(struct blk_mq_hw_ctx *hctx, void *driver_data,
1482 		unsigned int hctx_idx)
1483 {
1484 	struct ublk_device *ub = driver_data;
1485 	struct ublk_queue *ubq = ublk_get_queue(ub, hctx->queue_num);
1486 
1487 	hctx->driver_data = ubq;
1488 	return 0;
1489 }
1490 
1491 static const struct blk_mq_ops ublk_mq_ops = {
1492 	.queue_rq       = ublk_queue_rq,
1493 	.queue_rqs      = ublk_queue_rqs,
1494 	.init_hctx	= ublk_init_hctx,
1495 	.timeout	= ublk_timeout,
1496 };
1497 
ublk_queue_reinit(struct ublk_device * ub,struct ublk_queue * ubq)1498 static void ublk_queue_reinit(struct ublk_device *ub, struct ublk_queue *ubq)
1499 {
1500 	int i;
1501 
1502 	/* All old ioucmds have to be completed */
1503 	ubq->nr_io_ready = 0;
1504 
1505 	for (i = 0; i < ubq->q_depth; i++) {
1506 		struct ublk_io *io = &ubq->ios[i];
1507 
1508 		/*
1509 		 * UBLK_IO_FLAG_CANCELED is kept for avoiding to touch
1510 		 * io->cmd
1511 		 */
1512 		io->flags &= UBLK_IO_FLAG_CANCELED;
1513 		io->cmd = NULL;
1514 		io->addr = 0;
1515 
1516 		/*
1517 		 * old task is PF_EXITING, put it now
1518 		 *
1519 		 * It could be NULL in case of closing one quiesced
1520 		 * device.
1521 		 */
1522 		if (io->task) {
1523 			put_task_struct(io->task);
1524 			io->task = NULL;
1525 		}
1526 
1527 		WARN_ON_ONCE(refcount_read(&io->ref));
1528 		WARN_ON_ONCE(io->task_registered_buffers);
1529 	}
1530 }
1531 
ublk_ch_open(struct inode * inode,struct file * filp)1532 static int ublk_ch_open(struct inode *inode, struct file *filp)
1533 {
1534 	struct ublk_device *ub = container_of(inode->i_cdev,
1535 			struct ublk_device, cdev);
1536 
1537 	if (test_and_set_bit(UB_STATE_OPEN, &ub->state))
1538 		return -EBUSY;
1539 	filp->private_data = ub;
1540 	ub->ublksrv_tgid = current->tgid;
1541 	return 0;
1542 }
1543 
ublk_reset_ch_dev(struct ublk_device * ub)1544 static void ublk_reset_ch_dev(struct ublk_device *ub)
1545 {
1546 	int i;
1547 
1548 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1549 		ublk_queue_reinit(ub, ublk_get_queue(ub, i));
1550 
1551 	/* set to NULL, otherwise new tasks cannot mmap io_cmd_buf */
1552 	ub->mm = NULL;
1553 	ub->nr_queues_ready = 0;
1554 	ub->unprivileged_daemons = false;
1555 	ub->ublksrv_tgid = -1;
1556 }
1557 
ublk_get_disk(struct ublk_device * ub)1558 static struct gendisk *ublk_get_disk(struct ublk_device *ub)
1559 {
1560 	struct gendisk *disk;
1561 
1562 	spin_lock(&ub->lock);
1563 	disk = ub->ub_disk;
1564 	if (disk)
1565 		get_device(disk_to_dev(disk));
1566 	spin_unlock(&ub->lock);
1567 
1568 	return disk;
1569 }
1570 
ublk_put_disk(struct gendisk * disk)1571 static void ublk_put_disk(struct gendisk *disk)
1572 {
1573 	if (disk)
1574 		put_device(disk_to_dev(disk));
1575 }
1576 
1577 /*
1578  * Use this function to ensure that ->canceling is consistently set for
1579  * the device and all queues. Do not set these flags directly.
1580  *
1581  * Caller must ensure that:
1582  * - cancel_mutex is held. This ensures that there is no concurrent
1583  *   access to ub->canceling and no concurrent writes to ubq->canceling.
1584  * - there are no concurrent reads of ubq->canceling from the queue_rq
1585  *   path. This can be done by quiescing the queue, or through other
1586  *   means.
1587  */
ublk_set_canceling(struct ublk_device * ub,bool canceling)1588 static void ublk_set_canceling(struct ublk_device *ub, bool canceling)
1589 	__must_hold(&ub->cancel_mutex)
1590 {
1591 	int i;
1592 
1593 	ub->canceling = canceling;
1594 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1595 		ublk_get_queue(ub, i)->canceling = canceling;
1596 }
1597 
ublk_ch_release(struct inode * inode,struct file * filp)1598 static int ublk_ch_release(struct inode *inode, struct file *filp)
1599 {
1600 	struct ublk_device *ub = filp->private_data;
1601 	struct gendisk *disk;
1602 	int i;
1603 
1604 	/*
1605 	 * disk isn't attached yet, either device isn't live, or it has
1606 	 * been removed already, so we needn't to do anything
1607 	 */
1608 	disk = ublk_get_disk(ub);
1609 	if (!disk)
1610 		goto out;
1611 
1612 	/*
1613 	 * All uring_cmd are done now, so abort any request outstanding to
1614 	 * the ublk server
1615 	 *
1616 	 * This can be done in lockless way because ublk server has been
1617 	 * gone
1618 	 *
1619 	 * More importantly, we have to provide forward progress guarantee
1620 	 * without holding ub->mutex, otherwise control task grabbing
1621 	 * ub->mutex triggers deadlock
1622 	 *
1623 	 * All requests may be inflight, so ->canceling may not be set, set
1624 	 * it now.
1625 	 */
1626 	mutex_lock(&ub->cancel_mutex);
1627 	ublk_set_canceling(ub, true);
1628 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1629 		ublk_abort_queue(ub, ublk_get_queue(ub, i));
1630 	mutex_unlock(&ub->cancel_mutex);
1631 	blk_mq_kick_requeue_list(disk->queue);
1632 
1633 	/*
1634 	 * All infligh requests have been completed or requeued and any new
1635 	 * request will be failed or requeued via `->canceling` now, so it is
1636 	 * fine to grab ub->mutex now.
1637 	 */
1638 	mutex_lock(&ub->mutex);
1639 
1640 	/* double check after grabbing lock */
1641 	if (!ub->ub_disk)
1642 		goto unlock;
1643 
1644 	/*
1645 	 * Transition the device to the nosrv state. What exactly this
1646 	 * means depends on the recovery flags
1647 	 */
1648 	if (ublk_nosrv_should_stop_dev(ub)) {
1649 		/*
1650 		 * Allow any pending/future I/O to pass through quickly
1651 		 * with an error. This is needed because del_gendisk
1652 		 * waits for all pending I/O to complete
1653 		 */
1654 		for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1655 			WRITE_ONCE(ublk_get_queue(ub, i)->force_abort, true);
1656 
1657 		ublk_stop_dev_unlocked(ub);
1658 	} else {
1659 		if (ublk_nosrv_dev_should_queue_io(ub)) {
1660 			/* ->canceling is set and all requests are aborted */
1661 			ub->dev_info.state = UBLK_S_DEV_QUIESCED;
1662 		} else {
1663 			ub->dev_info.state = UBLK_S_DEV_FAIL_IO;
1664 			for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1665 				WRITE_ONCE(ublk_get_queue(ub, i)->fail_io, true);
1666 		}
1667 	}
1668 unlock:
1669 	mutex_unlock(&ub->mutex);
1670 	ublk_put_disk(disk);
1671 
1672 	/* all uring_cmd has been done now, reset device & ubq */
1673 	ublk_reset_ch_dev(ub);
1674 out:
1675 	clear_bit(UB_STATE_OPEN, &ub->state);
1676 	return 0;
1677 }
1678 
1679 /* map pre-allocated per-queue cmd buffer to ublksrv daemon */
ublk_ch_mmap(struct file * filp,struct vm_area_struct * vma)1680 static int ublk_ch_mmap(struct file *filp, struct vm_area_struct *vma)
1681 {
1682 	struct ublk_device *ub = filp->private_data;
1683 	size_t sz = vma->vm_end - vma->vm_start;
1684 	unsigned max_sz = ublk_max_cmd_buf_size();
1685 	unsigned long pfn, end, phys_off = vma->vm_pgoff << PAGE_SHIFT;
1686 	int q_id, ret = 0;
1687 
1688 	spin_lock(&ub->lock);
1689 	if (!ub->mm)
1690 		ub->mm = current->mm;
1691 	if (current->mm != ub->mm)
1692 		ret = -EINVAL;
1693 	spin_unlock(&ub->lock);
1694 
1695 	if (ret)
1696 		return ret;
1697 
1698 	if (vma->vm_flags & VM_WRITE)
1699 		return -EPERM;
1700 
1701 	end = UBLKSRV_CMD_BUF_OFFSET + ub->dev_info.nr_hw_queues * max_sz;
1702 	if (phys_off < UBLKSRV_CMD_BUF_OFFSET || phys_off >= end)
1703 		return -EINVAL;
1704 
1705 	q_id = (phys_off - UBLKSRV_CMD_BUF_OFFSET) / max_sz;
1706 	pr_devel("%s: qid %d, pid %d, addr %lx pg_off %lx sz %lu\n",
1707 			__func__, q_id, current->pid, vma->vm_start,
1708 			phys_off, (unsigned long)sz);
1709 
1710 	if (sz != ublk_queue_cmd_buf_size(ub, q_id))
1711 		return -EINVAL;
1712 
1713 	pfn = virt_to_phys(ublk_queue_cmd_buf(ub, q_id)) >> PAGE_SHIFT;
1714 	return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
1715 }
1716 
__ublk_fail_req(struct ublk_queue * ubq,struct ublk_io * io,struct request * req)1717 static void __ublk_fail_req(struct ublk_queue *ubq, struct ublk_io *io,
1718 		struct request *req)
1719 {
1720 	WARN_ON_ONCE(io->flags & UBLK_IO_FLAG_ACTIVE);
1721 
1722 	if (ublk_nosrv_should_reissue_outstanding(ubq->dev))
1723 		blk_mq_requeue_request(req, false);
1724 	else {
1725 		io->res = -EIO;
1726 		__ublk_complete_rq(req);
1727 	}
1728 }
1729 
1730 /*
1731  * Called from ublk char device release handler, when any uring_cmd is
1732  * done, meantime request queue is "quiesced" since all inflight requests
1733  * can't be completed because ublk server is dead.
1734  *
1735  * So no one can hold our request IO reference any more, simply ignore the
1736  * reference, and complete the request immediately
1737  */
ublk_abort_queue(struct ublk_device * ub,struct ublk_queue * ubq)1738 static void ublk_abort_queue(struct ublk_device *ub, struct ublk_queue *ubq)
1739 {
1740 	int i;
1741 
1742 	for (i = 0; i < ubq->q_depth; i++) {
1743 		struct ublk_io *io = &ubq->ios[i];
1744 
1745 		if (io->flags & UBLK_IO_FLAG_OWNED_BY_SRV)
1746 			__ublk_fail_req(ubq, io, io->req);
1747 	}
1748 }
1749 
ublk_start_cancel(struct ublk_device * ub)1750 static void ublk_start_cancel(struct ublk_device *ub)
1751 {
1752 	struct gendisk *disk = ublk_get_disk(ub);
1753 
1754 	/* Our disk has been dead */
1755 	if (!disk)
1756 		return;
1757 
1758 	mutex_lock(&ub->cancel_mutex);
1759 	if (ub->canceling)
1760 		goto out;
1761 	/*
1762 	 * Now we are serialized with ublk_queue_rq()
1763 	 *
1764 	 * Make sure that ubq->canceling is set when queue is frozen,
1765 	 * because ublk_queue_rq() has to rely on this flag for avoiding to
1766 	 * touch completed uring_cmd
1767 	 */
1768 	blk_mq_quiesce_queue(disk->queue);
1769 	ublk_set_canceling(ub, true);
1770 	blk_mq_unquiesce_queue(disk->queue);
1771 out:
1772 	mutex_unlock(&ub->cancel_mutex);
1773 	ublk_put_disk(disk);
1774 }
1775 
ublk_cancel_cmd(struct ublk_queue * ubq,unsigned tag,unsigned int issue_flags)1776 static void ublk_cancel_cmd(struct ublk_queue *ubq, unsigned tag,
1777 		unsigned int issue_flags)
1778 {
1779 	struct ublk_io *io = &ubq->ios[tag];
1780 	struct ublk_device *ub = ubq->dev;
1781 	struct request *req;
1782 	bool done;
1783 
1784 	if (!(io->flags & UBLK_IO_FLAG_ACTIVE))
1785 		return;
1786 
1787 	/*
1788 	 * Don't try to cancel this command if the request is started for
1789 	 * avoiding race between io_uring_cmd_done() and
1790 	 * io_uring_cmd_complete_in_task().
1791 	 *
1792 	 * Either the started request will be aborted via __ublk_abort_rq(),
1793 	 * then this uring_cmd is canceled next time, or it will be done in
1794 	 * task work function ublk_dispatch_req() because io_uring guarantees
1795 	 * that ublk_dispatch_req() is always called
1796 	 */
1797 	req = blk_mq_tag_to_rq(ub->tag_set.tags[ubq->q_id], tag);
1798 	if (req && blk_mq_request_started(req) && req->tag == tag)
1799 		return;
1800 
1801 	spin_lock(&ubq->cancel_lock);
1802 	done = !!(io->flags & UBLK_IO_FLAG_CANCELED);
1803 	if (!done)
1804 		io->flags |= UBLK_IO_FLAG_CANCELED;
1805 	spin_unlock(&ubq->cancel_lock);
1806 
1807 	if (!done)
1808 		io_uring_cmd_done(io->cmd, UBLK_IO_RES_ABORT, 0, issue_flags);
1809 }
1810 
1811 /*
1812  * The ublk char device won't be closed when calling cancel fn, so both
1813  * ublk device and queue are guaranteed to be live
1814  *
1815  * Two-stage cancel:
1816  *
1817  * - make every active uring_cmd done in ->cancel_fn()
1818  *
1819  * - aborting inflight ublk IO requests in ublk char device release handler,
1820  *   which depends on 1st stage because device can only be closed iff all
1821  *   uring_cmd are done
1822  *
1823  * Do _not_ try to acquire ub->mutex before all inflight requests are
1824  * aborted, otherwise deadlock may be caused.
1825  */
ublk_uring_cmd_cancel_fn(struct io_uring_cmd * cmd,unsigned int issue_flags)1826 static void ublk_uring_cmd_cancel_fn(struct io_uring_cmd *cmd,
1827 		unsigned int issue_flags)
1828 {
1829 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
1830 	struct ublk_queue *ubq = pdu->ubq;
1831 	struct task_struct *task;
1832 	struct ublk_io *io;
1833 
1834 	if (WARN_ON_ONCE(!ubq))
1835 		return;
1836 
1837 	if (WARN_ON_ONCE(pdu->tag >= ubq->q_depth))
1838 		return;
1839 
1840 	task = io_uring_cmd_get_task(cmd);
1841 	io = &ubq->ios[pdu->tag];
1842 	if (WARN_ON_ONCE(task && task != io->task))
1843 		return;
1844 
1845 	ublk_start_cancel(ubq->dev);
1846 
1847 	WARN_ON_ONCE(io->cmd != cmd);
1848 	ublk_cancel_cmd(ubq, pdu->tag, issue_flags);
1849 }
1850 
ublk_queue_ready(struct ublk_queue * ubq)1851 static inline bool ublk_queue_ready(struct ublk_queue *ubq)
1852 {
1853 	return ubq->nr_io_ready == ubq->q_depth;
1854 }
1855 
ublk_cancel_queue(struct ublk_queue * ubq)1856 static void ublk_cancel_queue(struct ublk_queue *ubq)
1857 {
1858 	int i;
1859 
1860 	for (i = 0; i < ubq->q_depth; i++)
1861 		ublk_cancel_cmd(ubq, i, IO_URING_F_UNLOCKED);
1862 }
1863 
1864 /* Cancel all pending commands, must be called after del_gendisk() returns */
ublk_cancel_dev(struct ublk_device * ub)1865 static void ublk_cancel_dev(struct ublk_device *ub)
1866 {
1867 	int i;
1868 
1869 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1870 		ublk_cancel_queue(ublk_get_queue(ub, i));
1871 }
1872 
ublk_check_inflight_rq(struct request * rq,void * data)1873 static bool ublk_check_inflight_rq(struct request *rq, void *data)
1874 {
1875 	bool *idle = data;
1876 
1877 	if (blk_mq_request_started(rq)) {
1878 		*idle = false;
1879 		return false;
1880 	}
1881 	return true;
1882 }
1883 
ublk_wait_tagset_rqs_idle(struct ublk_device * ub)1884 static void ublk_wait_tagset_rqs_idle(struct ublk_device *ub)
1885 {
1886 	bool idle;
1887 
1888 	WARN_ON_ONCE(!blk_queue_quiesced(ub->ub_disk->queue));
1889 	while (true) {
1890 		idle = true;
1891 		blk_mq_tagset_busy_iter(&ub->tag_set,
1892 				ublk_check_inflight_rq, &idle);
1893 		if (idle)
1894 			break;
1895 		msleep(UBLK_REQUEUE_DELAY_MS);
1896 	}
1897 }
1898 
ublk_force_abort_dev(struct ublk_device * ub)1899 static void ublk_force_abort_dev(struct ublk_device *ub)
1900 {
1901 	int i;
1902 
1903 	pr_devel("%s: force abort ub: dev_id %d state %s\n",
1904 			__func__, ub->dev_info.dev_id,
1905 			ub->dev_info.state == UBLK_S_DEV_LIVE ?
1906 			"LIVE" : "QUIESCED");
1907 	blk_mq_quiesce_queue(ub->ub_disk->queue);
1908 	if (ub->dev_info.state == UBLK_S_DEV_LIVE)
1909 		ublk_wait_tagset_rqs_idle(ub);
1910 
1911 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1912 		ublk_get_queue(ub, i)->force_abort = true;
1913 	blk_mq_unquiesce_queue(ub->ub_disk->queue);
1914 	/* We may have requeued some rqs in ublk_quiesce_queue() */
1915 	blk_mq_kick_requeue_list(ub->ub_disk->queue);
1916 }
1917 
ublk_detach_disk(struct ublk_device * ub)1918 static struct gendisk *ublk_detach_disk(struct ublk_device *ub)
1919 {
1920 	struct gendisk *disk;
1921 
1922 	/* Sync with ublk_abort_queue() by holding the lock */
1923 	spin_lock(&ub->lock);
1924 	disk = ub->ub_disk;
1925 	ub->dev_info.state = UBLK_S_DEV_DEAD;
1926 	ub->dev_info.ublksrv_pid = -1;
1927 	ub->ub_disk = NULL;
1928 	spin_unlock(&ub->lock);
1929 
1930 	return disk;
1931 }
1932 
ublk_stop_dev_unlocked(struct ublk_device * ub)1933 static void ublk_stop_dev_unlocked(struct ublk_device *ub)
1934 	__must_hold(&ub->mutex)
1935 {
1936 	struct gendisk *disk;
1937 
1938 	if (ub->dev_info.state == UBLK_S_DEV_DEAD)
1939 		return;
1940 
1941 	if (ublk_nosrv_dev_should_queue_io(ub))
1942 		ublk_force_abort_dev(ub);
1943 	del_gendisk(ub->ub_disk);
1944 	disk = ublk_detach_disk(ub);
1945 	put_disk(disk);
1946 }
1947 
ublk_stop_dev(struct ublk_device * ub)1948 static void ublk_stop_dev(struct ublk_device *ub)
1949 {
1950 	mutex_lock(&ub->mutex);
1951 	ublk_stop_dev_unlocked(ub);
1952 	mutex_unlock(&ub->mutex);
1953 	ublk_cancel_dev(ub);
1954 }
1955 
1956 /* reset ublk io_uring queue & io flags */
ublk_reset_io_flags(struct ublk_device * ub)1957 static void ublk_reset_io_flags(struct ublk_device *ub)
1958 {
1959 	int i, j;
1960 
1961 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++) {
1962 		struct ublk_queue *ubq = ublk_get_queue(ub, i);
1963 
1964 		/* UBLK_IO_FLAG_CANCELED can be cleared now */
1965 		spin_lock(&ubq->cancel_lock);
1966 		for (j = 0; j < ubq->q_depth; j++)
1967 			ubq->ios[j].flags &= ~UBLK_IO_FLAG_CANCELED;
1968 		spin_unlock(&ubq->cancel_lock);
1969 		ubq->fail_io = false;
1970 	}
1971 	mutex_lock(&ub->cancel_mutex);
1972 	ublk_set_canceling(ub, false);
1973 	mutex_unlock(&ub->cancel_mutex);
1974 }
1975 
1976 /* device can only be started after all IOs are ready */
ublk_mark_io_ready(struct ublk_device * ub,struct ublk_queue * ubq)1977 static void ublk_mark_io_ready(struct ublk_device *ub, struct ublk_queue *ubq)
1978 	__must_hold(&ub->mutex)
1979 {
1980 	ubq->nr_io_ready++;
1981 	if (ublk_queue_ready(ubq))
1982 		ub->nr_queues_ready++;
1983 	if (!ub->unprivileged_daemons && !capable(CAP_SYS_ADMIN))
1984 		ub->unprivileged_daemons = true;
1985 
1986 	if (ub->nr_queues_ready == ub->dev_info.nr_hw_queues) {
1987 		/* now we are ready for handling ublk io request */
1988 		ublk_reset_io_flags(ub);
1989 		complete_all(&ub->completion);
1990 	}
1991 }
1992 
ublk_check_cmd_op(u32 cmd_op)1993 static inline int ublk_check_cmd_op(u32 cmd_op)
1994 {
1995 	u32 ioc_type = _IOC_TYPE(cmd_op);
1996 
1997 	if (!IS_ENABLED(CONFIG_BLKDEV_UBLK_LEGACY_OPCODES) && ioc_type != 'u')
1998 		return -EOPNOTSUPP;
1999 
2000 	if (ioc_type != 'u' && ioc_type != 0)
2001 		return -EOPNOTSUPP;
2002 
2003 	return 0;
2004 }
2005 
ublk_set_auto_buf_reg(struct ublk_io * io,struct io_uring_cmd * cmd)2006 static inline int ublk_set_auto_buf_reg(struct ublk_io *io, struct io_uring_cmd *cmd)
2007 {
2008 	io->buf = ublk_sqe_addr_to_auto_buf_reg(READ_ONCE(cmd->sqe->addr));
2009 
2010 	if (io->buf.reserved0 || io->buf.reserved1)
2011 		return -EINVAL;
2012 
2013 	if (io->buf.flags & ~UBLK_AUTO_BUF_REG_F_MASK)
2014 		return -EINVAL;
2015 	return 0;
2016 }
2017 
ublk_handle_auto_buf_reg(struct ublk_io * io,struct io_uring_cmd * cmd,u16 * buf_idx)2018 static int ublk_handle_auto_buf_reg(struct ublk_io *io,
2019 				    struct io_uring_cmd *cmd,
2020 				    u16 *buf_idx)
2021 {
2022 	if (io->flags & UBLK_IO_FLAG_AUTO_BUF_REG) {
2023 		io->flags &= ~UBLK_IO_FLAG_AUTO_BUF_REG;
2024 
2025 		/*
2026 		 * `UBLK_F_AUTO_BUF_REG` only works iff `UBLK_IO_FETCH_REQ`
2027 		 * and `UBLK_IO_COMMIT_AND_FETCH_REQ` are issued from same
2028 		 * `io_ring_ctx`.
2029 		 *
2030 		 * If this uring_cmd's io_ring_ctx isn't same with the
2031 		 * one for registering the buffer, it is ublk server's
2032 		 * responsibility for unregistering the buffer, otherwise
2033 		 * this ublk request gets stuck.
2034 		 */
2035 		if (io->buf_ctx_handle == io_uring_cmd_ctx_handle(cmd))
2036 			*buf_idx = io->buf.index;
2037 	}
2038 
2039 	return ublk_set_auto_buf_reg(io, cmd);
2040 }
2041 
2042 /* Once we return, `io->req` can't be used any more */
2043 static inline struct request *
ublk_fill_io_cmd(struct ublk_io * io,struct io_uring_cmd * cmd)2044 ublk_fill_io_cmd(struct ublk_io *io, struct io_uring_cmd *cmd)
2045 {
2046 	struct request *req = io->req;
2047 
2048 	io->cmd = cmd;
2049 	io->flags |= UBLK_IO_FLAG_ACTIVE;
2050 	/* now this cmd slot is owned by ublk driver */
2051 	io->flags &= ~UBLK_IO_FLAG_OWNED_BY_SRV;
2052 
2053 	return req;
2054 }
2055 
2056 static inline int
ublk_config_io_buf(const struct ublk_queue * ubq,struct ublk_io * io,struct io_uring_cmd * cmd,unsigned long buf_addr,u16 * buf_idx)2057 ublk_config_io_buf(const struct ublk_queue *ubq, struct ublk_io *io,
2058 		   struct io_uring_cmd *cmd, unsigned long buf_addr,
2059 		   u16 *buf_idx)
2060 {
2061 	if (ublk_support_auto_buf_reg(ubq))
2062 		return ublk_handle_auto_buf_reg(io, cmd, buf_idx);
2063 
2064 	io->addr = buf_addr;
2065 	return 0;
2066 }
2067 
ublk_prep_cancel(struct io_uring_cmd * cmd,unsigned int issue_flags,struct ublk_queue * ubq,unsigned int tag)2068 static inline void ublk_prep_cancel(struct io_uring_cmd *cmd,
2069 				    unsigned int issue_flags,
2070 				    struct ublk_queue *ubq, unsigned int tag)
2071 {
2072 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
2073 
2074 	/*
2075 	 * Safe to refer to @ubq since ublk_queue won't be died until its
2076 	 * commands are completed
2077 	 */
2078 	pdu->ubq = ubq;
2079 	pdu->tag = tag;
2080 	io_uring_cmd_mark_cancelable(cmd, issue_flags);
2081 }
2082 
ublk_io_release(void * priv)2083 static void ublk_io_release(void *priv)
2084 {
2085 	struct request *rq = priv;
2086 	struct ublk_queue *ubq = rq->mq_hctx->driver_data;
2087 	struct ublk_io *io = &ubq->ios[rq->tag];
2088 
2089 	/*
2090 	 * task_registered_buffers may be 0 if buffers were registered off task
2091 	 * but unregistered on task. Or after UBLK_IO_COMMIT_AND_FETCH_REQ.
2092 	 */
2093 	if (current == io->task && io->task_registered_buffers)
2094 		io->task_registered_buffers--;
2095 	else
2096 		ublk_put_req_ref(io, rq);
2097 }
2098 
ublk_register_io_buf(struct io_uring_cmd * cmd,const struct ublk_queue * ubq,struct ublk_io * io,unsigned int index,unsigned int issue_flags)2099 static int ublk_register_io_buf(struct io_uring_cmd *cmd,
2100 				const struct ublk_queue *ubq,
2101 				struct ublk_io *io,
2102 				unsigned int index, unsigned int issue_flags)
2103 {
2104 	struct ublk_device *ub = cmd->file->private_data;
2105 	struct request *req;
2106 	int ret;
2107 
2108 	if (!ublk_support_zero_copy(ubq))
2109 		return -EINVAL;
2110 
2111 	req = __ublk_check_and_get_req(ub, ubq, io, 0);
2112 	if (!req)
2113 		return -EINVAL;
2114 
2115 	ret = io_buffer_register_bvec(cmd, req, ublk_io_release, index,
2116 				      issue_flags);
2117 	if (ret) {
2118 		ublk_put_req_ref(io, req);
2119 		return ret;
2120 	}
2121 
2122 	return 0;
2123 }
2124 
2125 static int
ublk_daemon_register_io_buf(struct io_uring_cmd * cmd,const struct ublk_queue * ubq,struct ublk_io * io,unsigned index,unsigned issue_flags)2126 ublk_daemon_register_io_buf(struct io_uring_cmd *cmd,
2127 			    const struct ublk_queue *ubq, struct ublk_io *io,
2128 			    unsigned index, unsigned issue_flags)
2129 {
2130 	unsigned new_registered_buffers;
2131 	struct request *req = io->req;
2132 	int ret;
2133 
2134 	/*
2135 	 * Ensure there are still references for ublk_sub_req_ref() to release.
2136 	 * If not, fall back on the thread-safe buffer registration.
2137 	 */
2138 	new_registered_buffers = io->task_registered_buffers + 1;
2139 	if (unlikely(new_registered_buffers >= UBLK_REFCOUNT_INIT))
2140 		return ublk_register_io_buf(cmd, ubq, io, index, issue_flags);
2141 
2142 	if (!ublk_support_zero_copy(ubq) || !ublk_rq_has_data(req))
2143 		return -EINVAL;
2144 
2145 	ret = io_buffer_register_bvec(cmd, req, ublk_io_release, index,
2146 				      issue_flags);
2147 	if (ret)
2148 		return ret;
2149 
2150 	io->task_registered_buffers = new_registered_buffers;
2151 	return 0;
2152 }
2153 
ublk_unregister_io_buf(struct io_uring_cmd * cmd,const struct ublk_device * ub,unsigned int index,unsigned int issue_flags)2154 static int ublk_unregister_io_buf(struct io_uring_cmd *cmd,
2155 				  const struct ublk_device *ub,
2156 				  unsigned int index, unsigned int issue_flags)
2157 {
2158 	if (!(ub->dev_info.flags & UBLK_F_SUPPORT_ZERO_COPY))
2159 		return -EINVAL;
2160 
2161 	return io_buffer_unregister_bvec(cmd, index, issue_flags);
2162 }
2163 
ublk_check_fetch_buf(const struct ublk_queue * ubq,__u64 buf_addr)2164 static int ublk_check_fetch_buf(const struct ublk_queue *ubq, __u64 buf_addr)
2165 {
2166 	if (ublk_need_map_io(ubq)) {
2167 		/*
2168 		 * FETCH_RQ has to provide IO buffer if NEED GET
2169 		 * DATA is not enabled
2170 		 */
2171 		if (!buf_addr && !ublk_need_get_data(ubq))
2172 			return -EINVAL;
2173 	} else if (buf_addr) {
2174 		/* User copy requires addr to be unset */
2175 		return -EINVAL;
2176 	}
2177 	return 0;
2178 }
2179 
ublk_fetch(struct io_uring_cmd * cmd,struct ublk_queue * ubq,struct ublk_io * io,__u64 buf_addr)2180 static int ublk_fetch(struct io_uring_cmd *cmd, struct ublk_queue *ubq,
2181 		      struct ublk_io *io, __u64 buf_addr)
2182 {
2183 	struct ublk_device *ub = ubq->dev;
2184 	int ret = 0;
2185 
2186 	/*
2187 	 * When handling FETCH command for setting up ublk uring queue,
2188 	 * ub->mutex is the innermost lock, and we won't block for handling
2189 	 * FETCH, so it is fine even for IO_URING_F_NONBLOCK.
2190 	 */
2191 	mutex_lock(&ub->mutex);
2192 	/* UBLK_IO_FETCH_REQ is only allowed before queue is setup */
2193 	if (ublk_queue_ready(ubq)) {
2194 		ret = -EBUSY;
2195 		goto out;
2196 	}
2197 
2198 	/* allow each command to be FETCHed at most once */
2199 	if (io->flags & UBLK_IO_FLAG_ACTIVE) {
2200 		ret = -EINVAL;
2201 		goto out;
2202 	}
2203 
2204 	WARN_ON_ONCE(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV);
2205 
2206 	ublk_fill_io_cmd(io, cmd);
2207 	ret = ublk_config_io_buf(ubq, io, cmd, buf_addr, NULL);
2208 	if (ret)
2209 		goto out;
2210 
2211 	WRITE_ONCE(io->task, get_task_struct(current));
2212 	ublk_mark_io_ready(ub, ubq);
2213 out:
2214 	mutex_unlock(&ub->mutex);
2215 	return ret;
2216 }
2217 
ublk_check_commit_and_fetch(const struct ublk_queue * ubq,struct ublk_io * io,__u64 buf_addr)2218 static int ublk_check_commit_and_fetch(const struct ublk_queue *ubq,
2219 				       struct ublk_io *io, __u64 buf_addr)
2220 {
2221 	struct request *req = io->req;
2222 
2223 	if (ublk_need_map_io(ubq)) {
2224 		/*
2225 		 * COMMIT_AND_FETCH_REQ has to provide IO buffer if
2226 		 * NEED GET DATA is not enabled or it is Read IO.
2227 		 */
2228 		if (!buf_addr && (!ublk_need_get_data(ubq) ||
2229 					req_op(req) == REQ_OP_READ))
2230 			return -EINVAL;
2231 	} else if (req_op(req) != REQ_OP_ZONE_APPEND && buf_addr) {
2232 		/*
2233 		 * User copy requires addr to be unset when command is
2234 		 * not zone append
2235 		 */
2236 		return -EINVAL;
2237 	}
2238 
2239 	return 0;
2240 }
2241 
ublk_need_complete_req(const struct ublk_queue * ubq,struct ublk_io * io)2242 static bool ublk_need_complete_req(const struct ublk_queue *ubq,
2243 				   struct ublk_io *io)
2244 {
2245 	if (ublk_need_req_ref(ubq))
2246 		return ublk_sub_req_ref(io);
2247 	return true;
2248 }
2249 
ublk_get_data(const struct ublk_queue * ubq,struct ublk_io * io,struct request * req)2250 static bool ublk_get_data(const struct ublk_queue *ubq, struct ublk_io *io,
2251 			  struct request *req)
2252 {
2253 	/*
2254 	 * We have handled UBLK_IO_NEED_GET_DATA command,
2255 	 * so clear UBLK_IO_FLAG_NEED_GET_DATA now and just
2256 	 * do the copy work.
2257 	 */
2258 	io->flags &= ~UBLK_IO_FLAG_NEED_GET_DATA;
2259 	/* update iod->addr because ublksrv may have passed a new io buffer */
2260 	ublk_get_iod(ubq, req->tag)->addr = io->addr;
2261 	pr_devel("%s: update iod->addr: qid %d tag %d io_flags %x addr %llx\n",
2262 			__func__, ubq->q_id, req->tag, io->flags,
2263 			ublk_get_iod(ubq, req->tag)->addr);
2264 
2265 	return ublk_start_io(ubq, req, io);
2266 }
2267 
__ublk_ch_uring_cmd(struct io_uring_cmd * cmd,unsigned int issue_flags,const struct ublksrv_io_cmd * ub_cmd)2268 static int __ublk_ch_uring_cmd(struct io_uring_cmd *cmd,
2269 			       unsigned int issue_flags,
2270 			       const struct ublksrv_io_cmd *ub_cmd)
2271 {
2272 	u16 buf_idx = UBLK_INVALID_BUF_IDX;
2273 	struct ublk_device *ub = cmd->file->private_data;
2274 	struct ublk_queue *ubq;
2275 	struct ublk_io *io;
2276 	u32 cmd_op = cmd->cmd_op;
2277 	unsigned tag = ub_cmd->tag;
2278 	struct request *req;
2279 	int ret;
2280 	bool compl;
2281 
2282 	pr_devel("%s: received: cmd op %d queue %d tag %d result %d\n",
2283 			__func__, cmd->cmd_op, ub_cmd->q_id, tag,
2284 			ub_cmd->result);
2285 
2286 	ret = ublk_check_cmd_op(cmd_op);
2287 	if (ret)
2288 		goto out;
2289 
2290 	/*
2291 	 * io_buffer_unregister_bvec() doesn't access the ubq or io,
2292 	 * so no need to validate the q_id, tag, or task
2293 	 */
2294 	if (_IOC_NR(cmd_op) == UBLK_IO_UNREGISTER_IO_BUF)
2295 		return ublk_unregister_io_buf(cmd, ub, ub_cmd->addr,
2296 					      issue_flags);
2297 
2298 	ret = -EINVAL;
2299 	if (ub_cmd->q_id >= ub->dev_info.nr_hw_queues)
2300 		goto out;
2301 
2302 	ubq = ublk_get_queue(ub, ub_cmd->q_id);
2303 
2304 	if (tag >= ubq->q_depth)
2305 		goto out;
2306 
2307 	io = &ubq->ios[tag];
2308 	/* UBLK_IO_FETCH_REQ can be handled on any task, which sets io->task */
2309 	if (unlikely(_IOC_NR(cmd_op) == UBLK_IO_FETCH_REQ)) {
2310 		ret = ublk_check_fetch_buf(ubq, ub_cmd->addr);
2311 		if (ret)
2312 			goto out;
2313 		ret = ublk_fetch(cmd, ubq, io, ub_cmd->addr);
2314 		if (ret)
2315 			goto out;
2316 
2317 		ublk_prep_cancel(cmd, issue_flags, ubq, tag);
2318 		return -EIOCBQUEUED;
2319 	}
2320 
2321 	if (READ_ONCE(io->task) != current) {
2322 		/*
2323 		 * ublk_register_io_buf() accesses only the io's refcount,
2324 		 * so can be handled on any task
2325 		 */
2326 		if (_IOC_NR(cmd_op) == UBLK_IO_REGISTER_IO_BUF)
2327 			return ublk_register_io_buf(cmd, ubq, io, ub_cmd->addr,
2328 						    issue_flags);
2329 
2330 		goto out;
2331 	}
2332 
2333 	/* there is pending io cmd, something must be wrong */
2334 	if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV)) {
2335 		ret = -EBUSY;
2336 		goto out;
2337 	}
2338 
2339 	/*
2340 	 * ensure that the user issues UBLK_IO_NEED_GET_DATA
2341 	 * iff the driver have set the UBLK_IO_FLAG_NEED_GET_DATA.
2342 	 */
2343 	if ((!!(io->flags & UBLK_IO_FLAG_NEED_GET_DATA))
2344 			^ (_IOC_NR(cmd_op) == UBLK_IO_NEED_GET_DATA))
2345 		goto out;
2346 
2347 	switch (_IOC_NR(cmd_op)) {
2348 	case UBLK_IO_REGISTER_IO_BUF:
2349 		return ublk_daemon_register_io_buf(cmd, ubq, io, ub_cmd->addr,
2350 						   issue_flags);
2351 	case UBLK_IO_COMMIT_AND_FETCH_REQ:
2352 		ret = ublk_check_commit_and_fetch(ubq, io, ub_cmd->addr);
2353 		if (ret)
2354 			goto out;
2355 		io->res = ub_cmd->result;
2356 		req = ublk_fill_io_cmd(io, cmd);
2357 		ret = ublk_config_io_buf(ubq, io, cmd, ub_cmd->addr, &buf_idx);
2358 		compl = ublk_need_complete_req(ubq, io);
2359 
2360 		/* can't touch 'ublk_io' any more */
2361 		if (buf_idx != UBLK_INVALID_BUF_IDX)
2362 			io_buffer_unregister_bvec(cmd, buf_idx, issue_flags);
2363 		if (req_op(req) == REQ_OP_ZONE_APPEND)
2364 			req->__sector = ub_cmd->zone_append_lba;
2365 		if (compl)
2366 			__ublk_complete_rq(req);
2367 
2368 		if (ret)
2369 			goto out;
2370 		break;
2371 	case UBLK_IO_NEED_GET_DATA:
2372 		/*
2373 		 * ublk_get_data() may fail and fallback to requeue, so keep
2374 		 * uring_cmd active first and prepare for handling new requeued
2375 		 * request
2376 		 */
2377 		req = ublk_fill_io_cmd(io, cmd);
2378 		ret = ublk_config_io_buf(ubq, io, cmd, ub_cmd->addr, NULL);
2379 		WARN_ON_ONCE(ret);
2380 		if (likely(ublk_get_data(ubq, io, req))) {
2381 			__ublk_prep_compl_io_cmd(io, req);
2382 			return UBLK_IO_RES_OK;
2383 		}
2384 		break;
2385 	default:
2386 		goto out;
2387 	}
2388 	ublk_prep_cancel(cmd, issue_flags, ubq, tag);
2389 	return -EIOCBQUEUED;
2390 
2391  out:
2392 	pr_devel("%s: complete: cmd op %d, tag %d ret %x io_flags %x\n",
2393 			__func__, cmd_op, tag, ret, io->flags);
2394 	return ret;
2395 }
2396 
__ublk_check_and_get_req(struct ublk_device * ub,const struct ublk_queue * ubq,struct ublk_io * io,size_t offset)2397 static inline struct request *__ublk_check_and_get_req(struct ublk_device *ub,
2398 		const struct ublk_queue *ubq, struct ublk_io *io, size_t offset)
2399 {
2400 	unsigned tag = io - ubq->ios;
2401 	struct request *req;
2402 
2403 	/*
2404 	 * can't use io->req in case of concurrent UBLK_IO_COMMIT_AND_FETCH_REQ,
2405 	 * which would overwrite it with io->cmd
2406 	 */
2407 	req = blk_mq_tag_to_rq(ub->tag_set.tags[ubq->q_id], tag);
2408 	if (!req)
2409 		return NULL;
2410 
2411 	if (!ublk_get_req_ref(io))
2412 		return NULL;
2413 
2414 	if (unlikely(!blk_mq_request_started(req) || req->tag != tag))
2415 		goto fail_put;
2416 
2417 	if (!ublk_rq_has_data(req))
2418 		goto fail_put;
2419 
2420 	if (offset > blk_rq_bytes(req))
2421 		goto fail_put;
2422 
2423 	return req;
2424 fail_put:
2425 	ublk_put_req_ref(io, req);
2426 	return NULL;
2427 }
2428 
ublk_ch_uring_cmd_local(struct io_uring_cmd * cmd,unsigned int issue_flags)2429 static inline int ublk_ch_uring_cmd_local(struct io_uring_cmd *cmd,
2430 		unsigned int issue_flags)
2431 {
2432 	/*
2433 	 * Not necessary for async retry, but let's keep it simple and always
2434 	 * copy the values to avoid any potential reuse.
2435 	 */
2436 	const struct ublksrv_io_cmd *ub_src = io_uring_sqe_cmd(cmd->sqe);
2437 	const struct ublksrv_io_cmd ub_cmd = {
2438 		.q_id = READ_ONCE(ub_src->q_id),
2439 		.tag = READ_ONCE(ub_src->tag),
2440 		.result = READ_ONCE(ub_src->result),
2441 		.addr = READ_ONCE(ub_src->addr)
2442 	};
2443 
2444 	WARN_ON_ONCE(issue_flags & IO_URING_F_UNLOCKED);
2445 
2446 	return __ublk_ch_uring_cmd(cmd, issue_flags, &ub_cmd);
2447 }
2448 
ublk_ch_uring_cmd_cb(struct io_uring_cmd * cmd,unsigned int issue_flags)2449 static void ublk_ch_uring_cmd_cb(struct io_uring_cmd *cmd,
2450 		unsigned int issue_flags)
2451 {
2452 	int ret = ublk_ch_uring_cmd_local(cmd, issue_flags);
2453 
2454 	if (ret != -EIOCBQUEUED)
2455 		io_uring_cmd_done(cmd, ret, 0, issue_flags);
2456 }
2457 
ublk_ch_uring_cmd(struct io_uring_cmd * cmd,unsigned int issue_flags)2458 static int ublk_ch_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags)
2459 {
2460 	if (unlikely(issue_flags & IO_URING_F_CANCEL)) {
2461 		ublk_uring_cmd_cancel_fn(cmd, issue_flags);
2462 		return 0;
2463 	}
2464 
2465 	/* well-implemented server won't run into unlocked */
2466 	if (unlikely(issue_flags & IO_URING_F_UNLOCKED)) {
2467 		io_uring_cmd_complete_in_task(cmd, ublk_ch_uring_cmd_cb);
2468 		return -EIOCBQUEUED;
2469 	}
2470 
2471 	return ublk_ch_uring_cmd_local(cmd, issue_flags);
2472 }
2473 
ublk_check_ubuf_dir(const struct request * req,int ubuf_dir)2474 static inline bool ublk_check_ubuf_dir(const struct request *req,
2475 		int ubuf_dir)
2476 {
2477 	/* copy ubuf to request pages */
2478 	if ((req_op(req) == REQ_OP_READ || req_op(req) == REQ_OP_DRV_IN) &&
2479 	    ubuf_dir == ITER_SOURCE)
2480 		return true;
2481 
2482 	/* copy request pages to ubuf */
2483 	if ((req_op(req) == REQ_OP_WRITE ||
2484 	     req_op(req) == REQ_OP_ZONE_APPEND) &&
2485 	    ubuf_dir == ITER_DEST)
2486 		return true;
2487 
2488 	return false;
2489 }
2490 
ublk_check_and_get_req(struct kiocb * iocb,struct iov_iter * iter,size_t * off,int dir,struct ublk_io ** io)2491 static struct request *ublk_check_and_get_req(struct kiocb *iocb,
2492 		struct iov_iter *iter, size_t *off, int dir,
2493 		struct ublk_io **io)
2494 {
2495 	struct ublk_device *ub = iocb->ki_filp->private_data;
2496 	struct ublk_queue *ubq;
2497 	struct request *req;
2498 	size_t buf_off;
2499 	u16 tag, q_id;
2500 
2501 	if (!ub)
2502 		return ERR_PTR(-EACCES);
2503 
2504 	if (!user_backed_iter(iter))
2505 		return ERR_PTR(-EACCES);
2506 
2507 	if (ub->dev_info.state == UBLK_S_DEV_DEAD)
2508 		return ERR_PTR(-EACCES);
2509 
2510 	tag = ublk_pos_to_tag(iocb->ki_pos);
2511 	q_id = ublk_pos_to_hwq(iocb->ki_pos);
2512 	buf_off = ublk_pos_to_buf_off(iocb->ki_pos);
2513 
2514 	if (q_id >= ub->dev_info.nr_hw_queues)
2515 		return ERR_PTR(-EINVAL);
2516 
2517 	ubq = ublk_get_queue(ub, q_id);
2518 	if (!ubq)
2519 		return ERR_PTR(-EINVAL);
2520 
2521 	if (!ublk_support_user_copy(ubq))
2522 		return ERR_PTR(-EACCES);
2523 
2524 	if (tag >= ubq->q_depth)
2525 		return ERR_PTR(-EINVAL);
2526 
2527 	*io = &ubq->ios[tag];
2528 	req = __ublk_check_and_get_req(ub, ubq, *io, buf_off);
2529 	if (!req)
2530 		return ERR_PTR(-EINVAL);
2531 
2532 	if (!req->mq_hctx || !req->mq_hctx->driver_data)
2533 		goto fail;
2534 
2535 	if (!ublk_check_ubuf_dir(req, dir))
2536 		goto fail;
2537 
2538 	*off = buf_off;
2539 	return req;
2540 fail:
2541 	ublk_put_req_ref(*io, req);
2542 	return ERR_PTR(-EACCES);
2543 }
2544 
ublk_ch_read_iter(struct kiocb * iocb,struct iov_iter * to)2545 static ssize_t ublk_ch_read_iter(struct kiocb *iocb, struct iov_iter *to)
2546 {
2547 	struct request *req;
2548 	struct ublk_io *io;
2549 	size_t buf_off;
2550 	size_t ret;
2551 
2552 	req = ublk_check_and_get_req(iocb, to, &buf_off, ITER_DEST, &io);
2553 	if (IS_ERR(req))
2554 		return PTR_ERR(req);
2555 
2556 	ret = ublk_copy_user_pages(req, buf_off, to, ITER_DEST);
2557 	ublk_put_req_ref(io, req);
2558 
2559 	return ret;
2560 }
2561 
ublk_ch_write_iter(struct kiocb * iocb,struct iov_iter * from)2562 static ssize_t ublk_ch_write_iter(struct kiocb *iocb, struct iov_iter *from)
2563 {
2564 	struct request *req;
2565 	struct ublk_io *io;
2566 	size_t buf_off;
2567 	size_t ret;
2568 
2569 	req = ublk_check_and_get_req(iocb, from, &buf_off, ITER_SOURCE, &io);
2570 	if (IS_ERR(req))
2571 		return PTR_ERR(req);
2572 
2573 	ret = ublk_copy_user_pages(req, buf_off, from, ITER_SOURCE);
2574 	ublk_put_req_ref(io, req);
2575 
2576 	return ret;
2577 }
2578 
2579 static const struct file_operations ublk_ch_fops = {
2580 	.owner = THIS_MODULE,
2581 	.open = ublk_ch_open,
2582 	.release = ublk_ch_release,
2583 	.read_iter = ublk_ch_read_iter,
2584 	.write_iter = ublk_ch_write_iter,
2585 	.uring_cmd = ublk_ch_uring_cmd,
2586 	.mmap = ublk_ch_mmap,
2587 };
2588 
ublk_deinit_queue(struct ublk_device * ub,int q_id)2589 static void ublk_deinit_queue(struct ublk_device *ub, int q_id)
2590 {
2591 	int size = ublk_queue_cmd_buf_size(ub, q_id);
2592 	struct ublk_queue *ubq = ublk_get_queue(ub, q_id);
2593 	int i;
2594 
2595 	for (i = 0; i < ubq->q_depth; i++) {
2596 		struct ublk_io *io = &ubq->ios[i];
2597 		if (io->task)
2598 			put_task_struct(io->task);
2599 		WARN_ON_ONCE(refcount_read(&io->ref));
2600 		WARN_ON_ONCE(io->task_registered_buffers);
2601 	}
2602 
2603 	if (ubq->io_cmd_buf)
2604 		free_pages((unsigned long)ubq->io_cmd_buf, get_order(size));
2605 }
2606 
ublk_init_queue(struct ublk_device * ub,int q_id)2607 static int ublk_init_queue(struct ublk_device *ub, int q_id)
2608 {
2609 	struct ublk_queue *ubq = ublk_get_queue(ub, q_id);
2610 	gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO;
2611 	void *ptr;
2612 	int size;
2613 
2614 	spin_lock_init(&ubq->cancel_lock);
2615 	ubq->flags = ub->dev_info.flags;
2616 	ubq->q_id = q_id;
2617 	ubq->q_depth = ub->dev_info.queue_depth;
2618 	size = ublk_queue_cmd_buf_size(ub, q_id);
2619 
2620 	ptr = (void *) __get_free_pages(gfp_flags, get_order(size));
2621 	if (!ptr)
2622 		return -ENOMEM;
2623 
2624 	ubq->io_cmd_buf = ptr;
2625 	ubq->dev = ub;
2626 	return 0;
2627 }
2628 
ublk_deinit_queues(struct ublk_device * ub)2629 static void ublk_deinit_queues(struct ublk_device *ub)
2630 {
2631 	int nr_queues = ub->dev_info.nr_hw_queues;
2632 	int i;
2633 
2634 	if (!ub->__queues)
2635 		return;
2636 
2637 	for (i = 0; i < nr_queues; i++)
2638 		ublk_deinit_queue(ub, i);
2639 	kvfree(ub->__queues);
2640 }
2641 
ublk_init_queues(struct ublk_device * ub)2642 static int ublk_init_queues(struct ublk_device *ub)
2643 {
2644 	int nr_queues = ub->dev_info.nr_hw_queues;
2645 	int depth = ub->dev_info.queue_depth;
2646 	int ubq_size = sizeof(struct ublk_queue) + depth * sizeof(struct ublk_io);
2647 	int i, ret = -ENOMEM;
2648 
2649 	ub->queue_size = ubq_size;
2650 	ub->__queues = kvcalloc(nr_queues, ubq_size, GFP_KERNEL);
2651 	if (!ub->__queues)
2652 		return ret;
2653 
2654 	for (i = 0; i < nr_queues; i++) {
2655 		if (ublk_init_queue(ub, i))
2656 			goto fail;
2657 	}
2658 
2659 	init_completion(&ub->completion);
2660 	return 0;
2661 
2662  fail:
2663 	ublk_deinit_queues(ub);
2664 	return ret;
2665 }
2666 
ublk_alloc_dev_number(struct ublk_device * ub,int idx)2667 static int ublk_alloc_dev_number(struct ublk_device *ub, int idx)
2668 {
2669 	int i = idx;
2670 	int err;
2671 
2672 	spin_lock(&ublk_idr_lock);
2673 	/* allocate id, if @id >= 0, we're requesting that specific id */
2674 	if (i >= 0) {
2675 		err = idr_alloc(&ublk_index_idr, ub, i, i + 1, GFP_NOWAIT);
2676 		if (err == -ENOSPC)
2677 			err = -EEXIST;
2678 	} else {
2679 		err = idr_alloc(&ublk_index_idr, ub, 0, UBLK_MAX_UBLKS,
2680 				GFP_NOWAIT);
2681 	}
2682 	spin_unlock(&ublk_idr_lock);
2683 
2684 	if (err >= 0)
2685 		ub->ub_number = err;
2686 
2687 	return err;
2688 }
2689 
ublk_free_dev_number(struct ublk_device * ub)2690 static void ublk_free_dev_number(struct ublk_device *ub)
2691 {
2692 	spin_lock(&ublk_idr_lock);
2693 	idr_remove(&ublk_index_idr, ub->ub_number);
2694 	wake_up_all(&ublk_idr_wq);
2695 	spin_unlock(&ublk_idr_lock);
2696 }
2697 
ublk_cdev_rel(struct device * dev)2698 static void ublk_cdev_rel(struct device *dev)
2699 {
2700 	struct ublk_device *ub = container_of(dev, struct ublk_device, cdev_dev);
2701 
2702 	blk_mq_free_tag_set(&ub->tag_set);
2703 	ublk_deinit_queues(ub);
2704 	ublk_free_dev_number(ub);
2705 	mutex_destroy(&ub->mutex);
2706 	mutex_destroy(&ub->cancel_mutex);
2707 	kfree(ub);
2708 }
2709 
ublk_add_chdev(struct ublk_device * ub)2710 static int ublk_add_chdev(struct ublk_device *ub)
2711 {
2712 	struct device *dev = &ub->cdev_dev;
2713 	int minor = ub->ub_number;
2714 	int ret;
2715 
2716 	dev->parent = ublk_misc.this_device;
2717 	dev->devt = MKDEV(MAJOR(ublk_chr_devt), minor);
2718 	dev->class = &ublk_chr_class;
2719 	dev->release = ublk_cdev_rel;
2720 	device_initialize(dev);
2721 
2722 	ret = dev_set_name(dev, "ublkc%d", minor);
2723 	if (ret)
2724 		goto fail;
2725 
2726 	cdev_init(&ub->cdev, &ublk_ch_fops);
2727 	ret = cdev_device_add(&ub->cdev, dev);
2728 	if (ret)
2729 		goto fail;
2730 
2731 	if (ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV)
2732 		unprivileged_ublks_added++;
2733 	return 0;
2734  fail:
2735 	put_device(dev);
2736 	return ret;
2737 }
2738 
2739 /* align max io buffer size with PAGE_SIZE */
ublk_align_max_io_size(struct ublk_device * ub)2740 static void ublk_align_max_io_size(struct ublk_device *ub)
2741 {
2742 	unsigned int max_io_bytes = ub->dev_info.max_io_buf_bytes;
2743 
2744 	ub->dev_info.max_io_buf_bytes =
2745 		round_down(max_io_bytes, PAGE_SIZE);
2746 }
2747 
ublk_add_tag_set(struct ublk_device * ub)2748 static int ublk_add_tag_set(struct ublk_device *ub)
2749 {
2750 	ub->tag_set.ops = &ublk_mq_ops;
2751 	ub->tag_set.nr_hw_queues = ub->dev_info.nr_hw_queues;
2752 	ub->tag_set.queue_depth = ub->dev_info.queue_depth;
2753 	ub->tag_set.numa_node = NUMA_NO_NODE;
2754 	ub->tag_set.driver_data = ub;
2755 	return blk_mq_alloc_tag_set(&ub->tag_set);
2756 }
2757 
ublk_remove(struct ublk_device * ub)2758 static void ublk_remove(struct ublk_device *ub)
2759 {
2760 	bool unprivileged;
2761 
2762 	ublk_stop_dev(ub);
2763 	cdev_device_del(&ub->cdev, &ub->cdev_dev);
2764 	unprivileged = ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV;
2765 	ublk_put_device(ub);
2766 
2767 	if (unprivileged)
2768 		unprivileged_ublks_added--;
2769 }
2770 
ublk_get_device_from_id(int idx)2771 static struct ublk_device *ublk_get_device_from_id(int idx)
2772 {
2773 	struct ublk_device *ub = NULL;
2774 
2775 	if (idx < 0)
2776 		return NULL;
2777 
2778 	spin_lock(&ublk_idr_lock);
2779 	ub = idr_find(&ublk_index_idr, idx);
2780 	if (ub)
2781 		ub = ublk_get_device(ub);
2782 	spin_unlock(&ublk_idr_lock);
2783 
2784 	return ub;
2785 }
2786 
ublk_ctrl_start_dev(struct ublk_device * ub,const struct ublksrv_ctrl_cmd * header)2787 static int ublk_ctrl_start_dev(struct ublk_device *ub,
2788 		const struct ublksrv_ctrl_cmd *header)
2789 {
2790 	const struct ublk_param_basic *p = &ub->params.basic;
2791 	int ublksrv_pid = (int)header->data[0];
2792 	struct queue_limits lim = {
2793 		.logical_block_size	= 1 << p->logical_bs_shift,
2794 		.physical_block_size	= 1 << p->physical_bs_shift,
2795 		.io_min			= 1 << p->io_min_shift,
2796 		.io_opt			= 1 << p->io_opt_shift,
2797 		.max_hw_sectors		= p->max_sectors,
2798 		.chunk_sectors		= p->chunk_sectors,
2799 		.virt_boundary_mask	= p->virt_boundary_mask,
2800 		.max_segments		= USHRT_MAX,
2801 		.max_segment_size	= UINT_MAX,
2802 		.dma_alignment		= 3,
2803 	};
2804 	struct gendisk *disk;
2805 	int ret = -EINVAL;
2806 
2807 	if (ublksrv_pid <= 0)
2808 		return -EINVAL;
2809 	if (!(ub->params.types & UBLK_PARAM_TYPE_BASIC))
2810 		return -EINVAL;
2811 
2812 	if (ub->params.types & UBLK_PARAM_TYPE_DISCARD) {
2813 		const struct ublk_param_discard *pd = &ub->params.discard;
2814 
2815 		lim.discard_alignment = pd->discard_alignment;
2816 		lim.discard_granularity = pd->discard_granularity;
2817 		lim.max_hw_discard_sectors = pd->max_discard_sectors;
2818 		lim.max_write_zeroes_sectors = pd->max_write_zeroes_sectors;
2819 		lim.max_discard_segments = pd->max_discard_segments;
2820 	}
2821 
2822 	if (ub->params.types & UBLK_PARAM_TYPE_ZONED) {
2823 		const struct ublk_param_zoned *p = &ub->params.zoned;
2824 
2825 		if (!IS_ENABLED(CONFIG_BLK_DEV_ZONED))
2826 			return -EOPNOTSUPP;
2827 
2828 		lim.features |= BLK_FEAT_ZONED;
2829 		lim.max_active_zones = p->max_active_zones;
2830 		lim.max_open_zones =  p->max_open_zones;
2831 		lim.max_hw_zone_append_sectors = p->max_zone_append_sectors;
2832 	}
2833 
2834 	if (ub->params.basic.attrs & UBLK_ATTR_VOLATILE_CACHE) {
2835 		lim.features |= BLK_FEAT_WRITE_CACHE;
2836 		if (ub->params.basic.attrs & UBLK_ATTR_FUA)
2837 			lim.features |= BLK_FEAT_FUA;
2838 	}
2839 
2840 	if (ub->params.basic.attrs & UBLK_ATTR_ROTATIONAL)
2841 		lim.features |= BLK_FEAT_ROTATIONAL;
2842 
2843 	if (ub->params.types & UBLK_PARAM_TYPE_DMA_ALIGN)
2844 		lim.dma_alignment = ub->params.dma.alignment;
2845 
2846 	if (ub->params.types & UBLK_PARAM_TYPE_SEGMENT) {
2847 		lim.seg_boundary_mask = ub->params.seg.seg_boundary_mask;
2848 		lim.max_segment_size = ub->params.seg.max_segment_size;
2849 		lim.max_segments = ub->params.seg.max_segments;
2850 	}
2851 
2852 	if (wait_for_completion_interruptible(&ub->completion) != 0)
2853 		return -EINTR;
2854 
2855 	if (ub->ublksrv_tgid != ublksrv_pid)
2856 		return -EINVAL;
2857 
2858 	mutex_lock(&ub->mutex);
2859 	if (ub->dev_info.state == UBLK_S_DEV_LIVE ||
2860 	    test_bit(UB_STATE_USED, &ub->state)) {
2861 		ret = -EEXIST;
2862 		goto out_unlock;
2863 	}
2864 
2865 	disk = blk_mq_alloc_disk(&ub->tag_set, &lim, NULL);
2866 	if (IS_ERR(disk)) {
2867 		ret = PTR_ERR(disk);
2868 		goto out_unlock;
2869 	}
2870 	sprintf(disk->disk_name, "ublkb%d", ub->ub_number);
2871 	disk->fops = &ub_fops;
2872 	disk->private_data = ub;
2873 
2874 	ub->dev_info.ublksrv_pid = ublksrv_pid;
2875 	ub->ub_disk = disk;
2876 
2877 	ublk_apply_params(ub);
2878 
2879 	/* don't probe partitions if any daemon task is un-trusted */
2880 	if (ub->unprivileged_daemons)
2881 		set_bit(GD_SUPPRESS_PART_SCAN, &disk->state);
2882 
2883 	ublk_get_device(ub);
2884 	ub->dev_info.state = UBLK_S_DEV_LIVE;
2885 
2886 	if (ublk_dev_is_zoned(ub)) {
2887 		ret = ublk_revalidate_disk_zones(ub);
2888 		if (ret)
2889 			goto out_put_cdev;
2890 	}
2891 
2892 	ret = add_disk(disk);
2893 	if (ret)
2894 		goto out_put_cdev;
2895 
2896 	set_bit(UB_STATE_USED, &ub->state);
2897 
2898 out_put_cdev:
2899 	if (ret) {
2900 		ublk_detach_disk(ub);
2901 		ublk_put_device(ub);
2902 	}
2903 	if (ret)
2904 		put_disk(disk);
2905 out_unlock:
2906 	mutex_unlock(&ub->mutex);
2907 	return ret;
2908 }
2909 
ublk_ctrl_get_queue_affinity(struct ublk_device * ub,const struct ublksrv_ctrl_cmd * header)2910 static int ublk_ctrl_get_queue_affinity(struct ublk_device *ub,
2911 		const struct ublksrv_ctrl_cmd *header)
2912 {
2913 	void __user *argp = (void __user *)(unsigned long)header->addr;
2914 	cpumask_var_t cpumask;
2915 	unsigned long queue;
2916 	unsigned int retlen;
2917 	unsigned int i;
2918 	int ret;
2919 
2920 	if (header->len * BITS_PER_BYTE < nr_cpu_ids)
2921 		return -EINVAL;
2922 	if (header->len & (sizeof(unsigned long)-1))
2923 		return -EINVAL;
2924 	if (!header->addr)
2925 		return -EINVAL;
2926 
2927 	queue = header->data[0];
2928 	if (queue >= ub->dev_info.nr_hw_queues)
2929 		return -EINVAL;
2930 
2931 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
2932 		return -ENOMEM;
2933 
2934 	for_each_possible_cpu(i) {
2935 		if (ub->tag_set.map[HCTX_TYPE_DEFAULT].mq_map[i] == queue)
2936 			cpumask_set_cpu(i, cpumask);
2937 	}
2938 
2939 	ret = -EFAULT;
2940 	retlen = min_t(unsigned short, header->len, cpumask_size());
2941 	if (copy_to_user(argp, cpumask, retlen))
2942 		goto out_free_cpumask;
2943 	if (retlen != header->len &&
2944 	    clear_user(argp + retlen, header->len - retlen))
2945 		goto out_free_cpumask;
2946 
2947 	ret = 0;
2948 out_free_cpumask:
2949 	free_cpumask_var(cpumask);
2950 	return ret;
2951 }
2952 
ublk_dump_dev_info(struct ublksrv_ctrl_dev_info * info)2953 static inline void ublk_dump_dev_info(struct ublksrv_ctrl_dev_info *info)
2954 {
2955 	pr_devel("%s: dev id %d flags %llx\n", __func__,
2956 			info->dev_id, info->flags);
2957 	pr_devel("\t nr_hw_queues %d queue_depth %d\n",
2958 			info->nr_hw_queues, info->queue_depth);
2959 }
2960 
ublk_ctrl_add_dev(const struct ublksrv_ctrl_cmd * header)2961 static int ublk_ctrl_add_dev(const struct ublksrv_ctrl_cmd *header)
2962 {
2963 	void __user *argp = (void __user *)(unsigned long)header->addr;
2964 	struct ublksrv_ctrl_dev_info info;
2965 	struct ublk_device *ub;
2966 	int ret = -EINVAL;
2967 
2968 	if (header->len < sizeof(info) || !header->addr)
2969 		return -EINVAL;
2970 	if (header->queue_id != (u16)-1) {
2971 		pr_warn("%s: queue_id is wrong %x\n",
2972 			__func__, header->queue_id);
2973 		return -EINVAL;
2974 	}
2975 
2976 	if (copy_from_user(&info, argp, sizeof(info)))
2977 		return -EFAULT;
2978 
2979 	if (info.queue_depth > UBLK_MAX_QUEUE_DEPTH || !info.queue_depth ||
2980 	    info.nr_hw_queues > UBLK_MAX_NR_QUEUES || !info.nr_hw_queues)
2981 		return -EINVAL;
2982 
2983 	if (capable(CAP_SYS_ADMIN))
2984 		info.flags &= ~UBLK_F_UNPRIVILEGED_DEV;
2985 	else if (!(info.flags & UBLK_F_UNPRIVILEGED_DEV))
2986 		return -EPERM;
2987 
2988 	/* forbid nonsense combinations of recovery flags */
2989 	switch (info.flags & UBLK_F_ALL_RECOVERY_FLAGS) {
2990 	case 0:
2991 	case UBLK_F_USER_RECOVERY:
2992 	case (UBLK_F_USER_RECOVERY | UBLK_F_USER_RECOVERY_REISSUE):
2993 	case (UBLK_F_USER_RECOVERY | UBLK_F_USER_RECOVERY_FAIL_IO):
2994 		break;
2995 	default:
2996 		pr_warn("%s: invalid recovery flags %llx\n", __func__,
2997 			info.flags & UBLK_F_ALL_RECOVERY_FLAGS);
2998 		return -EINVAL;
2999 	}
3000 
3001 	if ((info.flags & UBLK_F_QUIESCE) && !(info.flags & UBLK_F_USER_RECOVERY)) {
3002 		pr_warn("UBLK_F_QUIESCE requires UBLK_F_USER_RECOVERY\n");
3003 		return -EINVAL;
3004 	}
3005 
3006 	/*
3007 	 * unprivileged device can't be trusted, but RECOVERY and
3008 	 * RECOVERY_REISSUE still may hang error handling, so can't
3009 	 * support recovery features for unprivileged ublk now
3010 	 *
3011 	 * TODO: provide forward progress for RECOVERY handler, so that
3012 	 * unprivileged device can benefit from it
3013 	 */
3014 	if (info.flags & UBLK_F_UNPRIVILEGED_DEV) {
3015 		info.flags &= ~(UBLK_F_USER_RECOVERY_REISSUE |
3016 				UBLK_F_USER_RECOVERY);
3017 
3018 		/*
3019 		 * For USER_COPY, we depends on userspace to fill request
3020 		 * buffer by pwrite() to ublk char device, which can't be
3021 		 * used for unprivileged device
3022 		 *
3023 		 * Same with zero copy or auto buffer register.
3024 		 */
3025 		if (info.flags & (UBLK_F_USER_COPY | UBLK_F_SUPPORT_ZERO_COPY |
3026 					UBLK_F_AUTO_BUF_REG))
3027 			return -EINVAL;
3028 	}
3029 
3030 	/* the created device is always owned by current user */
3031 	ublk_store_owner_uid_gid(&info.owner_uid, &info.owner_gid);
3032 
3033 	if (header->dev_id != info.dev_id) {
3034 		pr_warn("%s: dev id not match %u %u\n",
3035 			__func__, header->dev_id, info.dev_id);
3036 		return -EINVAL;
3037 	}
3038 
3039 	if (header->dev_id != U32_MAX && header->dev_id >= UBLK_MAX_UBLKS) {
3040 		pr_warn("%s: dev id is too large. Max supported is %d\n",
3041 			__func__, UBLK_MAX_UBLKS - 1);
3042 		return -EINVAL;
3043 	}
3044 
3045 	ublk_dump_dev_info(&info);
3046 
3047 	ret = mutex_lock_killable(&ublk_ctl_mutex);
3048 	if (ret)
3049 		return ret;
3050 
3051 	ret = -EACCES;
3052 	if ((info.flags & UBLK_F_UNPRIVILEGED_DEV) &&
3053 	    unprivileged_ublks_added >= unprivileged_ublks_max)
3054 		goto out_unlock;
3055 
3056 	ret = -ENOMEM;
3057 	ub = kzalloc(sizeof(*ub), GFP_KERNEL);
3058 	if (!ub)
3059 		goto out_unlock;
3060 	mutex_init(&ub->mutex);
3061 	spin_lock_init(&ub->lock);
3062 	mutex_init(&ub->cancel_mutex);
3063 
3064 	ret = ublk_alloc_dev_number(ub, header->dev_id);
3065 	if (ret < 0)
3066 		goto out_free_ub;
3067 
3068 	memcpy(&ub->dev_info, &info, sizeof(info));
3069 
3070 	/* update device id */
3071 	ub->dev_info.dev_id = ub->ub_number;
3072 
3073 	/*
3074 	 * 64bit flags will be copied back to userspace as feature
3075 	 * negotiation result, so have to clear flags which driver
3076 	 * doesn't support yet, then userspace can get correct flags
3077 	 * (features) to handle.
3078 	 */
3079 	ub->dev_info.flags &= UBLK_F_ALL;
3080 
3081 	ub->dev_info.flags |= UBLK_F_CMD_IOCTL_ENCODE |
3082 		UBLK_F_URING_CMD_COMP_IN_TASK |
3083 		UBLK_F_PER_IO_DAEMON |
3084 		UBLK_F_BUF_REG_OFF_DAEMON;
3085 
3086 	/* GET_DATA isn't needed any more with USER_COPY or ZERO COPY */
3087 	if (ub->dev_info.flags & (UBLK_F_USER_COPY | UBLK_F_SUPPORT_ZERO_COPY |
3088 				UBLK_F_AUTO_BUF_REG))
3089 		ub->dev_info.flags &= ~UBLK_F_NEED_GET_DATA;
3090 
3091 	/*
3092 	 * Zoned storage support requires reuse `ublksrv_io_cmd->addr` for
3093 	 * returning write_append_lba, which is only allowed in case of
3094 	 * user copy or zero copy
3095 	 */
3096 	if (ublk_dev_is_zoned(ub) &&
3097 	    (!IS_ENABLED(CONFIG_BLK_DEV_ZONED) || !(ub->dev_info.flags &
3098 	     (UBLK_F_USER_COPY | UBLK_F_SUPPORT_ZERO_COPY)))) {
3099 		ret = -EINVAL;
3100 		goto out_free_dev_number;
3101 	}
3102 
3103 	ub->dev_info.nr_hw_queues = min_t(unsigned int,
3104 			ub->dev_info.nr_hw_queues, nr_cpu_ids);
3105 	ublk_align_max_io_size(ub);
3106 
3107 	ret = ublk_init_queues(ub);
3108 	if (ret)
3109 		goto out_free_dev_number;
3110 
3111 	ret = ublk_add_tag_set(ub);
3112 	if (ret)
3113 		goto out_deinit_queues;
3114 
3115 	ret = -EFAULT;
3116 	if (copy_to_user(argp, &ub->dev_info, sizeof(info)))
3117 		goto out_free_tag_set;
3118 
3119 	/*
3120 	 * Add the char dev so that ublksrv daemon can be setup.
3121 	 * ublk_add_chdev() will cleanup everything if it fails.
3122 	 */
3123 	ret = ublk_add_chdev(ub);
3124 	goto out_unlock;
3125 
3126 out_free_tag_set:
3127 	blk_mq_free_tag_set(&ub->tag_set);
3128 out_deinit_queues:
3129 	ublk_deinit_queues(ub);
3130 out_free_dev_number:
3131 	ublk_free_dev_number(ub);
3132 out_free_ub:
3133 	mutex_destroy(&ub->mutex);
3134 	mutex_destroy(&ub->cancel_mutex);
3135 	kfree(ub);
3136 out_unlock:
3137 	mutex_unlock(&ublk_ctl_mutex);
3138 	return ret;
3139 }
3140 
ublk_idr_freed(int id)3141 static inline bool ublk_idr_freed(int id)
3142 {
3143 	void *ptr;
3144 
3145 	spin_lock(&ublk_idr_lock);
3146 	ptr = idr_find(&ublk_index_idr, id);
3147 	spin_unlock(&ublk_idr_lock);
3148 
3149 	return ptr == NULL;
3150 }
3151 
ublk_ctrl_del_dev(struct ublk_device ** p_ub,bool wait)3152 static int ublk_ctrl_del_dev(struct ublk_device **p_ub, bool wait)
3153 {
3154 	struct ublk_device *ub = *p_ub;
3155 	int idx = ub->ub_number;
3156 	int ret;
3157 
3158 	ret = mutex_lock_killable(&ublk_ctl_mutex);
3159 	if (ret)
3160 		return ret;
3161 
3162 	if (!test_bit(UB_STATE_DELETED, &ub->state)) {
3163 		ublk_remove(ub);
3164 		set_bit(UB_STATE_DELETED, &ub->state);
3165 	}
3166 
3167 	/* Mark the reference as consumed */
3168 	*p_ub = NULL;
3169 	ublk_put_device(ub);
3170 	mutex_unlock(&ublk_ctl_mutex);
3171 
3172 	/*
3173 	 * Wait until the idr is removed, then it can be reused after
3174 	 * DEL_DEV command is returned.
3175 	 *
3176 	 * If we returns because of user interrupt, future delete command
3177 	 * may come:
3178 	 *
3179 	 * - the device number isn't freed, this device won't or needn't
3180 	 *   be deleted again, since UB_STATE_DELETED is set, and device
3181 	 *   will be released after the last reference is dropped
3182 	 *
3183 	 * - the device number is freed already, we will not find this
3184 	 *   device via ublk_get_device_from_id()
3185 	 */
3186 	if (wait && wait_event_interruptible(ublk_idr_wq, ublk_idr_freed(idx)))
3187 		return -EINTR;
3188 	return 0;
3189 }
3190 
ublk_ctrl_cmd_dump(struct io_uring_cmd * cmd)3191 static inline void ublk_ctrl_cmd_dump(struct io_uring_cmd *cmd)
3192 {
3193 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
3194 
3195 	pr_devel("%s: cmd_op %x, dev id %d qid %d data %llx buf %llx len %u\n",
3196 			__func__, cmd->cmd_op, header->dev_id, header->queue_id,
3197 			header->data[0], header->addr, header->len);
3198 }
3199 
ublk_ctrl_stop_dev(struct ublk_device * ub)3200 static int ublk_ctrl_stop_dev(struct ublk_device *ub)
3201 {
3202 	ublk_stop_dev(ub);
3203 	return 0;
3204 }
3205 
ublk_ctrl_get_dev_info(struct ublk_device * ub,const struct ublksrv_ctrl_cmd * header)3206 static int ublk_ctrl_get_dev_info(struct ublk_device *ub,
3207 		const struct ublksrv_ctrl_cmd *header)
3208 {
3209 	void __user *argp = (void __user *)(unsigned long)header->addr;
3210 
3211 	if (header->len < sizeof(struct ublksrv_ctrl_dev_info) || !header->addr)
3212 		return -EINVAL;
3213 
3214 	if (copy_to_user(argp, &ub->dev_info, sizeof(ub->dev_info)))
3215 		return -EFAULT;
3216 
3217 	return 0;
3218 }
3219 
3220 /* TYPE_DEVT is readonly, so fill it up before returning to userspace */
ublk_ctrl_fill_params_devt(struct ublk_device * ub)3221 static void ublk_ctrl_fill_params_devt(struct ublk_device *ub)
3222 {
3223 	ub->params.devt.char_major = MAJOR(ub->cdev_dev.devt);
3224 	ub->params.devt.char_minor = MINOR(ub->cdev_dev.devt);
3225 
3226 	if (ub->ub_disk) {
3227 		ub->params.devt.disk_major = MAJOR(disk_devt(ub->ub_disk));
3228 		ub->params.devt.disk_minor = MINOR(disk_devt(ub->ub_disk));
3229 	} else {
3230 		ub->params.devt.disk_major = 0;
3231 		ub->params.devt.disk_minor = 0;
3232 	}
3233 	ub->params.types |= UBLK_PARAM_TYPE_DEVT;
3234 }
3235 
ublk_ctrl_get_params(struct ublk_device * ub,const struct ublksrv_ctrl_cmd * header)3236 static int ublk_ctrl_get_params(struct ublk_device *ub,
3237 		const struct ublksrv_ctrl_cmd *header)
3238 {
3239 	void __user *argp = (void __user *)(unsigned long)header->addr;
3240 	struct ublk_params_header ph;
3241 	int ret;
3242 
3243 	if (header->len <= sizeof(ph) || !header->addr)
3244 		return -EINVAL;
3245 
3246 	if (copy_from_user(&ph, argp, sizeof(ph)))
3247 		return -EFAULT;
3248 
3249 	if (ph.len > header->len || !ph.len)
3250 		return -EINVAL;
3251 
3252 	if (ph.len > sizeof(struct ublk_params))
3253 		ph.len = sizeof(struct ublk_params);
3254 
3255 	mutex_lock(&ub->mutex);
3256 	ublk_ctrl_fill_params_devt(ub);
3257 	if (copy_to_user(argp, &ub->params, ph.len))
3258 		ret = -EFAULT;
3259 	else
3260 		ret = 0;
3261 	mutex_unlock(&ub->mutex);
3262 
3263 	return ret;
3264 }
3265 
ublk_ctrl_set_params(struct ublk_device * ub,const struct ublksrv_ctrl_cmd * header)3266 static int ublk_ctrl_set_params(struct ublk_device *ub,
3267 		const struct ublksrv_ctrl_cmd *header)
3268 {
3269 	void __user *argp = (void __user *)(unsigned long)header->addr;
3270 	struct ublk_params_header ph;
3271 	int ret = -EFAULT;
3272 
3273 	if (header->len <= sizeof(ph) || !header->addr)
3274 		return -EINVAL;
3275 
3276 	if (copy_from_user(&ph, argp, sizeof(ph)))
3277 		return -EFAULT;
3278 
3279 	if (ph.len > header->len || !ph.len || !ph.types)
3280 		return -EINVAL;
3281 
3282 	if (ph.len > sizeof(struct ublk_params))
3283 		ph.len = sizeof(struct ublk_params);
3284 
3285 	mutex_lock(&ub->mutex);
3286 	if (test_bit(UB_STATE_USED, &ub->state)) {
3287 		/*
3288 		 * Parameters can only be changed when device hasn't
3289 		 * been started yet
3290 		 */
3291 		ret = -EACCES;
3292 	} else if (copy_from_user(&ub->params, argp, ph.len)) {
3293 		ret = -EFAULT;
3294 	} else {
3295 		/* clear all we don't support yet */
3296 		ub->params.types &= UBLK_PARAM_TYPE_ALL;
3297 		ret = ublk_validate_params(ub);
3298 		if (ret)
3299 			ub->params.types = 0;
3300 	}
3301 	mutex_unlock(&ub->mutex);
3302 
3303 	return ret;
3304 }
3305 
ublk_ctrl_start_recovery(struct ublk_device * ub,const struct ublksrv_ctrl_cmd * header)3306 static int ublk_ctrl_start_recovery(struct ublk_device *ub,
3307 		const struct ublksrv_ctrl_cmd *header)
3308 {
3309 	int ret = -EINVAL;
3310 
3311 	mutex_lock(&ub->mutex);
3312 	if (ublk_nosrv_should_stop_dev(ub))
3313 		goto out_unlock;
3314 	/*
3315 	 * START_RECOVERY is only allowd after:
3316 	 *
3317 	 * (1) UB_STATE_OPEN is not set, which means the dying process is exited
3318 	 *     and related io_uring ctx is freed so file struct of /dev/ublkcX is
3319 	 *     released.
3320 	 *
3321 	 * and one of the following holds
3322 	 *
3323 	 * (2) UBLK_S_DEV_QUIESCED is set, which means the quiesce_work:
3324 	 *     (a)has quiesced request queue
3325 	 *     (b)has requeued every inflight rqs whose io_flags is ACTIVE
3326 	 *     (c)has requeued/aborted every inflight rqs whose io_flags is NOT ACTIVE
3327 	 *     (d)has completed/camceled all ioucmds owned by ther dying process
3328 	 *
3329 	 * (3) UBLK_S_DEV_FAIL_IO is set, which means the queue is not
3330 	 *     quiesced, but all I/O is being immediately errored
3331 	 */
3332 	if (test_bit(UB_STATE_OPEN, &ub->state) || !ublk_dev_in_recoverable_state(ub)) {
3333 		ret = -EBUSY;
3334 		goto out_unlock;
3335 	}
3336 	pr_devel("%s: start recovery for dev id %d.\n", __func__, header->dev_id);
3337 	init_completion(&ub->completion);
3338 	ret = 0;
3339  out_unlock:
3340 	mutex_unlock(&ub->mutex);
3341 	return ret;
3342 }
3343 
ublk_ctrl_end_recovery(struct ublk_device * ub,const struct ublksrv_ctrl_cmd * header)3344 static int ublk_ctrl_end_recovery(struct ublk_device *ub,
3345 		const struct ublksrv_ctrl_cmd *header)
3346 {
3347 	int ublksrv_pid = (int)header->data[0];
3348 	int ret = -EINVAL;
3349 
3350 	pr_devel("%s: Waiting for all FETCH_REQs, dev id %d...\n", __func__,
3351 		 header->dev_id);
3352 
3353 	if (wait_for_completion_interruptible(&ub->completion))
3354 		return -EINTR;
3355 
3356 	pr_devel("%s: All FETCH_REQs received, dev id %d\n", __func__,
3357 		 header->dev_id);
3358 
3359 	if (ub->ublksrv_tgid != ublksrv_pid)
3360 		return -EINVAL;
3361 
3362 	mutex_lock(&ub->mutex);
3363 	if (ublk_nosrv_should_stop_dev(ub))
3364 		goto out_unlock;
3365 
3366 	if (!ublk_dev_in_recoverable_state(ub)) {
3367 		ret = -EBUSY;
3368 		goto out_unlock;
3369 	}
3370 	ub->dev_info.ublksrv_pid = ublksrv_pid;
3371 	ub->dev_info.state = UBLK_S_DEV_LIVE;
3372 	pr_devel("%s: new ublksrv_pid %d, dev id %d\n",
3373 			__func__, ublksrv_pid, header->dev_id);
3374 	blk_mq_kick_requeue_list(ub->ub_disk->queue);
3375 	ret = 0;
3376  out_unlock:
3377 	mutex_unlock(&ub->mutex);
3378 	return ret;
3379 }
3380 
ublk_ctrl_get_features(const struct ublksrv_ctrl_cmd * header)3381 static int ublk_ctrl_get_features(const struct ublksrv_ctrl_cmd *header)
3382 {
3383 	void __user *argp = (void __user *)(unsigned long)header->addr;
3384 	u64 features = UBLK_F_ALL;
3385 
3386 	if (header->len != UBLK_FEATURES_LEN || !header->addr)
3387 		return -EINVAL;
3388 
3389 	if (copy_to_user(argp, &features, UBLK_FEATURES_LEN))
3390 		return -EFAULT;
3391 
3392 	return 0;
3393 }
3394 
ublk_ctrl_set_size(struct ublk_device * ub,const struct ublksrv_ctrl_cmd * header)3395 static void ublk_ctrl_set_size(struct ublk_device *ub, const struct ublksrv_ctrl_cmd *header)
3396 {
3397 	struct ublk_param_basic *p = &ub->params.basic;
3398 	u64 new_size = header->data[0];
3399 
3400 	mutex_lock(&ub->mutex);
3401 	p->dev_sectors = new_size;
3402 	set_capacity_and_notify(ub->ub_disk, p->dev_sectors);
3403 	mutex_unlock(&ub->mutex);
3404 }
3405 
3406 struct count_busy {
3407 	const struct ublk_queue *ubq;
3408 	unsigned int nr_busy;
3409 };
3410 
ublk_count_busy_req(struct request * rq,void * data)3411 static bool ublk_count_busy_req(struct request *rq, void *data)
3412 {
3413 	struct count_busy *idle = data;
3414 
3415 	if (!blk_mq_request_started(rq) && rq->mq_hctx->driver_data == idle->ubq)
3416 		idle->nr_busy += 1;
3417 	return true;
3418 }
3419 
3420 /* uring_cmd is guaranteed to be active if the associated request is idle */
ubq_has_idle_io(const struct ublk_queue * ubq)3421 static bool ubq_has_idle_io(const struct ublk_queue *ubq)
3422 {
3423 	struct count_busy data = {
3424 		.ubq = ubq,
3425 	};
3426 
3427 	blk_mq_tagset_busy_iter(&ubq->dev->tag_set, ublk_count_busy_req, &data);
3428 	return data.nr_busy < ubq->q_depth;
3429 }
3430 
3431 /* Wait until each hw queue has at least one idle IO */
ublk_wait_for_idle_io(struct ublk_device * ub,unsigned int timeout_ms)3432 static int ublk_wait_for_idle_io(struct ublk_device *ub,
3433 				 unsigned int timeout_ms)
3434 {
3435 	unsigned int elapsed = 0;
3436 	int ret;
3437 
3438 	while (elapsed < timeout_ms && !signal_pending(current)) {
3439 		unsigned int queues_cancelable = 0;
3440 		int i;
3441 
3442 		for (i = 0; i < ub->dev_info.nr_hw_queues; i++) {
3443 			struct ublk_queue *ubq = ublk_get_queue(ub, i);
3444 
3445 			queues_cancelable += !!ubq_has_idle_io(ubq);
3446 		}
3447 
3448 		/*
3449 		 * Each queue needs at least one active command for
3450 		 * notifying ublk server
3451 		 */
3452 		if (queues_cancelable == ub->dev_info.nr_hw_queues)
3453 			break;
3454 
3455 		msleep(UBLK_REQUEUE_DELAY_MS);
3456 		elapsed += UBLK_REQUEUE_DELAY_MS;
3457 	}
3458 
3459 	if (signal_pending(current))
3460 		ret = -EINTR;
3461 	else if (elapsed >= timeout_ms)
3462 		ret = -EBUSY;
3463 	else
3464 		ret = 0;
3465 
3466 	return ret;
3467 }
3468 
ublk_ctrl_quiesce_dev(struct ublk_device * ub,const struct ublksrv_ctrl_cmd * header)3469 static int ublk_ctrl_quiesce_dev(struct ublk_device *ub,
3470 				 const struct ublksrv_ctrl_cmd *header)
3471 {
3472 	/* zero means wait forever */
3473 	u64 timeout_ms = header->data[0];
3474 	struct gendisk *disk;
3475 	int ret = -ENODEV;
3476 
3477 	if (!(ub->dev_info.flags & UBLK_F_QUIESCE))
3478 		return -EOPNOTSUPP;
3479 
3480 	mutex_lock(&ub->mutex);
3481 	disk = ublk_get_disk(ub);
3482 	if (!disk)
3483 		goto unlock;
3484 	if (ub->dev_info.state == UBLK_S_DEV_DEAD)
3485 		goto put_disk;
3486 
3487 	ret = 0;
3488 	/* already in expected state */
3489 	if (ub->dev_info.state != UBLK_S_DEV_LIVE)
3490 		goto put_disk;
3491 
3492 	/* Mark the device as canceling */
3493 	mutex_lock(&ub->cancel_mutex);
3494 	blk_mq_quiesce_queue(disk->queue);
3495 	ublk_set_canceling(ub, true);
3496 	blk_mq_unquiesce_queue(disk->queue);
3497 	mutex_unlock(&ub->cancel_mutex);
3498 
3499 	if (!timeout_ms)
3500 		timeout_ms = UINT_MAX;
3501 	ret = ublk_wait_for_idle_io(ub, timeout_ms);
3502 
3503 put_disk:
3504 	ublk_put_disk(disk);
3505 unlock:
3506 	mutex_unlock(&ub->mutex);
3507 
3508 	/* Cancel pending uring_cmd */
3509 	if (!ret)
3510 		ublk_cancel_dev(ub);
3511 	return ret;
3512 }
3513 
3514 /*
3515  * All control commands are sent via /dev/ublk-control, so we have to check
3516  * the destination device's permission
3517  */
ublk_char_dev_permission(struct ublk_device * ub,const char * dev_path,int mask)3518 static int ublk_char_dev_permission(struct ublk_device *ub,
3519 		const char *dev_path, int mask)
3520 {
3521 	int err;
3522 	struct path path;
3523 	struct kstat stat;
3524 
3525 	err = kern_path(dev_path, LOOKUP_FOLLOW, &path);
3526 	if (err)
3527 		return err;
3528 
3529 	err = vfs_getattr(&path, &stat, STATX_TYPE, AT_STATX_SYNC_AS_STAT);
3530 	if (err)
3531 		goto exit;
3532 
3533 	err = -EPERM;
3534 	if (stat.rdev != ub->cdev_dev.devt || !S_ISCHR(stat.mode))
3535 		goto exit;
3536 
3537 	err = inode_permission(&nop_mnt_idmap,
3538 			d_backing_inode(path.dentry), mask);
3539 exit:
3540 	path_put(&path);
3541 	return err;
3542 }
3543 
ublk_ctrl_uring_cmd_permission(struct ublk_device * ub,struct io_uring_cmd * cmd)3544 static int ublk_ctrl_uring_cmd_permission(struct ublk_device *ub,
3545 		struct io_uring_cmd *cmd)
3546 {
3547 	struct ublksrv_ctrl_cmd *header = (struct ublksrv_ctrl_cmd *)io_uring_sqe_cmd(cmd->sqe);
3548 	bool unprivileged = ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV;
3549 	void __user *argp = (void __user *)(unsigned long)header->addr;
3550 	char *dev_path = NULL;
3551 	int ret = 0;
3552 	int mask;
3553 
3554 	if (!unprivileged) {
3555 		if (!capable(CAP_SYS_ADMIN))
3556 			return -EPERM;
3557 		/*
3558 		 * The new added command of UBLK_CMD_GET_DEV_INFO2 includes
3559 		 * char_dev_path in payload too, since userspace may not
3560 		 * know if the specified device is created as unprivileged
3561 		 * mode.
3562 		 */
3563 		if (_IOC_NR(cmd->cmd_op) != UBLK_CMD_GET_DEV_INFO2)
3564 			return 0;
3565 	}
3566 
3567 	/*
3568 	 * User has to provide the char device path for unprivileged ublk
3569 	 *
3570 	 * header->addr always points to the dev path buffer, and
3571 	 * header->dev_path_len records length of dev path buffer.
3572 	 */
3573 	if (!header->dev_path_len || header->dev_path_len > PATH_MAX)
3574 		return -EINVAL;
3575 
3576 	if (header->len < header->dev_path_len)
3577 		return -EINVAL;
3578 
3579 	dev_path = memdup_user_nul(argp, header->dev_path_len);
3580 	if (IS_ERR(dev_path))
3581 		return PTR_ERR(dev_path);
3582 
3583 	ret = -EINVAL;
3584 	switch (_IOC_NR(cmd->cmd_op)) {
3585 	case UBLK_CMD_GET_DEV_INFO:
3586 	case UBLK_CMD_GET_DEV_INFO2:
3587 	case UBLK_CMD_GET_QUEUE_AFFINITY:
3588 	case UBLK_CMD_GET_PARAMS:
3589 	case (_IOC_NR(UBLK_U_CMD_GET_FEATURES)):
3590 		mask = MAY_READ;
3591 		break;
3592 	case UBLK_CMD_START_DEV:
3593 	case UBLK_CMD_STOP_DEV:
3594 	case UBLK_CMD_ADD_DEV:
3595 	case UBLK_CMD_DEL_DEV:
3596 	case UBLK_CMD_SET_PARAMS:
3597 	case UBLK_CMD_START_USER_RECOVERY:
3598 	case UBLK_CMD_END_USER_RECOVERY:
3599 	case UBLK_CMD_UPDATE_SIZE:
3600 	case UBLK_CMD_QUIESCE_DEV:
3601 		mask = MAY_READ | MAY_WRITE;
3602 		break;
3603 	default:
3604 		goto exit;
3605 	}
3606 
3607 	ret = ublk_char_dev_permission(ub, dev_path, mask);
3608 	if (!ret) {
3609 		header->len -= header->dev_path_len;
3610 		header->addr += header->dev_path_len;
3611 	}
3612 	pr_devel("%s: dev id %d cmd_op %x uid %d gid %d path %s ret %d\n",
3613 			__func__, ub->ub_number, cmd->cmd_op,
3614 			ub->dev_info.owner_uid, ub->dev_info.owner_gid,
3615 			dev_path, ret);
3616 exit:
3617 	kfree(dev_path);
3618 	return ret;
3619 }
3620 
ublk_ctrl_uring_cmd(struct io_uring_cmd * cmd,unsigned int issue_flags)3621 static int ublk_ctrl_uring_cmd(struct io_uring_cmd *cmd,
3622 		unsigned int issue_flags)
3623 {
3624 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
3625 	struct ublk_device *ub = NULL;
3626 	u32 cmd_op = cmd->cmd_op;
3627 	int ret = -EINVAL;
3628 
3629 	if (issue_flags & IO_URING_F_NONBLOCK)
3630 		return -EAGAIN;
3631 
3632 	ublk_ctrl_cmd_dump(cmd);
3633 
3634 	if (!(issue_flags & IO_URING_F_SQE128))
3635 		goto out;
3636 
3637 	ret = ublk_check_cmd_op(cmd_op);
3638 	if (ret)
3639 		goto out;
3640 
3641 	if (cmd_op == UBLK_U_CMD_GET_FEATURES) {
3642 		ret = ublk_ctrl_get_features(header);
3643 		goto out;
3644 	}
3645 
3646 	if (_IOC_NR(cmd_op) != UBLK_CMD_ADD_DEV) {
3647 		ret = -ENODEV;
3648 		ub = ublk_get_device_from_id(header->dev_id);
3649 		if (!ub)
3650 			goto out;
3651 
3652 		ret = ublk_ctrl_uring_cmd_permission(ub, cmd);
3653 		if (ret)
3654 			goto put_dev;
3655 	}
3656 
3657 	switch (_IOC_NR(cmd_op)) {
3658 	case UBLK_CMD_START_DEV:
3659 		ret = ublk_ctrl_start_dev(ub, header);
3660 		break;
3661 	case UBLK_CMD_STOP_DEV:
3662 		ret = ublk_ctrl_stop_dev(ub);
3663 		break;
3664 	case UBLK_CMD_GET_DEV_INFO:
3665 	case UBLK_CMD_GET_DEV_INFO2:
3666 		ret = ublk_ctrl_get_dev_info(ub, header);
3667 		break;
3668 	case UBLK_CMD_ADD_DEV:
3669 		ret = ublk_ctrl_add_dev(header);
3670 		break;
3671 	case UBLK_CMD_DEL_DEV:
3672 		ret = ublk_ctrl_del_dev(&ub, true);
3673 		break;
3674 	case UBLK_CMD_DEL_DEV_ASYNC:
3675 		ret = ublk_ctrl_del_dev(&ub, false);
3676 		break;
3677 	case UBLK_CMD_GET_QUEUE_AFFINITY:
3678 		ret = ublk_ctrl_get_queue_affinity(ub, header);
3679 		break;
3680 	case UBLK_CMD_GET_PARAMS:
3681 		ret = ublk_ctrl_get_params(ub, header);
3682 		break;
3683 	case UBLK_CMD_SET_PARAMS:
3684 		ret = ublk_ctrl_set_params(ub, header);
3685 		break;
3686 	case UBLK_CMD_START_USER_RECOVERY:
3687 		ret = ublk_ctrl_start_recovery(ub, header);
3688 		break;
3689 	case UBLK_CMD_END_USER_RECOVERY:
3690 		ret = ublk_ctrl_end_recovery(ub, header);
3691 		break;
3692 	case UBLK_CMD_UPDATE_SIZE:
3693 		ublk_ctrl_set_size(ub, header);
3694 		ret = 0;
3695 		break;
3696 	case UBLK_CMD_QUIESCE_DEV:
3697 		ret = ublk_ctrl_quiesce_dev(ub, header);
3698 		break;
3699 	default:
3700 		ret = -EOPNOTSUPP;
3701 		break;
3702 	}
3703 
3704  put_dev:
3705 	if (ub)
3706 		ublk_put_device(ub);
3707  out:
3708 	pr_devel("%s: cmd done ret %d cmd_op %x, dev id %d qid %d\n",
3709 			__func__, ret, cmd->cmd_op, header->dev_id, header->queue_id);
3710 	return ret;
3711 }
3712 
3713 static const struct file_operations ublk_ctl_fops = {
3714 	.open		= nonseekable_open,
3715 	.uring_cmd      = ublk_ctrl_uring_cmd,
3716 	.owner		= THIS_MODULE,
3717 	.llseek		= noop_llseek,
3718 };
3719 
3720 static struct miscdevice ublk_misc = {
3721 	.minor		= MISC_DYNAMIC_MINOR,
3722 	.name		= "ublk-control",
3723 	.fops		= &ublk_ctl_fops,
3724 };
3725 
ublk_init(void)3726 static int __init ublk_init(void)
3727 {
3728 	int ret;
3729 
3730 	BUILD_BUG_ON((u64)UBLKSRV_IO_BUF_OFFSET +
3731 			UBLKSRV_IO_BUF_TOTAL_SIZE < UBLKSRV_IO_BUF_OFFSET);
3732 	BUILD_BUG_ON(sizeof(struct ublk_auto_buf_reg) != 8);
3733 
3734 	init_waitqueue_head(&ublk_idr_wq);
3735 
3736 	ret = misc_register(&ublk_misc);
3737 	if (ret)
3738 		return ret;
3739 
3740 	ret = alloc_chrdev_region(&ublk_chr_devt, 0, UBLK_MINORS, "ublk-char");
3741 	if (ret)
3742 		goto unregister_mis;
3743 
3744 	ret = class_register(&ublk_chr_class);
3745 	if (ret)
3746 		goto free_chrdev_region;
3747 
3748 	return 0;
3749 
3750 free_chrdev_region:
3751 	unregister_chrdev_region(ublk_chr_devt, UBLK_MINORS);
3752 unregister_mis:
3753 	misc_deregister(&ublk_misc);
3754 	return ret;
3755 }
3756 
ublk_exit(void)3757 static void __exit ublk_exit(void)
3758 {
3759 	struct ublk_device *ub;
3760 	int id;
3761 
3762 	idr_for_each_entry(&ublk_index_idr, ub, id)
3763 		ublk_remove(ub);
3764 
3765 	class_unregister(&ublk_chr_class);
3766 	misc_deregister(&ublk_misc);
3767 
3768 	idr_destroy(&ublk_index_idr);
3769 	unregister_chrdev_region(ublk_chr_devt, UBLK_MINORS);
3770 }
3771 
3772 module_init(ublk_init);
3773 module_exit(ublk_exit);
3774 
ublk_set_max_unprivileged_ublks(const char * buf,const struct kernel_param * kp)3775 static int ublk_set_max_unprivileged_ublks(const char *buf,
3776 					   const struct kernel_param *kp)
3777 {
3778 	return param_set_uint_minmax(buf, kp, 0, UBLK_MAX_UBLKS);
3779 }
3780 
ublk_get_max_unprivileged_ublks(char * buf,const struct kernel_param * kp)3781 static int ublk_get_max_unprivileged_ublks(char *buf,
3782 					   const struct kernel_param *kp)
3783 {
3784 	return sysfs_emit(buf, "%u\n", unprivileged_ublks_max);
3785 }
3786 
3787 static const struct kernel_param_ops ublk_max_unprivileged_ublks_ops = {
3788 	.set = ublk_set_max_unprivileged_ublks,
3789 	.get = ublk_get_max_unprivileged_ublks,
3790 };
3791 
3792 module_param_cb(ublks_max, &ublk_max_unprivileged_ublks_ops,
3793 		&unprivileged_ublks_max, 0644);
3794 MODULE_PARM_DESC(ublks_max, "max number of unprivileged ublk devices allowed to add(default: 64)");
3795 
3796 MODULE_AUTHOR("Ming Lei <ming.lei@redhat.com>");
3797 MODULE_DESCRIPTION("Userspace block device");
3798 MODULE_LICENSE("GPL");
3799