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