xref: /linux/drivers/block/virtio_blk.c (revision e7d759f31ca295d589f7420719c311870bb3166f)
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 	} while (!virtqueue_enable_cb(vq));
371 
372 	/* In case queue is stopped waiting for more buffers. */
373 	if (req_done)
374 		blk_mq_start_stopped_hw_queues(vblk->disk->queue, true);
375 	spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
376 }
377 
378 static void virtio_commit_rqs(struct blk_mq_hw_ctx *hctx)
379 {
380 	struct virtio_blk *vblk = hctx->queue->queuedata;
381 	struct virtio_blk_vq *vq = &vblk->vqs[hctx->queue_num];
382 	bool kick;
383 
384 	spin_lock_irq(&vq->lock);
385 	kick = virtqueue_kick_prepare(vq->vq);
386 	spin_unlock_irq(&vq->lock);
387 
388 	if (kick)
389 		virtqueue_notify(vq->vq);
390 }
391 
392 static blk_status_t virtblk_fail_to_queue(struct request *req, int rc)
393 {
394 	virtblk_cleanup_cmd(req);
395 	switch (rc) {
396 	case -ENOSPC:
397 		return BLK_STS_DEV_RESOURCE;
398 	case -ENOMEM:
399 		return BLK_STS_RESOURCE;
400 	default:
401 		return BLK_STS_IOERR;
402 	}
403 }
404 
405 static blk_status_t virtblk_prep_rq(struct blk_mq_hw_ctx *hctx,
406 					struct virtio_blk *vblk,
407 					struct request *req,
408 					struct virtblk_req *vbr)
409 {
410 	blk_status_t status;
411 	int num;
412 
413 	status = virtblk_setup_cmd(vblk->vdev, req, vbr);
414 	if (unlikely(status))
415 		return status;
416 
417 	num = virtblk_map_data(hctx, req, vbr);
418 	if (unlikely(num < 0))
419 		return virtblk_fail_to_queue(req, -ENOMEM);
420 	vbr->sg_table.nents = num;
421 
422 	blk_mq_start_request(req);
423 
424 	return BLK_STS_OK;
425 }
426 
427 static blk_status_t virtio_queue_rq(struct blk_mq_hw_ctx *hctx,
428 			   const struct blk_mq_queue_data *bd)
429 {
430 	struct virtio_blk *vblk = hctx->queue->queuedata;
431 	struct request *req = bd->rq;
432 	struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
433 	unsigned long flags;
434 	int qid = hctx->queue_num;
435 	bool notify = false;
436 	blk_status_t status;
437 	int err;
438 
439 	status = virtblk_prep_rq(hctx, vblk, req, vbr);
440 	if (unlikely(status))
441 		return status;
442 
443 	spin_lock_irqsave(&vblk->vqs[qid].lock, flags);
444 	err = virtblk_add_req(vblk->vqs[qid].vq, vbr);
445 	if (err) {
446 		virtqueue_kick(vblk->vqs[qid].vq);
447 		/* Don't stop the queue if -ENOMEM: we may have failed to
448 		 * bounce the buffer due to global resource outage.
449 		 */
450 		if (err == -ENOSPC)
451 			blk_mq_stop_hw_queue(hctx);
452 		spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
453 		virtblk_unmap_data(req, vbr);
454 		return virtblk_fail_to_queue(req, err);
455 	}
456 
457 	if (bd->last && virtqueue_kick_prepare(vblk->vqs[qid].vq))
458 		notify = true;
459 	spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
460 
461 	if (notify)
462 		virtqueue_notify(vblk->vqs[qid].vq);
463 	return BLK_STS_OK;
464 }
465 
466 static bool virtblk_prep_rq_batch(struct request *req)
467 {
468 	struct virtio_blk *vblk = req->mq_hctx->queue->queuedata;
469 	struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
470 
471 	return virtblk_prep_rq(req->mq_hctx, vblk, req, vbr) == BLK_STS_OK;
472 }
473 
474 static bool virtblk_add_req_batch(struct virtio_blk_vq *vq,
475 					struct request **rqlist)
476 {
477 	unsigned long flags;
478 	int err;
479 	bool kick;
480 
481 	spin_lock_irqsave(&vq->lock, flags);
482 
483 	while (!rq_list_empty(*rqlist)) {
484 		struct request *req = rq_list_pop(rqlist);
485 		struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
486 
487 		err = virtblk_add_req(vq->vq, vbr);
488 		if (err) {
489 			virtblk_unmap_data(req, vbr);
490 			virtblk_cleanup_cmd(req);
491 			blk_mq_requeue_request(req, true);
492 		}
493 	}
494 
495 	kick = virtqueue_kick_prepare(vq->vq);
496 	spin_unlock_irqrestore(&vq->lock, flags);
497 
498 	return kick;
499 }
500 
501 static void virtio_queue_rqs(struct request **rqlist)
502 {
503 	struct request *req, *next, *prev = NULL;
504 	struct request *requeue_list = NULL;
505 
506 	rq_list_for_each_safe(rqlist, req, next) {
507 		struct virtio_blk_vq *vq = get_virtio_blk_vq(req->mq_hctx);
508 		bool kick;
509 
510 		if (!virtblk_prep_rq_batch(req)) {
511 			rq_list_move(rqlist, &requeue_list, req, prev);
512 			req = prev;
513 			if (!req)
514 				continue;
515 		}
516 
517 		if (!next || req->mq_hctx != next->mq_hctx) {
518 			req->rq_next = NULL;
519 			kick = virtblk_add_req_batch(vq, rqlist);
520 			if (kick)
521 				virtqueue_notify(vq->vq);
522 
523 			*rqlist = next;
524 			prev = NULL;
525 		} else
526 			prev = req;
527 	}
528 
529 	*rqlist = requeue_list;
530 }
531 
532 #ifdef CONFIG_BLK_DEV_ZONED
533 static void *virtblk_alloc_report_buffer(struct virtio_blk *vblk,
534 					  unsigned int nr_zones,
535 					  size_t *buflen)
536 {
537 	struct request_queue *q = vblk->disk->queue;
538 	size_t bufsize;
539 	void *buf;
540 
541 	nr_zones = min_t(unsigned int, nr_zones,
542 			 get_capacity(vblk->disk) >> ilog2(vblk->zone_sectors));
543 
544 	bufsize = sizeof(struct virtio_blk_zone_report) +
545 		nr_zones * sizeof(struct virtio_blk_zone_descriptor);
546 	bufsize = min_t(size_t, bufsize,
547 			queue_max_hw_sectors(q) << SECTOR_SHIFT);
548 	bufsize = min_t(size_t, bufsize, queue_max_segments(q) << PAGE_SHIFT);
549 
550 	while (bufsize >= sizeof(struct virtio_blk_zone_report)) {
551 		buf = __vmalloc(bufsize, GFP_KERNEL | __GFP_NORETRY);
552 		if (buf) {
553 			*buflen = bufsize;
554 			return buf;
555 		}
556 		bufsize >>= 1;
557 	}
558 
559 	return NULL;
560 }
561 
562 static int virtblk_submit_zone_report(struct virtio_blk *vblk,
563 				       char *report_buf, size_t report_len,
564 				       sector_t sector)
565 {
566 	struct request_queue *q = vblk->disk->queue;
567 	struct request *req;
568 	struct virtblk_req *vbr;
569 	int err;
570 
571 	req = blk_mq_alloc_request(q, REQ_OP_DRV_IN, 0);
572 	if (IS_ERR(req))
573 		return PTR_ERR(req);
574 
575 	vbr = blk_mq_rq_to_pdu(req);
576 	vbr->in_hdr_len = sizeof(vbr->in_hdr.status);
577 	vbr->out_hdr.type = cpu_to_virtio32(vblk->vdev, VIRTIO_BLK_T_ZONE_REPORT);
578 	vbr->out_hdr.sector = cpu_to_virtio64(vblk->vdev, sector);
579 
580 	err = blk_rq_map_kern(q, req, report_buf, report_len, GFP_KERNEL);
581 	if (err)
582 		goto out;
583 
584 	blk_execute_rq(req, false);
585 	err = blk_status_to_errno(virtblk_result(vbr->in_hdr.status));
586 out:
587 	blk_mq_free_request(req);
588 	return err;
589 }
590 
591 static int virtblk_parse_zone(struct virtio_blk *vblk,
592 			       struct virtio_blk_zone_descriptor *entry,
593 			       unsigned int idx, report_zones_cb cb, void *data)
594 {
595 	struct blk_zone zone = { };
596 
597 	zone.start = virtio64_to_cpu(vblk->vdev, entry->z_start);
598 	if (zone.start + vblk->zone_sectors <= get_capacity(vblk->disk))
599 		zone.len = vblk->zone_sectors;
600 	else
601 		zone.len = get_capacity(vblk->disk) - zone.start;
602 	zone.capacity = virtio64_to_cpu(vblk->vdev, entry->z_cap);
603 	zone.wp = virtio64_to_cpu(vblk->vdev, entry->z_wp);
604 
605 	switch (entry->z_type) {
606 	case VIRTIO_BLK_ZT_SWR:
607 		zone.type = BLK_ZONE_TYPE_SEQWRITE_REQ;
608 		break;
609 	case VIRTIO_BLK_ZT_SWP:
610 		zone.type = BLK_ZONE_TYPE_SEQWRITE_PREF;
611 		break;
612 	case VIRTIO_BLK_ZT_CONV:
613 		zone.type = BLK_ZONE_TYPE_CONVENTIONAL;
614 		break;
615 	default:
616 		dev_err(&vblk->vdev->dev, "zone %llu: invalid type %#x\n",
617 			zone.start, entry->z_type);
618 		return -EIO;
619 	}
620 
621 	switch (entry->z_state) {
622 	case VIRTIO_BLK_ZS_EMPTY:
623 		zone.cond = BLK_ZONE_COND_EMPTY;
624 		break;
625 	case VIRTIO_BLK_ZS_CLOSED:
626 		zone.cond = BLK_ZONE_COND_CLOSED;
627 		break;
628 	case VIRTIO_BLK_ZS_FULL:
629 		zone.cond = BLK_ZONE_COND_FULL;
630 		zone.wp = zone.start + zone.len;
631 		break;
632 	case VIRTIO_BLK_ZS_EOPEN:
633 		zone.cond = BLK_ZONE_COND_EXP_OPEN;
634 		break;
635 	case VIRTIO_BLK_ZS_IOPEN:
636 		zone.cond = BLK_ZONE_COND_IMP_OPEN;
637 		break;
638 	case VIRTIO_BLK_ZS_NOT_WP:
639 		zone.cond = BLK_ZONE_COND_NOT_WP;
640 		break;
641 	case VIRTIO_BLK_ZS_RDONLY:
642 		zone.cond = BLK_ZONE_COND_READONLY;
643 		zone.wp = ULONG_MAX;
644 		break;
645 	case VIRTIO_BLK_ZS_OFFLINE:
646 		zone.cond = BLK_ZONE_COND_OFFLINE;
647 		zone.wp = ULONG_MAX;
648 		break;
649 	default:
650 		dev_err(&vblk->vdev->dev, "zone %llu: invalid condition %#x\n",
651 			zone.start, entry->z_state);
652 		return -EIO;
653 	}
654 
655 	/*
656 	 * The callback below checks the validity of the reported
657 	 * entry data, no need to further validate it here.
658 	 */
659 	return cb(&zone, idx, data);
660 }
661 
662 static int virtblk_report_zones(struct gendisk *disk, sector_t sector,
663 				 unsigned int nr_zones, report_zones_cb cb,
664 				 void *data)
665 {
666 	struct virtio_blk *vblk = disk->private_data;
667 	struct virtio_blk_zone_report *report;
668 	unsigned long long nz, i;
669 	size_t buflen;
670 	unsigned int zone_idx = 0;
671 	int ret;
672 
673 	if (WARN_ON_ONCE(!vblk->zone_sectors))
674 		return -EOPNOTSUPP;
675 
676 	report = virtblk_alloc_report_buffer(vblk, nr_zones, &buflen);
677 	if (!report)
678 		return -ENOMEM;
679 
680 	mutex_lock(&vblk->vdev_mutex);
681 
682 	if (!vblk->vdev) {
683 		ret = -ENXIO;
684 		goto fail_report;
685 	}
686 
687 	while (zone_idx < nr_zones && sector < get_capacity(vblk->disk)) {
688 		memset(report, 0, buflen);
689 
690 		ret = virtblk_submit_zone_report(vblk, (char *)report,
691 						 buflen, sector);
692 		if (ret)
693 			goto fail_report;
694 
695 		nz = min_t(u64, virtio64_to_cpu(vblk->vdev, report->nr_zones),
696 			   nr_zones);
697 		if (!nz)
698 			break;
699 
700 		for (i = 0; i < nz && zone_idx < nr_zones; i++) {
701 			ret = virtblk_parse_zone(vblk, &report->zones[i],
702 						 zone_idx, cb, data);
703 			if (ret)
704 				goto fail_report;
705 
706 			sector = virtio64_to_cpu(vblk->vdev,
707 						 report->zones[i].z_start) +
708 				 vblk->zone_sectors;
709 			zone_idx++;
710 		}
711 	}
712 
713 	if (zone_idx > 0)
714 		ret = zone_idx;
715 	else
716 		ret = -EINVAL;
717 fail_report:
718 	mutex_unlock(&vblk->vdev_mutex);
719 	kvfree(report);
720 	return ret;
721 }
722 
723 static int virtblk_probe_zoned_device(struct virtio_device *vdev,
724 				       struct virtio_blk *vblk,
725 				       struct request_queue *q)
726 {
727 	u32 v, wg;
728 
729 	dev_dbg(&vdev->dev, "probing host-managed zoned device\n");
730 
731 	disk_set_zoned(vblk->disk);
732 	blk_queue_flag_set(QUEUE_FLAG_ZONE_RESETALL, q);
733 
734 	virtio_cread(vdev, struct virtio_blk_config,
735 		     zoned.max_open_zones, &v);
736 	disk_set_max_open_zones(vblk->disk, v);
737 	dev_dbg(&vdev->dev, "max open zones = %u\n", v);
738 
739 	virtio_cread(vdev, struct virtio_blk_config,
740 		     zoned.max_active_zones, &v);
741 	disk_set_max_active_zones(vblk->disk, v);
742 	dev_dbg(&vdev->dev, "max active zones = %u\n", v);
743 
744 	virtio_cread(vdev, struct virtio_blk_config,
745 		     zoned.write_granularity, &wg);
746 	if (!wg) {
747 		dev_warn(&vdev->dev, "zero write granularity reported\n");
748 		return -ENODEV;
749 	}
750 	blk_queue_physical_block_size(q, wg);
751 	blk_queue_io_min(q, wg);
752 
753 	dev_dbg(&vdev->dev, "write granularity = %u\n", wg);
754 
755 	/*
756 	 * virtio ZBD specification doesn't require zones to be a power of
757 	 * two sectors in size, but the code in this driver expects that.
758 	 */
759 	virtio_cread(vdev, struct virtio_blk_config, zoned.zone_sectors,
760 		     &vblk->zone_sectors);
761 	if (vblk->zone_sectors == 0 || !is_power_of_2(vblk->zone_sectors)) {
762 		dev_err(&vdev->dev,
763 			"zoned device with non power of two zone size %u\n",
764 			vblk->zone_sectors);
765 		return -ENODEV;
766 	}
767 	blk_queue_chunk_sectors(q, vblk->zone_sectors);
768 	dev_dbg(&vdev->dev, "zone sectors = %u\n", vblk->zone_sectors);
769 
770 	if (virtio_has_feature(vdev, VIRTIO_BLK_F_DISCARD)) {
771 		dev_warn(&vblk->vdev->dev,
772 			 "ignoring negotiated F_DISCARD for zoned device\n");
773 		blk_queue_max_discard_sectors(q, 0);
774 	}
775 
776 	virtio_cread(vdev, struct virtio_blk_config,
777 		     zoned.max_append_sectors, &v);
778 	if (!v) {
779 		dev_warn(&vdev->dev, "zero max_append_sectors reported\n");
780 		return -ENODEV;
781 	}
782 	if ((v << SECTOR_SHIFT) < wg) {
783 		dev_err(&vdev->dev,
784 			"write granularity %u exceeds max_append_sectors %u limit\n",
785 			wg, v);
786 		return -ENODEV;
787 	}
788 	blk_queue_max_zone_append_sectors(q, v);
789 	dev_dbg(&vdev->dev, "max append sectors = %u\n", v);
790 
791 	return blk_revalidate_disk_zones(vblk->disk, NULL);
792 }
793 
794 #else
795 
796 /*
797  * Zoned block device support is not configured in this kernel.
798  * Host-managed zoned devices can't be supported, but others are
799  * good to go as regular block devices.
800  */
801 #define virtblk_report_zones       NULL
802 
803 static inline int virtblk_probe_zoned_device(struct virtio_device *vdev,
804 			struct virtio_blk *vblk, struct request_queue *q)
805 {
806 	dev_err(&vdev->dev,
807 		"virtio_blk: zoned devices are not supported");
808 	return -EOPNOTSUPP;
809 }
810 #endif /* CONFIG_BLK_DEV_ZONED */
811 
812 /* return id (s/n) string for *disk to *id_str
813  */
814 static int virtblk_get_id(struct gendisk *disk, char *id_str)
815 {
816 	struct virtio_blk *vblk = disk->private_data;
817 	struct request_queue *q = vblk->disk->queue;
818 	struct request *req;
819 	struct virtblk_req *vbr;
820 	int err;
821 
822 	req = blk_mq_alloc_request(q, REQ_OP_DRV_IN, 0);
823 	if (IS_ERR(req))
824 		return PTR_ERR(req);
825 
826 	vbr = blk_mq_rq_to_pdu(req);
827 	vbr->in_hdr_len = sizeof(vbr->in_hdr.status);
828 	vbr->out_hdr.type = cpu_to_virtio32(vblk->vdev, VIRTIO_BLK_T_GET_ID);
829 	vbr->out_hdr.sector = 0;
830 
831 	err = blk_rq_map_kern(q, req, id_str, VIRTIO_BLK_ID_BYTES, GFP_KERNEL);
832 	if (err)
833 		goto out;
834 
835 	blk_execute_rq(req, false);
836 	err = blk_status_to_errno(virtblk_result(vbr->in_hdr.status));
837 out:
838 	blk_mq_free_request(req);
839 	return err;
840 }
841 
842 /* We provide getgeo only to please some old bootloader/partitioning tools */
843 static int virtblk_getgeo(struct block_device *bd, struct hd_geometry *geo)
844 {
845 	struct virtio_blk *vblk = bd->bd_disk->private_data;
846 	int ret = 0;
847 
848 	mutex_lock(&vblk->vdev_mutex);
849 
850 	if (!vblk->vdev) {
851 		ret = -ENXIO;
852 		goto out;
853 	}
854 
855 	/* see if the host passed in geometry config */
856 	if (virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_GEOMETRY)) {
857 		virtio_cread(vblk->vdev, struct virtio_blk_config,
858 			     geometry.cylinders, &geo->cylinders);
859 		virtio_cread(vblk->vdev, struct virtio_blk_config,
860 			     geometry.heads, &geo->heads);
861 		virtio_cread(vblk->vdev, struct virtio_blk_config,
862 			     geometry.sectors, &geo->sectors);
863 	} else {
864 		/* some standard values, similar to sd */
865 		geo->heads = 1 << 6;
866 		geo->sectors = 1 << 5;
867 		geo->cylinders = get_capacity(bd->bd_disk) >> 11;
868 	}
869 out:
870 	mutex_unlock(&vblk->vdev_mutex);
871 	return ret;
872 }
873 
874 static void virtblk_free_disk(struct gendisk *disk)
875 {
876 	struct virtio_blk *vblk = disk->private_data;
877 
878 	ida_free(&vd_index_ida, vblk->index);
879 	mutex_destroy(&vblk->vdev_mutex);
880 	kfree(vblk);
881 }
882 
883 static const struct block_device_operations virtblk_fops = {
884 	.owner  	= THIS_MODULE,
885 	.getgeo		= virtblk_getgeo,
886 	.free_disk	= virtblk_free_disk,
887 	.report_zones	= virtblk_report_zones,
888 };
889 
890 static int index_to_minor(int index)
891 {
892 	return index << PART_BITS;
893 }
894 
895 static int minor_to_index(int minor)
896 {
897 	return minor >> PART_BITS;
898 }
899 
900 static ssize_t serial_show(struct device *dev,
901 			   struct device_attribute *attr, char *buf)
902 {
903 	struct gendisk *disk = dev_to_disk(dev);
904 	int err;
905 
906 	/* sysfs gives us a PAGE_SIZE buffer */
907 	BUILD_BUG_ON(PAGE_SIZE < VIRTIO_BLK_ID_BYTES);
908 
909 	buf[VIRTIO_BLK_ID_BYTES] = '\0';
910 	err = virtblk_get_id(disk, buf);
911 	if (!err)
912 		return strlen(buf);
913 
914 	if (err == -EIO) /* Unsupported? Make it empty. */
915 		return 0;
916 
917 	return err;
918 }
919 
920 static DEVICE_ATTR_RO(serial);
921 
922 /* The queue's logical block size must be set before calling this */
923 static void virtblk_update_capacity(struct virtio_blk *vblk, bool resize)
924 {
925 	struct virtio_device *vdev = vblk->vdev;
926 	struct request_queue *q = vblk->disk->queue;
927 	char cap_str_2[10], cap_str_10[10];
928 	unsigned long long nblocks;
929 	u64 capacity;
930 
931 	/* Host must always specify the capacity. */
932 	virtio_cread(vdev, struct virtio_blk_config, capacity, &capacity);
933 
934 	nblocks = DIV_ROUND_UP_ULL(capacity, queue_logical_block_size(q) >> 9);
935 
936 	string_get_size(nblocks, queue_logical_block_size(q),
937 			STRING_UNITS_2, cap_str_2, sizeof(cap_str_2));
938 	string_get_size(nblocks, queue_logical_block_size(q),
939 			STRING_UNITS_10, cap_str_10, sizeof(cap_str_10));
940 
941 	dev_notice(&vdev->dev,
942 		   "[%s] %s%llu %d-byte logical blocks (%s/%s)\n",
943 		   vblk->disk->disk_name,
944 		   resize ? "new size: " : "",
945 		   nblocks,
946 		   queue_logical_block_size(q),
947 		   cap_str_10,
948 		   cap_str_2);
949 
950 	set_capacity_and_notify(vblk->disk, capacity);
951 }
952 
953 static void virtblk_config_changed_work(struct work_struct *work)
954 {
955 	struct virtio_blk *vblk =
956 		container_of(work, struct virtio_blk, config_work);
957 
958 	virtblk_update_capacity(vblk, true);
959 }
960 
961 static void virtblk_config_changed(struct virtio_device *vdev)
962 {
963 	struct virtio_blk *vblk = vdev->priv;
964 
965 	queue_work(virtblk_wq, &vblk->config_work);
966 }
967 
968 static int init_vq(struct virtio_blk *vblk)
969 {
970 	int err;
971 	unsigned short i;
972 	vq_callback_t **callbacks;
973 	const char **names;
974 	struct virtqueue **vqs;
975 	unsigned short num_vqs;
976 	unsigned short num_poll_vqs;
977 	struct virtio_device *vdev = vblk->vdev;
978 	struct irq_affinity desc = { 0, };
979 
980 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_MQ,
981 				   struct virtio_blk_config, num_queues,
982 				   &num_vqs);
983 	if (err)
984 		num_vqs = 1;
985 
986 	if (!err && !num_vqs) {
987 		dev_err(&vdev->dev, "MQ advertised but zero queues reported\n");
988 		return -EINVAL;
989 	}
990 
991 	num_vqs = min_t(unsigned int,
992 			min_not_zero(num_request_queues, nr_cpu_ids),
993 			num_vqs);
994 
995 	num_poll_vqs = min_t(unsigned int, poll_queues, num_vqs - 1);
996 
997 	vblk->io_queues[HCTX_TYPE_DEFAULT] = num_vqs - num_poll_vqs;
998 	vblk->io_queues[HCTX_TYPE_READ] = 0;
999 	vblk->io_queues[HCTX_TYPE_POLL] = num_poll_vqs;
1000 
1001 	dev_info(&vdev->dev, "%d/%d/%d default/read/poll queues\n",
1002 				vblk->io_queues[HCTX_TYPE_DEFAULT],
1003 				vblk->io_queues[HCTX_TYPE_READ],
1004 				vblk->io_queues[HCTX_TYPE_POLL]);
1005 
1006 	vblk->vqs = kmalloc_array(num_vqs, sizeof(*vblk->vqs), GFP_KERNEL);
1007 	if (!vblk->vqs)
1008 		return -ENOMEM;
1009 
1010 	names = kmalloc_array(num_vqs, sizeof(*names), GFP_KERNEL);
1011 	callbacks = kmalloc_array(num_vqs, sizeof(*callbacks), GFP_KERNEL);
1012 	vqs = kmalloc_array(num_vqs, sizeof(*vqs), GFP_KERNEL);
1013 	if (!names || !callbacks || !vqs) {
1014 		err = -ENOMEM;
1015 		goto out;
1016 	}
1017 
1018 	for (i = 0; i < num_vqs - num_poll_vqs; i++) {
1019 		callbacks[i] = virtblk_done;
1020 		snprintf(vblk->vqs[i].name, VQ_NAME_LEN, "req.%u", i);
1021 		names[i] = vblk->vqs[i].name;
1022 	}
1023 
1024 	for (; i < num_vqs; i++) {
1025 		callbacks[i] = NULL;
1026 		snprintf(vblk->vqs[i].name, VQ_NAME_LEN, "req_poll.%u", i);
1027 		names[i] = vblk->vqs[i].name;
1028 	}
1029 
1030 	/* Discover virtqueues and write information to configuration.  */
1031 	err = virtio_find_vqs(vdev, num_vqs, vqs, callbacks, names, &desc);
1032 	if (err)
1033 		goto out;
1034 
1035 	for (i = 0; i < num_vqs; i++) {
1036 		spin_lock_init(&vblk->vqs[i].lock);
1037 		vblk->vqs[i].vq = vqs[i];
1038 	}
1039 	vblk->num_vqs = num_vqs;
1040 
1041 out:
1042 	kfree(vqs);
1043 	kfree(callbacks);
1044 	kfree(names);
1045 	if (err)
1046 		kfree(vblk->vqs);
1047 	return err;
1048 }
1049 
1050 /*
1051  * Legacy naming scheme used for virtio devices.  We are stuck with it for
1052  * virtio blk but don't ever use it for any new driver.
1053  */
1054 static int virtblk_name_format(char *prefix, int index, char *buf, int buflen)
1055 {
1056 	const int base = 'z' - 'a' + 1;
1057 	char *begin = buf + strlen(prefix);
1058 	char *end = buf + buflen;
1059 	char *p;
1060 	int unit;
1061 
1062 	p = end - 1;
1063 	*p = '\0';
1064 	unit = base;
1065 	do {
1066 		if (p == begin)
1067 			return -EINVAL;
1068 		*--p = 'a' + (index % unit);
1069 		index = (index / unit) - 1;
1070 	} while (index >= 0);
1071 
1072 	memmove(begin, p, end - p);
1073 	memcpy(buf, prefix, strlen(prefix));
1074 
1075 	return 0;
1076 }
1077 
1078 static int virtblk_get_cache_mode(struct virtio_device *vdev)
1079 {
1080 	u8 writeback;
1081 	int err;
1082 
1083 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE,
1084 				   struct virtio_blk_config, wce,
1085 				   &writeback);
1086 
1087 	/*
1088 	 * If WCE is not configurable and flush is not available,
1089 	 * assume no writeback cache is in use.
1090 	 */
1091 	if (err)
1092 		writeback = virtio_has_feature(vdev, VIRTIO_BLK_F_FLUSH);
1093 
1094 	return writeback;
1095 }
1096 
1097 static void virtblk_update_cache_mode(struct virtio_device *vdev)
1098 {
1099 	u8 writeback = virtblk_get_cache_mode(vdev);
1100 	struct virtio_blk *vblk = vdev->priv;
1101 
1102 	blk_queue_write_cache(vblk->disk->queue, writeback, false);
1103 }
1104 
1105 static const char *const virtblk_cache_types[] = {
1106 	"write through", "write back"
1107 };
1108 
1109 static ssize_t
1110 cache_type_store(struct device *dev, struct device_attribute *attr,
1111 		 const char *buf, size_t count)
1112 {
1113 	struct gendisk *disk = dev_to_disk(dev);
1114 	struct virtio_blk *vblk = disk->private_data;
1115 	struct virtio_device *vdev = vblk->vdev;
1116 	int i;
1117 
1118 	BUG_ON(!virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_CONFIG_WCE));
1119 	i = sysfs_match_string(virtblk_cache_types, buf);
1120 	if (i < 0)
1121 		return i;
1122 
1123 	virtio_cwrite8(vdev, offsetof(struct virtio_blk_config, wce), i);
1124 	virtblk_update_cache_mode(vdev);
1125 	return count;
1126 }
1127 
1128 static ssize_t
1129 cache_type_show(struct device *dev, struct device_attribute *attr, char *buf)
1130 {
1131 	struct gendisk *disk = dev_to_disk(dev);
1132 	struct virtio_blk *vblk = disk->private_data;
1133 	u8 writeback = virtblk_get_cache_mode(vblk->vdev);
1134 
1135 	BUG_ON(writeback >= ARRAY_SIZE(virtblk_cache_types));
1136 	return sysfs_emit(buf, "%s\n", virtblk_cache_types[writeback]);
1137 }
1138 
1139 static DEVICE_ATTR_RW(cache_type);
1140 
1141 static struct attribute *virtblk_attrs[] = {
1142 	&dev_attr_serial.attr,
1143 	&dev_attr_cache_type.attr,
1144 	NULL,
1145 };
1146 
1147 static umode_t virtblk_attrs_are_visible(struct kobject *kobj,
1148 		struct attribute *a, int n)
1149 {
1150 	struct device *dev = kobj_to_dev(kobj);
1151 	struct gendisk *disk = dev_to_disk(dev);
1152 	struct virtio_blk *vblk = disk->private_data;
1153 	struct virtio_device *vdev = vblk->vdev;
1154 
1155 	if (a == &dev_attr_cache_type.attr &&
1156 	    !virtio_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE))
1157 		return S_IRUGO;
1158 
1159 	return a->mode;
1160 }
1161 
1162 static const struct attribute_group virtblk_attr_group = {
1163 	.attrs = virtblk_attrs,
1164 	.is_visible = virtblk_attrs_are_visible,
1165 };
1166 
1167 static const struct attribute_group *virtblk_attr_groups[] = {
1168 	&virtblk_attr_group,
1169 	NULL,
1170 };
1171 
1172 static void virtblk_map_queues(struct blk_mq_tag_set *set)
1173 {
1174 	struct virtio_blk *vblk = set->driver_data;
1175 	int i, qoff;
1176 
1177 	for (i = 0, qoff = 0; i < set->nr_maps; i++) {
1178 		struct blk_mq_queue_map *map = &set->map[i];
1179 
1180 		map->nr_queues = vblk->io_queues[i];
1181 		map->queue_offset = qoff;
1182 		qoff += map->nr_queues;
1183 
1184 		if (map->nr_queues == 0)
1185 			continue;
1186 
1187 		/*
1188 		 * Regular queues have interrupts and hence CPU affinity is
1189 		 * defined by the core virtio code, but polling queues have
1190 		 * no interrupts so we let the block layer assign CPU affinity.
1191 		 */
1192 		if (i == HCTX_TYPE_POLL)
1193 			blk_mq_map_queues(&set->map[i]);
1194 		else
1195 			blk_mq_virtio_map_queues(&set->map[i], vblk->vdev, 0);
1196 	}
1197 }
1198 
1199 static void virtblk_complete_batch(struct io_comp_batch *iob)
1200 {
1201 	struct request *req;
1202 
1203 	rq_list_for_each(&iob->req_list, req) {
1204 		virtblk_unmap_data(req, blk_mq_rq_to_pdu(req));
1205 		virtblk_cleanup_cmd(req);
1206 	}
1207 	blk_mq_end_request_batch(iob);
1208 }
1209 
1210 static int virtblk_poll(struct blk_mq_hw_ctx *hctx, struct io_comp_batch *iob)
1211 {
1212 	struct virtio_blk *vblk = hctx->queue->queuedata;
1213 	struct virtio_blk_vq *vq = get_virtio_blk_vq(hctx);
1214 	struct virtblk_req *vbr;
1215 	unsigned long flags;
1216 	unsigned int len;
1217 	int found = 0;
1218 
1219 	spin_lock_irqsave(&vq->lock, flags);
1220 
1221 	while ((vbr = virtqueue_get_buf(vq->vq, &len)) != NULL) {
1222 		struct request *req = blk_mq_rq_from_pdu(vbr);
1223 
1224 		found++;
1225 		if (!blk_mq_complete_request_remote(req) &&
1226 		    !blk_mq_add_to_batch(req, iob, virtblk_vbr_status(vbr),
1227 						virtblk_complete_batch))
1228 			virtblk_request_done(req);
1229 	}
1230 
1231 	if (found)
1232 		blk_mq_start_stopped_hw_queues(vblk->disk->queue, true);
1233 
1234 	spin_unlock_irqrestore(&vq->lock, flags);
1235 
1236 	return found;
1237 }
1238 
1239 static const struct blk_mq_ops virtio_mq_ops = {
1240 	.queue_rq	= virtio_queue_rq,
1241 	.queue_rqs	= virtio_queue_rqs,
1242 	.commit_rqs	= virtio_commit_rqs,
1243 	.complete	= virtblk_request_done,
1244 	.map_queues	= virtblk_map_queues,
1245 	.poll		= virtblk_poll,
1246 };
1247 
1248 static unsigned int virtblk_queue_depth;
1249 module_param_named(queue_depth, virtblk_queue_depth, uint, 0444);
1250 
1251 static int virtblk_probe(struct virtio_device *vdev)
1252 {
1253 	struct virtio_blk *vblk;
1254 	struct request_queue *q;
1255 	int err, index;
1256 
1257 	u32 v, blk_size, max_size, sg_elems, opt_io_size;
1258 	u32 max_discard_segs = 0;
1259 	u32 discard_granularity = 0;
1260 	u16 min_io_size;
1261 	u8 physical_block_exp, alignment_offset;
1262 	unsigned int queue_depth;
1263 	size_t max_dma_size;
1264 
1265 	if (!vdev->config->get) {
1266 		dev_err(&vdev->dev, "%s failure: config access disabled\n",
1267 			__func__);
1268 		return -EINVAL;
1269 	}
1270 
1271 	err = ida_alloc_range(&vd_index_ida, 0,
1272 			      minor_to_index(1 << MINORBITS) - 1, GFP_KERNEL);
1273 	if (err < 0)
1274 		goto out;
1275 	index = err;
1276 
1277 	/* We need to know how many segments before we allocate. */
1278 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SEG_MAX,
1279 				   struct virtio_blk_config, seg_max,
1280 				   &sg_elems);
1281 
1282 	/* We need at least one SG element, whatever they say. */
1283 	if (err || !sg_elems)
1284 		sg_elems = 1;
1285 
1286 	/* Prevent integer overflows and honor max vq size */
1287 	sg_elems = min_t(u32, sg_elems, VIRTIO_BLK_MAX_SG_ELEMS - 2);
1288 
1289 	vdev->priv = vblk = kmalloc(sizeof(*vblk), GFP_KERNEL);
1290 	if (!vblk) {
1291 		err = -ENOMEM;
1292 		goto out_free_index;
1293 	}
1294 
1295 	mutex_init(&vblk->vdev_mutex);
1296 
1297 	vblk->vdev = vdev;
1298 
1299 	INIT_WORK(&vblk->config_work, virtblk_config_changed_work);
1300 
1301 	err = init_vq(vblk);
1302 	if (err)
1303 		goto out_free_vblk;
1304 
1305 	/* Default queue sizing is to fill the ring. */
1306 	if (!virtblk_queue_depth) {
1307 		queue_depth = vblk->vqs[0].vq->num_free;
1308 		/* ... but without indirect descs, we use 2 descs per req */
1309 		if (!virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC))
1310 			queue_depth /= 2;
1311 	} else {
1312 		queue_depth = virtblk_queue_depth;
1313 	}
1314 
1315 	memset(&vblk->tag_set, 0, sizeof(vblk->tag_set));
1316 	vblk->tag_set.ops = &virtio_mq_ops;
1317 	vblk->tag_set.queue_depth = queue_depth;
1318 	vblk->tag_set.numa_node = NUMA_NO_NODE;
1319 	vblk->tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
1320 	vblk->tag_set.cmd_size =
1321 		sizeof(struct virtblk_req) +
1322 		sizeof(struct scatterlist) * VIRTIO_BLK_INLINE_SG_CNT;
1323 	vblk->tag_set.driver_data = vblk;
1324 	vblk->tag_set.nr_hw_queues = vblk->num_vqs;
1325 	vblk->tag_set.nr_maps = 1;
1326 	if (vblk->io_queues[HCTX_TYPE_POLL])
1327 		vblk->tag_set.nr_maps = 3;
1328 
1329 	err = blk_mq_alloc_tag_set(&vblk->tag_set);
1330 	if (err)
1331 		goto out_free_vq;
1332 
1333 	vblk->disk = blk_mq_alloc_disk(&vblk->tag_set, vblk);
1334 	if (IS_ERR(vblk->disk)) {
1335 		err = PTR_ERR(vblk->disk);
1336 		goto out_free_tags;
1337 	}
1338 	q = vblk->disk->queue;
1339 
1340 	virtblk_name_format("vd", index, vblk->disk->disk_name, DISK_NAME_LEN);
1341 
1342 	vblk->disk->major = major;
1343 	vblk->disk->first_minor = index_to_minor(index);
1344 	vblk->disk->minors = 1 << PART_BITS;
1345 	vblk->disk->private_data = vblk;
1346 	vblk->disk->fops = &virtblk_fops;
1347 	vblk->index = index;
1348 
1349 	/* configure queue flush support */
1350 	virtblk_update_cache_mode(vdev);
1351 
1352 	/* If disk is read-only in the host, the guest should obey */
1353 	if (virtio_has_feature(vdev, VIRTIO_BLK_F_RO))
1354 		set_disk_ro(vblk->disk, 1);
1355 
1356 	/* We can handle whatever the host told us to handle. */
1357 	blk_queue_max_segments(q, sg_elems);
1358 
1359 	/* No real sector limit. */
1360 	blk_queue_max_hw_sectors(q, UINT_MAX);
1361 
1362 	max_dma_size = virtio_max_dma_size(vdev);
1363 	max_size = max_dma_size > U32_MAX ? U32_MAX : max_dma_size;
1364 
1365 	/* Host can optionally specify maximum segment size and number of
1366 	 * segments. */
1367 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SIZE_MAX,
1368 				   struct virtio_blk_config, size_max, &v);
1369 	if (!err)
1370 		max_size = min(max_size, v);
1371 
1372 	blk_queue_max_segment_size(q, max_size);
1373 
1374 	/* Host can optionally specify the block size of the device */
1375 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_BLK_SIZE,
1376 				   struct virtio_blk_config, blk_size,
1377 				   &blk_size);
1378 	if (!err) {
1379 		err = blk_validate_block_size(blk_size);
1380 		if (err) {
1381 			dev_err(&vdev->dev,
1382 				"virtio_blk: invalid block size: 0x%x\n",
1383 				blk_size);
1384 			goto out_cleanup_disk;
1385 		}
1386 
1387 		blk_queue_logical_block_size(q, blk_size);
1388 	} else
1389 		blk_size = queue_logical_block_size(q);
1390 
1391 	/* Use topology information if available */
1392 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1393 				   struct virtio_blk_config, physical_block_exp,
1394 				   &physical_block_exp);
1395 	if (!err && physical_block_exp)
1396 		blk_queue_physical_block_size(q,
1397 				blk_size * (1 << physical_block_exp));
1398 
1399 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1400 				   struct virtio_blk_config, alignment_offset,
1401 				   &alignment_offset);
1402 	if (!err && alignment_offset)
1403 		blk_queue_alignment_offset(q, blk_size * alignment_offset);
1404 
1405 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1406 				   struct virtio_blk_config, min_io_size,
1407 				   &min_io_size);
1408 	if (!err && min_io_size)
1409 		blk_queue_io_min(q, blk_size * min_io_size);
1410 
1411 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1412 				   struct virtio_blk_config, opt_io_size,
1413 				   &opt_io_size);
1414 	if (!err && opt_io_size)
1415 		blk_queue_io_opt(q, blk_size * opt_io_size);
1416 
1417 	if (virtio_has_feature(vdev, VIRTIO_BLK_F_DISCARD)) {
1418 		virtio_cread(vdev, struct virtio_blk_config,
1419 			     discard_sector_alignment, &discard_granularity);
1420 
1421 		virtio_cread(vdev, struct virtio_blk_config,
1422 			     max_discard_sectors, &v);
1423 		blk_queue_max_discard_sectors(q, v ? v : UINT_MAX);
1424 
1425 		virtio_cread(vdev, struct virtio_blk_config, max_discard_seg,
1426 			     &max_discard_segs);
1427 	}
1428 
1429 	if (virtio_has_feature(vdev, VIRTIO_BLK_F_WRITE_ZEROES)) {
1430 		virtio_cread(vdev, struct virtio_blk_config,
1431 			     max_write_zeroes_sectors, &v);
1432 		blk_queue_max_write_zeroes_sectors(q, v ? v : UINT_MAX);
1433 	}
1434 
1435 	/* The discard and secure erase limits are combined since the Linux
1436 	 * block layer uses the same limit for both commands.
1437 	 *
1438 	 * If both VIRTIO_BLK_F_SECURE_ERASE and VIRTIO_BLK_F_DISCARD features
1439 	 * are negotiated, we will use the minimum between the limits.
1440 	 *
1441 	 * discard sector alignment is set to the minimum between discard_sector_alignment
1442 	 * and secure_erase_sector_alignment.
1443 	 *
1444 	 * max discard sectors is set to the minimum between max_discard_seg and
1445 	 * max_secure_erase_seg.
1446 	 */
1447 	if (virtio_has_feature(vdev, VIRTIO_BLK_F_SECURE_ERASE)) {
1448 
1449 		virtio_cread(vdev, struct virtio_blk_config,
1450 			     secure_erase_sector_alignment, &v);
1451 
1452 		/* secure_erase_sector_alignment should not be zero, the device should set a
1453 		 * valid number of sectors.
1454 		 */
1455 		if (!v) {
1456 			dev_err(&vdev->dev,
1457 				"virtio_blk: secure_erase_sector_alignment can't be 0\n");
1458 			err = -EINVAL;
1459 			goto out_cleanup_disk;
1460 		}
1461 
1462 		discard_granularity = min_not_zero(discard_granularity, v);
1463 
1464 		virtio_cread(vdev, struct virtio_blk_config,
1465 			     max_secure_erase_sectors, &v);
1466 
1467 		/* max_secure_erase_sectors should not be zero, the device should set a
1468 		 * valid number of sectors.
1469 		 */
1470 		if (!v) {
1471 			dev_err(&vdev->dev,
1472 				"virtio_blk: max_secure_erase_sectors can't be 0\n");
1473 			err = -EINVAL;
1474 			goto out_cleanup_disk;
1475 		}
1476 
1477 		blk_queue_max_secure_erase_sectors(q, v);
1478 
1479 		virtio_cread(vdev, struct virtio_blk_config,
1480 			     max_secure_erase_seg, &v);
1481 
1482 		/* max_secure_erase_seg should not be zero, the device should set a
1483 		 * valid number of segments
1484 		 */
1485 		if (!v) {
1486 			dev_err(&vdev->dev,
1487 				"virtio_blk: max_secure_erase_seg can't be 0\n");
1488 			err = -EINVAL;
1489 			goto out_cleanup_disk;
1490 		}
1491 
1492 		max_discard_segs = min_not_zero(max_discard_segs, v);
1493 	}
1494 
1495 	if (virtio_has_feature(vdev, VIRTIO_BLK_F_DISCARD) ||
1496 	    virtio_has_feature(vdev, VIRTIO_BLK_F_SECURE_ERASE)) {
1497 		/* max_discard_seg and discard_granularity will be 0 only
1498 		 * if max_discard_seg and discard_sector_alignment fields in the virtio
1499 		 * config are 0 and VIRTIO_BLK_F_SECURE_ERASE feature is not negotiated.
1500 		 * In this case, we use default values.
1501 		 */
1502 		if (!max_discard_segs)
1503 			max_discard_segs = sg_elems;
1504 
1505 		blk_queue_max_discard_segments(q,
1506 					       min(max_discard_segs, MAX_DISCARD_SEGMENTS));
1507 
1508 		if (discard_granularity)
1509 			q->limits.discard_granularity = discard_granularity << SECTOR_SHIFT;
1510 		else
1511 			q->limits.discard_granularity = blk_size;
1512 	}
1513 
1514 	virtblk_update_capacity(vblk, false);
1515 	virtio_device_ready(vdev);
1516 
1517 	/*
1518 	 * All steps that follow use the VQs therefore they need to be
1519 	 * placed after the virtio_device_ready() call above.
1520 	 */
1521 	if (virtio_has_feature(vdev, VIRTIO_BLK_F_ZONED)) {
1522 		u8 model;
1523 
1524 		virtio_cread(vdev, struct virtio_blk_config, zoned.model,
1525 				&model);
1526 		switch (model) {
1527 		case VIRTIO_BLK_Z_NONE:
1528 		case VIRTIO_BLK_Z_HA:
1529 			/* Present the host-aware device as non-zoned */
1530 			break;
1531 		case VIRTIO_BLK_Z_HM:
1532 			err = virtblk_probe_zoned_device(vdev, vblk, q);
1533 			if (err)
1534 				goto out_cleanup_disk;
1535 			break;
1536 		default:
1537 			dev_err(&vdev->dev, "unsupported zone model %d\n",
1538 				model);
1539 			err = -EINVAL;
1540 			goto out_cleanup_disk;
1541 		}
1542 	}
1543 
1544 	err = device_add_disk(&vdev->dev, vblk->disk, virtblk_attr_groups);
1545 	if (err)
1546 		goto out_cleanup_disk;
1547 
1548 	return 0;
1549 
1550 out_cleanup_disk:
1551 	put_disk(vblk->disk);
1552 out_free_tags:
1553 	blk_mq_free_tag_set(&vblk->tag_set);
1554 out_free_vq:
1555 	vdev->config->del_vqs(vdev);
1556 	kfree(vblk->vqs);
1557 out_free_vblk:
1558 	kfree(vblk);
1559 out_free_index:
1560 	ida_free(&vd_index_ida, index);
1561 out:
1562 	return err;
1563 }
1564 
1565 static void virtblk_remove(struct virtio_device *vdev)
1566 {
1567 	struct virtio_blk *vblk = vdev->priv;
1568 
1569 	/* Make sure no work handler is accessing the device. */
1570 	flush_work(&vblk->config_work);
1571 
1572 	del_gendisk(vblk->disk);
1573 	blk_mq_free_tag_set(&vblk->tag_set);
1574 
1575 	mutex_lock(&vblk->vdev_mutex);
1576 
1577 	/* Stop all the virtqueues. */
1578 	virtio_reset_device(vdev);
1579 
1580 	/* Virtqueues are stopped, nothing can use vblk->vdev anymore. */
1581 	vblk->vdev = NULL;
1582 
1583 	vdev->config->del_vqs(vdev);
1584 	kfree(vblk->vqs);
1585 
1586 	mutex_unlock(&vblk->vdev_mutex);
1587 
1588 	put_disk(vblk->disk);
1589 }
1590 
1591 #ifdef CONFIG_PM_SLEEP
1592 static int virtblk_freeze(struct virtio_device *vdev)
1593 {
1594 	struct virtio_blk *vblk = vdev->priv;
1595 
1596 	/* Ensure we don't receive any more interrupts */
1597 	virtio_reset_device(vdev);
1598 
1599 	/* Make sure no work handler is accessing the device. */
1600 	flush_work(&vblk->config_work);
1601 
1602 	blk_mq_quiesce_queue(vblk->disk->queue);
1603 
1604 	vdev->config->del_vqs(vdev);
1605 	kfree(vblk->vqs);
1606 
1607 	return 0;
1608 }
1609 
1610 static int virtblk_restore(struct virtio_device *vdev)
1611 {
1612 	struct virtio_blk *vblk = vdev->priv;
1613 	int ret;
1614 
1615 	ret = init_vq(vdev->priv);
1616 	if (ret)
1617 		return ret;
1618 
1619 	virtio_device_ready(vdev);
1620 
1621 	blk_mq_unquiesce_queue(vblk->disk->queue);
1622 	return 0;
1623 }
1624 #endif
1625 
1626 static const struct virtio_device_id id_table[] = {
1627 	{ VIRTIO_ID_BLOCK, VIRTIO_DEV_ANY_ID },
1628 	{ 0 },
1629 };
1630 
1631 static unsigned int features_legacy[] = {
1632 	VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_F_SIZE_MAX, VIRTIO_BLK_F_GEOMETRY,
1633 	VIRTIO_BLK_F_RO, VIRTIO_BLK_F_BLK_SIZE,
1634 	VIRTIO_BLK_F_FLUSH, VIRTIO_BLK_F_TOPOLOGY, VIRTIO_BLK_F_CONFIG_WCE,
1635 	VIRTIO_BLK_F_MQ, VIRTIO_BLK_F_DISCARD, VIRTIO_BLK_F_WRITE_ZEROES,
1636 	VIRTIO_BLK_F_SECURE_ERASE,
1637 }
1638 ;
1639 static unsigned int features[] = {
1640 	VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_F_SIZE_MAX, VIRTIO_BLK_F_GEOMETRY,
1641 	VIRTIO_BLK_F_RO, VIRTIO_BLK_F_BLK_SIZE,
1642 	VIRTIO_BLK_F_FLUSH, VIRTIO_BLK_F_TOPOLOGY, VIRTIO_BLK_F_CONFIG_WCE,
1643 	VIRTIO_BLK_F_MQ, VIRTIO_BLK_F_DISCARD, VIRTIO_BLK_F_WRITE_ZEROES,
1644 	VIRTIO_BLK_F_SECURE_ERASE, VIRTIO_BLK_F_ZONED,
1645 };
1646 
1647 static struct virtio_driver virtio_blk = {
1648 	.feature_table			= features,
1649 	.feature_table_size		= ARRAY_SIZE(features),
1650 	.feature_table_legacy		= features_legacy,
1651 	.feature_table_size_legacy	= ARRAY_SIZE(features_legacy),
1652 	.driver.name			= KBUILD_MODNAME,
1653 	.driver.owner			= THIS_MODULE,
1654 	.id_table			= id_table,
1655 	.probe				= virtblk_probe,
1656 	.remove				= virtblk_remove,
1657 	.config_changed			= virtblk_config_changed,
1658 #ifdef CONFIG_PM_SLEEP
1659 	.freeze				= virtblk_freeze,
1660 	.restore			= virtblk_restore,
1661 #endif
1662 };
1663 
1664 static int __init virtio_blk_init(void)
1665 {
1666 	int error;
1667 
1668 	virtblk_wq = alloc_workqueue("virtio-blk", 0, 0);
1669 	if (!virtblk_wq)
1670 		return -ENOMEM;
1671 
1672 	major = register_blkdev(0, "virtblk");
1673 	if (major < 0) {
1674 		error = major;
1675 		goto out_destroy_workqueue;
1676 	}
1677 
1678 	error = register_virtio_driver(&virtio_blk);
1679 	if (error)
1680 		goto out_unregister_blkdev;
1681 	return 0;
1682 
1683 out_unregister_blkdev:
1684 	unregister_blkdev(major, "virtblk");
1685 out_destroy_workqueue:
1686 	destroy_workqueue(virtblk_wq);
1687 	return error;
1688 }
1689 
1690 static void __exit virtio_blk_fini(void)
1691 {
1692 	unregister_virtio_driver(&virtio_blk);
1693 	unregister_blkdev(major, "virtblk");
1694 	destroy_workqueue(virtblk_wq);
1695 }
1696 module_init(virtio_blk_init);
1697 module_exit(virtio_blk_fini);
1698 
1699 MODULE_DEVICE_TABLE(virtio, id_table);
1700 MODULE_DESCRIPTION("Virtio block driver");
1701 MODULE_LICENSE("GPL");
1702