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