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