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