xref: /linux/drivers/block/virtio_blk.c (revision 5dfe7a7e52ccdf60dfd11ccbe509e4365ea721ca)
1 // SPDX-License-Identifier: GPL-2.0-only
2 //#define DEBUG
3 #include <linux/spinlock.h>
4 #include <linux/slab.h>
5 #include <linux/blkdev.h>
6 #include <linux/hdreg.h>
7 #include <linux/module.h>
8 #include <linux/mutex.h>
9 #include <linux/interrupt.h>
10 #include <linux/virtio.h>
11 #include <linux/virtio_blk.h>
12 #include <linux/scatterlist.h>
13 #include <linux/string_helpers.h>
14 #include <linux/idr.h>
15 #include <linux/blk-mq.h>
16 #include <linux/blk-mq-virtio.h>
17 #include <linux/numa.h>
18 #include <linux/vmalloc.h>
19 #include <uapi/linux/virtio_ring.h>
20 
21 #define PART_BITS 4
22 #define VQ_NAME_LEN 16
23 #define MAX_DISCARD_SEGMENTS 256u
24 
25 /* The maximum number of sg elements that fit into a virtqueue */
26 #define VIRTIO_BLK_MAX_SG_ELEMS 32768
27 
28 #ifdef CONFIG_ARCH_NO_SG_CHAIN
29 #define VIRTIO_BLK_INLINE_SG_CNT	0
30 #else
31 #define VIRTIO_BLK_INLINE_SG_CNT	2
32 #endif
33 
34 static unsigned int num_request_queues;
35 module_param(num_request_queues, uint, 0644);
36 MODULE_PARM_DESC(num_request_queues,
37 		 "Limit the number of request queues to use for blk device. "
38 		 "0 for no limit. "
39 		 "Values > nr_cpu_ids truncated to nr_cpu_ids.");
40 
41 static unsigned int poll_queues;
42 module_param(poll_queues, uint, 0644);
43 MODULE_PARM_DESC(poll_queues, "The number of dedicated virtqueues for polling I/O");
44 
45 static int major;
46 static DEFINE_IDA(vd_index_ida);
47 
48 static struct workqueue_struct *virtblk_wq;
49 
50 struct virtio_blk_vq {
51 	struct virtqueue *vq;
52 	spinlock_t lock;
53 	char name[VQ_NAME_LEN];
54 } ____cacheline_aligned_in_smp;
55 
56 struct virtio_blk {
57 	/*
58 	 * This mutex must be held by anything that may run after
59 	 * virtblk_remove() sets vblk->vdev to NULL.
60 	 *
61 	 * blk-mq, virtqueue processing, and sysfs attribute code paths are
62 	 * shut down before vblk->vdev is set to NULL and therefore do not need
63 	 * to hold this mutex.
64 	 */
65 	struct mutex vdev_mutex;
66 	struct virtio_device *vdev;
67 
68 	/* The disk structure for the kernel. */
69 	struct gendisk *disk;
70 
71 	/* Block layer tags. */
72 	struct blk_mq_tag_set tag_set;
73 
74 	/* Process context for config space updates */
75 	struct work_struct config_work;
76 
77 	/* Ida index - used to track minor number allocations. */
78 	int index;
79 
80 	/* num of vqs */
81 	int num_vqs;
82 	int io_queues[HCTX_MAX_TYPES];
83 	struct virtio_blk_vq *vqs;
84 
85 	/* For zoned device */
86 	unsigned int zone_sectors;
87 };
88 
89 struct virtblk_req {
90 	/* Out header */
91 	struct virtio_blk_outhdr out_hdr;
92 
93 	/* In header */
94 	union {
95 		u8 status;
96 
97 		/*
98 		 * The zone append command has an extended in header.
99 		 * The status field in zone_append_in_hdr must always
100 		 * be the last byte.
101 		 */
102 		struct {
103 			__virtio64 sector;
104 			u8 status;
105 		} zone_append;
106 	} in_hdr;
107 
108 	size_t in_hdr_len;
109 
110 	struct sg_table sg_table;
111 	struct scatterlist sg[];
112 };
113 
114 static inline blk_status_t virtblk_result(u8 status)
115 {
116 	switch (status) {
117 	case VIRTIO_BLK_S_OK:
118 		return BLK_STS_OK;
119 	case VIRTIO_BLK_S_UNSUPP:
120 		return BLK_STS_NOTSUPP;
121 	case VIRTIO_BLK_S_ZONE_OPEN_RESOURCE:
122 		return BLK_STS_ZONE_OPEN_RESOURCE;
123 	case VIRTIO_BLK_S_ZONE_ACTIVE_RESOURCE:
124 		return BLK_STS_ZONE_ACTIVE_RESOURCE;
125 	case VIRTIO_BLK_S_IOERR:
126 	case VIRTIO_BLK_S_ZONE_UNALIGNED_WP:
127 	default:
128 		return BLK_STS_IOERR;
129 	}
130 }
131 
132 static inline struct virtio_blk_vq *get_virtio_blk_vq(struct blk_mq_hw_ctx *hctx)
133 {
134 	struct virtio_blk *vblk = hctx->queue->queuedata;
135 	struct virtio_blk_vq *vq = &vblk->vqs[hctx->queue_num];
136 
137 	return vq;
138 }
139 
140 static int virtblk_add_req(struct virtqueue *vq, struct virtblk_req *vbr)
141 {
142 	struct scatterlist out_hdr, in_hdr, *sgs[3];
143 	unsigned int num_out = 0, num_in = 0;
144 
145 	sg_init_one(&out_hdr, &vbr->out_hdr, sizeof(vbr->out_hdr));
146 	sgs[num_out++] = &out_hdr;
147 
148 	if (vbr->sg_table.nents) {
149 		if (vbr->out_hdr.type & cpu_to_virtio32(vq->vdev, VIRTIO_BLK_T_OUT))
150 			sgs[num_out++] = vbr->sg_table.sgl;
151 		else
152 			sgs[num_out + num_in++] = vbr->sg_table.sgl;
153 	}
154 
155 	sg_init_one(&in_hdr, &vbr->in_hdr.status, vbr->in_hdr_len);
156 	sgs[num_out + num_in++] = &in_hdr;
157 
158 	return virtqueue_add_sgs(vq, sgs, num_out, num_in, vbr, GFP_ATOMIC);
159 }
160 
161 static int virtblk_setup_discard_write_zeroes_erase(struct request *req, bool unmap)
162 {
163 	unsigned short segments = blk_rq_nr_discard_segments(req);
164 	unsigned short n = 0;
165 	struct virtio_blk_discard_write_zeroes *range;
166 	struct bio *bio;
167 	u32 flags = 0;
168 
169 	if (unmap)
170 		flags |= VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP;
171 
172 	range = kmalloc_array(segments, sizeof(*range), GFP_ATOMIC);
173 	if (!range)
174 		return -ENOMEM;
175 
176 	/*
177 	 * Single max discard segment means multi-range discard isn't
178 	 * supported, and block layer only runs contiguity merge like
179 	 * normal RW request. So we can't reply on bio for retrieving
180 	 * each range info.
181 	 */
182 	if (queue_max_discard_segments(req->q) == 1) {
183 		range[0].flags = cpu_to_le32(flags);
184 		range[0].num_sectors = cpu_to_le32(blk_rq_sectors(req));
185 		range[0].sector = cpu_to_le64(blk_rq_pos(req));
186 		n = 1;
187 	} else {
188 		__rq_for_each_bio(bio, req) {
189 			u64 sector = bio->bi_iter.bi_sector;
190 			u32 num_sectors = bio->bi_iter.bi_size >> SECTOR_SHIFT;
191 
192 			range[n].flags = cpu_to_le32(flags);
193 			range[n].num_sectors = cpu_to_le32(num_sectors);
194 			range[n].sector = cpu_to_le64(sector);
195 			n++;
196 		}
197 	}
198 
199 	WARN_ON_ONCE(n != segments);
200 
201 	bvec_set_virt(&req->special_vec, range, sizeof(*range) * segments);
202 	req->rq_flags |= RQF_SPECIAL_PAYLOAD;
203 
204 	return 0;
205 }
206 
207 static void virtblk_unmap_data(struct request *req, struct virtblk_req *vbr)
208 {
209 	if (blk_rq_nr_phys_segments(req))
210 		sg_free_table_chained(&vbr->sg_table,
211 				      VIRTIO_BLK_INLINE_SG_CNT);
212 }
213 
214 static int virtblk_map_data(struct blk_mq_hw_ctx *hctx, struct request *req,
215 		struct virtblk_req *vbr)
216 {
217 	int err;
218 
219 	if (!blk_rq_nr_phys_segments(req))
220 		return 0;
221 
222 	vbr->sg_table.sgl = vbr->sg;
223 	err = sg_alloc_table_chained(&vbr->sg_table,
224 				     blk_rq_nr_phys_segments(req),
225 				     vbr->sg_table.sgl,
226 				     VIRTIO_BLK_INLINE_SG_CNT);
227 	if (unlikely(err))
228 		return -ENOMEM;
229 
230 	return blk_rq_map_sg(hctx->queue, req, vbr->sg_table.sgl);
231 }
232 
233 static void virtblk_cleanup_cmd(struct request *req)
234 {
235 	if (req->rq_flags & RQF_SPECIAL_PAYLOAD)
236 		kfree(bvec_virt(&req->special_vec));
237 }
238 
239 static blk_status_t virtblk_setup_cmd(struct virtio_device *vdev,
240 				      struct request *req,
241 				      struct virtblk_req *vbr)
242 {
243 	size_t in_hdr_len = sizeof(vbr->in_hdr.status);
244 	bool unmap = false;
245 	u32 type;
246 	u64 sector = 0;
247 
248 	if (!IS_ENABLED(CONFIG_BLK_DEV_ZONED) && op_is_zone_mgmt(req_op(req)))
249 		return BLK_STS_NOTSUPP;
250 
251 	/* Set fields for all request types */
252 	vbr->out_hdr.ioprio = cpu_to_virtio32(vdev, req_get_ioprio(req));
253 
254 	switch (req_op(req)) {
255 	case REQ_OP_READ:
256 		type = VIRTIO_BLK_T_IN;
257 		sector = blk_rq_pos(req);
258 		break;
259 	case REQ_OP_WRITE:
260 		type = VIRTIO_BLK_T_OUT;
261 		sector = blk_rq_pos(req);
262 		break;
263 	case REQ_OP_FLUSH:
264 		type = VIRTIO_BLK_T_FLUSH;
265 		break;
266 	case REQ_OP_DISCARD:
267 		type = VIRTIO_BLK_T_DISCARD;
268 		break;
269 	case REQ_OP_WRITE_ZEROES:
270 		type = VIRTIO_BLK_T_WRITE_ZEROES;
271 		unmap = !(req->cmd_flags & REQ_NOUNMAP);
272 		break;
273 	case REQ_OP_SECURE_ERASE:
274 		type = VIRTIO_BLK_T_SECURE_ERASE;
275 		break;
276 	case REQ_OP_ZONE_OPEN:
277 		type = VIRTIO_BLK_T_ZONE_OPEN;
278 		sector = blk_rq_pos(req);
279 		break;
280 	case REQ_OP_ZONE_CLOSE:
281 		type = VIRTIO_BLK_T_ZONE_CLOSE;
282 		sector = blk_rq_pos(req);
283 		break;
284 	case REQ_OP_ZONE_FINISH:
285 		type = VIRTIO_BLK_T_ZONE_FINISH;
286 		sector = blk_rq_pos(req);
287 		break;
288 	case REQ_OP_ZONE_APPEND:
289 		type = VIRTIO_BLK_T_ZONE_APPEND;
290 		sector = blk_rq_pos(req);
291 		in_hdr_len = sizeof(vbr->in_hdr.zone_append);
292 		break;
293 	case REQ_OP_ZONE_RESET:
294 		type = VIRTIO_BLK_T_ZONE_RESET;
295 		sector = blk_rq_pos(req);
296 		break;
297 	case REQ_OP_ZONE_RESET_ALL:
298 		type = VIRTIO_BLK_T_ZONE_RESET_ALL;
299 		break;
300 	case REQ_OP_DRV_IN:
301 		/*
302 		 * Out header has already been prepared by the caller (virtblk_get_id()
303 		 * or virtblk_submit_zone_report()), nothing to do here.
304 		 */
305 		return 0;
306 	default:
307 		WARN_ON_ONCE(1);
308 		return BLK_STS_IOERR;
309 	}
310 
311 	/* Set fields for non-REQ_OP_DRV_IN request types */
312 	vbr->in_hdr_len = in_hdr_len;
313 	vbr->out_hdr.type = cpu_to_virtio32(vdev, type);
314 	vbr->out_hdr.sector = cpu_to_virtio64(vdev, sector);
315 
316 	if (type == VIRTIO_BLK_T_DISCARD || type == VIRTIO_BLK_T_WRITE_ZEROES ||
317 	    type == VIRTIO_BLK_T_SECURE_ERASE) {
318 		if (virtblk_setup_discard_write_zeroes_erase(req, unmap))
319 			return BLK_STS_RESOURCE;
320 	}
321 
322 	return 0;
323 }
324 
325 /*
326  * The status byte is always the last byte of the virtblk request
327  * in-header. This helper fetches its value for all in-header formats
328  * that are currently defined.
329  */
330 static inline u8 virtblk_vbr_status(struct virtblk_req *vbr)
331 {
332 	return *((u8 *)&vbr->in_hdr + vbr->in_hdr_len - 1);
333 }
334 
335 static inline void virtblk_request_done(struct request *req)
336 {
337 	struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
338 	blk_status_t status = virtblk_result(virtblk_vbr_status(vbr));
339 	struct virtio_blk *vblk = req->mq_hctx->queue->queuedata;
340 
341 	virtblk_unmap_data(req, vbr);
342 	virtblk_cleanup_cmd(req);
343 
344 	if (req_op(req) == REQ_OP_ZONE_APPEND)
345 		req->__sector = virtio64_to_cpu(vblk->vdev,
346 						vbr->in_hdr.zone_append.sector);
347 
348 	blk_mq_end_request(req, status);
349 }
350 
351 static void virtblk_done(struct virtqueue *vq)
352 {
353 	struct virtio_blk *vblk = vq->vdev->priv;
354 	bool req_done = false;
355 	int qid = vq->index;
356 	struct virtblk_req *vbr;
357 	unsigned long flags;
358 	unsigned int len;
359 
360 	spin_lock_irqsave(&vblk->vqs[qid].lock, flags);
361 	do {
362 		virtqueue_disable_cb(vq);
363 		while ((vbr = virtqueue_get_buf(vblk->vqs[qid].vq, &len)) != NULL) {
364 			struct request *req = blk_mq_rq_from_pdu(vbr);
365 
366 			if (likely(!blk_should_fake_timeout(req->q)))
367 				blk_mq_complete_request(req);
368 			req_done = true;
369 		}
370 		if (unlikely(virtqueue_is_broken(vq)))
371 			break;
372 	} while (!virtqueue_enable_cb(vq));
373 
374 	/* In case queue is stopped waiting for more buffers. */
375 	if (req_done)
376 		blk_mq_start_stopped_hw_queues(vblk->disk->queue, true);
377 	spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
378 }
379 
380 static void virtio_commit_rqs(struct blk_mq_hw_ctx *hctx)
381 {
382 	struct virtio_blk *vblk = hctx->queue->queuedata;
383 	struct virtio_blk_vq *vq = &vblk->vqs[hctx->queue_num];
384 	bool kick;
385 
386 	spin_lock_irq(&vq->lock);
387 	kick = virtqueue_kick_prepare(vq->vq);
388 	spin_unlock_irq(&vq->lock);
389 
390 	if (kick)
391 		virtqueue_notify(vq->vq);
392 }
393 
394 static blk_status_t virtblk_fail_to_queue(struct request *req, int rc)
395 {
396 	virtblk_cleanup_cmd(req);
397 	switch (rc) {
398 	case -ENOSPC:
399 		return BLK_STS_DEV_RESOURCE;
400 	case -ENOMEM:
401 		return BLK_STS_RESOURCE;
402 	default:
403 		return BLK_STS_IOERR;
404 	}
405 }
406 
407 static blk_status_t virtblk_prep_rq(struct blk_mq_hw_ctx *hctx,
408 					struct virtio_blk *vblk,
409 					struct request *req,
410 					struct virtblk_req *vbr)
411 {
412 	blk_status_t status;
413 	int num;
414 
415 	status = virtblk_setup_cmd(vblk->vdev, req, vbr);
416 	if (unlikely(status))
417 		return status;
418 
419 	num = virtblk_map_data(hctx, req, vbr);
420 	if (unlikely(num < 0))
421 		return virtblk_fail_to_queue(req, -ENOMEM);
422 	vbr->sg_table.nents = num;
423 
424 	blk_mq_start_request(req);
425 
426 	return BLK_STS_OK;
427 }
428 
429 static blk_status_t virtio_queue_rq(struct blk_mq_hw_ctx *hctx,
430 			   const struct blk_mq_queue_data *bd)
431 {
432 	struct virtio_blk *vblk = hctx->queue->queuedata;
433 	struct request *req = bd->rq;
434 	struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
435 	unsigned long flags;
436 	int qid = hctx->queue_num;
437 	bool notify = false;
438 	blk_status_t status;
439 	int err;
440 
441 	status = virtblk_prep_rq(hctx, vblk, req, vbr);
442 	if (unlikely(status))
443 		return status;
444 
445 	spin_lock_irqsave(&vblk->vqs[qid].lock, flags);
446 	err = virtblk_add_req(vblk->vqs[qid].vq, vbr);
447 	if (err) {
448 		virtqueue_kick(vblk->vqs[qid].vq);
449 		/* Don't stop the queue if -ENOMEM: we may have failed to
450 		 * bounce the buffer due to global resource outage.
451 		 */
452 		if (err == -ENOSPC)
453 			blk_mq_stop_hw_queue(hctx);
454 		spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
455 		virtblk_unmap_data(req, vbr);
456 		return virtblk_fail_to_queue(req, err);
457 	}
458 
459 	if (bd->last && virtqueue_kick_prepare(vblk->vqs[qid].vq))
460 		notify = true;
461 	spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
462 
463 	if (notify)
464 		virtqueue_notify(vblk->vqs[qid].vq);
465 	return BLK_STS_OK;
466 }
467 
468 static bool virtblk_prep_rq_batch(struct request *req)
469 {
470 	struct virtio_blk *vblk = req->mq_hctx->queue->queuedata;
471 	struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
472 
473 	req->mq_hctx->tags->rqs[req->tag] = req;
474 
475 	return virtblk_prep_rq(req->mq_hctx, vblk, req, vbr) == BLK_STS_OK;
476 }
477 
478 static bool virtblk_add_req_batch(struct virtio_blk_vq *vq,
479 					struct request **rqlist)
480 {
481 	unsigned long flags;
482 	int err;
483 	bool kick;
484 
485 	spin_lock_irqsave(&vq->lock, flags);
486 
487 	while (!rq_list_empty(*rqlist)) {
488 		struct request *req = rq_list_pop(rqlist);
489 		struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
490 
491 		err = virtblk_add_req(vq->vq, vbr);
492 		if (err) {
493 			virtblk_unmap_data(req, vbr);
494 			virtblk_cleanup_cmd(req);
495 			blk_mq_requeue_request(req, true);
496 		}
497 	}
498 
499 	kick = virtqueue_kick_prepare(vq->vq);
500 	spin_unlock_irqrestore(&vq->lock, flags);
501 
502 	return kick;
503 }
504 
505 static void virtio_queue_rqs(struct request **rqlist)
506 {
507 	struct request *req, *next, *prev = NULL;
508 	struct request *requeue_list = NULL;
509 
510 	rq_list_for_each_safe(rqlist, req, next) {
511 		struct virtio_blk_vq *vq = get_virtio_blk_vq(req->mq_hctx);
512 		bool kick;
513 
514 		if (!virtblk_prep_rq_batch(req)) {
515 			rq_list_move(rqlist, &requeue_list, req, prev);
516 			req = prev;
517 			if (!req)
518 				continue;
519 		}
520 
521 		if (!next || req->mq_hctx != next->mq_hctx) {
522 			req->rq_next = NULL;
523 			kick = virtblk_add_req_batch(vq, rqlist);
524 			if (kick)
525 				virtqueue_notify(vq->vq);
526 
527 			*rqlist = next;
528 			prev = NULL;
529 		} else
530 			prev = req;
531 	}
532 
533 	*rqlist = requeue_list;
534 }
535 
536 #ifdef CONFIG_BLK_DEV_ZONED
537 static void *virtblk_alloc_report_buffer(struct virtio_blk *vblk,
538 					  unsigned int nr_zones,
539 					  size_t *buflen)
540 {
541 	struct request_queue *q = vblk->disk->queue;
542 	size_t bufsize;
543 	void *buf;
544 
545 	nr_zones = min_t(unsigned int, nr_zones,
546 			 get_capacity(vblk->disk) >> ilog2(vblk->zone_sectors));
547 
548 	bufsize = sizeof(struct virtio_blk_zone_report) +
549 		nr_zones * sizeof(struct virtio_blk_zone_descriptor);
550 	bufsize = min_t(size_t, bufsize,
551 			queue_max_hw_sectors(q) << SECTOR_SHIFT);
552 	bufsize = min_t(size_t, bufsize, queue_max_segments(q) << PAGE_SHIFT);
553 
554 	while (bufsize >= sizeof(struct virtio_blk_zone_report)) {
555 		buf = __vmalloc(bufsize, GFP_KERNEL | __GFP_NORETRY);
556 		if (buf) {
557 			*buflen = bufsize;
558 			return buf;
559 		}
560 		bufsize >>= 1;
561 	}
562 
563 	return NULL;
564 }
565 
566 static int virtblk_submit_zone_report(struct virtio_blk *vblk,
567 				       char *report_buf, size_t report_len,
568 				       sector_t sector)
569 {
570 	struct request_queue *q = vblk->disk->queue;
571 	struct request *req;
572 	struct virtblk_req *vbr;
573 	int err;
574 
575 	req = blk_mq_alloc_request(q, REQ_OP_DRV_IN, 0);
576 	if (IS_ERR(req))
577 		return PTR_ERR(req);
578 
579 	vbr = blk_mq_rq_to_pdu(req);
580 	vbr->in_hdr_len = sizeof(vbr->in_hdr.status);
581 	vbr->out_hdr.type = cpu_to_virtio32(vblk->vdev, VIRTIO_BLK_T_ZONE_REPORT);
582 	vbr->out_hdr.sector = cpu_to_virtio64(vblk->vdev, sector);
583 
584 	err = blk_rq_map_kern(q, req, report_buf, report_len, GFP_KERNEL);
585 	if (err)
586 		goto out;
587 
588 	blk_execute_rq(req, false);
589 	err = blk_status_to_errno(virtblk_result(vbr->in_hdr.status));
590 out:
591 	blk_mq_free_request(req);
592 	return err;
593 }
594 
595 static int virtblk_parse_zone(struct virtio_blk *vblk,
596 			       struct virtio_blk_zone_descriptor *entry,
597 			       unsigned int idx, report_zones_cb cb, void *data)
598 {
599 	struct blk_zone zone = { };
600 
601 	zone.start = virtio64_to_cpu(vblk->vdev, entry->z_start);
602 	if (zone.start + vblk->zone_sectors <= get_capacity(vblk->disk))
603 		zone.len = vblk->zone_sectors;
604 	else
605 		zone.len = get_capacity(vblk->disk) - zone.start;
606 	zone.capacity = virtio64_to_cpu(vblk->vdev, entry->z_cap);
607 	zone.wp = virtio64_to_cpu(vblk->vdev, entry->z_wp);
608 
609 	switch (entry->z_type) {
610 	case VIRTIO_BLK_ZT_SWR:
611 		zone.type = BLK_ZONE_TYPE_SEQWRITE_REQ;
612 		break;
613 	case VIRTIO_BLK_ZT_SWP:
614 		zone.type = BLK_ZONE_TYPE_SEQWRITE_PREF;
615 		break;
616 	case VIRTIO_BLK_ZT_CONV:
617 		zone.type = BLK_ZONE_TYPE_CONVENTIONAL;
618 		break;
619 	default:
620 		dev_err(&vblk->vdev->dev, "zone %llu: invalid type %#x\n",
621 			zone.start, entry->z_type);
622 		return -EIO;
623 	}
624 
625 	switch (entry->z_state) {
626 	case VIRTIO_BLK_ZS_EMPTY:
627 		zone.cond = BLK_ZONE_COND_EMPTY;
628 		break;
629 	case VIRTIO_BLK_ZS_CLOSED:
630 		zone.cond = BLK_ZONE_COND_CLOSED;
631 		break;
632 	case VIRTIO_BLK_ZS_FULL:
633 		zone.cond = BLK_ZONE_COND_FULL;
634 		zone.wp = zone.start + zone.len;
635 		break;
636 	case VIRTIO_BLK_ZS_EOPEN:
637 		zone.cond = BLK_ZONE_COND_EXP_OPEN;
638 		break;
639 	case VIRTIO_BLK_ZS_IOPEN:
640 		zone.cond = BLK_ZONE_COND_IMP_OPEN;
641 		break;
642 	case VIRTIO_BLK_ZS_NOT_WP:
643 		zone.cond = BLK_ZONE_COND_NOT_WP;
644 		break;
645 	case VIRTIO_BLK_ZS_RDONLY:
646 		zone.cond = BLK_ZONE_COND_READONLY;
647 		zone.wp = ULONG_MAX;
648 		break;
649 	case VIRTIO_BLK_ZS_OFFLINE:
650 		zone.cond = BLK_ZONE_COND_OFFLINE;
651 		zone.wp = ULONG_MAX;
652 		break;
653 	default:
654 		dev_err(&vblk->vdev->dev, "zone %llu: invalid condition %#x\n",
655 			zone.start, entry->z_state);
656 		return -EIO;
657 	}
658 
659 	/*
660 	 * The callback below checks the validity of the reported
661 	 * entry data, no need to further validate it here.
662 	 */
663 	return cb(&zone, idx, data);
664 }
665 
666 static int virtblk_report_zones(struct gendisk *disk, sector_t sector,
667 				 unsigned int nr_zones, report_zones_cb cb,
668 				 void *data)
669 {
670 	struct virtio_blk *vblk = disk->private_data;
671 	struct virtio_blk_zone_report *report;
672 	unsigned long long nz, i;
673 	size_t buflen;
674 	unsigned int zone_idx = 0;
675 	int ret;
676 
677 	if (WARN_ON_ONCE(!vblk->zone_sectors))
678 		return -EOPNOTSUPP;
679 
680 	report = virtblk_alloc_report_buffer(vblk, nr_zones, &buflen);
681 	if (!report)
682 		return -ENOMEM;
683 
684 	mutex_lock(&vblk->vdev_mutex);
685 
686 	if (!vblk->vdev) {
687 		ret = -ENXIO;
688 		goto fail_report;
689 	}
690 
691 	while (zone_idx < nr_zones && sector < get_capacity(vblk->disk)) {
692 		memset(report, 0, buflen);
693 
694 		ret = virtblk_submit_zone_report(vblk, (char *)report,
695 						 buflen, sector);
696 		if (ret)
697 			goto fail_report;
698 
699 		nz = min_t(u64, virtio64_to_cpu(vblk->vdev, report->nr_zones),
700 			   nr_zones);
701 		if (!nz)
702 			break;
703 
704 		for (i = 0; i < nz && zone_idx < nr_zones; i++) {
705 			ret = virtblk_parse_zone(vblk, &report->zones[i],
706 						 zone_idx, cb, data);
707 			if (ret)
708 				goto fail_report;
709 
710 			sector = virtio64_to_cpu(vblk->vdev,
711 						 report->zones[i].z_start) +
712 				 vblk->zone_sectors;
713 			zone_idx++;
714 		}
715 	}
716 
717 	if (zone_idx > 0)
718 		ret = zone_idx;
719 	else
720 		ret = -EINVAL;
721 fail_report:
722 	mutex_unlock(&vblk->vdev_mutex);
723 	kvfree(report);
724 	return ret;
725 }
726 
727 static void virtblk_revalidate_zones(struct virtio_blk *vblk)
728 {
729 	u8 model;
730 
731 	virtio_cread(vblk->vdev, struct virtio_blk_config,
732 		     zoned.model, &model);
733 	switch (model) {
734 	default:
735 		dev_err(&vblk->vdev->dev, "unknown zone model %d\n", model);
736 		fallthrough;
737 	case VIRTIO_BLK_Z_NONE:
738 	case VIRTIO_BLK_Z_HA:
739 		disk_set_zoned(vblk->disk, BLK_ZONED_NONE);
740 		return;
741 	case VIRTIO_BLK_Z_HM:
742 		WARN_ON_ONCE(!vblk->zone_sectors);
743 		if (!blk_revalidate_disk_zones(vblk->disk, NULL))
744 			set_capacity_and_notify(vblk->disk, 0);
745 	}
746 }
747 
748 static int virtblk_probe_zoned_device(struct virtio_device *vdev,
749 				       struct virtio_blk *vblk,
750 				       struct request_queue *q)
751 {
752 	u32 v, wg;
753 	u8 model;
754 	int ret;
755 
756 	virtio_cread(vdev, struct virtio_blk_config,
757 		     zoned.model, &model);
758 
759 	switch (model) {
760 	case VIRTIO_BLK_Z_NONE:
761 	case VIRTIO_BLK_Z_HA:
762 		/* Present the host-aware device as non-zoned */
763 		return 0;
764 	case VIRTIO_BLK_Z_HM:
765 		break;
766 	default:
767 		dev_err(&vdev->dev, "unsupported zone model %d\n", model);
768 		return -EINVAL;
769 	}
770 
771 	dev_dbg(&vdev->dev, "probing host-managed zoned device\n");
772 
773 	disk_set_zoned(vblk->disk, BLK_ZONED_HM);
774 	blk_queue_flag_set(QUEUE_FLAG_ZONE_RESETALL, q);
775 
776 	virtio_cread(vdev, struct virtio_blk_config,
777 		     zoned.max_open_zones, &v);
778 	disk_set_max_open_zones(vblk->disk, v);
779 	dev_dbg(&vdev->dev, "max open zones = %u\n", v);
780 
781 	virtio_cread(vdev, struct virtio_blk_config,
782 		     zoned.max_active_zones, &v);
783 	disk_set_max_active_zones(vblk->disk, v);
784 	dev_dbg(&vdev->dev, "max active zones = %u\n", v);
785 
786 	virtio_cread(vdev, struct virtio_blk_config,
787 		     zoned.write_granularity, &wg);
788 	if (!wg) {
789 		dev_warn(&vdev->dev, "zero write granularity reported\n");
790 		return -ENODEV;
791 	}
792 	blk_queue_physical_block_size(q, wg);
793 	blk_queue_io_min(q, wg);
794 
795 	dev_dbg(&vdev->dev, "write granularity = %u\n", wg);
796 
797 	/*
798 	 * virtio ZBD specification doesn't require zones to be a power of
799 	 * two sectors in size, but the code in this driver expects that.
800 	 */
801 	virtio_cread(vdev, struct virtio_blk_config, zoned.zone_sectors,
802 		     &vblk->zone_sectors);
803 	if (vblk->zone_sectors == 0 || !is_power_of_2(vblk->zone_sectors)) {
804 		dev_err(&vdev->dev,
805 			"zoned device with non power of two zone size %u\n",
806 			vblk->zone_sectors);
807 		return -ENODEV;
808 	}
809 	dev_dbg(&vdev->dev, "zone sectors = %u\n", vblk->zone_sectors);
810 
811 	if (virtio_has_feature(vdev, VIRTIO_BLK_F_DISCARD)) {
812 		dev_warn(&vblk->vdev->dev,
813 			 "ignoring negotiated F_DISCARD for zoned device\n");
814 		blk_queue_max_discard_sectors(q, 0);
815 	}
816 
817 	ret = blk_revalidate_disk_zones(vblk->disk, NULL);
818 	if (!ret) {
819 		virtio_cread(vdev, struct virtio_blk_config,
820 			     zoned.max_append_sectors, &v);
821 		if (!v) {
822 			dev_warn(&vdev->dev, "zero max_append_sectors reported\n");
823 			return -ENODEV;
824 		}
825 		if ((v << SECTOR_SHIFT) < wg) {
826 			dev_err(&vdev->dev,
827 				"write granularity %u exceeds max_append_sectors %u limit\n",
828 				wg, v);
829 			return -ENODEV;
830 		}
831 
832 		blk_queue_max_zone_append_sectors(q, v);
833 		dev_dbg(&vdev->dev, "max append sectors = %u\n", v);
834 	}
835 
836 	return ret;
837 }
838 
839 #else
840 
841 /*
842  * Zoned block device support is not configured in this kernel.
843  * Host-managed zoned devices can't be supported, but others are
844  * good to go as regular block devices.
845  */
846 #define virtblk_report_zones       NULL
847 
848 static inline void virtblk_revalidate_zones(struct virtio_blk *vblk)
849 {
850 }
851 
852 static inline int virtblk_probe_zoned_device(struct virtio_device *vdev,
853 			struct virtio_blk *vblk, struct request_queue *q)
854 {
855 	u8 model;
856 
857 	virtio_cread(vdev, struct virtio_blk_config, zoned.model, &model);
858 	if (model == VIRTIO_BLK_Z_HM) {
859 		dev_err(&vdev->dev,
860 			"virtio_blk: zoned devices are not supported");
861 		return -EOPNOTSUPP;
862 	}
863 
864 	return 0;
865 }
866 #endif /* CONFIG_BLK_DEV_ZONED */
867 
868 /* return id (s/n) string for *disk to *id_str
869  */
870 static int virtblk_get_id(struct gendisk *disk, char *id_str)
871 {
872 	struct virtio_blk *vblk = disk->private_data;
873 	struct request_queue *q = vblk->disk->queue;
874 	struct request *req;
875 	struct virtblk_req *vbr;
876 	int err;
877 
878 	req = blk_mq_alloc_request(q, REQ_OP_DRV_IN, 0);
879 	if (IS_ERR(req))
880 		return PTR_ERR(req);
881 
882 	vbr = blk_mq_rq_to_pdu(req);
883 	vbr->in_hdr_len = sizeof(vbr->in_hdr.status);
884 	vbr->out_hdr.type = cpu_to_virtio32(vblk->vdev, VIRTIO_BLK_T_GET_ID);
885 	vbr->out_hdr.sector = 0;
886 
887 	err = blk_rq_map_kern(q, req, id_str, VIRTIO_BLK_ID_BYTES, GFP_KERNEL);
888 	if (err)
889 		goto out;
890 
891 	blk_execute_rq(req, false);
892 	err = blk_status_to_errno(virtblk_result(vbr->in_hdr.status));
893 out:
894 	blk_mq_free_request(req);
895 	return err;
896 }
897 
898 /* We provide getgeo only to please some old bootloader/partitioning tools */
899 static int virtblk_getgeo(struct block_device *bd, struct hd_geometry *geo)
900 {
901 	struct virtio_blk *vblk = bd->bd_disk->private_data;
902 	int ret = 0;
903 
904 	mutex_lock(&vblk->vdev_mutex);
905 
906 	if (!vblk->vdev) {
907 		ret = -ENXIO;
908 		goto out;
909 	}
910 
911 	/* see if the host passed in geometry config */
912 	if (virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_GEOMETRY)) {
913 		virtio_cread(vblk->vdev, struct virtio_blk_config,
914 			     geometry.cylinders, &geo->cylinders);
915 		virtio_cread(vblk->vdev, struct virtio_blk_config,
916 			     geometry.heads, &geo->heads);
917 		virtio_cread(vblk->vdev, struct virtio_blk_config,
918 			     geometry.sectors, &geo->sectors);
919 	} else {
920 		/* some standard values, similar to sd */
921 		geo->heads = 1 << 6;
922 		geo->sectors = 1 << 5;
923 		geo->cylinders = get_capacity(bd->bd_disk) >> 11;
924 	}
925 out:
926 	mutex_unlock(&vblk->vdev_mutex);
927 	return ret;
928 }
929 
930 static void virtblk_free_disk(struct gendisk *disk)
931 {
932 	struct virtio_blk *vblk = disk->private_data;
933 
934 	ida_free(&vd_index_ida, vblk->index);
935 	mutex_destroy(&vblk->vdev_mutex);
936 	kfree(vblk);
937 }
938 
939 static const struct block_device_operations virtblk_fops = {
940 	.owner  	= THIS_MODULE,
941 	.getgeo		= virtblk_getgeo,
942 	.free_disk	= virtblk_free_disk,
943 	.report_zones	= virtblk_report_zones,
944 };
945 
946 static int index_to_minor(int index)
947 {
948 	return index << PART_BITS;
949 }
950 
951 static int minor_to_index(int minor)
952 {
953 	return minor >> PART_BITS;
954 }
955 
956 static ssize_t serial_show(struct device *dev,
957 			   struct device_attribute *attr, char *buf)
958 {
959 	struct gendisk *disk = dev_to_disk(dev);
960 	int err;
961 
962 	/* sysfs gives us a PAGE_SIZE buffer */
963 	BUILD_BUG_ON(PAGE_SIZE < VIRTIO_BLK_ID_BYTES);
964 
965 	buf[VIRTIO_BLK_ID_BYTES] = '\0';
966 	err = virtblk_get_id(disk, buf);
967 	if (!err)
968 		return strlen(buf);
969 
970 	if (err == -EIO) /* Unsupported? Make it empty. */
971 		return 0;
972 
973 	return err;
974 }
975 
976 static DEVICE_ATTR_RO(serial);
977 
978 /* The queue's logical block size must be set before calling this */
979 static void virtblk_update_capacity(struct virtio_blk *vblk, bool resize)
980 {
981 	struct virtio_device *vdev = vblk->vdev;
982 	struct request_queue *q = vblk->disk->queue;
983 	char cap_str_2[10], cap_str_10[10];
984 	unsigned long long nblocks;
985 	u64 capacity;
986 
987 	/* Host must always specify the capacity. */
988 	virtio_cread(vdev, struct virtio_blk_config, capacity, &capacity);
989 
990 	nblocks = DIV_ROUND_UP_ULL(capacity, queue_logical_block_size(q) >> 9);
991 
992 	string_get_size(nblocks, queue_logical_block_size(q),
993 			STRING_UNITS_2, cap_str_2, sizeof(cap_str_2));
994 	string_get_size(nblocks, queue_logical_block_size(q),
995 			STRING_UNITS_10, cap_str_10, sizeof(cap_str_10));
996 
997 	dev_notice(&vdev->dev,
998 		   "[%s] %s%llu %d-byte logical blocks (%s/%s)\n",
999 		   vblk->disk->disk_name,
1000 		   resize ? "new size: " : "",
1001 		   nblocks,
1002 		   queue_logical_block_size(q),
1003 		   cap_str_10,
1004 		   cap_str_2);
1005 
1006 	set_capacity_and_notify(vblk->disk, capacity);
1007 }
1008 
1009 static void virtblk_config_changed_work(struct work_struct *work)
1010 {
1011 	struct virtio_blk *vblk =
1012 		container_of(work, struct virtio_blk, config_work);
1013 
1014 	virtblk_revalidate_zones(vblk);
1015 	virtblk_update_capacity(vblk, true);
1016 }
1017 
1018 static void virtblk_config_changed(struct virtio_device *vdev)
1019 {
1020 	struct virtio_blk *vblk = vdev->priv;
1021 
1022 	queue_work(virtblk_wq, &vblk->config_work);
1023 }
1024 
1025 static int init_vq(struct virtio_blk *vblk)
1026 {
1027 	int err;
1028 	int i;
1029 	vq_callback_t **callbacks;
1030 	const char **names;
1031 	struct virtqueue **vqs;
1032 	unsigned short num_vqs;
1033 	unsigned int num_poll_vqs;
1034 	struct virtio_device *vdev = vblk->vdev;
1035 	struct irq_affinity desc = { 0, };
1036 
1037 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_MQ,
1038 				   struct virtio_blk_config, num_queues,
1039 				   &num_vqs);
1040 	if (err)
1041 		num_vqs = 1;
1042 
1043 	if (!err && !num_vqs) {
1044 		dev_err(&vdev->dev, "MQ advertised but zero queues reported\n");
1045 		return -EINVAL;
1046 	}
1047 
1048 	num_vqs = min_t(unsigned int,
1049 			min_not_zero(num_request_queues, nr_cpu_ids),
1050 			num_vqs);
1051 
1052 	num_poll_vqs = min_t(unsigned int, poll_queues, num_vqs - 1);
1053 
1054 	vblk->io_queues[HCTX_TYPE_DEFAULT] = num_vqs - num_poll_vqs;
1055 	vblk->io_queues[HCTX_TYPE_READ] = 0;
1056 	vblk->io_queues[HCTX_TYPE_POLL] = num_poll_vqs;
1057 
1058 	dev_info(&vdev->dev, "%d/%d/%d default/read/poll queues\n",
1059 				vblk->io_queues[HCTX_TYPE_DEFAULT],
1060 				vblk->io_queues[HCTX_TYPE_READ],
1061 				vblk->io_queues[HCTX_TYPE_POLL]);
1062 
1063 	vblk->vqs = kmalloc_array(num_vqs, sizeof(*vblk->vqs), GFP_KERNEL);
1064 	if (!vblk->vqs)
1065 		return -ENOMEM;
1066 
1067 	names = kmalloc_array(num_vqs, sizeof(*names), GFP_KERNEL);
1068 	callbacks = kmalloc_array(num_vqs, sizeof(*callbacks), GFP_KERNEL);
1069 	vqs = kmalloc_array(num_vqs, sizeof(*vqs), GFP_KERNEL);
1070 	if (!names || !callbacks || !vqs) {
1071 		err = -ENOMEM;
1072 		goto out;
1073 	}
1074 
1075 	for (i = 0; i < num_vqs - num_poll_vqs; i++) {
1076 		callbacks[i] = virtblk_done;
1077 		snprintf(vblk->vqs[i].name, VQ_NAME_LEN, "req.%d", i);
1078 		names[i] = vblk->vqs[i].name;
1079 	}
1080 
1081 	for (; i < num_vqs; i++) {
1082 		callbacks[i] = NULL;
1083 		snprintf(vblk->vqs[i].name, VQ_NAME_LEN, "req_poll.%d", i);
1084 		names[i] = vblk->vqs[i].name;
1085 	}
1086 
1087 	/* Discover virtqueues and write information to configuration.  */
1088 	err = virtio_find_vqs(vdev, num_vqs, vqs, callbacks, names, &desc);
1089 	if (err)
1090 		goto out;
1091 
1092 	for (i = 0; i < num_vqs; i++) {
1093 		spin_lock_init(&vblk->vqs[i].lock);
1094 		vblk->vqs[i].vq = vqs[i];
1095 	}
1096 	vblk->num_vqs = num_vqs;
1097 
1098 out:
1099 	kfree(vqs);
1100 	kfree(callbacks);
1101 	kfree(names);
1102 	if (err)
1103 		kfree(vblk->vqs);
1104 	return err;
1105 }
1106 
1107 /*
1108  * Legacy naming scheme used for virtio devices.  We are stuck with it for
1109  * virtio blk but don't ever use it for any new driver.
1110  */
1111 static int virtblk_name_format(char *prefix, int index, char *buf, int buflen)
1112 {
1113 	const int base = 'z' - 'a' + 1;
1114 	char *begin = buf + strlen(prefix);
1115 	char *end = buf + buflen;
1116 	char *p;
1117 	int unit;
1118 
1119 	p = end - 1;
1120 	*p = '\0';
1121 	unit = base;
1122 	do {
1123 		if (p == begin)
1124 			return -EINVAL;
1125 		*--p = 'a' + (index % unit);
1126 		index = (index / unit) - 1;
1127 	} while (index >= 0);
1128 
1129 	memmove(begin, p, end - p);
1130 	memcpy(buf, prefix, strlen(prefix));
1131 
1132 	return 0;
1133 }
1134 
1135 static int virtblk_get_cache_mode(struct virtio_device *vdev)
1136 {
1137 	u8 writeback;
1138 	int err;
1139 
1140 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE,
1141 				   struct virtio_blk_config, wce,
1142 				   &writeback);
1143 
1144 	/*
1145 	 * If WCE is not configurable and flush is not available,
1146 	 * assume no writeback cache is in use.
1147 	 */
1148 	if (err)
1149 		writeback = virtio_has_feature(vdev, VIRTIO_BLK_F_FLUSH);
1150 
1151 	return writeback;
1152 }
1153 
1154 static void virtblk_update_cache_mode(struct virtio_device *vdev)
1155 {
1156 	u8 writeback = virtblk_get_cache_mode(vdev);
1157 	struct virtio_blk *vblk = vdev->priv;
1158 
1159 	blk_queue_write_cache(vblk->disk->queue, writeback, false);
1160 }
1161 
1162 static const char *const virtblk_cache_types[] = {
1163 	"write through", "write back"
1164 };
1165 
1166 static ssize_t
1167 cache_type_store(struct device *dev, struct device_attribute *attr,
1168 		 const char *buf, size_t count)
1169 {
1170 	struct gendisk *disk = dev_to_disk(dev);
1171 	struct virtio_blk *vblk = disk->private_data;
1172 	struct virtio_device *vdev = vblk->vdev;
1173 	int i;
1174 
1175 	BUG_ON(!virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_CONFIG_WCE));
1176 	i = sysfs_match_string(virtblk_cache_types, buf);
1177 	if (i < 0)
1178 		return i;
1179 
1180 	virtio_cwrite8(vdev, offsetof(struct virtio_blk_config, wce), i);
1181 	virtblk_update_cache_mode(vdev);
1182 	return count;
1183 }
1184 
1185 static ssize_t
1186 cache_type_show(struct device *dev, struct device_attribute *attr, char *buf)
1187 {
1188 	struct gendisk *disk = dev_to_disk(dev);
1189 	struct virtio_blk *vblk = disk->private_data;
1190 	u8 writeback = virtblk_get_cache_mode(vblk->vdev);
1191 
1192 	BUG_ON(writeback >= ARRAY_SIZE(virtblk_cache_types));
1193 	return sysfs_emit(buf, "%s\n", virtblk_cache_types[writeback]);
1194 }
1195 
1196 static DEVICE_ATTR_RW(cache_type);
1197 
1198 static struct attribute *virtblk_attrs[] = {
1199 	&dev_attr_serial.attr,
1200 	&dev_attr_cache_type.attr,
1201 	NULL,
1202 };
1203 
1204 static umode_t virtblk_attrs_are_visible(struct kobject *kobj,
1205 		struct attribute *a, int n)
1206 {
1207 	struct device *dev = kobj_to_dev(kobj);
1208 	struct gendisk *disk = dev_to_disk(dev);
1209 	struct virtio_blk *vblk = disk->private_data;
1210 	struct virtio_device *vdev = vblk->vdev;
1211 
1212 	if (a == &dev_attr_cache_type.attr &&
1213 	    !virtio_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE))
1214 		return S_IRUGO;
1215 
1216 	return a->mode;
1217 }
1218 
1219 static const struct attribute_group virtblk_attr_group = {
1220 	.attrs = virtblk_attrs,
1221 	.is_visible = virtblk_attrs_are_visible,
1222 };
1223 
1224 static const struct attribute_group *virtblk_attr_groups[] = {
1225 	&virtblk_attr_group,
1226 	NULL,
1227 };
1228 
1229 static void virtblk_map_queues(struct blk_mq_tag_set *set)
1230 {
1231 	struct virtio_blk *vblk = set->driver_data;
1232 	int i, qoff;
1233 
1234 	for (i = 0, qoff = 0; i < set->nr_maps; i++) {
1235 		struct blk_mq_queue_map *map = &set->map[i];
1236 
1237 		map->nr_queues = vblk->io_queues[i];
1238 		map->queue_offset = qoff;
1239 		qoff += map->nr_queues;
1240 
1241 		if (map->nr_queues == 0)
1242 			continue;
1243 
1244 		/*
1245 		 * Regular queues have interrupts and hence CPU affinity is
1246 		 * defined by the core virtio code, but polling queues have
1247 		 * no interrupts so we let the block layer assign CPU affinity.
1248 		 */
1249 		if (i == HCTX_TYPE_POLL)
1250 			blk_mq_map_queues(&set->map[i]);
1251 		else
1252 			blk_mq_virtio_map_queues(&set->map[i], vblk->vdev, 0);
1253 	}
1254 }
1255 
1256 static void virtblk_complete_batch(struct io_comp_batch *iob)
1257 {
1258 	struct request *req;
1259 
1260 	rq_list_for_each(&iob->req_list, req) {
1261 		virtblk_unmap_data(req, blk_mq_rq_to_pdu(req));
1262 		virtblk_cleanup_cmd(req);
1263 	}
1264 	blk_mq_end_request_batch(iob);
1265 }
1266 
1267 static int virtblk_poll(struct blk_mq_hw_ctx *hctx, struct io_comp_batch *iob)
1268 {
1269 	struct virtio_blk *vblk = hctx->queue->queuedata;
1270 	struct virtio_blk_vq *vq = get_virtio_blk_vq(hctx);
1271 	struct virtblk_req *vbr;
1272 	unsigned long flags;
1273 	unsigned int len;
1274 	int found = 0;
1275 
1276 	spin_lock_irqsave(&vq->lock, flags);
1277 
1278 	while ((vbr = virtqueue_get_buf(vq->vq, &len)) != NULL) {
1279 		struct request *req = blk_mq_rq_from_pdu(vbr);
1280 
1281 		found++;
1282 		if (!blk_mq_complete_request_remote(req) &&
1283 		    !blk_mq_add_to_batch(req, iob, virtblk_vbr_status(vbr),
1284 						virtblk_complete_batch))
1285 			virtblk_request_done(req);
1286 	}
1287 
1288 	if (found)
1289 		blk_mq_start_stopped_hw_queues(vblk->disk->queue, true);
1290 
1291 	spin_unlock_irqrestore(&vq->lock, flags);
1292 
1293 	return found;
1294 }
1295 
1296 static const struct blk_mq_ops virtio_mq_ops = {
1297 	.queue_rq	= virtio_queue_rq,
1298 	.queue_rqs	= virtio_queue_rqs,
1299 	.commit_rqs	= virtio_commit_rqs,
1300 	.complete	= virtblk_request_done,
1301 	.map_queues	= virtblk_map_queues,
1302 	.poll		= virtblk_poll,
1303 };
1304 
1305 static unsigned int virtblk_queue_depth;
1306 module_param_named(queue_depth, virtblk_queue_depth, uint, 0444);
1307 
1308 static int virtblk_probe(struct virtio_device *vdev)
1309 {
1310 	struct virtio_blk *vblk;
1311 	struct request_queue *q;
1312 	int err, index;
1313 
1314 	u32 v, blk_size, max_size, sg_elems, opt_io_size;
1315 	u32 max_discard_segs = 0;
1316 	u32 discard_granularity = 0;
1317 	u16 min_io_size;
1318 	u8 physical_block_exp, alignment_offset;
1319 	unsigned int queue_depth;
1320 
1321 	if (!vdev->config->get) {
1322 		dev_err(&vdev->dev, "%s failure: config access disabled\n",
1323 			__func__);
1324 		return -EINVAL;
1325 	}
1326 
1327 	err = ida_alloc_range(&vd_index_ida, 0,
1328 			      minor_to_index(1 << MINORBITS) - 1, GFP_KERNEL);
1329 	if (err < 0)
1330 		goto out;
1331 	index = err;
1332 
1333 	/* We need to know how many segments before we allocate. */
1334 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SEG_MAX,
1335 				   struct virtio_blk_config, seg_max,
1336 				   &sg_elems);
1337 
1338 	/* We need at least one SG element, whatever they say. */
1339 	if (err || !sg_elems)
1340 		sg_elems = 1;
1341 
1342 	/* Prevent integer overflows and honor max vq size */
1343 	sg_elems = min_t(u32, sg_elems, VIRTIO_BLK_MAX_SG_ELEMS - 2);
1344 
1345 	vdev->priv = vblk = kmalloc(sizeof(*vblk), GFP_KERNEL);
1346 	if (!vblk) {
1347 		err = -ENOMEM;
1348 		goto out_free_index;
1349 	}
1350 
1351 	mutex_init(&vblk->vdev_mutex);
1352 
1353 	vblk->vdev = vdev;
1354 
1355 	INIT_WORK(&vblk->config_work, virtblk_config_changed_work);
1356 
1357 	err = init_vq(vblk);
1358 	if (err)
1359 		goto out_free_vblk;
1360 
1361 	/* Default queue sizing is to fill the ring. */
1362 	if (!virtblk_queue_depth) {
1363 		queue_depth = vblk->vqs[0].vq->num_free;
1364 		/* ... but without indirect descs, we use 2 descs per req */
1365 		if (!virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC))
1366 			queue_depth /= 2;
1367 	} else {
1368 		queue_depth = virtblk_queue_depth;
1369 	}
1370 
1371 	memset(&vblk->tag_set, 0, sizeof(vblk->tag_set));
1372 	vblk->tag_set.ops = &virtio_mq_ops;
1373 	vblk->tag_set.queue_depth = queue_depth;
1374 	vblk->tag_set.numa_node = NUMA_NO_NODE;
1375 	vblk->tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
1376 	vblk->tag_set.cmd_size =
1377 		sizeof(struct virtblk_req) +
1378 		sizeof(struct scatterlist) * VIRTIO_BLK_INLINE_SG_CNT;
1379 	vblk->tag_set.driver_data = vblk;
1380 	vblk->tag_set.nr_hw_queues = vblk->num_vqs;
1381 	vblk->tag_set.nr_maps = 1;
1382 	if (vblk->io_queues[HCTX_TYPE_POLL])
1383 		vblk->tag_set.nr_maps = 3;
1384 
1385 	err = blk_mq_alloc_tag_set(&vblk->tag_set);
1386 	if (err)
1387 		goto out_free_vq;
1388 
1389 	vblk->disk = blk_mq_alloc_disk(&vblk->tag_set, vblk);
1390 	if (IS_ERR(vblk->disk)) {
1391 		err = PTR_ERR(vblk->disk);
1392 		goto out_free_tags;
1393 	}
1394 	q = vblk->disk->queue;
1395 
1396 	virtblk_name_format("vd", index, vblk->disk->disk_name, DISK_NAME_LEN);
1397 
1398 	vblk->disk->major = major;
1399 	vblk->disk->first_minor = index_to_minor(index);
1400 	vblk->disk->minors = 1 << PART_BITS;
1401 	vblk->disk->private_data = vblk;
1402 	vblk->disk->fops = &virtblk_fops;
1403 	vblk->index = index;
1404 
1405 	/* configure queue flush support */
1406 	virtblk_update_cache_mode(vdev);
1407 
1408 	/* If disk is read-only in the host, the guest should obey */
1409 	if (virtio_has_feature(vdev, VIRTIO_BLK_F_RO))
1410 		set_disk_ro(vblk->disk, 1);
1411 
1412 	/* We can handle whatever the host told us to handle. */
1413 	blk_queue_max_segments(q, sg_elems);
1414 
1415 	/* No real sector limit. */
1416 	blk_queue_max_hw_sectors(q, UINT_MAX);
1417 
1418 	max_size = virtio_max_dma_size(vdev);
1419 
1420 	/* Host can optionally specify maximum segment size and number of
1421 	 * segments. */
1422 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SIZE_MAX,
1423 				   struct virtio_blk_config, size_max, &v);
1424 	if (!err)
1425 		max_size = min(max_size, v);
1426 
1427 	blk_queue_max_segment_size(q, max_size);
1428 
1429 	/* Host can optionally specify the block size of the device */
1430 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_BLK_SIZE,
1431 				   struct virtio_blk_config, blk_size,
1432 				   &blk_size);
1433 	if (!err) {
1434 		err = blk_validate_block_size(blk_size);
1435 		if (err) {
1436 			dev_err(&vdev->dev,
1437 				"virtio_blk: invalid block size: 0x%x\n",
1438 				blk_size);
1439 			goto out_cleanup_disk;
1440 		}
1441 
1442 		blk_queue_logical_block_size(q, blk_size);
1443 	} else
1444 		blk_size = queue_logical_block_size(q);
1445 
1446 	/* Use topology information if available */
1447 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1448 				   struct virtio_blk_config, physical_block_exp,
1449 				   &physical_block_exp);
1450 	if (!err && physical_block_exp)
1451 		blk_queue_physical_block_size(q,
1452 				blk_size * (1 << physical_block_exp));
1453 
1454 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1455 				   struct virtio_blk_config, alignment_offset,
1456 				   &alignment_offset);
1457 	if (!err && alignment_offset)
1458 		blk_queue_alignment_offset(q, blk_size * alignment_offset);
1459 
1460 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1461 				   struct virtio_blk_config, min_io_size,
1462 				   &min_io_size);
1463 	if (!err && min_io_size)
1464 		blk_queue_io_min(q, blk_size * min_io_size);
1465 
1466 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1467 				   struct virtio_blk_config, opt_io_size,
1468 				   &opt_io_size);
1469 	if (!err && opt_io_size)
1470 		blk_queue_io_opt(q, blk_size * opt_io_size);
1471 
1472 	if (virtio_has_feature(vdev, VIRTIO_BLK_F_DISCARD)) {
1473 		virtio_cread(vdev, struct virtio_blk_config,
1474 			     discard_sector_alignment, &discard_granularity);
1475 
1476 		virtio_cread(vdev, struct virtio_blk_config,
1477 			     max_discard_sectors, &v);
1478 		blk_queue_max_discard_sectors(q, v ? v : UINT_MAX);
1479 
1480 		virtio_cread(vdev, struct virtio_blk_config, max_discard_seg,
1481 			     &max_discard_segs);
1482 	}
1483 
1484 	if (virtio_has_feature(vdev, VIRTIO_BLK_F_WRITE_ZEROES)) {
1485 		virtio_cread(vdev, struct virtio_blk_config,
1486 			     max_write_zeroes_sectors, &v);
1487 		blk_queue_max_write_zeroes_sectors(q, v ? v : UINT_MAX);
1488 	}
1489 
1490 	/* The discard and secure erase limits are combined since the Linux
1491 	 * block layer uses the same limit for both commands.
1492 	 *
1493 	 * If both VIRTIO_BLK_F_SECURE_ERASE and VIRTIO_BLK_F_DISCARD features
1494 	 * are negotiated, we will use the minimum between the limits.
1495 	 *
1496 	 * discard sector alignment is set to the minimum between discard_sector_alignment
1497 	 * and secure_erase_sector_alignment.
1498 	 *
1499 	 * max discard sectors is set to the minimum between max_discard_seg and
1500 	 * max_secure_erase_seg.
1501 	 */
1502 	if (virtio_has_feature(vdev, VIRTIO_BLK_F_SECURE_ERASE)) {
1503 
1504 		virtio_cread(vdev, struct virtio_blk_config,
1505 			     secure_erase_sector_alignment, &v);
1506 
1507 		/* secure_erase_sector_alignment should not be zero, the device should set a
1508 		 * valid number of sectors.
1509 		 */
1510 		if (!v) {
1511 			dev_err(&vdev->dev,
1512 				"virtio_blk: secure_erase_sector_alignment can't be 0\n");
1513 			err = -EINVAL;
1514 			goto out_cleanup_disk;
1515 		}
1516 
1517 		discard_granularity = min_not_zero(discard_granularity, v);
1518 
1519 		virtio_cread(vdev, struct virtio_blk_config,
1520 			     max_secure_erase_sectors, &v);
1521 
1522 		/* max_secure_erase_sectors should not be zero, the device should set a
1523 		 * valid number of sectors.
1524 		 */
1525 		if (!v) {
1526 			dev_err(&vdev->dev,
1527 				"virtio_blk: max_secure_erase_sectors can't be 0\n");
1528 			err = -EINVAL;
1529 			goto out_cleanup_disk;
1530 		}
1531 
1532 		blk_queue_max_secure_erase_sectors(q, v);
1533 
1534 		virtio_cread(vdev, struct virtio_blk_config,
1535 			     max_secure_erase_seg, &v);
1536 
1537 		/* max_secure_erase_seg should not be zero, the device should set a
1538 		 * valid number of segments
1539 		 */
1540 		if (!v) {
1541 			dev_err(&vdev->dev,
1542 				"virtio_blk: max_secure_erase_seg can't be 0\n");
1543 			err = -EINVAL;
1544 			goto out_cleanup_disk;
1545 		}
1546 
1547 		max_discard_segs = min_not_zero(max_discard_segs, v);
1548 	}
1549 
1550 	if (virtio_has_feature(vdev, VIRTIO_BLK_F_DISCARD) ||
1551 	    virtio_has_feature(vdev, VIRTIO_BLK_F_SECURE_ERASE)) {
1552 		/* max_discard_seg and discard_granularity will be 0 only
1553 		 * if max_discard_seg and discard_sector_alignment fields in the virtio
1554 		 * config are 0 and VIRTIO_BLK_F_SECURE_ERASE feature is not negotiated.
1555 		 * In this case, we use default values.
1556 		 */
1557 		if (!max_discard_segs)
1558 			max_discard_segs = sg_elems;
1559 
1560 		blk_queue_max_discard_segments(q,
1561 					       min(max_discard_segs, MAX_DISCARD_SEGMENTS));
1562 
1563 		if (discard_granularity)
1564 			q->limits.discard_granularity = discard_granularity << SECTOR_SHIFT;
1565 		else
1566 			q->limits.discard_granularity = blk_size;
1567 	}
1568 
1569 	virtblk_update_capacity(vblk, false);
1570 	virtio_device_ready(vdev);
1571 
1572 	/*
1573 	 * All steps that follow use the VQs therefore they need to be
1574 	 * placed after the virtio_device_ready() call above.
1575 	 */
1576 	if (virtio_has_feature(vdev, VIRTIO_BLK_F_ZONED)) {
1577 		err = virtblk_probe_zoned_device(vdev, vblk, q);
1578 		if (err)
1579 			goto out_cleanup_disk;
1580 	}
1581 
1582 	err = device_add_disk(&vdev->dev, vblk->disk, virtblk_attr_groups);
1583 	if (err)
1584 		goto out_cleanup_disk;
1585 
1586 	return 0;
1587 
1588 out_cleanup_disk:
1589 	put_disk(vblk->disk);
1590 out_free_tags:
1591 	blk_mq_free_tag_set(&vblk->tag_set);
1592 out_free_vq:
1593 	vdev->config->del_vqs(vdev);
1594 	kfree(vblk->vqs);
1595 out_free_vblk:
1596 	kfree(vblk);
1597 out_free_index:
1598 	ida_free(&vd_index_ida, index);
1599 out:
1600 	return err;
1601 }
1602 
1603 static void virtblk_remove(struct virtio_device *vdev)
1604 {
1605 	struct virtio_blk *vblk = vdev->priv;
1606 
1607 	/* Make sure no work handler is accessing the device. */
1608 	flush_work(&vblk->config_work);
1609 
1610 	del_gendisk(vblk->disk);
1611 	blk_mq_free_tag_set(&vblk->tag_set);
1612 
1613 	mutex_lock(&vblk->vdev_mutex);
1614 
1615 	/* Stop all the virtqueues. */
1616 	virtio_reset_device(vdev);
1617 
1618 	/* Virtqueues are stopped, nothing can use vblk->vdev anymore. */
1619 	vblk->vdev = NULL;
1620 
1621 	vdev->config->del_vqs(vdev);
1622 	kfree(vblk->vqs);
1623 
1624 	mutex_unlock(&vblk->vdev_mutex);
1625 
1626 	put_disk(vblk->disk);
1627 }
1628 
1629 #ifdef CONFIG_PM_SLEEP
1630 static int virtblk_freeze(struct virtio_device *vdev)
1631 {
1632 	struct virtio_blk *vblk = vdev->priv;
1633 
1634 	/* Ensure we don't receive any more interrupts */
1635 	virtio_reset_device(vdev);
1636 
1637 	/* Make sure no work handler is accessing the device. */
1638 	flush_work(&vblk->config_work);
1639 
1640 	blk_mq_quiesce_queue(vblk->disk->queue);
1641 
1642 	vdev->config->del_vqs(vdev);
1643 	kfree(vblk->vqs);
1644 
1645 	return 0;
1646 }
1647 
1648 static int virtblk_restore(struct virtio_device *vdev)
1649 {
1650 	struct virtio_blk *vblk = vdev->priv;
1651 	int ret;
1652 
1653 	ret = init_vq(vdev->priv);
1654 	if (ret)
1655 		return ret;
1656 
1657 	virtio_device_ready(vdev);
1658 
1659 	blk_mq_unquiesce_queue(vblk->disk->queue);
1660 	return 0;
1661 }
1662 #endif
1663 
1664 static const struct virtio_device_id id_table[] = {
1665 	{ VIRTIO_ID_BLOCK, VIRTIO_DEV_ANY_ID },
1666 	{ 0 },
1667 };
1668 
1669 static unsigned int features_legacy[] = {
1670 	VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_F_SIZE_MAX, VIRTIO_BLK_F_GEOMETRY,
1671 	VIRTIO_BLK_F_RO, VIRTIO_BLK_F_BLK_SIZE,
1672 	VIRTIO_BLK_F_FLUSH, VIRTIO_BLK_F_TOPOLOGY, VIRTIO_BLK_F_CONFIG_WCE,
1673 	VIRTIO_BLK_F_MQ, VIRTIO_BLK_F_DISCARD, VIRTIO_BLK_F_WRITE_ZEROES,
1674 	VIRTIO_BLK_F_SECURE_ERASE,
1675 }
1676 ;
1677 static unsigned int features[] = {
1678 	VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_F_SIZE_MAX, VIRTIO_BLK_F_GEOMETRY,
1679 	VIRTIO_BLK_F_RO, VIRTIO_BLK_F_BLK_SIZE,
1680 	VIRTIO_BLK_F_FLUSH, VIRTIO_BLK_F_TOPOLOGY, VIRTIO_BLK_F_CONFIG_WCE,
1681 	VIRTIO_BLK_F_MQ, VIRTIO_BLK_F_DISCARD, VIRTIO_BLK_F_WRITE_ZEROES,
1682 	VIRTIO_BLK_F_SECURE_ERASE, VIRTIO_BLK_F_ZONED,
1683 };
1684 
1685 static struct virtio_driver virtio_blk = {
1686 	.feature_table			= features,
1687 	.feature_table_size		= ARRAY_SIZE(features),
1688 	.feature_table_legacy		= features_legacy,
1689 	.feature_table_size_legacy	= ARRAY_SIZE(features_legacy),
1690 	.driver.name			= KBUILD_MODNAME,
1691 	.driver.owner			= THIS_MODULE,
1692 	.id_table			= id_table,
1693 	.probe				= virtblk_probe,
1694 	.remove				= virtblk_remove,
1695 	.config_changed			= virtblk_config_changed,
1696 #ifdef CONFIG_PM_SLEEP
1697 	.freeze				= virtblk_freeze,
1698 	.restore			= virtblk_restore,
1699 #endif
1700 };
1701 
1702 static int __init virtio_blk_init(void)
1703 {
1704 	int error;
1705 
1706 	virtblk_wq = alloc_workqueue("virtio-blk", 0, 0);
1707 	if (!virtblk_wq)
1708 		return -ENOMEM;
1709 
1710 	major = register_blkdev(0, "virtblk");
1711 	if (major < 0) {
1712 		error = major;
1713 		goto out_destroy_workqueue;
1714 	}
1715 
1716 	error = register_virtio_driver(&virtio_blk);
1717 	if (error)
1718 		goto out_unregister_blkdev;
1719 	return 0;
1720 
1721 out_unregister_blkdev:
1722 	unregister_blkdev(major, "virtblk");
1723 out_destroy_workqueue:
1724 	destroy_workqueue(virtblk_wq);
1725 	return error;
1726 }
1727 
1728 static void __exit virtio_blk_fini(void)
1729 {
1730 	unregister_virtio_driver(&virtio_blk);
1731 	unregister_blkdev(major, "virtblk");
1732 	destroy_workqueue(virtblk_wq);
1733 }
1734 module_init(virtio_blk_init);
1735 module_exit(virtio_blk_fini);
1736 
1737 MODULE_DEVICE_TABLE(virtio, id_table);
1738 MODULE_DESCRIPTION("Virtio block driver");
1739 MODULE_LICENSE("GPL");
1740