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