xref: /openbmc/linux/drivers/block/ublk_drv.c (revision 9e68fcff)
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.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 /* All UBLK_F_* have to be included into UBLK_F_ALL */
52 #define UBLK_F_ALL (UBLK_F_SUPPORT_ZERO_COPY \
53 		| UBLK_F_URING_CMD_COMP_IN_TASK \
54 		| UBLK_F_NEED_GET_DATA \
55 		| UBLK_F_USER_RECOVERY \
56 		| UBLK_F_USER_RECOVERY_REISSUE \
57 		| UBLK_F_UNPRIVILEGED_DEV \
58 		| UBLK_F_CMD_IOCTL_ENCODE \
59 		| UBLK_F_USER_COPY \
60 		| UBLK_F_ZONED)
61 
62 /* All UBLK_PARAM_TYPE_* should be included here */
63 #define UBLK_PARAM_TYPE_ALL                                \
64 	(UBLK_PARAM_TYPE_BASIC | UBLK_PARAM_TYPE_DISCARD | \
65 	 UBLK_PARAM_TYPE_DEVT | UBLK_PARAM_TYPE_ZONED)
66 
67 struct ublk_rq_data {
68 	struct llist_node node;
69 
70 	struct kref ref;
71 };
72 
73 struct ublk_uring_cmd_pdu {
74 	struct ublk_queue *ubq;
75 };
76 
77 /*
78  * io command is active: sqe cmd is received, and its cqe isn't done
79  *
80  * If the flag is set, the io command is owned by ublk driver, and waited
81  * for incoming blk-mq request from the ublk block device.
82  *
83  * If the flag is cleared, the io command will be completed, and owned by
84  * ublk server.
85  */
86 #define UBLK_IO_FLAG_ACTIVE	0x01
87 
88 /*
89  * IO command is completed via cqe, and it is being handled by ublksrv, and
90  * not committed yet
91  *
92  * Basically exclusively with UBLK_IO_FLAG_ACTIVE, so can be served for
93  * cross verification
94  */
95 #define UBLK_IO_FLAG_OWNED_BY_SRV 0x02
96 
97 /*
98  * IO command is aborted, so this flag is set in case of
99  * !UBLK_IO_FLAG_ACTIVE.
100  *
101  * After this flag is observed, any pending or new incoming request
102  * associated with this io command will be failed immediately
103  */
104 #define UBLK_IO_FLAG_ABORTED 0x04
105 
106 /*
107  * UBLK_IO_FLAG_NEED_GET_DATA is set because IO command requires
108  * get data buffer address from ublksrv.
109  *
110  * Then, bio data could be copied into this data buffer for a WRITE request
111  * after the IO command is issued again and UBLK_IO_FLAG_NEED_GET_DATA is unset.
112  */
113 #define UBLK_IO_FLAG_NEED_GET_DATA 0x08
114 
115 /* atomic RW with ubq->cancel_lock */
116 #define UBLK_IO_FLAG_CANCELED	0x80000000
117 
118 struct ublk_io {
119 	/* userspace buffer address from io cmd */
120 	__u64	addr;
121 	unsigned int flags;
122 	int res;
123 
124 	struct io_uring_cmd *cmd;
125 };
126 
127 struct ublk_queue {
128 	int q_id;
129 	int q_depth;
130 
131 	unsigned long flags;
132 	struct task_struct	*ubq_daemon;
133 	char *io_cmd_buf;
134 
135 	struct llist_head	io_cmds;
136 
137 	unsigned long io_addr;	/* mapped vm address */
138 	unsigned int max_io_sz;
139 	bool force_abort;
140 	bool timeout;
141 	unsigned short nr_io_ready;	/* how many ios setup */
142 	spinlock_t		cancel_lock;
143 	struct ublk_device *dev;
144 	struct ublk_io ios[];
145 };
146 
147 #define UBLK_DAEMON_MONITOR_PERIOD	(5 * HZ)
148 
149 struct ublk_device {
150 	struct gendisk		*ub_disk;
151 
152 	char	*__queues;
153 
154 	unsigned int	queue_size;
155 	struct ublksrv_ctrl_dev_info	dev_info;
156 
157 	struct blk_mq_tag_set	tag_set;
158 
159 	struct cdev		cdev;
160 	struct device		cdev_dev;
161 
162 #define UB_STATE_OPEN		0
163 #define UB_STATE_USED		1
164 #define UB_STATE_DELETED	2
165 	unsigned long		state;
166 	int			ub_number;
167 
168 	struct mutex		mutex;
169 
170 	spinlock_t		mm_lock;
171 	struct mm_struct	*mm;
172 
173 	struct ublk_params	params;
174 
175 	struct completion	completion;
176 	unsigned int		nr_queues_ready;
177 	unsigned int		nr_privileged_daemon;
178 
179 	/*
180 	 * Our ubq->daemon may be killed without any notification, so
181 	 * monitor each queue's daemon periodically
182 	 */
183 	struct delayed_work	monitor_work;
184 	struct work_struct	quiesce_work;
185 	struct work_struct	stop_work;
186 };
187 
188 /* header of ublk_params */
189 struct ublk_params_header {
190 	__u32	len;
191 	__u32	types;
192 };
193 
194 static inline unsigned int ublk_req_build_flags(struct request *req);
195 static inline struct ublksrv_io_desc *ublk_get_iod(struct ublk_queue *ubq,
196 						   int tag);
197 
ublk_dev_is_user_copy(const struct ublk_device * ub)198 static inline bool ublk_dev_is_user_copy(const struct ublk_device *ub)
199 {
200 	return ub->dev_info.flags & UBLK_F_USER_COPY;
201 }
202 
ublk_dev_is_zoned(const struct ublk_device * ub)203 static inline bool ublk_dev_is_zoned(const struct ublk_device *ub)
204 {
205 	return ub->dev_info.flags & UBLK_F_ZONED;
206 }
207 
ublk_queue_is_zoned(struct ublk_queue * ubq)208 static inline bool ublk_queue_is_zoned(struct ublk_queue *ubq)
209 {
210 	return ubq->flags & UBLK_F_ZONED;
211 }
212 
213 #ifdef CONFIG_BLK_DEV_ZONED
214 
215 struct ublk_zoned_report_desc {
216 	__u64 sector;
217 	__u32 operation;
218 	__u32 nr_zones;
219 };
220 
221 static DEFINE_XARRAY(ublk_zoned_report_descs);
222 
ublk_zoned_insert_report_desc(const struct request * req,struct ublk_zoned_report_desc * desc)223 static int ublk_zoned_insert_report_desc(const struct request *req,
224 		struct ublk_zoned_report_desc *desc)
225 {
226 	return xa_insert(&ublk_zoned_report_descs, (unsigned long)req,
227 			    desc, GFP_KERNEL);
228 }
229 
ublk_zoned_erase_report_desc(const struct request * req)230 static struct ublk_zoned_report_desc *ublk_zoned_erase_report_desc(
231 		const struct request *req)
232 {
233 	return xa_erase(&ublk_zoned_report_descs, (unsigned long)req);
234 }
235 
ublk_zoned_get_report_desc(const struct request * req)236 static struct ublk_zoned_report_desc *ublk_zoned_get_report_desc(
237 		const struct request *req)
238 {
239 	return xa_load(&ublk_zoned_report_descs, (unsigned long)req);
240 }
241 
ublk_get_nr_zones(const struct ublk_device * ub)242 static int ublk_get_nr_zones(const struct ublk_device *ub)
243 {
244 	const struct ublk_param_basic *p = &ub->params.basic;
245 
246 	/* Zone size is a power of 2 */
247 	return p->dev_sectors >> ilog2(p->chunk_sectors);
248 }
249 
ublk_revalidate_disk_zones(struct ublk_device * ub)250 static int ublk_revalidate_disk_zones(struct ublk_device *ub)
251 {
252 	return blk_revalidate_disk_zones(ub->ub_disk, NULL);
253 }
254 
ublk_dev_param_zoned_validate(const struct ublk_device * ub)255 static int ublk_dev_param_zoned_validate(const struct ublk_device *ub)
256 {
257 	const struct ublk_param_zoned *p = &ub->params.zoned;
258 	int nr_zones;
259 
260 	if (!ublk_dev_is_zoned(ub))
261 		return -EINVAL;
262 
263 	if (!p->max_zone_append_sectors)
264 		return -EINVAL;
265 
266 	nr_zones = ublk_get_nr_zones(ub);
267 
268 	if (p->max_active_zones > nr_zones)
269 		return -EINVAL;
270 
271 	if (p->max_open_zones > nr_zones)
272 		return -EINVAL;
273 
274 	return 0;
275 }
276 
ublk_dev_param_zoned_apply(struct ublk_device * ub)277 static int ublk_dev_param_zoned_apply(struct ublk_device *ub)
278 {
279 	const struct ublk_param_zoned *p = &ub->params.zoned;
280 
281 	disk_set_zoned(ub->ub_disk, BLK_ZONED_HM);
282 	blk_queue_flag_set(QUEUE_FLAG_ZONE_RESETALL, ub->ub_disk->queue);
283 	blk_queue_required_elevator_features(ub->ub_disk->queue,
284 					     ELEVATOR_F_ZBD_SEQ_WRITE);
285 	disk_set_max_active_zones(ub->ub_disk, p->max_active_zones);
286 	disk_set_max_open_zones(ub->ub_disk, p->max_open_zones);
287 	blk_queue_max_zone_append_sectors(ub->ub_disk->queue, p->max_zone_append_sectors);
288 
289 	ub->ub_disk->nr_zones = ublk_get_nr_zones(ub);
290 
291 	return 0;
292 }
293 
294 /* Based on virtblk_alloc_report_buffer */
ublk_alloc_report_buffer(struct ublk_device * ublk,unsigned int nr_zones,size_t * buflen)295 static void *ublk_alloc_report_buffer(struct ublk_device *ublk,
296 				      unsigned int nr_zones, size_t *buflen)
297 {
298 	struct request_queue *q = ublk->ub_disk->queue;
299 	size_t bufsize;
300 	void *buf;
301 
302 	nr_zones = min_t(unsigned int, nr_zones,
303 			 ublk->ub_disk->nr_zones);
304 
305 	bufsize = nr_zones * sizeof(struct blk_zone);
306 	bufsize =
307 		min_t(size_t, bufsize, queue_max_hw_sectors(q) << SECTOR_SHIFT);
308 
309 	while (bufsize >= sizeof(struct blk_zone)) {
310 		buf = kvmalloc(bufsize, GFP_KERNEL | __GFP_NORETRY);
311 		if (buf) {
312 			*buflen = bufsize;
313 			return buf;
314 		}
315 		bufsize >>= 1;
316 	}
317 
318 	*buflen = 0;
319 	return NULL;
320 }
321 
ublk_report_zones(struct gendisk * disk,sector_t sector,unsigned int nr_zones,report_zones_cb cb,void * data)322 static int ublk_report_zones(struct gendisk *disk, sector_t sector,
323 		      unsigned int nr_zones, report_zones_cb cb, void *data)
324 {
325 	struct ublk_device *ub = disk->private_data;
326 	unsigned int zone_size_sectors = disk->queue->limits.chunk_sectors;
327 	unsigned int first_zone = sector >> ilog2(zone_size_sectors);
328 	unsigned int done_zones = 0;
329 	unsigned int max_zones_per_request;
330 	int ret;
331 	struct blk_zone *buffer;
332 	size_t buffer_length;
333 
334 	nr_zones = min_t(unsigned int, ub->ub_disk->nr_zones - first_zone,
335 			 nr_zones);
336 
337 	buffer = ublk_alloc_report_buffer(ub, nr_zones, &buffer_length);
338 	if (!buffer)
339 		return -ENOMEM;
340 
341 	max_zones_per_request = buffer_length / sizeof(struct blk_zone);
342 
343 	while (done_zones < nr_zones) {
344 		unsigned int remaining_zones = nr_zones - done_zones;
345 		unsigned int zones_in_request =
346 			min_t(unsigned int, remaining_zones, max_zones_per_request);
347 		struct request *req;
348 		struct ublk_zoned_report_desc desc;
349 		blk_status_t status;
350 
351 		memset(buffer, 0, buffer_length);
352 
353 		req = blk_mq_alloc_request(disk->queue, REQ_OP_DRV_IN, 0);
354 		if (IS_ERR(req)) {
355 			ret = PTR_ERR(req);
356 			goto out;
357 		}
358 
359 		desc.operation = UBLK_IO_OP_REPORT_ZONES;
360 		desc.sector = sector;
361 		desc.nr_zones = zones_in_request;
362 		ret = ublk_zoned_insert_report_desc(req, &desc);
363 		if (ret)
364 			goto free_req;
365 
366 		ret = blk_rq_map_kern(disk->queue, req, buffer, buffer_length,
367 					GFP_KERNEL);
368 		if (ret)
369 			goto erase_desc;
370 
371 		status = blk_execute_rq(req, 0);
372 		ret = blk_status_to_errno(status);
373 erase_desc:
374 		ublk_zoned_erase_report_desc(req);
375 free_req:
376 		blk_mq_free_request(req);
377 		if (ret)
378 			goto out;
379 
380 		for (unsigned int i = 0; i < zones_in_request; i++) {
381 			struct blk_zone *zone = buffer + i;
382 
383 			/* A zero length zone means no more zones in this response */
384 			if (!zone->len)
385 				break;
386 
387 			ret = cb(zone, i, data);
388 			if (ret)
389 				goto out;
390 
391 			done_zones++;
392 			sector += zone_size_sectors;
393 
394 		}
395 	}
396 
397 	ret = done_zones;
398 
399 out:
400 	kvfree(buffer);
401 	return ret;
402 }
403 
ublk_setup_iod_zoned(struct ublk_queue * ubq,struct request * req)404 static blk_status_t ublk_setup_iod_zoned(struct ublk_queue *ubq,
405 					 struct request *req)
406 {
407 	struct ublksrv_io_desc *iod = ublk_get_iod(ubq, req->tag);
408 	struct ublk_io *io = &ubq->ios[req->tag];
409 	struct ublk_zoned_report_desc *desc;
410 	u32 ublk_op;
411 
412 	switch (req_op(req)) {
413 	case REQ_OP_ZONE_OPEN:
414 		ublk_op = UBLK_IO_OP_ZONE_OPEN;
415 		break;
416 	case REQ_OP_ZONE_CLOSE:
417 		ublk_op = UBLK_IO_OP_ZONE_CLOSE;
418 		break;
419 	case REQ_OP_ZONE_FINISH:
420 		ublk_op = UBLK_IO_OP_ZONE_FINISH;
421 		break;
422 	case REQ_OP_ZONE_RESET:
423 		ublk_op = UBLK_IO_OP_ZONE_RESET;
424 		break;
425 	case REQ_OP_ZONE_APPEND:
426 		ublk_op = UBLK_IO_OP_ZONE_APPEND;
427 		break;
428 	case REQ_OP_ZONE_RESET_ALL:
429 		ublk_op = UBLK_IO_OP_ZONE_RESET_ALL;
430 		break;
431 	case REQ_OP_DRV_IN:
432 		desc = ublk_zoned_get_report_desc(req);
433 		if (!desc)
434 			return BLK_STS_IOERR;
435 		ublk_op = desc->operation;
436 		switch (ublk_op) {
437 		case UBLK_IO_OP_REPORT_ZONES:
438 			iod->op_flags = ublk_op | ublk_req_build_flags(req);
439 			iod->nr_zones = desc->nr_zones;
440 			iod->start_sector = desc->sector;
441 			return BLK_STS_OK;
442 		default:
443 			return BLK_STS_IOERR;
444 		}
445 	case REQ_OP_DRV_OUT:
446 		/* We do not support drv_out */
447 		return BLK_STS_NOTSUPP;
448 	default:
449 		return BLK_STS_IOERR;
450 	}
451 
452 	iod->op_flags = ublk_op | ublk_req_build_flags(req);
453 	iod->nr_sectors = blk_rq_sectors(req);
454 	iod->start_sector = blk_rq_pos(req);
455 	iod->addr = io->addr;
456 
457 	return BLK_STS_OK;
458 }
459 
460 #else
461 
462 #define ublk_report_zones (NULL)
463 
ublk_dev_param_zoned_validate(const struct ublk_device * ub)464 static int ublk_dev_param_zoned_validate(const struct ublk_device *ub)
465 {
466 	return -EOPNOTSUPP;
467 }
468 
ublk_dev_param_zoned_apply(struct ublk_device * ub)469 static int ublk_dev_param_zoned_apply(struct ublk_device *ub)
470 {
471 	return -EOPNOTSUPP;
472 }
473 
ublk_revalidate_disk_zones(struct ublk_device * ub)474 static int ublk_revalidate_disk_zones(struct ublk_device *ub)
475 {
476 	return 0;
477 }
478 
ublk_setup_iod_zoned(struct ublk_queue * ubq,struct request * req)479 static blk_status_t ublk_setup_iod_zoned(struct ublk_queue *ubq,
480 					 struct request *req)
481 {
482 	return BLK_STS_NOTSUPP;
483 }
484 
485 #endif
486 
487 static inline void __ublk_complete_rq(struct request *req);
488 static void ublk_complete_rq(struct kref *ref);
489 
490 static dev_t ublk_chr_devt;
491 static const struct class ublk_chr_class = {
492 	.name = "ublk-char",
493 };
494 
495 static DEFINE_IDR(ublk_index_idr);
496 static DEFINE_SPINLOCK(ublk_idr_lock);
497 static wait_queue_head_t ublk_idr_wq;	/* wait until one idr is freed */
498 
499 static DEFINE_MUTEX(ublk_ctl_mutex);
500 
501 /*
502  * Max ublk devices allowed to add
503  *
504  * It can be extended to one per-user limit in future or even controlled
505  * by cgroup.
506  */
507 static unsigned int ublks_max = 64;
508 static unsigned int ublks_added;	/* protected by ublk_ctl_mutex */
509 
510 static struct miscdevice ublk_misc;
511 
ublk_pos_to_hwq(loff_t pos)512 static inline unsigned ublk_pos_to_hwq(loff_t pos)
513 {
514 	return ((pos - UBLKSRV_IO_BUF_OFFSET) >> UBLK_QID_OFF) &
515 		UBLK_QID_BITS_MASK;
516 }
517 
ublk_pos_to_buf_off(loff_t pos)518 static inline unsigned ublk_pos_to_buf_off(loff_t pos)
519 {
520 	return (pos - UBLKSRV_IO_BUF_OFFSET) & UBLK_IO_BUF_BITS_MASK;
521 }
522 
ublk_pos_to_tag(loff_t pos)523 static inline unsigned ublk_pos_to_tag(loff_t pos)
524 {
525 	return ((pos - UBLKSRV_IO_BUF_OFFSET) >> UBLK_TAG_OFF) &
526 		UBLK_TAG_BITS_MASK;
527 }
528 
ublk_dev_param_basic_apply(struct ublk_device * ub)529 static void ublk_dev_param_basic_apply(struct ublk_device *ub)
530 {
531 	struct request_queue *q = ub->ub_disk->queue;
532 	const struct ublk_param_basic *p = &ub->params.basic;
533 
534 	blk_queue_logical_block_size(q, 1 << p->logical_bs_shift);
535 	blk_queue_physical_block_size(q, 1 << p->physical_bs_shift);
536 	blk_queue_io_min(q, 1 << p->io_min_shift);
537 	blk_queue_io_opt(q, 1 << p->io_opt_shift);
538 
539 	blk_queue_write_cache(q, p->attrs & UBLK_ATTR_VOLATILE_CACHE,
540 			p->attrs & UBLK_ATTR_FUA);
541 	if (p->attrs & UBLK_ATTR_ROTATIONAL)
542 		blk_queue_flag_clear(QUEUE_FLAG_NONROT, q);
543 	else
544 		blk_queue_flag_set(QUEUE_FLAG_NONROT, q);
545 
546 	blk_queue_max_hw_sectors(q, p->max_sectors);
547 	blk_queue_chunk_sectors(q, p->chunk_sectors);
548 	blk_queue_virt_boundary(q, p->virt_boundary_mask);
549 
550 	if (p->attrs & UBLK_ATTR_READ_ONLY)
551 		set_disk_ro(ub->ub_disk, true);
552 
553 	set_capacity(ub->ub_disk, p->dev_sectors);
554 }
555 
ublk_dev_param_discard_apply(struct ublk_device * ub)556 static void ublk_dev_param_discard_apply(struct ublk_device *ub)
557 {
558 	struct request_queue *q = ub->ub_disk->queue;
559 	const struct ublk_param_discard *p = &ub->params.discard;
560 
561 	q->limits.discard_alignment = p->discard_alignment;
562 	q->limits.discard_granularity = p->discard_granularity;
563 	blk_queue_max_discard_sectors(q, p->max_discard_sectors);
564 	blk_queue_max_write_zeroes_sectors(q,
565 			p->max_write_zeroes_sectors);
566 	blk_queue_max_discard_segments(q, p->max_discard_segments);
567 }
568 
ublk_validate_params(const struct ublk_device * ub)569 static int ublk_validate_params(const struct ublk_device *ub)
570 {
571 	/* basic param is the only one which must be set */
572 	if (ub->params.types & UBLK_PARAM_TYPE_BASIC) {
573 		const struct ublk_param_basic *p = &ub->params.basic;
574 
575 		if (p->logical_bs_shift > PAGE_SHIFT || p->logical_bs_shift < 9)
576 			return -EINVAL;
577 
578 		if (p->logical_bs_shift > p->physical_bs_shift)
579 			return -EINVAL;
580 
581 		if (p->max_sectors > (ub->dev_info.max_io_buf_bytes >> 9))
582 			return -EINVAL;
583 
584 		if (ublk_dev_is_zoned(ub) && !p->chunk_sectors)
585 			return -EINVAL;
586 	} else
587 		return -EINVAL;
588 
589 	if (ub->params.types & UBLK_PARAM_TYPE_DISCARD) {
590 		const struct ublk_param_discard *p = &ub->params.discard;
591 
592 		/* So far, only support single segment discard */
593 		if (p->max_discard_sectors && p->max_discard_segments != 1)
594 			return -EINVAL;
595 
596 		if (!p->discard_granularity)
597 			return -EINVAL;
598 	}
599 
600 	/* dev_t is read-only */
601 	if (ub->params.types & UBLK_PARAM_TYPE_DEVT)
602 		return -EINVAL;
603 
604 	if (ub->params.types & UBLK_PARAM_TYPE_ZONED)
605 		return ublk_dev_param_zoned_validate(ub);
606 	else if (ublk_dev_is_zoned(ub))
607 		return -EINVAL;
608 
609 	return 0;
610 }
611 
ublk_apply_params(struct ublk_device * ub)612 static int ublk_apply_params(struct ublk_device *ub)
613 {
614 	if (!(ub->params.types & UBLK_PARAM_TYPE_BASIC))
615 		return -EINVAL;
616 
617 	ublk_dev_param_basic_apply(ub);
618 
619 	if (ub->params.types & UBLK_PARAM_TYPE_DISCARD)
620 		ublk_dev_param_discard_apply(ub);
621 
622 	if (ub->params.types & UBLK_PARAM_TYPE_ZONED)
623 		return ublk_dev_param_zoned_apply(ub);
624 
625 	return 0;
626 }
627 
ublk_support_user_copy(const struct ublk_queue * ubq)628 static inline bool ublk_support_user_copy(const struct ublk_queue *ubq)
629 {
630 	return ubq->flags & UBLK_F_USER_COPY;
631 }
632 
ublk_need_req_ref(const struct ublk_queue * ubq)633 static inline bool ublk_need_req_ref(const struct ublk_queue *ubq)
634 {
635 	/*
636 	 * read()/write() is involved in user copy, so request reference
637 	 * has to be grabbed
638 	 */
639 	return ublk_support_user_copy(ubq);
640 }
641 
ublk_init_req_ref(const struct ublk_queue * ubq,struct request * req)642 static inline void ublk_init_req_ref(const struct ublk_queue *ubq,
643 		struct request *req)
644 {
645 	if (ublk_need_req_ref(ubq)) {
646 		struct ublk_rq_data *data = blk_mq_rq_to_pdu(req);
647 
648 		kref_init(&data->ref);
649 	}
650 }
651 
ublk_get_req_ref(const struct ublk_queue * ubq,struct request * req)652 static inline bool ublk_get_req_ref(const struct ublk_queue *ubq,
653 		struct request *req)
654 {
655 	if (ublk_need_req_ref(ubq)) {
656 		struct ublk_rq_data *data = blk_mq_rq_to_pdu(req);
657 
658 		return kref_get_unless_zero(&data->ref);
659 	}
660 
661 	return true;
662 }
663 
ublk_put_req_ref(const struct ublk_queue * ubq,struct request * req)664 static inline void ublk_put_req_ref(const struct ublk_queue *ubq,
665 		struct request *req)
666 {
667 	if (ublk_need_req_ref(ubq)) {
668 		struct ublk_rq_data *data = blk_mq_rq_to_pdu(req);
669 
670 		kref_put(&data->ref, ublk_complete_rq);
671 	} else {
672 		__ublk_complete_rq(req);
673 	}
674 }
675 
ublk_need_get_data(const struct ublk_queue * ubq)676 static inline bool ublk_need_get_data(const struct ublk_queue *ubq)
677 {
678 	return ubq->flags & UBLK_F_NEED_GET_DATA;
679 }
680 
ublk_get_device(struct ublk_device * ub)681 static struct ublk_device *ublk_get_device(struct ublk_device *ub)
682 {
683 	if (kobject_get_unless_zero(&ub->cdev_dev.kobj))
684 		return ub;
685 	return NULL;
686 }
687 
ublk_put_device(struct ublk_device * ub)688 static void ublk_put_device(struct ublk_device *ub)
689 {
690 	put_device(&ub->cdev_dev);
691 }
692 
ublk_get_queue(struct ublk_device * dev,int qid)693 static inline struct ublk_queue *ublk_get_queue(struct ublk_device *dev,
694 		int qid)
695 {
696        return (struct ublk_queue *)&(dev->__queues[qid * dev->queue_size]);
697 }
698 
ublk_rq_has_data(const struct request * rq)699 static inline bool ublk_rq_has_data(const struct request *rq)
700 {
701 	return bio_has_data(rq->bio);
702 }
703 
ublk_get_iod(struct ublk_queue * ubq,int tag)704 static inline struct ublksrv_io_desc *ublk_get_iod(struct ublk_queue *ubq,
705 		int tag)
706 {
707 	return (struct ublksrv_io_desc *)
708 		&(ubq->io_cmd_buf[tag * sizeof(struct ublksrv_io_desc)]);
709 }
710 
ublk_queue_cmd_buf(struct ublk_device * ub,int q_id)711 static inline char *ublk_queue_cmd_buf(struct ublk_device *ub, int q_id)
712 {
713 	return ublk_get_queue(ub, q_id)->io_cmd_buf;
714 }
715 
__ublk_queue_cmd_buf_size(int depth)716 static inline int __ublk_queue_cmd_buf_size(int depth)
717 {
718 	return round_up(depth * sizeof(struct ublksrv_io_desc), PAGE_SIZE);
719 }
720 
ublk_queue_cmd_buf_size(struct ublk_device * ub,int q_id)721 static inline int ublk_queue_cmd_buf_size(struct ublk_device *ub, int q_id)
722 {
723 	struct ublk_queue *ubq = ublk_get_queue(ub, q_id);
724 
725 	return __ublk_queue_cmd_buf_size(ubq->q_depth);
726 }
727 
ublk_max_cmd_buf_size(void)728 static int ublk_max_cmd_buf_size(void)
729 {
730 	return __ublk_queue_cmd_buf_size(UBLK_MAX_QUEUE_DEPTH);
731 }
732 
ublk_queue_can_use_recovery_reissue(struct ublk_queue * ubq)733 static inline bool ublk_queue_can_use_recovery_reissue(
734 		struct ublk_queue *ubq)
735 {
736 	return (ubq->flags & UBLK_F_USER_RECOVERY) &&
737 			(ubq->flags & UBLK_F_USER_RECOVERY_REISSUE);
738 }
739 
ublk_queue_can_use_recovery(struct ublk_queue * ubq)740 static inline bool ublk_queue_can_use_recovery(
741 		struct ublk_queue *ubq)
742 {
743 	return ubq->flags & UBLK_F_USER_RECOVERY;
744 }
745 
ublk_can_use_recovery(struct ublk_device * ub)746 static inline bool ublk_can_use_recovery(struct ublk_device *ub)
747 {
748 	return ub->dev_info.flags & UBLK_F_USER_RECOVERY;
749 }
750 
ublk_free_disk(struct gendisk * disk)751 static void ublk_free_disk(struct gendisk *disk)
752 {
753 	struct ublk_device *ub = disk->private_data;
754 
755 	clear_bit(UB_STATE_USED, &ub->state);
756 	put_device(&ub->cdev_dev);
757 }
758 
ublk_store_owner_uid_gid(unsigned int * owner_uid,unsigned int * owner_gid)759 static void ublk_store_owner_uid_gid(unsigned int *owner_uid,
760 		unsigned int *owner_gid)
761 {
762 	kuid_t uid;
763 	kgid_t gid;
764 
765 	current_uid_gid(&uid, &gid);
766 
767 	*owner_uid = from_kuid(&init_user_ns, uid);
768 	*owner_gid = from_kgid(&init_user_ns, gid);
769 }
770 
ublk_open(struct gendisk * disk,blk_mode_t mode)771 static int ublk_open(struct gendisk *disk, blk_mode_t mode)
772 {
773 	struct ublk_device *ub = disk->private_data;
774 
775 	if (capable(CAP_SYS_ADMIN))
776 		return 0;
777 
778 	/*
779 	 * If it is one unprivileged device, only owner can open
780 	 * the disk. Otherwise it could be one trap made by one
781 	 * evil user who grants this disk's privileges to other
782 	 * users deliberately.
783 	 *
784 	 * This way is reasonable too given anyone can create
785 	 * unprivileged device, and no need other's grant.
786 	 */
787 	if (ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV) {
788 		unsigned int curr_uid, curr_gid;
789 
790 		ublk_store_owner_uid_gid(&curr_uid, &curr_gid);
791 
792 		if (curr_uid != ub->dev_info.owner_uid || curr_gid !=
793 				ub->dev_info.owner_gid)
794 			return -EPERM;
795 	}
796 
797 	return 0;
798 }
799 
800 static const struct block_device_operations ub_fops = {
801 	.owner =	THIS_MODULE,
802 	.open =		ublk_open,
803 	.free_disk =	ublk_free_disk,
804 	.report_zones =	ublk_report_zones,
805 };
806 
807 #define UBLK_MAX_PIN_PAGES	32
808 
809 struct ublk_io_iter {
810 	struct page *pages[UBLK_MAX_PIN_PAGES];
811 	struct bio *bio;
812 	struct bvec_iter iter;
813 };
814 
815 /* return how many pages are copied */
ublk_copy_io_pages(struct ublk_io_iter * data,size_t total,size_t pg_off,int dir)816 static void ublk_copy_io_pages(struct ublk_io_iter *data,
817 		size_t total, size_t pg_off, int dir)
818 {
819 	unsigned done = 0;
820 	unsigned pg_idx = 0;
821 
822 	while (done < total) {
823 		struct bio_vec bv = bio_iter_iovec(data->bio, data->iter);
824 		unsigned int bytes = min3(bv.bv_len, (unsigned)total - done,
825 				(unsigned)(PAGE_SIZE - pg_off));
826 		void *bv_buf = bvec_kmap_local(&bv);
827 		void *pg_buf = kmap_local_page(data->pages[pg_idx]);
828 
829 		if (dir == ITER_DEST)
830 			memcpy(pg_buf + pg_off, bv_buf, bytes);
831 		else
832 			memcpy(bv_buf, pg_buf + pg_off, bytes);
833 
834 		kunmap_local(pg_buf);
835 		kunmap_local(bv_buf);
836 
837 		/* advance page array */
838 		pg_off += bytes;
839 		if (pg_off == PAGE_SIZE) {
840 			pg_idx += 1;
841 			pg_off = 0;
842 		}
843 
844 		done += bytes;
845 
846 		/* advance bio */
847 		bio_advance_iter_single(data->bio, &data->iter, bytes);
848 		if (!data->iter.bi_size) {
849 			data->bio = data->bio->bi_next;
850 			if (data->bio == NULL)
851 				break;
852 			data->iter = data->bio->bi_iter;
853 		}
854 	}
855 }
856 
ublk_advance_io_iter(const struct request * req,struct ublk_io_iter * iter,unsigned int offset)857 static bool ublk_advance_io_iter(const struct request *req,
858 		struct ublk_io_iter *iter, unsigned int offset)
859 {
860 	struct bio *bio = req->bio;
861 
862 	for_each_bio(bio) {
863 		if (bio->bi_iter.bi_size > offset) {
864 			iter->bio = bio;
865 			iter->iter = bio->bi_iter;
866 			bio_advance_iter(iter->bio, &iter->iter, offset);
867 			return true;
868 		}
869 		offset -= bio->bi_iter.bi_size;
870 	}
871 	return false;
872 }
873 
874 /*
875  * Copy data between request pages and io_iter, and 'offset'
876  * is the start point of linear offset of request.
877  */
ublk_copy_user_pages(const struct request * req,unsigned offset,struct iov_iter * uiter,int dir)878 static size_t ublk_copy_user_pages(const struct request *req,
879 		unsigned offset, struct iov_iter *uiter, int dir)
880 {
881 	struct ublk_io_iter iter;
882 	size_t done = 0;
883 
884 	if (!ublk_advance_io_iter(req, &iter, offset))
885 		return 0;
886 
887 	while (iov_iter_count(uiter) && iter.bio) {
888 		unsigned nr_pages;
889 		ssize_t len;
890 		size_t off;
891 		int i;
892 
893 		len = iov_iter_get_pages2(uiter, iter.pages,
894 				iov_iter_count(uiter),
895 				UBLK_MAX_PIN_PAGES, &off);
896 		if (len <= 0)
897 			return done;
898 
899 		ublk_copy_io_pages(&iter, len, off, dir);
900 		nr_pages = DIV_ROUND_UP(len + off, PAGE_SIZE);
901 		for (i = 0; i < nr_pages; i++) {
902 			if (dir == ITER_DEST)
903 				set_page_dirty(iter.pages[i]);
904 			put_page(iter.pages[i]);
905 		}
906 		done += len;
907 	}
908 
909 	return done;
910 }
911 
ublk_need_map_req(const struct request * req)912 static inline bool ublk_need_map_req(const struct request *req)
913 {
914 	return ublk_rq_has_data(req) && req_op(req) == REQ_OP_WRITE;
915 }
916 
ublk_need_unmap_req(const struct request * req)917 static inline bool ublk_need_unmap_req(const struct request *req)
918 {
919 	return ublk_rq_has_data(req) &&
920 	       (req_op(req) == REQ_OP_READ || req_op(req) == REQ_OP_DRV_IN);
921 }
922 
ublk_map_io(const struct ublk_queue * ubq,const struct request * req,struct ublk_io * io)923 static int ublk_map_io(const struct ublk_queue *ubq, const struct request *req,
924 		struct ublk_io *io)
925 {
926 	const unsigned int rq_bytes = blk_rq_bytes(req);
927 
928 	if (ublk_support_user_copy(ubq))
929 		return rq_bytes;
930 
931 	/*
932 	 * no zero copy, we delay copy WRITE request data into ublksrv
933 	 * context and the big benefit is that pinning pages in current
934 	 * context is pretty fast, see ublk_pin_user_pages
935 	 */
936 	if (ublk_need_map_req(req)) {
937 		struct iov_iter iter;
938 		struct iovec iov;
939 		const int dir = ITER_DEST;
940 
941 		import_single_range(dir, u64_to_user_ptr(io->addr), rq_bytes,
942 				&iov, &iter);
943 
944 		return ublk_copy_user_pages(req, 0, &iter, dir);
945 	}
946 	return rq_bytes;
947 }
948 
ublk_unmap_io(const struct ublk_queue * ubq,const struct request * req,struct ublk_io * io)949 static int ublk_unmap_io(const struct ublk_queue *ubq,
950 		const struct request *req,
951 		struct ublk_io *io)
952 {
953 	const unsigned int rq_bytes = blk_rq_bytes(req);
954 
955 	if (ublk_support_user_copy(ubq))
956 		return rq_bytes;
957 
958 	if (ublk_need_unmap_req(req)) {
959 		struct iov_iter iter;
960 		struct iovec iov;
961 		const int dir = ITER_SOURCE;
962 
963 		WARN_ON_ONCE(io->res > rq_bytes);
964 
965 		import_single_range(dir, u64_to_user_ptr(io->addr), io->res,
966 				&iov, &iter);
967 		return ublk_copy_user_pages(req, 0, &iter, dir);
968 	}
969 	return rq_bytes;
970 }
971 
ublk_req_build_flags(struct request * req)972 static inline unsigned int ublk_req_build_flags(struct request *req)
973 {
974 	unsigned flags = 0;
975 
976 	if (req->cmd_flags & REQ_FAILFAST_DEV)
977 		flags |= UBLK_IO_F_FAILFAST_DEV;
978 
979 	if (req->cmd_flags & REQ_FAILFAST_TRANSPORT)
980 		flags |= UBLK_IO_F_FAILFAST_TRANSPORT;
981 
982 	if (req->cmd_flags & REQ_FAILFAST_DRIVER)
983 		flags |= UBLK_IO_F_FAILFAST_DRIVER;
984 
985 	if (req->cmd_flags & REQ_META)
986 		flags |= UBLK_IO_F_META;
987 
988 	if (req->cmd_flags & REQ_FUA)
989 		flags |= UBLK_IO_F_FUA;
990 
991 	if (req->cmd_flags & REQ_NOUNMAP)
992 		flags |= UBLK_IO_F_NOUNMAP;
993 
994 	if (req->cmd_flags & REQ_SWAP)
995 		flags |= UBLK_IO_F_SWAP;
996 
997 	return flags;
998 }
999 
ublk_setup_iod(struct ublk_queue * ubq,struct request * req)1000 static blk_status_t ublk_setup_iod(struct ublk_queue *ubq, struct request *req)
1001 {
1002 	struct ublksrv_io_desc *iod = ublk_get_iod(ubq, req->tag);
1003 	struct ublk_io *io = &ubq->ios[req->tag];
1004 	enum req_op op = req_op(req);
1005 	u32 ublk_op;
1006 
1007 	if (!ublk_queue_is_zoned(ubq) &&
1008 	    (op_is_zone_mgmt(op) || op == REQ_OP_ZONE_APPEND))
1009 		return BLK_STS_IOERR;
1010 
1011 	switch (req_op(req)) {
1012 	case REQ_OP_READ:
1013 		ublk_op = UBLK_IO_OP_READ;
1014 		break;
1015 	case REQ_OP_WRITE:
1016 		ublk_op = UBLK_IO_OP_WRITE;
1017 		break;
1018 	case REQ_OP_FLUSH:
1019 		ublk_op = UBLK_IO_OP_FLUSH;
1020 		break;
1021 	case REQ_OP_DISCARD:
1022 		ublk_op = UBLK_IO_OP_DISCARD;
1023 		break;
1024 	case REQ_OP_WRITE_ZEROES:
1025 		ublk_op = UBLK_IO_OP_WRITE_ZEROES;
1026 		break;
1027 	default:
1028 		if (ublk_queue_is_zoned(ubq))
1029 			return ublk_setup_iod_zoned(ubq, req);
1030 		return BLK_STS_IOERR;
1031 	}
1032 
1033 	/* need to translate since kernel may change */
1034 	iod->op_flags = ublk_op | ublk_req_build_flags(req);
1035 	iod->nr_sectors = blk_rq_sectors(req);
1036 	iod->start_sector = blk_rq_pos(req);
1037 	iod->addr = io->addr;
1038 
1039 	return BLK_STS_OK;
1040 }
1041 
ublk_get_uring_cmd_pdu(struct io_uring_cmd * ioucmd)1042 static inline struct ublk_uring_cmd_pdu *ublk_get_uring_cmd_pdu(
1043 		struct io_uring_cmd *ioucmd)
1044 {
1045 	return (struct ublk_uring_cmd_pdu *)&ioucmd->pdu;
1046 }
1047 
ubq_daemon_is_dying(struct ublk_queue * ubq)1048 static inline bool ubq_daemon_is_dying(struct ublk_queue *ubq)
1049 {
1050 	return ubq->ubq_daemon->flags & PF_EXITING;
1051 }
1052 
1053 /* todo: handle partial completion */
__ublk_complete_rq(struct request * req)1054 static inline void __ublk_complete_rq(struct request *req)
1055 {
1056 	struct ublk_queue *ubq = req->mq_hctx->driver_data;
1057 	struct ublk_io *io = &ubq->ios[req->tag];
1058 	unsigned int unmapped_bytes;
1059 	blk_status_t res = BLK_STS_OK;
1060 
1061 	/* called from ublk_abort_queue() code path */
1062 	if (io->flags & UBLK_IO_FLAG_ABORTED) {
1063 		res = BLK_STS_IOERR;
1064 		goto exit;
1065 	}
1066 
1067 	/* failed read IO if nothing is read */
1068 	if (!io->res && req_op(req) == REQ_OP_READ)
1069 		io->res = -EIO;
1070 
1071 	if (io->res < 0) {
1072 		res = errno_to_blk_status(io->res);
1073 		goto exit;
1074 	}
1075 
1076 	/*
1077 	 * FLUSH, DISCARD or WRITE_ZEROES usually won't return bytes returned, so end them
1078 	 * directly.
1079 	 *
1080 	 * Both the two needn't unmap.
1081 	 */
1082 	if (req_op(req) != REQ_OP_READ && req_op(req) != REQ_OP_WRITE &&
1083 	    req_op(req) != REQ_OP_DRV_IN)
1084 		goto exit;
1085 
1086 	/* for READ request, writing data in iod->addr to rq buffers */
1087 	unmapped_bytes = ublk_unmap_io(ubq, req, io);
1088 
1089 	/*
1090 	 * Extremely impossible since we got data filled in just before
1091 	 *
1092 	 * Re-read simply for this unlikely case.
1093 	 */
1094 	if (unlikely(unmapped_bytes < io->res))
1095 		io->res = unmapped_bytes;
1096 
1097 	if (blk_update_request(req, BLK_STS_OK, io->res))
1098 		blk_mq_requeue_request(req, true);
1099 	else
1100 		__blk_mq_end_request(req, BLK_STS_OK);
1101 
1102 	return;
1103 exit:
1104 	blk_mq_end_request(req, res);
1105 }
1106 
ublk_complete_rq(struct kref * ref)1107 static void ublk_complete_rq(struct kref *ref)
1108 {
1109 	struct ublk_rq_data *data = container_of(ref, struct ublk_rq_data,
1110 			ref);
1111 	struct request *req = blk_mq_rq_from_pdu(data);
1112 
1113 	__ublk_complete_rq(req);
1114 }
1115 
1116 /*
1117  * Since __ublk_rq_task_work always fails requests immediately during
1118  * exiting, __ublk_fail_req() is only called from abort context during
1119  * exiting. So lock is unnecessary.
1120  *
1121  * Also aborting may not be started yet, keep in mind that one failed
1122  * request may be issued by block layer again.
1123  */
__ublk_fail_req(struct ublk_queue * ubq,struct ublk_io * io,struct request * req)1124 static void __ublk_fail_req(struct ublk_queue *ubq, struct ublk_io *io,
1125 		struct request *req)
1126 {
1127 	WARN_ON_ONCE(io->flags & UBLK_IO_FLAG_ACTIVE);
1128 
1129 	if (!(io->flags & UBLK_IO_FLAG_ABORTED)) {
1130 		io->flags |= UBLK_IO_FLAG_ABORTED;
1131 		if (ublk_queue_can_use_recovery_reissue(ubq))
1132 			blk_mq_requeue_request(req, false);
1133 		else
1134 			ublk_put_req_ref(ubq, req);
1135 	}
1136 }
1137 
ubq_complete_io_cmd(struct ublk_io * io,int res,unsigned issue_flags)1138 static void ubq_complete_io_cmd(struct ublk_io *io, int res,
1139 				unsigned issue_flags)
1140 {
1141 	/* mark this cmd owned by ublksrv */
1142 	io->flags |= UBLK_IO_FLAG_OWNED_BY_SRV;
1143 
1144 	/*
1145 	 * clear ACTIVE since we are done with this sqe/cmd slot
1146 	 * We can only accept io cmd in case of being not active.
1147 	 */
1148 	io->flags &= ~UBLK_IO_FLAG_ACTIVE;
1149 
1150 	/* tell ublksrv one io request is coming */
1151 	io_uring_cmd_done(io->cmd, res, 0, issue_flags);
1152 }
1153 
1154 #define UBLK_REQUEUE_DELAY_MS	3
1155 
__ublk_abort_rq(struct ublk_queue * ubq,struct request * rq)1156 static inline void __ublk_abort_rq(struct ublk_queue *ubq,
1157 		struct request *rq)
1158 {
1159 	/* We cannot process this rq so just requeue it. */
1160 	if (ublk_queue_can_use_recovery(ubq))
1161 		blk_mq_requeue_request(rq, false);
1162 	else
1163 		blk_mq_end_request(rq, BLK_STS_IOERR);
1164 
1165 	mod_delayed_work(system_wq, &ubq->dev->monitor_work, 0);
1166 }
1167 
__ublk_rq_task_work(struct request * req,unsigned issue_flags)1168 static inline void __ublk_rq_task_work(struct request *req,
1169 				       unsigned issue_flags)
1170 {
1171 	struct ublk_queue *ubq = req->mq_hctx->driver_data;
1172 	int tag = req->tag;
1173 	struct ublk_io *io = &ubq->ios[tag];
1174 	unsigned int mapped_bytes;
1175 
1176 	pr_devel("%s: complete: op %d, qid %d tag %d io_flags %x addr %llx\n",
1177 			__func__, io->cmd->cmd_op, ubq->q_id, req->tag, io->flags,
1178 			ublk_get_iod(ubq, req->tag)->addr);
1179 
1180 	/*
1181 	 * Task is exiting if either:
1182 	 *
1183 	 * (1) current != ubq_daemon.
1184 	 * io_uring_cmd_complete_in_task() tries to run task_work
1185 	 * in a workqueue if ubq_daemon(cmd's task) is PF_EXITING.
1186 	 *
1187 	 * (2) current->flags & PF_EXITING.
1188 	 */
1189 	if (unlikely(current != ubq->ubq_daemon || current->flags & PF_EXITING)) {
1190 		__ublk_abort_rq(ubq, req);
1191 		return;
1192 	}
1193 
1194 	if (ublk_need_get_data(ubq) && ublk_need_map_req(req)) {
1195 		/*
1196 		 * We have not handled UBLK_IO_NEED_GET_DATA command yet,
1197 		 * so immepdately pass UBLK_IO_RES_NEED_GET_DATA to ublksrv
1198 		 * and notify it.
1199 		 */
1200 		if (!(io->flags & UBLK_IO_FLAG_NEED_GET_DATA)) {
1201 			io->flags |= UBLK_IO_FLAG_NEED_GET_DATA;
1202 			pr_devel("%s: need get data. op %d, qid %d tag %d io_flags %x\n",
1203 					__func__, io->cmd->cmd_op, ubq->q_id,
1204 					req->tag, io->flags);
1205 			ubq_complete_io_cmd(io, UBLK_IO_RES_NEED_GET_DATA, issue_flags);
1206 			return;
1207 		}
1208 		/*
1209 		 * We have handled UBLK_IO_NEED_GET_DATA command,
1210 		 * so clear UBLK_IO_FLAG_NEED_GET_DATA now and just
1211 		 * do the copy work.
1212 		 */
1213 		io->flags &= ~UBLK_IO_FLAG_NEED_GET_DATA;
1214 		/* update iod->addr because ublksrv may have passed a new io buffer */
1215 		ublk_get_iod(ubq, req->tag)->addr = io->addr;
1216 		pr_devel("%s: update iod->addr: op %d, qid %d tag %d io_flags %x addr %llx\n",
1217 				__func__, io->cmd->cmd_op, ubq->q_id, req->tag, io->flags,
1218 				ublk_get_iod(ubq, req->tag)->addr);
1219 	}
1220 
1221 	mapped_bytes = ublk_map_io(ubq, req, io);
1222 
1223 	/* partially mapped, update io descriptor */
1224 	if (unlikely(mapped_bytes != blk_rq_bytes(req))) {
1225 		/*
1226 		 * Nothing mapped, retry until we succeed.
1227 		 *
1228 		 * We may never succeed in mapping any bytes here because
1229 		 * of OOM. TODO: reserve one buffer with single page pinned
1230 		 * for providing forward progress guarantee.
1231 		 */
1232 		if (unlikely(!mapped_bytes)) {
1233 			blk_mq_requeue_request(req, false);
1234 			blk_mq_delay_kick_requeue_list(req->q,
1235 					UBLK_REQUEUE_DELAY_MS);
1236 			return;
1237 		}
1238 
1239 		ublk_get_iod(ubq, req->tag)->nr_sectors =
1240 			mapped_bytes >> 9;
1241 	}
1242 
1243 	ublk_init_req_ref(ubq, req);
1244 	ubq_complete_io_cmd(io, UBLK_IO_RES_OK, issue_flags);
1245 }
1246 
ublk_forward_io_cmds(struct ublk_queue * ubq,unsigned issue_flags)1247 static inline void ublk_forward_io_cmds(struct ublk_queue *ubq,
1248 					unsigned issue_flags)
1249 {
1250 	struct llist_node *io_cmds = llist_del_all(&ubq->io_cmds);
1251 	struct ublk_rq_data *data, *tmp;
1252 
1253 	io_cmds = llist_reverse_order(io_cmds);
1254 	llist_for_each_entry_safe(data, tmp, io_cmds, node)
1255 		__ublk_rq_task_work(blk_mq_rq_from_pdu(data), issue_flags);
1256 }
1257 
ublk_abort_io_cmds(struct ublk_queue * ubq)1258 static inline void ublk_abort_io_cmds(struct ublk_queue *ubq)
1259 {
1260 	struct llist_node *io_cmds = llist_del_all(&ubq->io_cmds);
1261 	struct ublk_rq_data *data, *tmp;
1262 
1263 	llist_for_each_entry_safe(data, tmp, io_cmds, node)
1264 		__ublk_abort_rq(ubq, blk_mq_rq_from_pdu(data));
1265 }
1266 
ublk_rq_task_work_cb(struct io_uring_cmd * cmd,unsigned issue_flags)1267 static void ublk_rq_task_work_cb(struct io_uring_cmd *cmd, unsigned issue_flags)
1268 {
1269 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
1270 	struct ublk_queue *ubq = pdu->ubq;
1271 
1272 	ublk_forward_io_cmds(ubq, issue_flags);
1273 }
1274 
ublk_queue_cmd(struct ublk_queue * ubq,struct request * rq)1275 static void ublk_queue_cmd(struct ublk_queue *ubq, struct request *rq)
1276 {
1277 	struct ublk_rq_data *data = blk_mq_rq_to_pdu(rq);
1278 	struct ublk_io *io;
1279 
1280 	if (!llist_add(&data->node, &ubq->io_cmds))
1281 		return;
1282 
1283 	io = &ubq->ios[rq->tag];
1284 	/*
1285 	 * If the check pass, we know that this is a re-issued request aborted
1286 	 * previously in monitor_work because the ubq_daemon(cmd's task) is
1287 	 * PF_EXITING. We cannot call io_uring_cmd_complete_in_task() anymore
1288 	 * because this ioucmd's io_uring context may be freed now if no inflight
1289 	 * ioucmd exists. Otherwise we may cause null-deref in ctx->fallback_work.
1290 	 *
1291 	 * Note: monitor_work sets UBLK_IO_FLAG_ABORTED and ends this request(releasing
1292 	 * the tag). Then the request is re-started(allocating the tag) and we are here.
1293 	 * Since releasing/allocating a tag implies smp_mb(), finding UBLK_IO_FLAG_ABORTED
1294 	 * guarantees that here is a re-issued request aborted previously.
1295 	 */
1296 	if (unlikely(io->flags & UBLK_IO_FLAG_ABORTED)) {
1297 		ublk_abort_io_cmds(ubq);
1298 	} else {
1299 		struct io_uring_cmd *cmd = io->cmd;
1300 		struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
1301 
1302 		pdu->ubq = ubq;
1303 		io_uring_cmd_complete_in_task(cmd, ublk_rq_task_work_cb);
1304 	}
1305 }
1306 
ublk_timeout(struct request * rq)1307 static enum blk_eh_timer_return ublk_timeout(struct request *rq)
1308 {
1309 	struct ublk_queue *ubq = rq->mq_hctx->driver_data;
1310 
1311 	if (ubq->flags & UBLK_F_UNPRIVILEGED_DEV) {
1312 		if (!ubq->timeout) {
1313 			send_sig(SIGKILL, ubq->ubq_daemon, 0);
1314 			ubq->timeout = true;
1315 		}
1316 
1317 		return BLK_EH_DONE;
1318 	}
1319 
1320 	return BLK_EH_RESET_TIMER;
1321 }
1322 
ublk_queue_rq(struct blk_mq_hw_ctx * hctx,const struct blk_mq_queue_data * bd)1323 static blk_status_t ublk_queue_rq(struct blk_mq_hw_ctx *hctx,
1324 		const struct blk_mq_queue_data *bd)
1325 {
1326 	struct ublk_queue *ubq = hctx->driver_data;
1327 	struct request *rq = bd->rq;
1328 	blk_status_t res;
1329 
1330 	/* fill iod to slot in io cmd buffer */
1331 	res = ublk_setup_iod(ubq, rq);
1332 	if (unlikely(res != BLK_STS_OK))
1333 		return BLK_STS_IOERR;
1334 
1335 	/* With recovery feature enabled, force_abort is set in
1336 	 * ublk_stop_dev() before calling del_gendisk(). We have to
1337 	 * abort all requeued and new rqs here to let del_gendisk()
1338 	 * move on. Besides, we cannot not call io_uring_cmd_complete_in_task()
1339 	 * to avoid UAF on io_uring ctx.
1340 	 *
1341 	 * Note: force_abort is guaranteed to be seen because it is set
1342 	 * before request queue is unqiuesced.
1343 	 */
1344 	if (ublk_queue_can_use_recovery(ubq) && unlikely(ubq->force_abort))
1345 		return BLK_STS_IOERR;
1346 
1347 	blk_mq_start_request(bd->rq);
1348 
1349 	if (unlikely(ubq_daemon_is_dying(ubq))) {
1350 		__ublk_abort_rq(ubq, rq);
1351 		return BLK_STS_OK;
1352 	}
1353 
1354 	ublk_queue_cmd(ubq, rq);
1355 
1356 	return BLK_STS_OK;
1357 }
1358 
ublk_init_hctx(struct blk_mq_hw_ctx * hctx,void * driver_data,unsigned int hctx_idx)1359 static int ublk_init_hctx(struct blk_mq_hw_ctx *hctx, void *driver_data,
1360 		unsigned int hctx_idx)
1361 {
1362 	struct ublk_device *ub = driver_data;
1363 	struct ublk_queue *ubq = ublk_get_queue(ub, hctx->queue_num);
1364 
1365 	hctx->driver_data = ubq;
1366 	return 0;
1367 }
1368 
1369 static const struct blk_mq_ops ublk_mq_ops = {
1370 	.queue_rq       = ublk_queue_rq,
1371 	.init_hctx	= ublk_init_hctx,
1372 	.timeout	= ublk_timeout,
1373 };
1374 
ublk_ch_open(struct inode * inode,struct file * filp)1375 static int ublk_ch_open(struct inode *inode, struct file *filp)
1376 {
1377 	struct ublk_device *ub = container_of(inode->i_cdev,
1378 			struct ublk_device, cdev);
1379 
1380 	if (test_and_set_bit(UB_STATE_OPEN, &ub->state))
1381 		return -EBUSY;
1382 	filp->private_data = ub;
1383 	return 0;
1384 }
1385 
ublk_ch_release(struct inode * inode,struct file * filp)1386 static int ublk_ch_release(struct inode *inode, struct file *filp)
1387 {
1388 	struct ublk_device *ub = filp->private_data;
1389 
1390 	clear_bit(UB_STATE_OPEN, &ub->state);
1391 	return 0;
1392 }
1393 
1394 /* map pre-allocated per-queue cmd buffer to ublksrv daemon */
ublk_ch_mmap(struct file * filp,struct vm_area_struct * vma)1395 static int ublk_ch_mmap(struct file *filp, struct vm_area_struct *vma)
1396 {
1397 	struct ublk_device *ub = filp->private_data;
1398 	size_t sz = vma->vm_end - vma->vm_start;
1399 	unsigned max_sz = ublk_max_cmd_buf_size();
1400 	unsigned long pfn, end, phys_off = vma->vm_pgoff << PAGE_SHIFT;
1401 	int q_id, ret = 0;
1402 
1403 	spin_lock(&ub->mm_lock);
1404 	if (!ub->mm)
1405 		ub->mm = current->mm;
1406 	if (current->mm != ub->mm)
1407 		ret = -EINVAL;
1408 	spin_unlock(&ub->mm_lock);
1409 
1410 	if (ret)
1411 		return ret;
1412 
1413 	if (vma->vm_flags & VM_WRITE)
1414 		return -EPERM;
1415 
1416 	end = UBLKSRV_CMD_BUF_OFFSET + ub->dev_info.nr_hw_queues * max_sz;
1417 	if (phys_off < UBLKSRV_CMD_BUF_OFFSET || phys_off >= end)
1418 		return -EINVAL;
1419 
1420 	q_id = (phys_off - UBLKSRV_CMD_BUF_OFFSET) / max_sz;
1421 	pr_devel("%s: qid %d, pid %d, addr %lx pg_off %lx sz %lu\n",
1422 			__func__, q_id, current->pid, vma->vm_start,
1423 			phys_off, (unsigned long)sz);
1424 
1425 	if (sz != ublk_queue_cmd_buf_size(ub, q_id))
1426 		return -EINVAL;
1427 
1428 	pfn = virt_to_phys(ublk_queue_cmd_buf(ub, q_id)) >> PAGE_SHIFT;
1429 	return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
1430 }
1431 
ublk_commit_completion(struct ublk_device * ub,const struct ublksrv_io_cmd * ub_cmd)1432 static void ublk_commit_completion(struct ublk_device *ub,
1433 		const struct ublksrv_io_cmd *ub_cmd)
1434 {
1435 	u32 qid = ub_cmd->q_id, tag = ub_cmd->tag;
1436 	struct ublk_queue *ubq = ublk_get_queue(ub, qid);
1437 	struct ublk_io *io = &ubq->ios[tag];
1438 	struct request *req;
1439 
1440 	/* now this cmd slot is owned by nbd driver */
1441 	io->flags &= ~UBLK_IO_FLAG_OWNED_BY_SRV;
1442 	io->res = ub_cmd->result;
1443 
1444 	/* find the io request and complete */
1445 	req = blk_mq_tag_to_rq(ub->tag_set.tags[qid], tag);
1446 	if (WARN_ON_ONCE(unlikely(!req)))
1447 		return;
1448 
1449 	if (req_op(req) == REQ_OP_ZONE_APPEND)
1450 		req->__sector = ub_cmd->zone_append_lba;
1451 
1452 	if (likely(!blk_should_fake_timeout(req->q)))
1453 		ublk_put_req_ref(ubq, req);
1454 }
1455 
1456 /*
1457  * When ->ubq_daemon is exiting, either new request is ended immediately,
1458  * or any queued io command is drained, so it is safe to abort queue
1459  * lockless
1460  */
ublk_abort_queue(struct ublk_device * ub,struct ublk_queue * ubq)1461 static void ublk_abort_queue(struct ublk_device *ub, struct ublk_queue *ubq)
1462 {
1463 	int i;
1464 
1465 	if (!ublk_get_device(ub))
1466 		return;
1467 
1468 	for (i = 0; i < ubq->q_depth; i++) {
1469 		struct ublk_io *io = &ubq->ios[i];
1470 
1471 		if (!(io->flags & UBLK_IO_FLAG_ACTIVE)) {
1472 			struct request *rq;
1473 
1474 			/*
1475 			 * Either we fail the request or ublk_rq_task_work_fn
1476 			 * will do it
1477 			 */
1478 			rq = blk_mq_tag_to_rq(ub->tag_set.tags[ubq->q_id], i);
1479 			if (rq)
1480 				__ublk_fail_req(ubq, io, rq);
1481 		}
1482 	}
1483 	ublk_put_device(ub);
1484 }
1485 
ublk_daemon_monitor_work(struct work_struct * work)1486 static void ublk_daemon_monitor_work(struct work_struct *work)
1487 {
1488 	struct ublk_device *ub =
1489 		container_of(work, struct ublk_device, monitor_work.work);
1490 	int i;
1491 
1492 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++) {
1493 		struct ublk_queue *ubq = ublk_get_queue(ub, i);
1494 
1495 		if (ubq_daemon_is_dying(ubq)) {
1496 			if (ublk_queue_can_use_recovery(ubq))
1497 				schedule_work(&ub->quiesce_work);
1498 			else
1499 				schedule_work(&ub->stop_work);
1500 
1501 			/* abort queue is for making forward progress */
1502 			ublk_abort_queue(ub, ubq);
1503 		}
1504 	}
1505 
1506 	/*
1507 	 * We can't schedule monitor work after ub's state is not UBLK_S_DEV_LIVE.
1508 	 * after ublk_remove() or __ublk_quiesce_dev() is started.
1509 	 *
1510 	 * No need ub->mutex, monitor work are canceled after state is marked
1511 	 * as not LIVE, so new state is observed reliably.
1512 	 */
1513 	if (ub->dev_info.state == UBLK_S_DEV_LIVE)
1514 		schedule_delayed_work(&ub->monitor_work,
1515 				UBLK_DAEMON_MONITOR_PERIOD);
1516 }
1517 
ublk_queue_ready(struct ublk_queue * ubq)1518 static inline bool ublk_queue_ready(struct ublk_queue *ubq)
1519 {
1520 	return ubq->nr_io_ready == ubq->q_depth;
1521 }
1522 
ublk_cancel_queue(struct ublk_queue * ubq)1523 static void ublk_cancel_queue(struct ublk_queue *ubq)
1524 {
1525 	int i;
1526 
1527 	for (i = 0; i < ubq->q_depth; i++) {
1528 		struct ublk_io *io = &ubq->ios[i];
1529 
1530 		if (io->flags & UBLK_IO_FLAG_ACTIVE) {
1531 			bool done;
1532 
1533 			spin_lock(&ubq->cancel_lock);
1534 			done = !!(io->flags & UBLK_IO_FLAG_CANCELED);
1535 			if (!done)
1536 				io->flags |= UBLK_IO_FLAG_CANCELED;
1537 			spin_unlock(&ubq->cancel_lock);
1538 
1539 			if (!done)
1540 				io_uring_cmd_done(io->cmd,
1541 						UBLK_IO_RES_ABORT, 0,
1542 						IO_URING_F_UNLOCKED);
1543 		}
1544 	}
1545 }
1546 
1547 /* Cancel all pending commands, must be called after del_gendisk() returns */
ublk_cancel_dev(struct ublk_device * ub)1548 static void ublk_cancel_dev(struct ublk_device *ub)
1549 {
1550 	int i;
1551 
1552 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1553 		ublk_cancel_queue(ublk_get_queue(ub, i));
1554 }
1555 
ublk_check_inflight_rq(struct request * rq,void * data)1556 static bool ublk_check_inflight_rq(struct request *rq, void *data)
1557 {
1558 	bool *idle = data;
1559 
1560 	if (blk_mq_request_started(rq)) {
1561 		*idle = false;
1562 		return false;
1563 	}
1564 	return true;
1565 }
1566 
ublk_wait_tagset_rqs_idle(struct ublk_device * ub)1567 static void ublk_wait_tagset_rqs_idle(struct ublk_device *ub)
1568 {
1569 	bool idle;
1570 
1571 	WARN_ON_ONCE(!blk_queue_quiesced(ub->ub_disk->queue));
1572 	while (true) {
1573 		idle = true;
1574 		blk_mq_tagset_busy_iter(&ub->tag_set,
1575 				ublk_check_inflight_rq, &idle);
1576 		if (idle)
1577 			break;
1578 		msleep(UBLK_REQUEUE_DELAY_MS);
1579 	}
1580 }
1581 
__ublk_quiesce_dev(struct ublk_device * ub)1582 static void __ublk_quiesce_dev(struct ublk_device *ub)
1583 {
1584 	pr_devel("%s: quiesce ub: dev_id %d state %s\n",
1585 			__func__, ub->dev_info.dev_id,
1586 			ub->dev_info.state == UBLK_S_DEV_LIVE ?
1587 			"LIVE" : "QUIESCED");
1588 	blk_mq_quiesce_queue(ub->ub_disk->queue);
1589 	ublk_wait_tagset_rqs_idle(ub);
1590 	ub->dev_info.state = UBLK_S_DEV_QUIESCED;
1591 	/* we are going to release task_struct of ubq_daemon and resets
1592 	 * ->ubq_daemon to NULL. So in monitor_work, check on ubq_daemon causes UAF.
1593 	 * Besides, monitor_work is not necessary in QUIESCED state since we have
1594 	 * already scheduled quiesce_work and quiesced all ubqs.
1595 	 *
1596 	 * Do not let monitor_work schedule itself if state it QUIESCED. And we cancel
1597 	 * it here and re-schedule it in END_USER_RECOVERY to avoid UAF.
1598 	 */
1599 	cancel_delayed_work_sync(&ub->monitor_work);
1600 }
1601 
ublk_quiesce_work_fn(struct work_struct * work)1602 static void ublk_quiesce_work_fn(struct work_struct *work)
1603 {
1604 	struct ublk_device *ub =
1605 		container_of(work, struct ublk_device, quiesce_work);
1606 
1607 	mutex_lock(&ub->mutex);
1608 	if (ub->dev_info.state != UBLK_S_DEV_LIVE)
1609 		goto unlock;
1610 	__ublk_quiesce_dev(ub);
1611  unlock:
1612 	mutex_unlock(&ub->mutex);
1613 	ublk_cancel_dev(ub);
1614 }
1615 
ublk_unquiesce_dev(struct ublk_device * ub)1616 static void ublk_unquiesce_dev(struct ublk_device *ub)
1617 {
1618 	int i;
1619 
1620 	pr_devel("%s: unquiesce ub: dev_id %d state %s\n",
1621 			__func__, ub->dev_info.dev_id,
1622 			ub->dev_info.state == UBLK_S_DEV_LIVE ?
1623 			"LIVE" : "QUIESCED");
1624 	/* quiesce_work has run. We let requeued rqs be aborted
1625 	 * before running fallback_wq. "force_abort" must be seen
1626 	 * after request queue is unqiuesced. Then del_gendisk()
1627 	 * can move on.
1628 	 */
1629 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1630 		ublk_get_queue(ub, i)->force_abort = true;
1631 
1632 	blk_mq_unquiesce_queue(ub->ub_disk->queue);
1633 	/* We may have requeued some rqs in ublk_quiesce_queue() */
1634 	blk_mq_kick_requeue_list(ub->ub_disk->queue);
1635 }
1636 
ublk_stop_dev(struct ublk_device * ub)1637 static void ublk_stop_dev(struct ublk_device *ub)
1638 {
1639 	mutex_lock(&ub->mutex);
1640 	if (ub->dev_info.state == UBLK_S_DEV_DEAD)
1641 		goto unlock;
1642 	if (ublk_can_use_recovery(ub)) {
1643 		if (ub->dev_info.state == UBLK_S_DEV_LIVE)
1644 			__ublk_quiesce_dev(ub);
1645 		ublk_unquiesce_dev(ub);
1646 	}
1647 	del_gendisk(ub->ub_disk);
1648 	ub->dev_info.state = UBLK_S_DEV_DEAD;
1649 	ub->dev_info.ublksrv_pid = -1;
1650 	put_disk(ub->ub_disk);
1651 	ub->ub_disk = NULL;
1652  unlock:
1653 	mutex_unlock(&ub->mutex);
1654 	ublk_cancel_dev(ub);
1655 	cancel_delayed_work_sync(&ub->monitor_work);
1656 }
1657 
1658 /* device can only be started after all IOs are ready */
ublk_mark_io_ready(struct ublk_device * ub,struct ublk_queue * ubq)1659 static void ublk_mark_io_ready(struct ublk_device *ub, struct ublk_queue *ubq)
1660 {
1661 	mutex_lock(&ub->mutex);
1662 	ubq->nr_io_ready++;
1663 	if (ublk_queue_ready(ubq)) {
1664 		ubq->ubq_daemon = current;
1665 		get_task_struct(ubq->ubq_daemon);
1666 		ub->nr_queues_ready++;
1667 
1668 		if (capable(CAP_SYS_ADMIN))
1669 			ub->nr_privileged_daemon++;
1670 	}
1671 	if (ub->nr_queues_ready == ub->dev_info.nr_hw_queues)
1672 		complete_all(&ub->completion);
1673 	mutex_unlock(&ub->mutex);
1674 }
1675 
ublk_handle_need_get_data(struct ublk_device * ub,int q_id,int tag)1676 static void ublk_handle_need_get_data(struct ublk_device *ub, int q_id,
1677 		int tag)
1678 {
1679 	struct ublk_queue *ubq = ublk_get_queue(ub, q_id);
1680 	struct request *req = blk_mq_tag_to_rq(ub->tag_set.tags[q_id], tag);
1681 
1682 	ublk_queue_cmd(ubq, req);
1683 }
1684 
ublk_check_cmd_op(u32 cmd_op)1685 static inline int ublk_check_cmd_op(u32 cmd_op)
1686 {
1687 	u32 ioc_type = _IOC_TYPE(cmd_op);
1688 
1689 	if (!IS_ENABLED(CONFIG_BLKDEV_UBLK_LEGACY_OPCODES) && ioc_type != 'u')
1690 		return -EOPNOTSUPP;
1691 
1692 	if (ioc_type != 'u' && ioc_type != 0)
1693 		return -EOPNOTSUPP;
1694 
1695 	return 0;
1696 }
1697 
ublk_fill_io_cmd(struct ublk_io * io,struct io_uring_cmd * cmd,unsigned long buf_addr)1698 static inline void ublk_fill_io_cmd(struct ublk_io *io,
1699 		struct io_uring_cmd *cmd, unsigned long buf_addr)
1700 {
1701 	io->cmd = cmd;
1702 	io->flags |= UBLK_IO_FLAG_ACTIVE;
1703 	io->addr = buf_addr;
1704 }
1705 
__ublk_ch_uring_cmd(struct io_uring_cmd * cmd,unsigned int issue_flags,const struct ublksrv_io_cmd * ub_cmd)1706 static int __ublk_ch_uring_cmd(struct io_uring_cmd *cmd,
1707 			       unsigned int issue_flags,
1708 			       const struct ublksrv_io_cmd *ub_cmd)
1709 {
1710 	struct ublk_device *ub = cmd->file->private_data;
1711 	struct ublk_queue *ubq;
1712 	struct ublk_io *io;
1713 	u32 cmd_op = cmd->cmd_op;
1714 	unsigned tag = ub_cmd->tag;
1715 	int ret = -EINVAL;
1716 	struct request *req;
1717 
1718 	pr_devel("%s: received: cmd op %d queue %d tag %d result %d\n",
1719 			__func__, cmd->cmd_op, ub_cmd->q_id, tag,
1720 			ub_cmd->result);
1721 
1722 	if (ub_cmd->q_id >= ub->dev_info.nr_hw_queues)
1723 		goto out;
1724 
1725 	ubq = ublk_get_queue(ub, ub_cmd->q_id);
1726 	if (!ubq || ub_cmd->q_id != ubq->q_id)
1727 		goto out;
1728 
1729 	if (ubq->ubq_daemon && ubq->ubq_daemon != current)
1730 		goto out;
1731 
1732 	if (tag >= ubq->q_depth)
1733 		goto out;
1734 
1735 	io = &ubq->ios[tag];
1736 
1737 	/* there is pending io cmd, something must be wrong */
1738 	if (io->flags & UBLK_IO_FLAG_ACTIVE) {
1739 		ret = -EBUSY;
1740 		goto out;
1741 	}
1742 
1743 	/*
1744 	 * ensure that the user issues UBLK_IO_NEED_GET_DATA
1745 	 * iff the driver have set the UBLK_IO_FLAG_NEED_GET_DATA.
1746 	 */
1747 	if ((!!(io->flags & UBLK_IO_FLAG_NEED_GET_DATA))
1748 			^ (_IOC_NR(cmd_op) == UBLK_IO_NEED_GET_DATA))
1749 		goto out;
1750 
1751 	ret = ublk_check_cmd_op(cmd_op);
1752 	if (ret)
1753 		goto out;
1754 
1755 	ret = -EINVAL;
1756 	switch (_IOC_NR(cmd_op)) {
1757 	case UBLK_IO_FETCH_REQ:
1758 		/* UBLK_IO_FETCH_REQ is only allowed before queue is setup */
1759 		if (ublk_queue_ready(ubq)) {
1760 			ret = -EBUSY;
1761 			goto out;
1762 		}
1763 		/*
1764 		 * The io is being handled by server, so COMMIT_RQ is expected
1765 		 * instead of FETCH_REQ
1766 		 */
1767 		if (io->flags & UBLK_IO_FLAG_OWNED_BY_SRV)
1768 			goto out;
1769 
1770 		if (!ublk_support_user_copy(ubq)) {
1771 			/*
1772 			 * FETCH_RQ has to provide IO buffer if NEED GET
1773 			 * DATA is not enabled
1774 			 */
1775 			if (!ub_cmd->addr && !ublk_need_get_data(ubq))
1776 				goto out;
1777 		} else if (ub_cmd->addr) {
1778 			/* User copy requires addr to be unset */
1779 			ret = -EINVAL;
1780 			goto out;
1781 		}
1782 
1783 		ublk_fill_io_cmd(io, cmd, ub_cmd->addr);
1784 		ublk_mark_io_ready(ub, ubq);
1785 		break;
1786 	case UBLK_IO_COMMIT_AND_FETCH_REQ:
1787 		req = blk_mq_tag_to_rq(ub->tag_set.tags[ub_cmd->q_id], tag);
1788 
1789 		if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV))
1790 			goto out;
1791 
1792 		if (!ublk_support_user_copy(ubq)) {
1793 			/*
1794 			 * COMMIT_AND_FETCH_REQ has to provide IO buffer if
1795 			 * NEED GET DATA is not enabled or it is Read IO.
1796 			 */
1797 			if (!ub_cmd->addr && (!ublk_need_get_data(ubq) ||
1798 						req_op(req) == REQ_OP_READ))
1799 				goto out;
1800 		} else if (req_op(req) != REQ_OP_ZONE_APPEND && ub_cmd->addr) {
1801 			/*
1802 			 * User copy requires addr to be unset when command is
1803 			 * not zone append
1804 			 */
1805 			ret = -EINVAL;
1806 			goto out;
1807 		}
1808 
1809 		ublk_fill_io_cmd(io, cmd, ub_cmd->addr);
1810 		ublk_commit_completion(ub, ub_cmd);
1811 		break;
1812 	case UBLK_IO_NEED_GET_DATA:
1813 		if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV))
1814 			goto out;
1815 		ublk_fill_io_cmd(io, cmd, ub_cmd->addr);
1816 		ublk_handle_need_get_data(ub, ub_cmd->q_id, ub_cmd->tag);
1817 		break;
1818 	default:
1819 		goto out;
1820 	}
1821 	return -EIOCBQUEUED;
1822 
1823  out:
1824 	io_uring_cmd_done(cmd, ret, 0, issue_flags);
1825 	pr_devel("%s: complete: cmd op %d, tag %d ret %x io_flags %x\n",
1826 			__func__, cmd_op, tag, ret, io->flags);
1827 	return -EIOCBQUEUED;
1828 }
1829 
__ublk_check_and_get_req(struct ublk_device * ub,struct ublk_queue * ubq,int tag,size_t offset)1830 static inline struct request *__ublk_check_and_get_req(struct ublk_device *ub,
1831 		struct ublk_queue *ubq, int tag, size_t offset)
1832 {
1833 	struct request *req;
1834 
1835 	if (!ublk_need_req_ref(ubq))
1836 		return NULL;
1837 
1838 	req = blk_mq_tag_to_rq(ub->tag_set.tags[ubq->q_id], tag);
1839 	if (!req)
1840 		return NULL;
1841 
1842 	if (!ublk_get_req_ref(ubq, req))
1843 		return NULL;
1844 
1845 	if (unlikely(!blk_mq_request_started(req) || req->tag != tag))
1846 		goto fail_put;
1847 
1848 	if (!ublk_rq_has_data(req))
1849 		goto fail_put;
1850 
1851 	if (offset > blk_rq_bytes(req))
1852 		goto fail_put;
1853 
1854 	return req;
1855 fail_put:
1856 	ublk_put_req_ref(ubq, req);
1857 	return NULL;
1858 }
1859 
ublk_ch_uring_cmd(struct io_uring_cmd * cmd,unsigned int issue_flags)1860 static int ublk_ch_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags)
1861 {
1862 	/*
1863 	 * Not necessary for async retry, but let's keep it simple and always
1864 	 * copy the values to avoid any potential reuse.
1865 	 */
1866 	const struct ublksrv_io_cmd *ub_src = io_uring_sqe_cmd(cmd->sqe);
1867 	const struct ublksrv_io_cmd ub_cmd = {
1868 		.q_id = READ_ONCE(ub_src->q_id),
1869 		.tag = READ_ONCE(ub_src->tag),
1870 		.result = READ_ONCE(ub_src->result),
1871 		.addr = READ_ONCE(ub_src->addr)
1872 	};
1873 
1874 	return __ublk_ch_uring_cmd(cmd, issue_flags, &ub_cmd);
1875 }
1876 
ublk_check_ubuf_dir(const struct request * req,int ubuf_dir)1877 static inline bool ublk_check_ubuf_dir(const struct request *req,
1878 		int ubuf_dir)
1879 {
1880 	/* copy ubuf to request pages */
1881 	if ((req_op(req) == REQ_OP_READ || req_op(req) == REQ_OP_DRV_IN) &&
1882 	    ubuf_dir == ITER_SOURCE)
1883 		return true;
1884 
1885 	/* copy request pages to ubuf */
1886 	if ((req_op(req) == REQ_OP_WRITE ||
1887 	     req_op(req) == REQ_OP_ZONE_APPEND) &&
1888 	    ubuf_dir == ITER_DEST)
1889 		return true;
1890 
1891 	return false;
1892 }
1893 
ublk_check_and_get_req(struct kiocb * iocb,struct iov_iter * iter,size_t * off,int dir)1894 static struct request *ublk_check_and_get_req(struct kiocb *iocb,
1895 		struct iov_iter *iter, size_t *off, int dir)
1896 {
1897 	struct ublk_device *ub = iocb->ki_filp->private_data;
1898 	struct ublk_queue *ubq;
1899 	struct request *req;
1900 	size_t buf_off;
1901 	u16 tag, q_id;
1902 
1903 	if (!ub)
1904 		return ERR_PTR(-EACCES);
1905 
1906 	if (!user_backed_iter(iter))
1907 		return ERR_PTR(-EACCES);
1908 
1909 	if (ub->dev_info.state == UBLK_S_DEV_DEAD)
1910 		return ERR_PTR(-EACCES);
1911 
1912 	tag = ublk_pos_to_tag(iocb->ki_pos);
1913 	q_id = ublk_pos_to_hwq(iocb->ki_pos);
1914 	buf_off = ublk_pos_to_buf_off(iocb->ki_pos);
1915 
1916 	if (q_id >= ub->dev_info.nr_hw_queues)
1917 		return ERR_PTR(-EINVAL);
1918 
1919 	ubq = ublk_get_queue(ub, q_id);
1920 	if (!ubq)
1921 		return ERR_PTR(-EINVAL);
1922 
1923 	if (tag >= ubq->q_depth)
1924 		return ERR_PTR(-EINVAL);
1925 
1926 	req = __ublk_check_and_get_req(ub, ubq, tag, buf_off);
1927 	if (!req)
1928 		return ERR_PTR(-EINVAL);
1929 
1930 	if (!req->mq_hctx || !req->mq_hctx->driver_data)
1931 		goto fail;
1932 
1933 	if (!ublk_check_ubuf_dir(req, dir))
1934 		goto fail;
1935 
1936 	*off = buf_off;
1937 	return req;
1938 fail:
1939 	ublk_put_req_ref(ubq, req);
1940 	return ERR_PTR(-EACCES);
1941 }
1942 
ublk_ch_read_iter(struct kiocb * iocb,struct iov_iter * to)1943 static ssize_t ublk_ch_read_iter(struct kiocb *iocb, struct iov_iter *to)
1944 {
1945 	struct ublk_queue *ubq;
1946 	struct request *req;
1947 	size_t buf_off;
1948 	size_t ret;
1949 
1950 	req = ublk_check_and_get_req(iocb, to, &buf_off, ITER_DEST);
1951 	if (IS_ERR(req))
1952 		return PTR_ERR(req);
1953 
1954 	ret = ublk_copy_user_pages(req, buf_off, to, ITER_DEST);
1955 	ubq = req->mq_hctx->driver_data;
1956 	ublk_put_req_ref(ubq, req);
1957 
1958 	return ret;
1959 }
1960 
ublk_ch_write_iter(struct kiocb * iocb,struct iov_iter * from)1961 static ssize_t ublk_ch_write_iter(struct kiocb *iocb, struct iov_iter *from)
1962 {
1963 	struct ublk_queue *ubq;
1964 	struct request *req;
1965 	size_t buf_off;
1966 	size_t ret;
1967 
1968 	req = ublk_check_and_get_req(iocb, from, &buf_off, ITER_SOURCE);
1969 	if (IS_ERR(req))
1970 		return PTR_ERR(req);
1971 
1972 	ret = ublk_copy_user_pages(req, buf_off, from, ITER_SOURCE);
1973 	ubq = req->mq_hctx->driver_data;
1974 	ublk_put_req_ref(ubq, req);
1975 
1976 	return ret;
1977 }
1978 
1979 static const struct file_operations ublk_ch_fops = {
1980 	.owner = THIS_MODULE,
1981 	.open = ublk_ch_open,
1982 	.release = ublk_ch_release,
1983 	.llseek = no_llseek,
1984 	.read_iter = ublk_ch_read_iter,
1985 	.write_iter = ublk_ch_write_iter,
1986 	.uring_cmd = ublk_ch_uring_cmd,
1987 	.mmap = ublk_ch_mmap,
1988 };
1989 
ublk_deinit_queue(struct ublk_device * ub,int q_id)1990 static void ublk_deinit_queue(struct ublk_device *ub, int q_id)
1991 {
1992 	int size = ublk_queue_cmd_buf_size(ub, q_id);
1993 	struct ublk_queue *ubq = ublk_get_queue(ub, q_id);
1994 
1995 	if (ubq->ubq_daemon)
1996 		put_task_struct(ubq->ubq_daemon);
1997 	if (ubq->io_cmd_buf)
1998 		free_pages((unsigned long)ubq->io_cmd_buf, get_order(size));
1999 }
2000 
ublk_init_queue(struct ublk_device * ub,int q_id)2001 static int ublk_init_queue(struct ublk_device *ub, int q_id)
2002 {
2003 	struct ublk_queue *ubq = ublk_get_queue(ub, q_id);
2004 	gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO;
2005 	void *ptr;
2006 	int size;
2007 
2008 	spin_lock_init(&ubq->cancel_lock);
2009 	ubq->flags = ub->dev_info.flags;
2010 	ubq->q_id = q_id;
2011 	ubq->q_depth = ub->dev_info.queue_depth;
2012 	size = ublk_queue_cmd_buf_size(ub, q_id);
2013 
2014 	ptr = (void *) __get_free_pages(gfp_flags, get_order(size));
2015 	if (!ptr)
2016 		return -ENOMEM;
2017 
2018 	ubq->io_cmd_buf = ptr;
2019 	ubq->dev = ub;
2020 	return 0;
2021 }
2022 
ublk_deinit_queues(struct ublk_device * ub)2023 static void ublk_deinit_queues(struct ublk_device *ub)
2024 {
2025 	int nr_queues = ub->dev_info.nr_hw_queues;
2026 	int i;
2027 
2028 	if (!ub->__queues)
2029 		return;
2030 
2031 	for (i = 0; i < nr_queues; i++)
2032 		ublk_deinit_queue(ub, i);
2033 	kfree(ub->__queues);
2034 }
2035 
ublk_init_queues(struct ublk_device * ub)2036 static int ublk_init_queues(struct ublk_device *ub)
2037 {
2038 	int nr_queues = ub->dev_info.nr_hw_queues;
2039 	int depth = ub->dev_info.queue_depth;
2040 	int ubq_size = sizeof(struct ublk_queue) + depth * sizeof(struct ublk_io);
2041 	int i, ret = -ENOMEM;
2042 
2043 	ub->queue_size = ubq_size;
2044 	ub->__queues = kcalloc(nr_queues, ubq_size, GFP_KERNEL);
2045 	if (!ub->__queues)
2046 		return ret;
2047 
2048 	for (i = 0; i < nr_queues; i++) {
2049 		if (ublk_init_queue(ub, i))
2050 			goto fail;
2051 	}
2052 
2053 	init_completion(&ub->completion);
2054 	return 0;
2055 
2056  fail:
2057 	ublk_deinit_queues(ub);
2058 	return ret;
2059 }
2060 
ublk_alloc_dev_number(struct ublk_device * ub,int idx)2061 static int ublk_alloc_dev_number(struct ublk_device *ub, int idx)
2062 {
2063 	int i = idx;
2064 	int err;
2065 
2066 	spin_lock(&ublk_idr_lock);
2067 	/* allocate id, if @id >= 0, we're requesting that specific id */
2068 	if (i >= 0) {
2069 		err = idr_alloc(&ublk_index_idr, ub, i, i + 1, GFP_NOWAIT);
2070 		if (err == -ENOSPC)
2071 			err = -EEXIST;
2072 	} else {
2073 		err = idr_alloc(&ublk_index_idr, ub, 0, 0, GFP_NOWAIT);
2074 	}
2075 	spin_unlock(&ublk_idr_lock);
2076 
2077 	if (err >= 0)
2078 		ub->ub_number = err;
2079 
2080 	return err;
2081 }
2082 
ublk_free_dev_number(struct ublk_device * ub)2083 static void ublk_free_dev_number(struct ublk_device *ub)
2084 {
2085 	spin_lock(&ublk_idr_lock);
2086 	idr_remove(&ublk_index_idr, ub->ub_number);
2087 	wake_up_all(&ublk_idr_wq);
2088 	spin_unlock(&ublk_idr_lock);
2089 }
2090 
ublk_cdev_rel(struct device * dev)2091 static void ublk_cdev_rel(struct device *dev)
2092 {
2093 	struct ublk_device *ub = container_of(dev, struct ublk_device, cdev_dev);
2094 
2095 	blk_mq_free_tag_set(&ub->tag_set);
2096 	ublk_deinit_queues(ub);
2097 	ublk_free_dev_number(ub);
2098 	mutex_destroy(&ub->mutex);
2099 	kfree(ub);
2100 }
2101 
ublk_add_chdev(struct ublk_device * ub)2102 static int ublk_add_chdev(struct ublk_device *ub)
2103 {
2104 	struct device *dev = &ub->cdev_dev;
2105 	int minor = ub->ub_number;
2106 	int ret;
2107 
2108 	dev->parent = ublk_misc.this_device;
2109 	dev->devt = MKDEV(MAJOR(ublk_chr_devt), minor);
2110 	dev->class = &ublk_chr_class;
2111 	dev->release = ublk_cdev_rel;
2112 	device_initialize(dev);
2113 
2114 	ret = dev_set_name(dev, "ublkc%d", minor);
2115 	if (ret)
2116 		goto fail;
2117 
2118 	cdev_init(&ub->cdev, &ublk_ch_fops);
2119 	ret = cdev_device_add(&ub->cdev, dev);
2120 	if (ret)
2121 		goto fail;
2122 
2123 	ublks_added++;
2124 	return 0;
2125  fail:
2126 	put_device(dev);
2127 	return ret;
2128 }
2129 
ublk_stop_work_fn(struct work_struct * work)2130 static void ublk_stop_work_fn(struct work_struct *work)
2131 {
2132 	struct ublk_device *ub =
2133 		container_of(work, struct ublk_device, stop_work);
2134 
2135 	ublk_stop_dev(ub);
2136 }
2137 
2138 /* align max io buffer size with PAGE_SIZE */
ublk_align_max_io_size(struct ublk_device * ub)2139 static void ublk_align_max_io_size(struct ublk_device *ub)
2140 {
2141 	unsigned int max_io_bytes = ub->dev_info.max_io_buf_bytes;
2142 
2143 	ub->dev_info.max_io_buf_bytes =
2144 		round_down(max_io_bytes, PAGE_SIZE);
2145 }
2146 
ublk_add_tag_set(struct ublk_device * ub)2147 static int ublk_add_tag_set(struct ublk_device *ub)
2148 {
2149 	ub->tag_set.ops = &ublk_mq_ops;
2150 	ub->tag_set.nr_hw_queues = ub->dev_info.nr_hw_queues;
2151 	ub->tag_set.queue_depth = ub->dev_info.queue_depth;
2152 	ub->tag_set.numa_node = NUMA_NO_NODE;
2153 	ub->tag_set.cmd_size = sizeof(struct ublk_rq_data);
2154 	ub->tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
2155 	ub->tag_set.driver_data = ub;
2156 	return blk_mq_alloc_tag_set(&ub->tag_set);
2157 }
2158 
ublk_remove(struct ublk_device * ub)2159 static void ublk_remove(struct ublk_device *ub)
2160 {
2161 	ublk_stop_dev(ub);
2162 	cancel_work_sync(&ub->stop_work);
2163 	cancel_work_sync(&ub->quiesce_work);
2164 	cdev_device_del(&ub->cdev, &ub->cdev_dev);
2165 	put_device(&ub->cdev_dev);
2166 	ublks_added--;
2167 }
2168 
ublk_get_device_from_id(int idx)2169 static struct ublk_device *ublk_get_device_from_id(int idx)
2170 {
2171 	struct ublk_device *ub = NULL;
2172 
2173 	if (idx < 0)
2174 		return NULL;
2175 
2176 	spin_lock(&ublk_idr_lock);
2177 	ub = idr_find(&ublk_index_idr, idx);
2178 	if (ub)
2179 		ub = ublk_get_device(ub);
2180 	spin_unlock(&ublk_idr_lock);
2181 
2182 	return ub;
2183 }
2184 
ublk_ctrl_start_dev(struct ublk_device * ub,struct io_uring_cmd * cmd)2185 static int ublk_ctrl_start_dev(struct ublk_device *ub, struct io_uring_cmd *cmd)
2186 {
2187 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2188 	int ublksrv_pid = (int)header->data[0];
2189 	struct gendisk *disk;
2190 	int ret = -EINVAL;
2191 
2192 	if (ublksrv_pid <= 0)
2193 		return -EINVAL;
2194 
2195 	if (wait_for_completion_interruptible(&ub->completion) != 0)
2196 		return -EINTR;
2197 
2198 	schedule_delayed_work(&ub->monitor_work, UBLK_DAEMON_MONITOR_PERIOD);
2199 
2200 	mutex_lock(&ub->mutex);
2201 	if (ub->dev_info.state == UBLK_S_DEV_LIVE ||
2202 	    test_bit(UB_STATE_USED, &ub->state)) {
2203 		ret = -EEXIST;
2204 		goto out_unlock;
2205 	}
2206 
2207 	disk = blk_mq_alloc_disk(&ub->tag_set, NULL);
2208 	if (IS_ERR(disk)) {
2209 		ret = PTR_ERR(disk);
2210 		goto out_unlock;
2211 	}
2212 	sprintf(disk->disk_name, "ublkb%d", ub->ub_number);
2213 	disk->fops = &ub_fops;
2214 	disk->private_data = ub;
2215 
2216 	ub->dev_info.ublksrv_pid = ublksrv_pid;
2217 	ub->ub_disk = disk;
2218 
2219 	ret = ublk_apply_params(ub);
2220 	if (ret)
2221 		goto out_put_disk;
2222 
2223 	/* don't probe partitions if any one ubq daemon is un-trusted */
2224 	if (ub->nr_privileged_daemon != ub->nr_queues_ready)
2225 		set_bit(GD_SUPPRESS_PART_SCAN, &disk->state);
2226 
2227 	get_device(&ub->cdev_dev);
2228 	ub->dev_info.state = UBLK_S_DEV_LIVE;
2229 
2230 	if (ublk_dev_is_zoned(ub)) {
2231 		ret = ublk_revalidate_disk_zones(ub);
2232 		if (ret)
2233 			goto out_put_cdev;
2234 	}
2235 
2236 	ret = add_disk(disk);
2237 	if (ret)
2238 		goto out_put_cdev;
2239 
2240 	set_bit(UB_STATE_USED, &ub->state);
2241 
2242 out_put_cdev:
2243 	if (ret) {
2244 		ub->dev_info.state = UBLK_S_DEV_DEAD;
2245 		ublk_put_device(ub);
2246 	}
2247 out_put_disk:
2248 	if (ret)
2249 		put_disk(disk);
2250 out_unlock:
2251 	mutex_unlock(&ub->mutex);
2252 	return ret;
2253 }
2254 
ublk_ctrl_get_queue_affinity(struct ublk_device * ub,struct io_uring_cmd * cmd)2255 static int ublk_ctrl_get_queue_affinity(struct ublk_device *ub,
2256 		struct io_uring_cmd *cmd)
2257 {
2258 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2259 	void __user *argp = (void __user *)(unsigned long)header->addr;
2260 	cpumask_var_t cpumask;
2261 	unsigned long queue;
2262 	unsigned int retlen;
2263 	unsigned int i;
2264 	int ret;
2265 
2266 	if (header->len * BITS_PER_BYTE < nr_cpu_ids)
2267 		return -EINVAL;
2268 	if (header->len & (sizeof(unsigned long)-1))
2269 		return -EINVAL;
2270 	if (!header->addr)
2271 		return -EINVAL;
2272 
2273 	queue = header->data[0];
2274 	if (queue >= ub->dev_info.nr_hw_queues)
2275 		return -EINVAL;
2276 
2277 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
2278 		return -ENOMEM;
2279 
2280 	for_each_possible_cpu(i) {
2281 		if (ub->tag_set.map[HCTX_TYPE_DEFAULT].mq_map[i] == queue)
2282 			cpumask_set_cpu(i, cpumask);
2283 	}
2284 
2285 	ret = -EFAULT;
2286 	retlen = min_t(unsigned short, header->len, cpumask_size());
2287 	if (copy_to_user(argp, cpumask, retlen))
2288 		goto out_free_cpumask;
2289 	if (retlen != header->len &&
2290 	    clear_user(argp + retlen, header->len - retlen))
2291 		goto out_free_cpumask;
2292 
2293 	ret = 0;
2294 out_free_cpumask:
2295 	free_cpumask_var(cpumask);
2296 	return ret;
2297 }
2298 
ublk_dump_dev_info(struct ublksrv_ctrl_dev_info * info)2299 static inline void ublk_dump_dev_info(struct ublksrv_ctrl_dev_info *info)
2300 {
2301 	pr_devel("%s: dev id %d flags %llx\n", __func__,
2302 			info->dev_id, info->flags);
2303 	pr_devel("\t nr_hw_queues %d queue_depth %d\n",
2304 			info->nr_hw_queues, info->queue_depth);
2305 }
2306 
ublk_ctrl_add_dev(struct io_uring_cmd * cmd)2307 static int ublk_ctrl_add_dev(struct io_uring_cmd *cmd)
2308 {
2309 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2310 	void __user *argp = (void __user *)(unsigned long)header->addr;
2311 	struct ublksrv_ctrl_dev_info info;
2312 	struct ublk_device *ub;
2313 	int ret = -EINVAL;
2314 
2315 	if (header->len < sizeof(info) || !header->addr)
2316 		return -EINVAL;
2317 	if (header->queue_id != (u16)-1) {
2318 		pr_warn("%s: queue_id is wrong %x\n",
2319 			__func__, header->queue_id);
2320 		return -EINVAL;
2321 	}
2322 
2323 	if (copy_from_user(&info, argp, sizeof(info)))
2324 		return -EFAULT;
2325 
2326 	if (capable(CAP_SYS_ADMIN))
2327 		info.flags &= ~UBLK_F_UNPRIVILEGED_DEV;
2328 	else if (!(info.flags & UBLK_F_UNPRIVILEGED_DEV))
2329 		return -EPERM;
2330 
2331 	/*
2332 	 * unprivileged device can't be trusted, but RECOVERY and
2333 	 * RECOVERY_REISSUE still may hang error handling, so can't
2334 	 * support recovery features for unprivileged ublk now
2335 	 *
2336 	 * TODO: provide forward progress for RECOVERY handler, so that
2337 	 * unprivileged device can benefit from it
2338 	 */
2339 	if (info.flags & UBLK_F_UNPRIVILEGED_DEV) {
2340 		info.flags &= ~(UBLK_F_USER_RECOVERY_REISSUE |
2341 				UBLK_F_USER_RECOVERY);
2342 
2343 		/*
2344 		 * For USER_COPY, we depends on userspace to fill request
2345 		 * buffer by pwrite() to ublk char device, which can't be
2346 		 * used for unprivileged device
2347 		 */
2348 		if (info.flags & UBLK_F_USER_COPY)
2349 			return -EINVAL;
2350 	}
2351 
2352 	/* the created device is always owned by current user */
2353 	ublk_store_owner_uid_gid(&info.owner_uid, &info.owner_gid);
2354 
2355 	if (header->dev_id != info.dev_id) {
2356 		pr_warn("%s: dev id not match %u %u\n",
2357 			__func__, header->dev_id, info.dev_id);
2358 		return -EINVAL;
2359 	}
2360 
2361 	ublk_dump_dev_info(&info);
2362 
2363 	ret = mutex_lock_killable(&ublk_ctl_mutex);
2364 	if (ret)
2365 		return ret;
2366 
2367 	ret = -EACCES;
2368 	if (ublks_added >= ublks_max)
2369 		goto out_unlock;
2370 
2371 	ret = -ENOMEM;
2372 	ub = kzalloc(sizeof(*ub), GFP_KERNEL);
2373 	if (!ub)
2374 		goto out_unlock;
2375 	mutex_init(&ub->mutex);
2376 	spin_lock_init(&ub->mm_lock);
2377 	INIT_WORK(&ub->quiesce_work, ublk_quiesce_work_fn);
2378 	INIT_WORK(&ub->stop_work, ublk_stop_work_fn);
2379 	INIT_DELAYED_WORK(&ub->monitor_work, ublk_daemon_monitor_work);
2380 
2381 	ret = ublk_alloc_dev_number(ub, header->dev_id);
2382 	if (ret < 0)
2383 		goto out_free_ub;
2384 
2385 	memcpy(&ub->dev_info, &info, sizeof(info));
2386 
2387 	/* update device id */
2388 	ub->dev_info.dev_id = ub->ub_number;
2389 
2390 	/*
2391 	 * 64bit flags will be copied back to userspace as feature
2392 	 * negotiation result, so have to clear flags which driver
2393 	 * doesn't support yet, then userspace can get correct flags
2394 	 * (features) to handle.
2395 	 */
2396 	ub->dev_info.flags &= UBLK_F_ALL;
2397 
2398 	ub->dev_info.flags |= UBLK_F_CMD_IOCTL_ENCODE |
2399 		UBLK_F_URING_CMD_COMP_IN_TASK;
2400 
2401 	/* GET_DATA isn't needed any more with USER_COPY */
2402 	if (ublk_dev_is_user_copy(ub))
2403 		ub->dev_info.flags &= ~UBLK_F_NEED_GET_DATA;
2404 
2405 	/* Zoned storage support requires user copy feature */
2406 	if (ublk_dev_is_zoned(ub) &&
2407 	    (!IS_ENABLED(CONFIG_BLK_DEV_ZONED) || !ublk_dev_is_user_copy(ub))) {
2408 		ret = -EINVAL;
2409 		goto out_free_dev_number;
2410 	}
2411 
2412 	/* We are not ready to support zero copy */
2413 	ub->dev_info.flags &= ~UBLK_F_SUPPORT_ZERO_COPY;
2414 
2415 	ub->dev_info.nr_hw_queues = min_t(unsigned int,
2416 			ub->dev_info.nr_hw_queues, nr_cpu_ids);
2417 	ublk_align_max_io_size(ub);
2418 
2419 	ret = ublk_init_queues(ub);
2420 	if (ret)
2421 		goto out_free_dev_number;
2422 
2423 	ret = ublk_add_tag_set(ub);
2424 	if (ret)
2425 		goto out_deinit_queues;
2426 
2427 	ret = -EFAULT;
2428 	if (copy_to_user(argp, &ub->dev_info, sizeof(info)))
2429 		goto out_free_tag_set;
2430 
2431 	/*
2432 	 * Add the char dev so that ublksrv daemon can be setup.
2433 	 * ublk_add_chdev() will cleanup everything if it fails.
2434 	 */
2435 	ret = ublk_add_chdev(ub);
2436 	goto out_unlock;
2437 
2438 out_free_tag_set:
2439 	blk_mq_free_tag_set(&ub->tag_set);
2440 out_deinit_queues:
2441 	ublk_deinit_queues(ub);
2442 out_free_dev_number:
2443 	ublk_free_dev_number(ub);
2444 out_free_ub:
2445 	mutex_destroy(&ub->mutex);
2446 	kfree(ub);
2447 out_unlock:
2448 	mutex_unlock(&ublk_ctl_mutex);
2449 	return ret;
2450 }
2451 
ublk_idr_freed(int id)2452 static inline bool ublk_idr_freed(int id)
2453 {
2454 	void *ptr;
2455 
2456 	spin_lock(&ublk_idr_lock);
2457 	ptr = idr_find(&ublk_index_idr, id);
2458 	spin_unlock(&ublk_idr_lock);
2459 
2460 	return ptr == NULL;
2461 }
2462 
ublk_ctrl_del_dev(struct ublk_device ** p_ub)2463 static int ublk_ctrl_del_dev(struct ublk_device **p_ub)
2464 {
2465 	struct ublk_device *ub = *p_ub;
2466 	int idx = ub->ub_number;
2467 	int ret;
2468 
2469 	ret = mutex_lock_killable(&ublk_ctl_mutex);
2470 	if (ret)
2471 		return ret;
2472 
2473 	if (!test_bit(UB_STATE_DELETED, &ub->state)) {
2474 		ublk_remove(ub);
2475 		set_bit(UB_STATE_DELETED, &ub->state);
2476 	}
2477 
2478 	/* Mark the reference as consumed */
2479 	*p_ub = NULL;
2480 	ublk_put_device(ub);
2481 	mutex_unlock(&ublk_ctl_mutex);
2482 
2483 	/*
2484 	 * Wait until the idr is removed, then it can be reused after
2485 	 * DEL_DEV command is returned.
2486 	 *
2487 	 * If we returns because of user interrupt, future delete command
2488 	 * may come:
2489 	 *
2490 	 * - the device number isn't freed, this device won't or needn't
2491 	 *   be deleted again, since UB_STATE_DELETED is set, and device
2492 	 *   will be released after the last reference is dropped
2493 	 *
2494 	 * - the device number is freed already, we will not find this
2495 	 *   device via ublk_get_device_from_id()
2496 	 */
2497 	if (wait_event_interruptible(ublk_idr_wq, ublk_idr_freed(idx)))
2498 		return -EINTR;
2499 	return 0;
2500 }
2501 
ublk_ctrl_cmd_dump(struct io_uring_cmd * cmd)2502 static inline void ublk_ctrl_cmd_dump(struct io_uring_cmd *cmd)
2503 {
2504 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2505 
2506 	pr_devel("%s: cmd_op %x, dev id %d qid %d data %llx buf %llx len %u\n",
2507 			__func__, cmd->cmd_op, header->dev_id, header->queue_id,
2508 			header->data[0], header->addr, header->len);
2509 }
2510 
ublk_ctrl_stop_dev(struct ublk_device * ub)2511 static int ublk_ctrl_stop_dev(struct ublk_device *ub)
2512 {
2513 	ublk_stop_dev(ub);
2514 	cancel_work_sync(&ub->stop_work);
2515 	cancel_work_sync(&ub->quiesce_work);
2516 
2517 	return 0;
2518 }
2519 
ublk_ctrl_get_dev_info(struct ublk_device * ub,struct io_uring_cmd * cmd)2520 static int ublk_ctrl_get_dev_info(struct ublk_device *ub,
2521 		struct io_uring_cmd *cmd)
2522 {
2523 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2524 	void __user *argp = (void __user *)(unsigned long)header->addr;
2525 
2526 	if (header->len < sizeof(struct ublksrv_ctrl_dev_info) || !header->addr)
2527 		return -EINVAL;
2528 
2529 	if (copy_to_user(argp, &ub->dev_info, sizeof(ub->dev_info)))
2530 		return -EFAULT;
2531 
2532 	return 0;
2533 }
2534 
2535 /* TYPE_DEVT is readonly, so fill it up before returning to userspace */
ublk_ctrl_fill_params_devt(struct ublk_device * ub)2536 static void ublk_ctrl_fill_params_devt(struct ublk_device *ub)
2537 {
2538 	ub->params.devt.char_major = MAJOR(ub->cdev_dev.devt);
2539 	ub->params.devt.char_minor = MINOR(ub->cdev_dev.devt);
2540 
2541 	if (ub->ub_disk) {
2542 		ub->params.devt.disk_major = MAJOR(disk_devt(ub->ub_disk));
2543 		ub->params.devt.disk_minor = MINOR(disk_devt(ub->ub_disk));
2544 	} else {
2545 		ub->params.devt.disk_major = 0;
2546 		ub->params.devt.disk_minor = 0;
2547 	}
2548 	ub->params.types |= UBLK_PARAM_TYPE_DEVT;
2549 }
2550 
ublk_ctrl_get_params(struct ublk_device * ub,struct io_uring_cmd * cmd)2551 static int ublk_ctrl_get_params(struct ublk_device *ub,
2552 		struct io_uring_cmd *cmd)
2553 {
2554 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2555 	void __user *argp = (void __user *)(unsigned long)header->addr;
2556 	struct ublk_params_header ph;
2557 	int ret;
2558 
2559 	if (header->len <= sizeof(ph) || !header->addr)
2560 		return -EINVAL;
2561 
2562 	if (copy_from_user(&ph, argp, sizeof(ph)))
2563 		return -EFAULT;
2564 
2565 	if (ph.len > header->len || !ph.len)
2566 		return -EINVAL;
2567 
2568 	if (ph.len > sizeof(struct ublk_params))
2569 		ph.len = sizeof(struct ublk_params);
2570 
2571 	mutex_lock(&ub->mutex);
2572 	ublk_ctrl_fill_params_devt(ub);
2573 	if (copy_to_user(argp, &ub->params, ph.len))
2574 		ret = -EFAULT;
2575 	else
2576 		ret = 0;
2577 	mutex_unlock(&ub->mutex);
2578 
2579 	return ret;
2580 }
2581 
ublk_ctrl_set_params(struct ublk_device * ub,struct io_uring_cmd * cmd)2582 static int ublk_ctrl_set_params(struct ublk_device *ub,
2583 		struct io_uring_cmd *cmd)
2584 {
2585 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2586 	void __user *argp = (void __user *)(unsigned long)header->addr;
2587 	struct ublk_params_header ph;
2588 	int ret = -EFAULT;
2589 
2590 	if (header->len <= sizeof(ph) || !header->addr)
2591 		return -EINVAL;
2592 
2593 	if (copy_from_user(&ph, argp, sizeof(ph)))
2594 		return -EFAULT;
2595 
2596 	if (ph.len > header->len || !ph.len || !ph.types)
2597 		return -EINVAL;
2598 
2599 	if (ph.len > sizeof(struct ublk_params))
2600 		ph.len = sizeof(struct ublk_params);
2601 
2602 	/* parameters can only be changed when device isn't live */
2603 	mutex_lock(&ub->mutex);
2604 	if (ub->dev_info.state == UBLK_S_DEV_LIVE) {
2605 		ret = -EACCES;
2606 	} else if (copy_from_user(&ub->params, argp, ph.len)) {
2607 		ret = -EFAULT;
2608 	} else {
2609 		/* clear all we don't support yet */
2610 		ub->params.types &= UBLK_PARAM_TYPE_ALL;
2611 		ret = ublk_validate_params(ub);
2612 		if (ret)
2613 			ub->params.types = 0;
2614 	}
2615 	mutex_unlock(&ub->mutex);
2616 
2617 	return ret;
2618 }
2619 
ublk_queue_reinit(struct ublk_device * ub,struct ublk_queue * ubq)2620 static void ublk_queue_reinit(struct ublk_device *ub, struct ublk_queue *ubq)
2621 {
2622 	int i;
2623 
2624 	WARN_ON_ONCE(!(ubq->ubq_daemon && ubq_daemon_is_dying(ubq)));
2625 
2626 	/* All old ioucmds have to be completed */
2627 	ubq->nr_io_ready = 0;
2628 	/* old daemon is PF_EXITING, put it now */
2629 	put_task_struct(ubq->ubq_daemon);
2630 	/* We have to reset it to NULL, otherwise ub won't accept new FETCH_REQ */
2631 	ubq->ubq_daemon = NULL;
2632 	ubq->timeout = false;
2633 
2634 	for (i = 0; i < ubq->q_depth; i++) {
2635 		struct ublk_io *io = &ubq->ios[i];
2636 
2637 		/* forget everything now and be ready for new FETCH_REQ */
2638 		io->flags = 0;
2639 		io->cmd = NULL;
2640 		io->addr = 0;
2641 	}
2642 }
2643 
ublk_ctrl_start_recovery(struct ublk_device * ub,struct io_uring_cmd * cmd)2644 static int ublk_ctrl_start_recovery(struct ublk_device *ub,
2645 		struct io_uring_cmd *cmd)
2646 {
2647 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2648 	int ret = -EINVAL;
2649 	int i;
2650 
2651 	mutex_lock(&ub->mutex);
2652 	if (!ublk_can_use_recovery(ub))
2653 		goto out_unlock;
2654 	if (!ub->nr_queues_ready)
2655 		goto out_unlock;
2656 	/*
2657 	 * START_RECOVERY is only allowd after:
2658 	 *
2659 	 * (1) UB_STATE_OPEN is not set, which means the dying process is exited
2660 	 *     and related io_uring ctx is freed so file struct of /dev/ublkcX is
2661 	 *     released.
2662 	 *
2663 	 * (2) UBLK_S_DEV_QUIESCED is set, which means the quiesce_work:
2664 	 *     (a)has quiesced request queue
2665 	 *     (b)has requeued every inflight rqs whose io_flags is ACTIVE
2666 	 *     (c)has requeued/aborted every inflight rqs whose io_flags is NOT ACTIVE
2667 	 *     (d)has completed/camceled all ioucmds owned by ther dying process
2668 	 */
2669 	if (test_bit(UB_STATE_OPEN, &ub->state) ||
2670 			ub->dev_info.state != UBLK_S_DEV_QUIESCED) {
2671 		ret = -EBUSY;
2672 		goto out_unlock;
2673 	}
2674 	pr_devel("%s: start recovery for dev id %d.\n", __func__, header->dev_id);
2675 	for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
2676 		ublk_queue_reinit(ub, ublk_get_queue(ub, i));
2677 	/* set to NULL, otherwise new ubq_daemon cannot mmap the io_cmd_buf */
2678 	ub->mm = NULL;
2679 	ub->nr_queues_ready = 0;
2680 	ub->nr_privileged_daemon = 0;
2681 	init_completion(&ub->completion);
2682 	ret = 0;
2683  out_unlock:
2684 	mutex_unlock(&ub->mutex);
2685 	return ret;
2686 }
2687 
ublk_ctrl_end_recovery(struct ublk_device * ub,struct io_uring_cmd * cmd)2688 static int ublk_ctrl_end_recovery(struct ublk_device *ub,
2689 		struct io_uring_cmd *cmd)
2690 {
2691 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2692 	int ublksrv_pid = (int)header->data[0];
2693 	int ret = -EINVAL;
2694 
2695 	pr_devel("%s: Waiting for new ubq_daemons(nr: %d) are ready, dev id %d...\n",
2696 			__func__, ub->dev_info.nr_hw_queues, header->dev_id);
2697 	/* wait until new ubq_daemon sending all FETCH_REQ */
2698 	if (wait_for_completion_interruptible(&ub->completion))
2699 		return -EINTR;
2700 
2701 	pr_devel("%s: All new ubq_daemons(nr: %d) are ready, dev id %d\n",
2702 			__func__, ub->dev_info.nr_hw_queues, header->dev_id);
2703 
2704 	mutex_lock(&ub->mutex);
2705 	if (!ublk_can_use_recovery(ub))
2706 		goto out_unlock;
2707 
2708 	if (ub->dev_info.state != UBLK_S_DEV_QUIESCED) {
2709 		ret = -EBUSY;
2710 		goto out_unlock;
2711 	}
2712 	ub->dev_info.ublksrv_pid = ublksrv_pid;
2713 	pr_devel("%s: new ublksrv_pid %d, dev id %d\n",
2714 			__func__, ublksrv_pid, header->dev_id);
2715 	blk_mq_unquiesce_queue(ub->ub_disk->queue);
2716 	pr_devel("%s: queue unquiesced, dev id %d.\n",
2717 			__func__, header->dev_id);
2718 	blk_mq_kick_requeue_list(ub->ub_disk->queue);
2719 	ub->dev_info.state = UBLK_S_DEV_LIVE;
2720 	schedule_delayed_work(&ub->monitor_work, UBLK_DAEMON_MONITOR_PERIOD);
2721 	ret = 0;
2722  out_unlock:
2723 	mutex_unlock(&ub->mutex);
2724 	return ret;
2725 }
2726 
ublk_ctrl_get_features(struct io_uring_cmd * cmd)2727 static int ublk_ctrl_get_features(struct io_uring_cmd *cmd)
2728 {
2729 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2730 	void __user *argp = (void __user *)(unsigned long)header->addr;
2731 	u64 features = UBLK_F_ALL & ~UBLK_F_SUPPORT_ZERO_COPY;
2732 
2733 	if (header->len != UBLK_FEATURES_LEN || !header->addr)
2734 		return -EINVAL;
2735 
2736 	if (copy_to_user(argp, &features, UBLK_FEATURES_LEN))
2737 		return -EFAULT;
2738 
2739 	return 0;
2740 }
2741 
2742 /*
2743  * All control commands are sent via /dev/ublk-control, so we have to check
2744  * the destination device's permission
2745  */
ublk_char_dev_permission(struct ublk_device * ub,const char * dev_path,int mask)2746 static int ublk_char_dev_permission(struct ublk_device *ub,
2747 		const char *dev_path, int mask)
2748 {
2749 	int err;
2750 	struct path path;
2751 	struct kstat stat;
2752 
2753 	err = kern_path(dev_path, LOOKUP_FOLLOW, &path);
2754 	if (err)
2755 		return err;
2756 
2757 	err = vfs_getattr(&path, &stat, STATX_TYPE, AT_STATX_SYNC_AS_STAT);
2758 	if (err)
2759 		goto exit;
2760 
2761 	err = -EPERM;
2762 	if (stat.rdev != ub->cdev_dev.devt || !S_ISCHR(stat.mode))
2763 		goto exit;
2764 
2765 	err = inode_permission(&nop_mnt_idmap,
2766 			d_backing_inode(path.dentry), mask);
2767 exit:
2768 	path_put(&path);
2769 	return err;
2770 }
2771 
ublk_ctrl_uring_cmd_permission(struct ublk_device * ub,struct io_uring_cmd * cmd)2772 static int ublk_ctrl_uring_cmd_permission(struct ublk_device *ub,
2773 		struct io_uring_cmd *cmd)
2774 {
2775 	struct ublksrv_ctrl_cmd *header = (struct ublksrv_ctrl_cmd *)io_uring_sqe_cmd(cmd->sqe);
2776 	bool unprivileged = ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV;
2777 	void __user *argp = (void __user *)(unsigned long)header->addr;
2778 	char *dev_path = NULL;
2779 	int ret = 0;
2780 	int mask;
2781 
2782 	if (!unprivileged) {
2783 		if (!capable(CAP_SYS_ADMIN))
2784 			return -EPERM;
2785 		/*
2786 		 * The new added command of UBLK_CMD_GET_DEV_INFO2 includes
2787 		 * char_dev_path in payload too, since userspace may not
2788 		 * know if the specified device is created as unprivileged
2789 		 * mode.
2790 		 */
2791 		if (_IOC_NR(cmd->cmd_op) != UBLK_CMD_GET_DEV_INFO2)
2792 			return 0;
2793 	}
2794 
2795 	/*
2796 	 * User has to provide the char device path for unprivileged ublk
2797 	 *
2798 	 * header->addr always points to the dev path buffer, and
2799 	 * header->dev_path_len records length of dev path buffer.
2800 	 */
2801 	if (!header->dev_path_len || header->dev_path_len > PATH_MAX)
2802 		return -EINVAL;
2803 
2804 	if (header->len < header->dev_path_len)
2805 		return -EINVAL;
2806 
2807 	dev_path = memdup_user_nul(argp, header->dev_path_len);
2808 	if (IS_ERR(dev_path))
2809 		return PTR_ERR(dev_path);
2810 
2811 	ret = -EINVAL;
2812 	switch (_IOC_NR(cmd->cmd_op)) {
2813 	case UBLK_CMD_GET_DEV_INFO:
2814 	case UBLK_CMD_GET_DEV_INFO2:
2815 	case UBLK_CMD_GET_QUEUE_AFFINITY:
2816 	case UBLK_CMD_GET_PARAMS:
2817 	case (_IOC_NR(UBLK_U_CMD_GET_FEATURES)):
2818 		mask = MAY_READ;
2819 		break;
2820 	case UBLK_CMD_START_DEV:
2821 	case UBLK_CMD_STOP_DEV:
2822 	case UBLK_CMD_ADD_DEV:
2823 	case UBLK_CMD_DEL_DEV:
2824 	case UBLK_CMD_SET_PARAMS:
2825 	case UBLK_CMD_START_USER_RECOVERY:
2826 	case UBLK_CMD_END_USER_RECOVERY:
2827 		mask = MAY_READ | MAY_WRITE;
2828 		break;
2829 	default:
2830 		goto exit;
2831 	}
2832 
2833 	ret = ublk_char_dev_permission(ub, dev_path, mask);
2834 	if (!ret) {
2835 		header->len -= header->dev_path_len;
2836 		header->addr += header->dev_path_len;
2837 	}
2838 	pr_devel("%s: dev id %d cmd_op %x uid %d gid %d path %s ret %d\n",
2839 			__func__, ub->ub_number, cmd->cmd_op,
2840 			ub->dev_info.owner_uid, ub->dev_info.owner_gid,
2841 			dev_path, ret);
2842 exit:
2843 	kfree(dev_path);
2844 	return ret;
2845 }
2846 
ublk_ctrl_uring_cmd(struct io_uring_cmd * cmd,unsigned int issue_flags)2847 static int ublk_ctrl_uring_cmd(struct io_uring_cmd *cmd,
2848 		unsigned int issue_flags)
2849 {
2850 	const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2851 	struct ublk_device *ub = NULL;
2852 	u32 cmd_op = cmd->cmd_op;
2853 	int ret = -EINVAL;
2854 
2855 	if (issue_flags & IO_URING_F_NONBLOCK)
2856 		return -EAGAIN;
2857 
2858 	ublk_ctrl_cmd_dump(cmd);
2859 
2860 	if (!(issue_flags & IO_URING_F_SQE128))
2861 		goto out;
2862 
2863 	ret = ublk_check_cmd_op(cmd_op);
2864 	if (ret)
2865 		goto out;
2866 
2867 	if (cmd_op == UBLK_U_CMD_GET_FEATURES) {
2868 		ret = ublk_ctrl_get_features(cmd);
2869 		goto out;
2870 	}
2871 
2872 	if (_IOC_NR(cmd_op) != UBLK_CMD_ADD_DEV) {
2873 		ret = -ENODEV;
2874 		ub = ublk_get_device_from_id(header->dev_id);
2875 		if (!ub)
2876 			goto out;
2877 
2878 		ret = ublk_ctrl_uring_cmd_permission(ub, cmd);
2879 		if (ret)
2880 			goto put_dev;
2881 	}
2882 
2883 	switch (_IOC_NR(cmd_op)) {
2884 	case UBLK_CMD_START_DEV:
2885 		ret = ublk_ctrl_start_dev(ub, cmd);
2886 		break;
2887 	case UBLK_CMD_STOP_DEV:
2888 		ret = ublk_ctrl_stop_dev(ub);
2889 		break;
2890 	case UBLK_CMD_GET_DEV_INFO:
2891 	case UBLK_CMD_GET_DEV_INFO2:
2892 		ret = ublk_ctrl_get_dev_info(ub, cmd);
2893 		break;
2894 	case UBLK_CMD_ADD_DEV:
2895 		ret = ublk_ctrl_add_dev(cmd);
2896 		break;
2897 	case UBLK_CMD_DEL_DEV:
2898 		ret = ublk_ctrl_del_dev(&ub);
2899 		break;
2900 	case UBLK_CMD_GET_QUEUE_AFFINITY:
2901 		ret = ublk_ctrl_get_queue_affinity(ub, cmd);
2902 		break;
2903 	case UBLK_CMD_GET_PARAMS:
2904 		ret = ublk_ctrl_get_params(ub, cmd);
2905 		break;
2906 	case UBLK_CMD_SET_PARAMS:
2907 		ret = ublk_ctrl_set_params(ub, cmd);
2908 		break;
2909 	case UBLK_CMD_START_USER_RECOVERY:
2910 		ret = ublk_ctrl_start_recovery(ub, cmd);
2911 		break;
2912 	case UBLK_CMD_END_USER_RECOVERY:
2913 		ret = ublk_ctrl_end_recovery(ub, cmd);
2914 		break;
2915 	default:
2916 		ret = -EOPNOTSUPP;
2917 		break;
2918 	}
2919 
2920  put_dev:
2921 	if (ub)
2922 		ublk_put_device(ub);
2923  out:
2924 	io_uring_cmd_done(cmd, ret, 0, issue_flags);
2925 	pr_devel("%s: cmd done ret %d cmd_op %x, dev id %d qid %d\n",
2926 			__func__, ret, cmd->cmd_op, header->dev_id, header->queue_id);
2927 	return -EIOCBQUEUED;
2928 }
2929 
2930 static const struct file_operations ublk_ctl_fops = {
2931 	.open		= nonseekable_open,
2932 	.uring_cmd      = ublk_ctrl_uring_cmd,
2933 	.owner		= THIS_MODULE,
2934 	.llseek		= noop_llseek,
2935 };
2936 
2937 static struct miscdevice ublk_misc = {
2938 	.minor		= MISC_DYNAMIC_MINOR,
2939 	.name		= "ublk-control",
2940 	.fops		= &ublk_ctl_fops,
2941 };
2942 
ublk_init(void)2943 static int __init ublk_init(void)
2944 {
2945 	int ret;
2946 
2947 	BUILD_BUG_ON((u64)UBLKSRV_IO_BUF_OFFSET +
2948 			UBLKSRV_IO_BUF_TOTAL_SIZE < UBLKSRV_IO_BUF_OFFSET);
2949 
2950 	init_waitqueue_head(&ublk_idr_wq);
2951 
2952 	ret = misc_register(&ublk_misc);
2953 	if (ret)
2954 		return ret;
2955 
2956 	ret = alloc_chrdev_region(&ublk_chr_devt, 0, UBLK_MINORS, "ublk-char");
2957 	if (ret)
2958 		goto unregister_mis;
2959 
2960 	ret = class_register(&ublk_chr_class);
2961 	if (ret)
2962 		goto free_chrdev_region;
2963 
2964 	return 0;
2965 
2966 free_chrdev_region:
2967 	unregister_chrdev_region(ublk_chr_devt, UBLK_MINORS);
2968 unregister_mis:
2969 	misc_deregister(&ublk_misc);
2970 	return ret;
2971 }
2972 
ublk_exit(void)2973 static void __exit ublk_exit(void)
2974 {
2975 	struct ublk_device *ub;
2976 	int id;
2977 
2978 	idr_for_each_entry(&ublk_index_idr, ub, id)
2979 		ublk_remove(ub);
2980 
2981 	class_unregister(&ublk_chr_class);
2982 	misc_deregister(&ublk_misc);
2983 
2984 	idr_destroy(&ublk_index_idr);
2985 	unregister_chrdev_region(ublk_chr_devt, UBLK_MINORS);
2986 }
2987 
2988 module_init(ublk_init);
2989 module_exit(ublk_exit);
2990 
2991 module_param(ublks_max, int, 0444);
2992 MODULE_PARM_DESC(ublks_max, "max number of ublk devices allowed to add(default: 64)");
2993 
2994 MODULE_AUTHOR("Ming Lei <ming.lei@redhat.com>");
2995 MODULE_LICENSE("GPL");
2996