1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Userspace block device - block device which IO is handled from userspace
5 * Take full use of io_uring passthrough command for communicating with
6 * ublk userspace daemon(ublksrvd) for handling basic IO request.
8 * Copyright 2022 Ming Lei <ming.lei@redhat.com>
10 * (part of code stolen from loop.c)
12 #include <linux/module.h>
13 #include <linux/moduleparam.h>
14 #include <linux/sched.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>
44 #include <linux/task_work.h>
45 #include <linux/namei.h>
46 #include <linux/kref.h>
47 #include <uapi/linux/ublk_cmd.h>
49 #define UBLK_MINORS (1U << MINORBITS)
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 \
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)
68 struct llist_node node;
76 struct ublk_uring_cmd_pdu {
77 struct ublk_queue *ubq;
81 * io command is active: sqe cmd is received, and its cqe isn't done
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.
86 * If the flag is cleared, the io command will be completed, and owned by
89 #define UBLK_IO_FLAG_ACTIVE 0x01
92 * IO command is completed via cqe, and it is being handled by ublksrv, and
95 * Basically exclusively with UBLK_IO_FLAG_ACTIVE, so can be served for
98 #define UBLK_IO_FLAG_OWNED_BY_SRV 0x02
101 * IO command is aborted, so this flag is set in case of
102 * !UBLK_IO_FLAG_ACTIVE.
104 * After this flag is observed, any pending or new incoming request
105 * associated with this io command will be failed immediately
107 #define UBLK_IO_FLAG_ABORTED 0x04
110 * UBLK_IO_FLAG_NEED_GET_DATA is set because IO command requires
111 * get data buffer address from ublksrv.
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.
116 #define UBLK_IO_FLAG_NEED_GET_DATA 0x08
119 /* userspace buffer address from io cmd */
124 struct io_uring_cmd *cmd;
132 struct task_struct *ubq_daemon;
135 struct llist_head io_cmds;
137 unsigned long io_addr; /* mapped vm address */
138 unsigned int max_io_sz;
141 unsigned short nr_io_ready; /* how many ios setup */
142 struct ublk_device *dev;
143 struct ublk_io ios[];
146 #define UBLK_DAEMON_MONITOR_PERIOD (5 * HZ)
149 struct gendisk *ub_disk;
153 unsigned int queue_size;
154 struct ublksrv_ctrl_dev_info dev_info;
156 struct blk_mq_tag_set tag_set;
159 struct device cdev_dev;
161 #define UB_STATE_OPEN 0
162 #define UB_STATE_USED 1
163 #define UB_STATE_DELETED 2
170 struct mm_struct *mm;
172 struct ublk_params params;
174 struct completion completion;
175 unsigned int nr_queues_ready;
176 unsigned int nr_privileged_daemon;
179 * Our ubq->daemon may be killed without any notification, so
180 * monitor each queue's daemon periodically
182 struct delayed_work monitor_work;
183 struct work_struct quiesce_work;
184 struct work_struct stop_work;
187 /* header of ublk_params */
188 struct ublk_params_header {
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,
197 static inline bool ublk_dev_is_user_copy(const struct ublk_device *ub)
199 return ub->dev_info.flags & UBLK_F_USER_COPY;
202 static inline bool ublk_dev_is_zoned(const struct ublk_device *ub)
204 return ub->dev_info.flags & UBLK_F_ZONED;
207 static inline bool ublk_queue_is_zoned(struct ublk_queue *ubq)
209 return ubq->flags & UBLK_F_ZONED;
212 #ifdef CONFIG_BLK_DEV_ZONED
214 static int ublk_get_nr_zones(const struct ublk_device *ub)
216 const struct ublk_param_basic *p = &ub->params.basic;
218 /* Zone size is a power of 2 */
219 return p->dev_sectors >> ilog2(p->chunk_sectors);
222 static int ublk_revalidate_disk_zones(struct ublk_device *ub)
224 return blk_revalidate_disk_zones(ub->ub_disk, NULL);
227 static int ublk_dev_param_zoned_validate(const struct ublk_device *ub)
229 const struct ublk_param_zoned *p = &ub->params.zoned;
232 if (!ublk_dev_is_zoned(ub))
235 if (!p->max_zone_append_sectors)
238 nr_zones = ublk_get_nr_zones(ub);
240 if (p->max_active_zones > nr_zones)
243 if (p->max_open_zones > nr_zones)
249 static int ublk_dev_param_zoned_apply(struct ublk_device *ub)
251 const struct ublk_param_zoned *p = &ub->params.zoned;
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);
261 ub->ub_disk->nr_zones = ublk_get_nr_zones(ub);
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)
270 struct request_queue *q = ublk->ub_disk->queue;
274 nr_zones = min_t(unsigned int, nr_zones,
275 ublk->ub_disk->nr_zones);
277 bufsize = nr_zones * sizeof(struct blk_zone);
279 min_t(size_t, bufsize, queue_max_hw_sectors(q) << SECTOR_SHIFT);
281 while (bufsize >= sizeof(struct blk_zone)) {
282 buf = kvmalloc(bufsize, GFP_KERNEL | __GFP_NORETRY);
294 static int ublk_report_zones(struct gendisk *disk, sector_t sector,
295 unsigned int nr_zones, report_zones_cb cb, void *data)
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;
303 struct blk_zone *buffer;
304 size_t buffer_length;
306 nr_zones = min_t(unsigned int, ub->ub_disk->nr_zones - first_zone,
309 buffer = ublk_alloc_report_buffer(ub, nr_zones, &buffer_length);
313 max_zones_per_request = buffer_length / sizeof(struct blk_zone);
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);
320 struct ublk_rq_data *pdu;
323 memset(buffer, 0, buffer_length);
325 req = blk_mq_alloc_request(disk->queue, REQ_OP_DRV_IN, 0);
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;
336 ret = blk_rq_map_kern(disk->queue, req, buffer, buffer_length,
339 blk_mq_free_request(req);
343 status = blk_execute_rq(req, 0);
344 ret = blk_status_to_errno(status);
345 blk_mq_free_request(req);
349 for (unsigned int i = 0; i < zones_in_request; i++) {
350 struct blk_zone *zone = buffer + i;
352 /* A zero length zone means no more zones in this response */
356 ret = cb(zone, i, data);
361 sector += zone_size_sectors;
373 static blk_status_t ublk_setup_iod_zoned(struct ublk_queue *ubq,
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);
381 switch (req_op(req)) {
382 case REQ_OP_ZONE_OPEN:
383 ublk_op = UBLK_IO_OP_ZONE_OPEN;
385 case REQ_OP_ZONE_CLOSE:
386 ublk_op = UBLK_IO_OP_ZONE_CLOSE;
388 case REQ_OP_ZONE_FINISH:
389 ublk_op = UBLK_IO_OP_ZONE_FINISH;
391 case REQ_OP_ZONE_RESET:
392 ublk_op = UBLK_IO_OP_ZONE_RESET;
394 case REQ_OP_ZONE_APPEND:
395 ublk_op = UBLK_IO_OP_ZONE_APPEND;
397 case REQ_OP_ZONE_RESET_ALL:
398 ublk_op = UBLK_IO_OP_ZONE_RESET_ALL;
401 ublk_op = pdu->operation;
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;
409 return BLK_STS_IOERR;
412 /* We do not support drv_out */
413 return BLK_STS_NOTSUPP;
415 return BLK_STS_IOERR;
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;
428 #define ublk_report_zones (NULL)
430 static int ublk_dev_param_zoned_validate(const struct ublk_device *ub)
435 static int ublk_dev_param_zoned_apply(struct ublk_device *ub)
440 static int ublk_revalidate_disk_zones(struct ublk_device *ub)
445 static blk_status_t ublk_setup_iod_zoned(struct ublk_queue *ubq,
448 return BLK_STS_NOTSUPP;
453 static inline void __ublk_complete_rq(struct request *req);
454 static void ublk_complete_rq(struct kref *ref);
456 static dev_t ublk_chr_devt;
457 static const struct class ublk_chr_class = {
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 */
465 static DEFINE_MUTEX(ublk_ctl_mutex);
468 * Max ublk devices allowed to add
470 * It can be extended to one per-user limit in future or even controlled
473 static unsigned int ublks_max = 64;
474 static unsigned int ublks_added; /* protected by ublk_ctl_mutex */
476 static struct miscdevice ublk_misc;
478 static inline unsigned ublk_pos_to_hwq(loff_t pos)
480 return ((pos - UBLKSRV_IO_BUF_OFFSET) >> UBLK_QID_OFF) &
484 static inline unsigned ublk_pos_to_buf_off(loff_t pos)
486 return (pos - UBLKSRV_IO_BUF_OFFSET) & UBLK_IO_BUF_BITS_MASK;
489 static inline unsigned ublk_pos_to_tag(loff_t pos)
491 return ((pos - UBLKSRV_IO_BUF_OFFSET) >> UBLK_TAG_OFF) &
495 static void ublk_dev_param_basic_apply(struct ublk_device *ub)
497 struct request_queue *q = ub->ub_disk->queue;
498 const struct ublk_param_basic *p = &ub->params.basic;
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);
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);
510 blk_queue_flag_set(QUEUE_FLAG_NONROT, q);
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);
516 if (p->attrs & UBLK_ATTR_READ_ONLY)
517 set_disk_ro(ub->ub_disk, true);
519 set_capacity(ub->ub_disk, p->dev_sectors);
522 static void ublk_dev_param_discard_apply(struct ublk_device *ub)
524 struct request_queue *q = ub->ub_disk->queue;
525 const struct ublk_param_discard *p = &ub->params.discard;
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);
535 static int ublk_validate_params(const struct ublk_device *ub)
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;
541 if (p->logical_bs_shift > PAGE_SHIFT || p->logical_bs_shift < 9)
544 if (p->logical_bs_shift > p->physical_bs_shift)
547 if (p->max_sectors > (ub->dev_info.max_io_buf_bytes >> 9))
550 if (ublk_dev_is_zoned(ub) && !p->chunk_sectors)
555 if (ub->params.types & UBLK_PARAM_TYPE_DISCARD) {
556 const struct ublk_param_discard *p = &ub->params.discard;
558 /* So far, only support single segment discard */
559 if (p->max_discard_sectors && p->max_discard_segments != 1)
562 if (!p->discard_granularity)
566 /* dev_t is read-only */
567 if (ub->params.types & UBLK_PARAM_TYPE_DEVT)
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))
578 static int ublk_apply_params(struct ublk_device *ub)
580 if (!(ub->params.types & UBLK_PARAM_TYPE_BASIC))
583 ublk_dev_param_basic_apply(ub);
585 if (ub->params.types & UBLK_PARAM_TYPE_DISCARD)
586 ublk_dev_param_discard_apply(ub);
588 if (ub->params.types & UBLK_PARAM_TYPE_ZONED)
589 return ublk_dev_param_zoned_apply(ub);
594 static inline bool ublk_support_user_copy(const struct ublk_queue *ubq)
596 return ubq->flags & UBLK_F_USER_COPY;
599 static inline bool ublk_need_req_ref(const struct ublk_queue *ubq)
602 * read()/write() is involved in user copy, so request reference
605 return ublk_support_user_copy(ubq);
608 static inline void ublk_init_req_ref(const struct ublk_queue *ubq,
611 if (ublk_need_req_ref(ubq)) {
612 struct ublk_rq_data *data = blk_mq_rq_to_pdu(req);
614 kref_init(&data->ref);
618 static inline bool ublk_get_req_ref(const struct ublk_queue *ubq,
621 if (ublk_need_req_ref(ubq)) {
622 struct ublk_rq_data *data = blk_mq_rq_to_pdu(req);
624 return kref_get_unless_zero(&data->ref);
630 static inline void ublk_put_req_ref(const struct ublk_queue *ubq,
633 if (ublk_need_req_ref(ubq)) {
634 struct ublk_rq_data *data = blk_mq_rq_to_pdu(req);
636 kref_put(&data->ref, ublk_complete_rq);
638 __ublk_complete_rq(req);
642 static inline bool ublk_need_get_data(const struct ublk_queue *ubq)
644 return ubq->flags & UBLK_F_NEED_GET_DATA;
647 static struct ublk_device *ublk_get_device(struct ublk_device *ub)
649 if (kobject_get_unless_zero(&ub->cdev_dev.kobj))
654 static void ublk_put_device(struct ublk_device *ub)
656 put_device(&ub->cdev_dev);
659 static inline struct ublk_queue *ublk_get_queue(struct ublk_device *dev,
662 return (struct ublk_queue *)&(dev->__queues[qid * dev->queue_size]);
665 static inline bool ublk_rq_has_data(const struct request *rq)
667 return bio_has_data(rq->bio);
670 static inline struct ublksrv_io_desc *ublk_get_iod(struct ublk_queue *ubq,
673 return (struct ublksrv_io_desc *)
674 &(ubq->io_cmd_buf[tag * sizeof(struct ublksrv_io_desc)]);
677 static inline char *ublk_queue_cmd_buf(struct ublk_device *ub, int q_id)
679 return ublk_get_queue(ub, q_id)->io_cmd_buf;
682 static inline int ublk_queue_cmd_buf_size(struct ublk_device *ub, int q_id)
684 struct ublk_queue *ubq = ublk_get_queue(ub, q_id);
686 return round_up(ubq->q_depth * sizeof(struct ublksrv_io_desc),
690 static inline bool ublk_queue_can_use_recovery_reissue(
691 struct ublk_queue *ubq)
693 return (ubq->flags & UBLK_F_USER_RECOVERY) &&
694 (ubq->flags & UBLK_F_USER_RECOVERY_REISSUE);
697 static inline bool ublk_queue_can_use_recovery(
698 struct ublk_queue *ubq)
700 return ubq->flags & UBLK_F_USER_RECOVERY;
703 static inline bool ublk_can_use_recovery(struct ublk_device *ub)
705 return ub->dev_info.flags & UBLK_F_USER_RECOVERY;
708 static void ublk_free_disk(struct gendisk *disk)
710 struct ublk_device *ub = disk->private_data;
712 clear_bit(UB_STATE_USED, &ub->state);
713 put_device(&ub->cdev_dev);
716 static void ublk_store_owner_uid_gid(unsigned int *owner_uid,
717 unsigned int *owner_gid)
722 current_uid_gid(&uid, &gid);
724 *owner_uid = from_kuid(&init_user_ns, uid);
725 *owner_gid = from_kgid(&init_user_ns, gid);
728 static int ublk_open(struct gendisk *disk, blk_mode_t mode)
730 struct ublk_device *ub = disk->private_data;
732 if (capable(CAP_SYS_ADMIN))
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.
741 * This way is reasonable too given anyone can create
742 * unprivileged device, and no need other's grant.
744 if (ub->dev_info.flags & UBLK_F_UNPRIVILEGED_DEV) {
745 unsigned int curr_uid, curr_gid;
747 ublk_store_owner_uid_gid(&curr_uid, &curr_gid);
749 if (curr_uid != ub->dev_info.owner_uid || curr_gid !=
750 ub->dev_info.owner_gid)
757 static const struct block_device_operations ub_fops = {
758 .owner = THIS_MODULE,
760 .free_disk = ublk_free_disk,
761 .report_zones = ublk_report_zones,
764 #define UBLK_MAX_PIN_PAGES 32
766 struct ublk_io_iter {
767 struct page *pages[UBLK_MAX_PIN_PAGES];
769 struct bvec_iter iter;
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)
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]);
786 if (dir == ITER_DEST)
787 memcpy(pg_buf + pg_off, bv_buf, bytes);
789 memcpy(bv_buf, pg_buf + pg_off, bytes);
791 kunmap_local(pg_buf);
792 kunmap_local(bv_buf);
794 /* advance page array */
796 if (pg_off == PAGE_SIZE) {
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)
809 data->iter = data->bio->bi_iter;
814 static bool ublk_advance_io_iter(const struct request *req,
815 struct ublk_io_iter *iter, unsigned int offset)
817 struct bio *bio = req->bio;
820 if (bio->bi_iter.bi_size > offset) {
822 iter->iter = bio->bi_iter;
823 bio_advance_iter(iter->bio, &iter->iter, offset);
826 offset -= bio->bi_iter.bi_size;
832 * Copy data between request pages and io_iter, and 'offset'
833 * is the start point of linear offset of request.
835 static size_t ublk_copy_user_pages(const struct request *req,
836 unsigned offset, struct iov_iter *uiter, int dir)
838 struct ublk_io_iter iter;
841 if (!ublk_advance_io_iter(req, &iter, offset))
844 while (iov_iter_count(uiter) && iter.bio) {
850 len = iov_iter_get_pages2(uiter, iter.pages,
851 iov_iter_count(uiter),
852 UBLK_MAX_PIN_PAGES, &off);
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]);
869 static inline bool ublk_need_map_req(const struct request *req)
871 return ublk_rq_has_data(req) && req_op(req) == REQ_OP_WRITE;
874 static inline bool ublk_need_unmap_req(const struct request *req)
876 return ublk_rq_has_data(req) &&
877 (req_op(req) == REQ_OP_READ || req_op(req) == REQ_OP_DRV_IN);
880 static int ublk_map_io(const struct ublk_queue *ubq, const struct request *req,
883 const unsigned int rq_bytes = blk_rq_bytes(req);
885 if (ublk_support_user_copy(ubq))
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
893 if (ublk_need_map_req(req)) {
894 struct iov_iter iter;
896 const int dir = ITER_DEST;
898 import_single_range(dir, u64_to_user_ptr(io->addr), rq_bytes,
901 return ublk_copy_user_pages(req, 0, &iter, dir);
906 static int ublk_unmap_io(const struct ublk_queue *ubq,
907 const struct request *req,
910 const unsigned int rq_bytes = blk_rq_bytes(req);
912 if (ublk_support_user_copy(ubq))
915 if (ublk_need_unmap_req(req)) {
916 struct iov_iter iter;
918 const int dir = ITER_SOURCE;
920 WARN_ON_ONCE(io->res > rq_bytes);
922 import_single_range(dir, u64_to_user_ptr(io->addr), io->res,
924 return ublk_copy_user_pages(req, 0, &iter, dir);
929 static inline unsigned int ublk_req_build_flags(struct request *req)
933 if (req->cmd_flags & REQ_FAILFAST_DEV)
934 flags |= UBLK_IO_F_FAILFAST_DEV;
936 if (req->cmd_flags & REQ_FAILFAST_TRANSPORT)
937 flags |= UBLK_IO_F_FAILFAST_TRANSPORT;
939 if (req->cmd_flags & REQ_FAILFAST_DRIVER)
940 flags |= UBLK_IO_F_FAILFAST_DRIVER;
942 if (req->cmd_flags & REQ_META)
943 flags |= UBLK_IO_F_META;
945 if (req->cmd_flags & REQ_FUA)
946 flags |= UBLK_IO_F_FUA;
948 if (req->cmd_flags & REQ_NOUNMAP)
949 flags |= UBLK_IO_F_NOUNMAP;
951 if (req->cmd_flags & REQ_SWAP)
952 flags |= UBLK_IO_F_SWAP;
957 static blk_status_t ublk_setup_iod(struct ublk_queue *ubq, struct request *req)
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);
964 if (!ublk_queue_is_zoned(ubq) &&
965 (op_is_zone_mgmt(op) || op == REQ_OP_ZONE_APPEND))
966 return BLK_STS_IOERR;
968 switch (req_op(req)) {
970 ublk_op = UBLK_IO_OP_READ;
973 ublk_op = UBLK_IO_OP_WRITE;
976 ublk_op = UBLK_IO_OP_FLUSH;
979 ublk_op = UBLK_IO_OP_DISCARD;
981 case REQ_OP_WRITE_ZEROES:
982 ublk_op = UBLK_IO_OP_WRITE_ZEROES;
985 if (ublk_queue_is_zoned(ubq))
986 return ublk_setup_iod_zoned(ubq, req);
987 return BLK_STS_IOERR;
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;
999 static inline struct ublk_uring_cmd_pdu *ublk_get_uring_cmd_pdu(
1000 struct io_uring_cmd *ioucmd)
1002 return (struct ublk_uring_cmd_pdu *)&ioucmd->pdu;
1005 static inline bool ubq_daemon_is_dying(struct ublk_queue *ubq)
1007 return ubq->ubq_daemon->flags & PF_EXITING;
1010 /* todo: handle partial completion */
1011 static inline void __ublk_complete_rq(struct request *req)
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;
1018 /* called from ublk_abort_queue() code path */
1019 if (io->flags & UBLK_IO_FLAG_ABORTED) {
1020 res = BLK_STS_IOERR;
1024 /* failed read IO if nothing is read */
1025 if (!io->res && req_op(req) == REQ_OP_READ)
1029 res = errno_to_blk_status(io->res);
1034 * FLUSH, DISCARD or WRITE_ZEROES usually won't return bytes returned, so end them
1037 * Both the two needn't unmap.
1039 if (req_op(req) != REQ_OP_READ && req_op(req) != REQ_OP_WRITE &&
1040 req_op(req) != REQ_OP_DRV_IN)
1043 /* for READ request, writing data in iod->addr to rq buffers */
1044 unmapped_bytes = ublk_unmap_io(ubq, req, io);
1047 * Extremely impossible since we got data filled in just before
1049 * Re-read simply for this unlikely case.
1051 if (unlikely(unmapped_bytes < io->res))
1052 io->res = unmapped_bytes;
1054 if (blk_update_request(req, BLK_STS_OK, io->res))
1055 blk_mq_requeue_request(req, true);
1057 __blk_mq_end_request(req, BLK_STS_OK);
1061 blk_mq_end_request(req, res);
1064 static void ublk_complete_rq(struct kref *ref)
1066 struct ublk_rq_data *data = container_of(ref, struct ublk_rq_data,
1068 struct request *req = blk_mq_rq_from_pdu(data);
1070 __ublk_complete_rq(req);
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.
1078 * Also aborting may not be started yet, keep in mind that one failed
1079 * request may be issued by block layer again.
1081 static void __ublk_fail_req(struct ublk_queue *ubq, struct ublk_io *io,
1082 struct request *req)
1084 WARN_ON_ONCE(io->flags & UBLK_IO_FLAG_ACTIVE);
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);
1091 ublk_put_req_ref(ubq, req);
1095 static void ubq_complete_io_cmd(struct ublk_io *io, int res,
1096 unsigned issue_flags)
1098 /* mark this cmd owned by ublksrv */
1099 io->flags |= UBLK_IO_FLAG_OWNED_BY_SRV;
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.
1105 io->flags &= ~UBLK_IO_FLAG_ACTIVE;
1107 /* tell ublksrv one io request is coming */
1108 io_uring_cmd_done(io->cmd, res, 0, issue_flags);
1111 #define UBLK_REQUEUE_DELAY_MS 3
1113 static inline void __ublk_abort_rq(struct ublk_queue *ubq,
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);
1120 blk_mq_end_request(rq, BLK_STS_IOERR);
1122 mod_delayed_work(system_wq, &ubq->dev->monitor_work, 0);
1125 static inline void __ublk_rq_task_work(struct request *req,
1126 unsigned issue_flags)
1128 struct ublk_queue *ubq = req->mq_hctx->driver_data;
1130 struct ublk_io *io = &ubq->ios[tag];
1131 unsigned int mapped_bytes;
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);
1138 * Task is exiting if either:
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.
1144 * (2) current->flags & PF_EXITING.
1146 if (unlikely(current != ubq->ubq_daemon || current->flags & PF_EXITING)) {
1147 __ublk_abort_rq(ubq, req);
1151 if (ublk_need_get_data(ubq) && ublk_need_map_req(req)) {
1153 * We have not handled UBLK_IO_NEED_GET_DATA command yet,
1154 * so immepdately pass UBLK_IO_RES_NEED_GET_DATA to ublksrv
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);
1166 * We have handled UBLK_IO_NEED_GET_DATA command,
1167 * so clear UBLK_IO_FLAG_NEED_GET_DATA now and just
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);
1178 mapped_bytes = ublk_map_io(ubq, req, io);
1180 /* partially mapped, update io descriptor */
1181 if (unlikely(mapped_bytes != blk_rq_bytes(req))) {
1183 * Nothing mapped, retry until we succeed.
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.
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);
1196 ublk_get_iod(ubq, req->tag)->nr_sectors =
1200 ublk_init_req_ref(ubq, req);
1201 ubq_complete_io_cmd(io, UBLK_IO_RES_OK, issue_flags);
1204 static inline void ublk_forward_io_cmds(struct ublk_queue *ubq,
1205 unsigned issue_flags)
1207 struct llist_node *io_cmds = llist_del_all(&ubq->io_cmds);
1208 struct ublk_rq_data *data, *tmp;
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);
1215 static inline void ublk_abort_io_cmds(struct ublk_queue *ubq)
1217 struct llist_node *io_cmds = llist_del_all(&ubq->io_cmds);
1218 struct ublk_rq_data *data, *tmp;
1220 llist_for_each_entry_safe(data, tmp, io_cmds, node)
1221 __ublk_abort_rq(ubq, blk_mq_rq_from_pdu(data));
1224 static void ublk_rq_task_work_cb(struct io_uring_cmd *cmd, unsigned issue_flags)
1226 struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
1227 struct ublk_queue *ubq = pdu->ubq;
1229 ublk_forward_io_cmds(ubq, issue_flags);
1232 static void ublk_queue_cmd(struct ublk_queue *ubq, struct request *rq)
1234 struct ublk_rq_data *data = blk_mq_rq_to_pdu(rq);
1237 if (!llist_add(&data->node, &ubq->io_cmds))
1240 io = &ubq->ios[rq->tag];
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.
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.
1253 if (unlikely(io->flags & UBLK_IO_FLAG_ABORTED)) {
1254 ublk_abort_io_cmds(ubq);
1256 struct io_uring_cmd *cmd = io->cmd;
1257 struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
1260 io_uring_cmd_complete_in_task(cmd, ublk_rq_task_work_cb);
1264 static enum blk_eh_timer_return ublk_timeout(struct request *rq)
1266 struct ublk_queue *ubq = rq->mq_hctx->driver_data;
1268 if (ubq->flags & UBLK_F_UNPRIVILEGED_DEV) {
1269 if (!ubq->timeout) {
1270 send_sig(SIGKILL, ubq->ubq_daemon, 0);
1271 ubq->timeout = true;
1277 return BLK_EH_RESET_TIMER;
1280 static blk_status_t ublk_queue_rq(struct blk_mq_hw_ctx *hctx,
1281 const struct blk_mq_queue_data *bd)
1283 struct ublk_queue *ubq = hctx->driver_data;
1284 struct request *rq = bd->rq;
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;
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.
1298 * Note: force_abort is guaranteed to be seen because it is set
1299 * before request queue is unqiuesced.
1301 if (ublk_queue_can_use_recovery(ubq) && unlikely(ubq->force_abort))
1302 return BLK_STS_IOERR;
1304 blk_mq_start_request(bd->rq);
1306 if (unlikely(ubq_daemon_is_dying(ubq))) {
1307 __ublk_abort_rq(ubq, rq);
1311 ublk_queue_cmd(ubq, rq);
1316 static int ublk_init_hctx(struct blk_mq_hw_ctx *hctx, void *driver_data,
1317 unsigned int hctx_idx)
1319 struct ublk_device *ub = driver_data;
1320 struct ublk_queue *ubq = ublk_get_queue(ub, hctx->queue_num);
1322 hctx->driver_data = ubq;
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,
1332 static int ublk_ch_open(struct inode *inode, struct file *filp)
1334 struct ublk_device *ub = container_of(inode->i_cdev,
1335 struct ublk_device, cdev);
1337 if (test_and_set_bit(UB_STATE_OPEN, &ub->state))
1339 filp->private_data = ub;
1343 static int ublk_ch_release(struct inode *inode, struct file *filp)
1345 struct ublk_device *ub = filp->private_data;
1347 clear_bit(UB_STATE_OPEN, &ub->state);
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)
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;
1360 spin_lock(&ub->mm_lock);
1362 ub->mm = current->mm;
1363 if (current->mm != ub->mm)
1365 spin_unlock(&ub->mm_lock);
1370 if (vma->vm_flags & VM_WRITE)
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)
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);
1382 if (sz != ublk_queue_cmd_buf_size(ub, q_id))
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);
1389 static void ublk_commit_completion(struct ublk_device *ub,
1390 const struct ublksrv_io_cmd *ub_cmd)
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;
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;
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)))
1406 if (req_op(req) == REQ_OP_ZONE_APPEND)
1407 req->__sector = ub_cmd->zone_append_lba;
1409 if (likely(!blk_should_fake_timeout(req->q)))
1410 ublk_put_req_ref(ubq, req);
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
1418 static void ublk_abort_queue(struct ublk_device *ub, struct ublk_queue *ubq)
1422 if (!ublk_get_device(ub))
1425 for (i = 0; i < ubq->q_depth; i++) {
1426 struct ublk_io *io = &ubq->ios[i];
1428 if (!(io->flags & UBLK_IO_FLAG_ACTIVE)) {
1432 * Either we fail the request or ublk_rq_task_work_fn
1435 rq = blk_mq_tag_to_rq(ub->tag_set.tags[ubq->q_id], i);
1437 __ublk_fail_req(ubq, io, rq);
1440 ublk_put_device(ub);
1443 static void ublk_daemon_monitor_work(struct work_struct *work)
1445 struct ublk_device *ub =
1446 container_of(work, struct ublk_device, monitor_work.work);
1449 for (i = 0; i < ub->dev_info.nr_hw_queues; i++) {
1450 struct ublk_queue *ubq = ublk_get_queue(ub, i);
1452 if (ubq_daemon_is_dying(ubq)) {
1453 if (ublk_queue_can_use_recovery(ubq))
1454 schedule_work(&ub->quiesce_work);
1456 schedule_work(&ub->stop_work);
1458 /* abort queue is for making forward progress */
1459 ublk_abort_queue(ub, ubq);
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.
1467 * No need ub->mutex, monitor work are canceled after state is marked
1468 * as not LIVE, so new state is observed reliably.
1470 if (ub->dev_info.state == UBLK_S_DEV_LIVE)
1471 schedule_delayed_work(&ub->monitor_work,
1472 UBLK_DAEMON_MONITOR_PERIOD);
1475 static inline bool ublk_queue_ready(struct ublk_queue *ubq)
1477 return ubq->nr_io_ready == ubq->q_depth;
1480 static void ublk_cmd_cancel_cb(struct io_uring_cmd *cmd, unsigned issue_flags)
1482 io_uring_cmd_done(cmd, UBLK_IO_RES_ABORT, 0, issue_flags);
1485 static void ublk_cancel_queue(struct ublk_queue *ubq)
1489 if (!ublk_queue_ready(ubq))
1492 for (i = 0; i < ubq->q_depth; i++) {
1493 struct ublk_io *io = &ubq->ios[i];
1495 if (io->flags & UBLK_IO_FLAG_ACTIVE)
1496 io_uring_cmd_complete_in_task(io->cmd,
1497 ublk_cmd_cancel_cb);
1500 /* all io commands are canceled */
1501 ubq->nr_io_ready = 0;
1504 /* Cancel all pending commands, must be called after del_gendisk() returns */
1505 static void ublk_cancel_dev(struct ublk_device *ub)
1509 for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1510 ublk_cancel_queue(ublk_get_queue(ub, i));
1513 static bool ublk_check_inflight_rq(struct request *rq, void *data)
1517 if (blk_mq_request_started(rq)) {
1524 static void ublk_wait_tagset_rqs_idle(struct ublk_device *ub)
1528 WARN_ON_ONCE(!blk_queue_quiesced(ub->ub_disk->queue));
1531 blk_mq_tagset_busy_iter(&ub->tag_set,
1532 ublk_check_inflight_rq, &idle);
1535 msleep(UBLK_REQUEUE_DELAY_MS);
1539 static void __ublk_quiesce_dev(struct ublk_device *ub)
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.
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.
1557 cancel_delayed_work_sync(&ub->monitor_work);
1560 static void ublk_quiesce_work_fn(struct work_struct *work)
1562 struct ublk_device *ub =
1563 container_of(work, struct ublk_device, quiesce_work);
1565 mutex_lock(&ub->mutex);
1566 if (ub->dev_info.state != UBLK_S_DEV_LIVE)
1568 __ublk_quiesce_dev(ub);
1570 mutex_unlock(&ub->mutex);
1573 static void ublk_unquiesce_dev(struct ublk_device *ub)
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()
1586 for (i = 0; i < ub->dev_info.nr_hw_queues; i++)
1587 ublk_get_queue(ub, i)->force_abort = true;
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);
1594 static void ublk_stop_dev(struct ublk_device *ub)
1596 mutex_lock(&ub->mutex);
1597 if (ub->dev_info.state == UBLK_S_DEV_DEAD)
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);
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);
1610 ublk_cancel_dev(ub);
1611 mutex_unlock(&ub->mutex);
1612 cancel_delayed_work_sync(&ub->monitor_work);
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)
1618 mutex_lock(&ub->mutex);
1620 if (ublk_queue_ready(ubq)) {
1621 ubq->ubq_daemon = current;
1622 get_task_struct(ubq->ubq_daemon);
1623 ub->nr_queues_ready++;
1625 if (capable(CAP_SYS_ADMIN))
1626 ub->nr_privileged_daemon++;
1628 if (ub->nr_queues_ready == ub->dev_info.nr_hw_queues)
1629 complete_all(&ub->completion);
1630 mutex_unlock(&ub->mutex);
1633 static void ublk_handle_need_get_data(struct ublk_device *ub, int q_id,
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);
1639 ublk_queue_cmd(ubq, req);
1642 static inline int ublk_check_cmd_op(u32 cmd_op)
1644 u32 ioc_type = _IOC_TYPE(cmd_op);
1646 if (!IS_ENABLED(CONFIG_BLKDEV_UBLK_LEGACY_OPCODES) && ioc_type != 'u')
1649 if (ioc_type != 'u' && ioc_type != 0)
1655 static inline void ublk_fill_io_cmd(struct ublk_io *io,
1656 struct io_uring_cmd *cmd, unsigned long buf_addr)
1659 io->flags |= UBLK_IO_FLAG_ACTIVE;
1660 io->addr = buf_addr;
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)
1667 struct ublk_device *ub = cmd->file->private_data;
1668 struct ublk_queue *ubq;
1670 u32 cmd_op = cmd->cmd_op;
1671 unsigned tag = ub_cmd->tag;
1673 struct request *req;
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,
1679 if (ub_cmd->q_id >= ub->dev_info.nr_hw_queues)
1682 ubq = ublk_get_queue(ub, ub_cmd->q_id);
1683 if (!ubq || ub_cmd->q_id != ubq->q_id)
1686 if (ubq->ubq_daemon && ubq->ubq_daemon != current)
1689 if (tag >= ubq->q_depth)
1692 io = &ubq->ios[tag];
1694 /* there is pending io cmd, something must be wrong */
1695 if (io->flags & UBLK_IO_FLAG_ACTIVE) {
1701 * ensure that the user issues UBLK_IO_NEED_GET_DATA
1702 * iff the driver have set the UBLK_IO_FLAG_NEED_GET_DATA.
1704 if ((!!(io->flags & UBLK_IO_FLAG_NEED_GET_DATA))
1705 ^ (_IOC_NR(cmd_op) == UBLK_IO_NEED_GET_DATA))
1708 ret = ublk_check_cmd_op(cmd_op);
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)) {
1721 * The io is being handled by server, so COMMIT_RQ is expected
1722 * instead of FETCH_REQ
1724 if (io->flags & UBLK_IO_FLAG_OWNED_BY_SRV)
1727 if (!ublk_support_user_copy(ubq)) {
1729 * FETCH_RQ has to provide IO buffer if NEED GET
1730 * DATA is not enabled
1732 if (!ub_cmd->addr && !ublk_need_get_data(ubq))
1734 } else if (ub_cmd->addr) {
1735 /* User copy requires addr to be unset */
1740 ublk_fill_io_cmd(io, cmd, ub_cmd->addr);
1741 ublk_mark_io_ready(ub, ubq);
1743 case UBLK_IO_COMMIT_AND_FETCH_REQ:
1744 req = blk_mq_tag_to_rq(ub->tag_set.tags[ub_cmd->q_id], tag);
1746 if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV))
1749 if (!ublk_support_user_copy(ubq)) {
1751 * COMMIT_AND_FETCH_REQ has to provide IO buffer if
1752 * NEED GET DATA is not enabled or it is Read IO.
1754 if (!ub_cmd->addr && (!ublk_need_get_data(ubq) ||
1755 req_op(req) == REQ_OP_READ))
1757 } else if (req_op(req) != REQ_OP_ZONE_APPEND && ub_cmd->addr) {
1759 * User copy requires addr to be unset when command is
1766 ublk_fill_io_cmd(io, cmd, ub_cmd->addr);
1767 ublk_commit_completion(ub, ub_cmd);
1769 case UBLK_IO_NEED_GET_DATA:
1770 if (!(io->flags & UBLK_IO_FLAG_OWNED_BY_SRV))
1772 ublk_fill_io_cmd(io, cmd, ub_cmd->addr);
1773 ublk_handle_need_get_data(ub, ub_cmd->q_id, ub_cmd->tag);
1778 return -EIOCBQUEUED;
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;
1787 static inline struct request *__ublk_check_and_get_req(struct ublk_device *ub,
1788 struct ublk_queue *ubq, int tag, size_t offset)
1790 struct request *req;
1792 if (!ublk_need_req_ref(ubq))
1795 req = blk_mq_tag_to_rq(ub->tag_set.tags[ubq->q_id], tag);
1799 if (!ublk_get_req_ref(ubq, req))
1802 if (unlikely(!blk_mq_request_started(req) || req->tag != tag))
1805 if (!ublk_rq_has_data(req))
1808 if (offset > blk_rq_bytes(req))
1813 ublk_put_req_ref(ubq, req);
1817 static int ublk_ch_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags)
1820 * Not necessary for async retry, but let's keep it simple and always
1821 * copy the values to avoid any potential reuse.
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)
1831 return __ublk_ch_uring_cmd(cmd, issue_flags, &ub_cmd);
1834 static inline bool ublk_check_ubuf_dir(const struct request *req,
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)
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)
1851 static struct request *ublk_check_and_get_req(struct kiocb *iocb,
1852 struct iov_iter *iter, size_t *off, int dir)
1854 struct ublk_device *ub = iocb->ki_filp->private_data;
1855 struct ublk_queue *ubq;
1856 struct request *req;
1861 return ERR_PTR(-EACCES);
1863 if (!user_backed_iter(iter))
1864 return ERR_PTR(-EACCES);
1866 if (ub->dev_info.state == UBLK_S_DEV_DEAD)
1867 return ERR_PTR(-EACCES);
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);
1873 if (q_id >= ub->dev_info.nr_hw_queues)
1874 return ERR_PTR(-EINVAL);
1876 ubq = ublk_get_queue(ub, q_id);
1878 return ERR_PTR(-EINVAL);
1880 if (tag >= ubq->q_depth)
1881 return ERR_PTR(-EINVAL);
1883 req = __ublk_check_and_get_req(ub, ubq, tag, buf_off);
1885 return ERR_PTR(-EINVAL);
1887 if (!req->mq_hctx || !req->mq_hctx->driver_data)
1890 if (!ublk_check_ubuf_dir(req, dir))
1896 ublk_put_req_ref(ubq, req);
1897 return ERR_PTR(-EACCES);
1900 static ssize_t ublk_ch_read_iter(struct kiocb *iocb, struct iov_iter *to)
1902 struct ublk_queue *ubq;
1903 struct request *req;
1907 req = ublk_check_and_get_req(iocb, to, &buf_off, ITER_DEST);
1909 return PTR_ERR(req);
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);
1918 static ssize_t ublk_ch_write_iter(struct kiocb *iocb, struct iov_iter *from)
1920 struct ublk_queue *ubq;
1921 struct request *req;
1925 req = ublk_check_and_get_req(iocb, from, &buf_off, ITER_SOURCE);
1927 return PTR_ERR(req);
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);
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,
1947 static void ublk_deinit_queue(struct ublk_device *ub, int q_id)
1949 int size = ublk_queue_cmd_buf_size(ub, q_id);
1950 struct ublk_queue *ubq = ublk_get_queue(ub, q_id);
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));
1958 static int ublk_init_queue(struct ublk_device *ub, int q_id)
1960 struct ublk_queue *ubq = ublk_get_queue(ub, q_id);
1961 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO;
1965 ubq->flags = ub->dev_info.flags;
1967 ubq->q_depth = ub->dev_info.queue_depth;
1968 size = ublk_queue_cmd_buf_size(ub, q_id);
1970 ptr = (void *) __get_free_pages(gfp_flags, get_order(size));
1974 ubq->io_cmd_buf = ptr;
1979 static void ublk_deinit_queues(struct ublk_device *ub)
1981 int nr_queues = ub->dev_info.nr_hw_queues;
1987 for (i = 0; i < nr_queues; i++)
1988 ublk_deinit_queue(ub, i);
1989 kfree(ub->__queues);
1992 static int ublk_init_queues(struct ublk_device *ub)
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;
1999 ub->queue_size = ubq_size;
2000 ub->__queues = kcalloc(nr_queues, ubq_size, GFP_KERNEL);
2004 for (i = 0; i < nr_queues; i++) {
2005 if (ublk_init_queue(ub, i))
2009 init_completion(&ub->completion);
2013 ublk_deinit_queues(ub);
2017 static int ublk_alloc_dev_number(struct ublk_device *ub, int idx)
2022 spin_lock(&ublk_idr_lock);
2023 /* allocate id, if @id >= 0, we're requesting that specific id */
2025 err = idr_alloc(&ublk_index_idr, ub, i, i + 1, GFP_NOWAIT);
2029 err = idr_alloc(&ublk_index_idr, ub, 0, 0, GFP_NOWAIT);
2031 spin_unlock(&ublk_idr_lock);
2034 ub->ub_number = err;
2039 static void ublk_free_dev_number(struct ublk_device *ub)
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);
2047 static void ublk_cdev_rel(struct device *dev)
2049 struct ublk_device *ub = container_of(dev, struct ublk_device, cdev_dev);
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);
2058 static int ublk_add_chdev(struct ublk_device *ub)
2060 struct device *dev = &ub->cdev_dev;
2061 int minor = ub->ub_number;
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);
2070 ret = dev_set_name(dev, "ublkc%d", minor);
2074 cdev_init(&ub->cdev, &ublk_ch_fops);
2075 ret = cdev_device_add(&ub->cdev, dev);
2086 static void ublk_stop_work_fn(struct work_struct *work)
2088 struct ublk_device *ub =
2089 container_of(work, struct ublk_device, stop_work);
2094 /* align max io buffer size with PAGE_SIZE */
2095 static void ublk_align_max_io_size(struct ublk_device *ub)
2097 unsigned int max_io_bytes = ub->dev_info.max_io_buf_bytes;
2099 ub->dev_info.max_io_buf_bytes =
2100 round_down(max_io_bytes, PAGE_SIZE);
2103 static int ublk_add_tag_set(struct ublk_device *ub)
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);
2115 static void ublk_remove(struct ublk_device *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);
2125 static struct ublk_device *ublk_get_device_from_id(int idx)
2127 struct ublk_device *ub = NULL;
2132 spin_lock(&ublk_idr_lock);
2133 ub = idr_find(&ublk_index_idr, idx);
2135 ub = ublk_get_device(ub);
2136 spin_unlock(&ublk_idr_lock);
2141 static int ublk_ctrl_start_dev(struct ublk_device *ub, struct io_uring_cmd *cmd)
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;
2148 if (ublksrv_pid <= 0)
2151 if (wait_for_completion_interruptible(&ub->completion) != 0)
2154 schedule_delayed_work(&ub->monitor_work, UBLK_DAEMON_MONITOR_PERIOD);
2156 mutex_lock(&ub->mutex);
2157 if (ub->dev_info.state == UBLK_S_DEV_LIVE ||
2158 test_bit(UB_STATE_USED, &ub->state)) {
2163 disk = blk_mq_alloc_disk(&ub->tag_set, NULL);
2165 ret = PTR_ERR(disk);
2168 sprintf(disk->disk_name, "ublkb%d", ub->ub_number);
2169 disk->fops = &ub_fops;
2170 disk->private_data = ub;
2172 ub->dev_info.ublksrv_pid = ublksrv_pid;
2175 ret = ublk_apply_params(ub);
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);
2183 get_device(&ub->cdev_dev);
2184 ub->dev_info.state = UBLK_S_DEV_LIVE;
2186 if (ublk_dev_is_zoned(ub)) {
2187 ret = ublk_revalidate_disk_zones(ub);
2192 ret = add_disk(disk);
2196 set_bit(UB_STATE_USED, &ub->state);
2200 ub->dev_info.state = UBLK_S_DEV_DEAD;
2201 ublk_put_device(ub);
2207 mutex_unlock(&ub->mutex);
2211 static int ublk_ctrl_get_queue_affinity(struct ublk_device *ub,
2212 struct io_uring_cmd *cmd)
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;
2222 if (header->len * BITS_PER_BYTE < nr_cpu_ids)
2224 if (header->len & (sizeof(unsigned long)-1))
2229 queue = header->data[0];
2230 if (queue >= ub->dev_info.nr_hw_queues)
2233 if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
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);
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;
2251 free_cpumask_var(cpumask);
2255 static inline void ublk_dump_dev_info(struct ublksrv_ctrl_dev_info *info)
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);
2263 static int ublk_ctrl_add_dev(struct io_uring_cmd *cmd)
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;
2271 if (header->len < sizeof(info) || !header->addr)
2273 if (header->queue_id != (u16)-1) {
2274 pr_warn("%s: queue_id is wrong %x\n",
2275 __func__, header->queue_id);
2279 if (copy_from_user(&info, argp, sizeof(info)))
2282 if (capable(CAP_SYS_ADMIN))
2283 info.flags &= ~UBLK_F_UNPRIVILEGED_DEV;
2284 else if (!(info.flags & UBLK_F_UNPRIVILEGED_DEV))
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
2292 * TODO: provide forward progress for RECOVERY handler, so that
2293 * unprivileged device can benefit from it
2295 if (info.flags & UBLK_F_UNPRIVILEGED_DEV)
2296 info.flags &= ~(UBLK_F_USER_RECOVERY_REISSUE |
2297 UBLK_F_USER_RECOVERY);
2299 /* the created device is always owned by current user */
2300 ublk_store_owner_uid_gid(&info.owner_uid, &info.owner_gid);
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);
2308 ublk_dump_dev_info(&info);
2310 ret = mutex_lock_killable(&ublk_ctl_mutex);
2315 if (ublks_added >= ublks_max)
2319 ub = kzalloc(sizeof(*ub), GFP_KERNEL);
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);
2328 ret = ublk_alloc_dev_number(ub, header->dev_id);
2332 memcpy(&ub->dev_info, &info, sizeof(info));
2334 /* update device id */
2335 ub->dev_info.dev_id = ub->ub_number;
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.
2343 ub->dev_info.flags &= UBLK_F_ALL;
2345 ub->dev_info.flags |= UBLK_F_CMD_IOCTL_ENCODE |
2346 UBLK_F_URING_CMD_COMP_IN_TASK;
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;
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))) {
2356 goto out_free_dev_number;
2359 /* We are not ready to support zero copy */
2360 ub->dev_info.flags &= ~UBLK_F_SUPPORT_ZERO_COPY;
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);
2366 ret = ublk_init_queues(ub);
2368 goto out_free_dev_number;
2370 ret = ublk_add_tag_set(ub);
2372 goto out_deinit_queues;
2375 if (copy_to_user(argp, &ub->dev_info, sizeof(info)))
2376 goto out_free_tag_set;
2379 * Add the char dev so that ublksrv daemon can be setup.
2380 * ublk_add_chdev() will cleanup everything if it fails.
2382 ret = ublk_add_chdev(ub);
2386 blk_mq_free_tag_set(&ub->tag_set);
2388 ublk_deinit_queues(ub);
2389 out_free_dev_number:
2390 ublk_free_dev_number(ub);
2392 mutex_destroy(&ub->mutex);
2395 mutex_unlock(&ublk_ctl_mutex);
2399 static inline bool ublk_idr_freed(int id)
2403 spin_lock(&ublk_idr_lock);
2404 ptr = idr_find(&ublk_index_idr, id);
2405 spin_unlock(&ublk_idr_lock);
2410 static int ublk_ctrl_del_dev(struct ublk_device **p_ub)
2412 struct ublk_device *ub = *p_ub;
2413 int idx = ub->ub_number;
2416 ret = mutex_lock_killable(&ublk_ctl_mutex);
2420 if (!test_bit(UB_STATE_DELETED, &ub->state)) {
2422 set_bit(UB_STATE_DELETED, &ub->state);
2425 /* Mark the reference as consumed */
2427 ublk_put_device(ub);
2428 mutex_unlock(&ublk_ctl_mutex);
2431 * Wait until the idr is removed, then it can be reused after
2432 * DEL_DEV command is returned.
2434 * If we returns because of user interrupt, future delete command
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
2441 * - the device number is freed already, we will not find this
2442 * device via ublk_get_device_from_id()
2444 if (wait_event_interruptible(ublk_idr_wq, ublk_idr_freed(idx)))
2449 static inline void ublk_ctrl_cmd_dump(struct io_uring_cmd *cmd)
2451 const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
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);
2458 static int ublk_ctrl_stop_dev(struct ublk_device *ub)
2461 cancel_work_sync(&ub->stop_work);
2462 cancel_work_sync(&ub->quiesce_work);
2467 static int ublk_ctrl_get_dev_info(struct ublk_device *ub,
2468 struct io_uring_cmd *cmd)
2470 const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2471 void __user *argp = (void __user *)(unsigned long)header->addr;
2473 if (header->len < sizeof(struct ublksrv_ctrl_dev_info) || !header->addr)
2476 if (copy_to_user(argp, &ub->dev_info, sizeof(ub->dev_info)))
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)
2485 ub->params.devt.char_major = MAJOR(ub->cdev_dev.devt);
2486 ub->params.devt.char_minor = MINOR(ub->cdev_dev.devt);
2489 ub->params.devt.disk_major = MAJOR(disk_devt(ub->ub_disk));
2490 ub->params.devt.disk_minor = MINOR(disk_devt(ub->ub_disk));
2492 ub->params.devt.disk_major = 0;
2493 ub->params.devt.disk_minor = 0;
2495 ub->params.types |= UBLK_PARAM_TYPE_DEVT;
2498 static int ublk_ctrl_get_params(struct ublk_device *ub,
2499 struct io_uring_cmd *cmd)
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;
2506 if (header->len <= sizeof(ph) || !header->addr)
2509 if (copy_from_user(&ph, argp, sizeof(ph)))
2512 if (ph.len > header->len || !ph.len)
2515 if (ph.len > sizeof(struct ublk_params))
2516 ph.len = sizeof(struct ublk_params);
2518 mutex_lock(&ub->mutex);
2519 ublk_ctrl_fill_params_devt(ub);
2520 if (copy_to_user(argp, &ub->params, ph.len))
2524 mutex_unlock(&ub->mutex);
2529 static int ublk_ctrl_set_params(struct ublk_device *ub,
2530 struct io_uring_cmd *cmd)
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;
2537 if (header->len <= sizeof(ph) || !header->addr)
2540 if (copy_from_user(&ph, argp, sizeof(ph)))
2543 if (ph.len > header->len || !ph.len || !ph.types)
2546 if (ph.len > sizeof(struct ublk_params))
2547 ph.len = sizeof(struct ublk_params);
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) {
2553 } else if (copy_from_user(&ub->params, argp, ph.len)) {
2556 /* clear all we don't support yet */
2557 ub->params.types &= UBLK_PARAM_TYPE_ALL;
2558 ret = ublk_validate_params(ub);
2560 ub->params.types = 0;
2562 mutex_unlock(&ub->mutex);
2567 static void ublk_queue_reinit(struct ublk_device *ub, struct ublk_queue *ubq)
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;
2580 for (i = 0; i < ubq->q_depth; i++) {
2581 struct ublk_io *io = &ubq->ios[i];
2583 /* forget everything now and be ready for new FETCH_REQ */
2590 static int ublk_ctrl_start_recovery(struct ublk_device *ub,
2591 struct io_uring_cmd *cmd)
2593 const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2597 mutex_lock(&ub->mutex);
2598 if (!ublk_can_use_recovery(ub))
2601 * START_RECOVERY is only allowd after:
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
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
2613 if (test_bit(UB_STATE_OPEN, &ub->state) ||
2614 ub->dev_info.state != UBLK_S_DEV_QUIESCED) {
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 */
2623 ub->nr_queues_ready = 0;
2624 ub->nr_privileged_daemon = 0;
2625 init_completion(&ub->completion);
2628 mutex_unlock(&ub->mutex);
2632 static int ublk_ctrl_end_recovery(struct ublk_device *ub,
2633 struct io_uring_cmd *cmd)
2635 const struct ublksrv_ctrl_cmd *header = io_uring_sqe_cmd(cmd->sqe);
2636 int ublksrv_pid = (int)header->data[0];
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))
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);
2648 mutex_lock(&ub->mutex);
2649 if (!ublk_can_use_recovery(ub))
2652 if (ub->dev_info.state != UBLK_S_DEV_QUIESCED) {
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);
2667 mutex_unlock(&ub->mutex);
2671 static int ublk_ctrl_get_features(struct io_uring_cmd *cmd)
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;
2677 if (header->len != UBLK_FEATURES_LEN || !header->addr)
2680 if (copy_to_user(argp, &features, UBLK_FEATURES_LEN))
2687 * All control commands are sent via /dev/ublk-control, so we have to check
2688 * the destination device's permission
2690 static int ublk_char_dev_permission(struct ublk_device *ub,
2691 const char *dev_path, int mask)
2697 err = kern_path(dev_path, LOOKUP_FOLLOW, &path);
2701 err = vfs_getattr(&path, &stat, STATX_TYPE, AT_STATX_SYNC_AS_STAT);
2706 if (stat.rdev != ub->cdev_dev.devt || !S_ISCHR(stat.mode))
2709 err = inode_permission(&nop_mnt_idmap,
2710 d_backing_inode(path.dentry), mask);
2716 static int ublk_ctrl_uring_cmd_permission(struct ublk_device *ub,
2717 struct io_uring_cmd *cmd)
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;
2726 if (!unprivileged) {
2727 if (!capable(CAP_SYS_ADMIN))
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
2735 if (_IOC_NR(cmd->cmd_op) != UBLK_CMD_GET_DEV_INFO2)
2740 * User has to provide the char device path for unprivileged ublk
2742 * header->addr always points to the dev path buffer, and
2743 * header->dev_path_len records length of dev path buffer.
2745 if (!header->dev_path_len || header->dev_path_len > PATH_MAX)
2748 if (header->len < header->dev_path_len)
2751 dev_path = memdup_user_nul(argp, header->dev_path_len);
2752 if (IS_ERR(dev_path))
2753 return PTR_ERR(dev_path);
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)):
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;
2777 ret = ublk_char_dev_permission(ub, dev_path, mask);
2779 header->len -= header->dev_path_len;
2780 header->addr += header->dev_path_len;
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,
2791 static int ublk_ctrl_uring_cmd(struct io_uring_cmd *cmd,
2792 unsigned int issue_flags)
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;
2799 if (issue_flags & IO_URING_F_NONBLOCK)
2802 ublk_ctrl_cmd_dump(cmd);
2804 if (!(issue_flags & IO_URING_F_SQE128))
2807 ret = ublk_check_cmd_op(cmd_op);
2811 if (cmd_op == UBLK_U_CMD_GET_FEATURES) {
2812 ret = ublk_ctrl_get_features(cmd);
2816 if (_IOC_NR(cmd_op) != UBLK_CMD_ADD_DEV) {
2818 ub = ublk_get_device_from_id(header->dev_id);
2822 ret = ublk_ctrl_uring_cmd_permission(ub, cmd);
2827 switch (_IOC_NR(cmd_op)) {
2828 case UBLK_CMD_START_DEV:
2829 ret = ublk_ctrl_start_dev(ub, cmd);
2831 case UBLK_CMD_STOP_DEV:
2832 ret = ublk_ctrl_stop_dev(ub);
2834 case UBLK_CMD_GET_DEV_INFO:
2835 case UBLK_CMD_GET_DEV_INFO2:
2836 ret = ublk_ctrl_get_dev_info(ub, cmd);
2838 case UBLK_CMD_ADD_DEV:
2839 ret = ublk_ctrl_add_dev(cmd);
2841 case UBLK_CMD_DEL_DEV:
2842 ret = ublk_ctrl_del_dev(&ub);
2844 case UBLK_CMD_GET_QUEUE_AFFINITY:
2845 ret = ublk_ctrl_get_queue_affinity(ub, cmd);
2847 case UBLK_CMD_GET_PARAMS:
2848 ret = ublk_ctrl_get_params(ub, cmd);
2850 case UBLK_CMD_SET_PARAMS:
2851 ret = ublk_ctrl_set_params(ub, cmd);
2853 case UBLK_CMD_START_USER_RECOVERY:
2854 ret = ublk_ctrl_start_recovery(ub, cmd);
2856 case UBLK_CMD_END_USER_RECOVERY:
2857 ret = ublk_ctrl_end_recovery(ub, cmd);
2866 ublk_put_device(ub);
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;
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,
2881 static struct miscdevice ublk_misc = {
2882 .minor = MISC_DYNAMIC_MINOR,
2883 .name = "ublk-control",
2884 .fops = &ublk_ctl_fops,
2887 static int __init ublk_init(void)
2891 BUILD_BUG_ON((u64)UBLKSRV_IO_BUF_OFFSET +
2892 UBLKSRV_IO_BUF_TOTAL_SIZE < UBLKSRV_IO_BUF_OFFSET);
2894 init_waitqueue_head(&ublk_idr_wq);
2896 ret = misc_register(&ublk_misc);
2900 ret = alloc_chrdev_region(&ublk_chr_devt, 0, UBLK_MINORS, "ublk-char");
2902 goto unregister_mis;
2904 ret = class_register(&ublk_chr_class);
2906 goto free_chrdev_region;
2911 unregister_chrdev_region(ublk_chr_devt, UBLK_MINORS);
2913 misc_deregister(&ublk_misc);
2917 static void __exit ublk_exit(void)
2919 struct ublk_device *ub;
2922 idr_for_each_entry(&ublk_index_idr, ub, id)
2925 class_unregister(&ublk_chr_class);
2926 misc_deregister(&ublk_misc);
2928 idr_destroy(&ublk_index_idr);
2929 unregister_chrdev_region(ublk_chr_devt, UBLK_MINORS);
2932 module_init(ublk_init);
2933 module_exit(ublk_exit);
2935 module_param(ublks_max, int, 0444);
2936 MODULE_PARM_DESC(ublks_max, "max number of ublk devices allowed to add(default: 64)");
2938 MODULE_AUTHOR("Ming Lei <ming.lei@redhat.com>");
2939 MODULE_LICENSE("GPL");