xref: /OK3568_Linux_fs/kernel/drivers/block/virtio_blk.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1 // SPDX-License-Identifier: GPL-2.0-only
2 //#define DEBUG
3 #include <linux/spinlock.h>
4 #include <linux/slab.h>
5 #include <linux/blkdev.h>
6 #include <linux/hdreg.h>
7 #include <linux/module.h>
8 #include <linux/mutex.h>
9 #include <linux/interrupt.h>
10 #include <linux/virtio.h>
11 #include <linux/virtio_blk.h>
12 #include <linux/scatterlist.h>
13 #include <linux/string_helpers.h>
14 #include <linux/idr.h>
15 #include <linux/blk-mq.h>
16 #include <linux/blk-mq-virtio.h>
17 #include <linux/numa.h>
18 #include <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 static int major;
25 static DEFINE_IDA(vd_index_ida);
26 
27 static struct workqueue_struct *virtblk_wq;
28 
29 struct virtio_blk_vq {
30 	struct virtqueue *vq;
31 	spinlock_t lock;
32 	char name[VQ_NAME_LEN];
33 } ____cacheline_aligned_in_smp;
34 
35 struct virtio_blk {
36 	/*
37 	 * This mutex must be held by anything that may run after
38 	 * virtblk_remove() sets vblk->vdev to NULL.
39 	 *
40 	 * blk-mq, virtqueue processing, and sysfs attribute code paths are
41 	 * shut down before vblk->vdev is set to NULL and therefore do not need
42 	 * to hold this mutex.
43 	 */
44 	struct mutex vdev_mutex;
45 	struct virtio_device *vdev;
46 
47 	/* The disk structure for the kernel. */
48 	struct gendisk *disk;
49 
50 	/* Block layer tags. */
51 	struct blk_mq_tag_set tag_set;
52 
53 	/* Process context for config space updates */
54 	struct work_struct config_work;
55 
56 	/*
57 	 * Tracks references from block_device_operations open/release and
58 	 * virtio_driver probe/remove so this object can be freed once no
59 	 * longer in use.
60 	 */
61 	refcount_t refs;
62 
63 	/* What host tells us, plus 2 for header & tailer. */
64 	unsigned int sg_elems;
65 
66 	/* Ida index - used to track minor number allocations. */
67 	int index;
68 
69 	/* num of vqs */
70 	int num_vqs;
71 	struct virtio_blk_vq *vqs;
72 };
73 
74 struct virtblk_req {
75 	struct virtio_blk_outhdr out_hdr;
76 	u8 status;
77 	struct scatterlist sg[];
78 };
79 
virtblk_result(struct virtblk_req * vbr)80 static inline blk_status_t virtblk_result(struct virtblk_req *vbr)
81 {
82 	switch (vbr->status) {
83 	case VIRTIO_BLK_S_OK:
84 		return BLK_STS_OK;
85 	case VIRTIO_BLK_S_UNSUPP:
86 		return BLK_STS_NOTSUPP;
87 	default:
88 		return BLK_STS_IOERR;
89 	}
90 }
91 
virtblk_add_req(struct virtqueue * vq,struct virtblk_req * vbr,struct scatterlist * data_sg,bool have_data)92 static int virtblk_add_req(struct virtqueue *vq, struct virtblk_req *vbr,
93 		struct scatterlist *data_sg, bool have_data)
94 {
95 	struct scatterlist hdr, status, *sgs[3];
96 	unsigned int num_out = 0, num_in = 0;
97 
98 	sg_init_one(&hdr, &vbr->out_hdr, sizeof(vbr->out_hdr));
99 	sgs[num_out++] = &hdr;
100 
101 	if (have_data) {
102 		if (vbr->out_hdr.type & cpu_to_virtio32(vq->vdev, VIRTIO_BLK_T_OUT))
103 			sgs[num_out++] = data_sg;
104 		else
105 			sgs[num_out + num_in++] = data_sg;
106 	}
107 
108 	sg_init_one(&status, &vbr->status, sizeof(vbr->status));
109 	sgs[num_out + num_in++] = &status;
110 
111 	return virtqueue_add_sgs(vq, sgs, num_out, num_in, vbr, GFP_ATOMIC);
112 }
113 
virtblk_setup_discard_write_zeroes(struct request * req,bool unmap)114 static int virtblk_setup_discard_write_zeroes(struct request *req, bool unmap)
115 {
116 	unsigned short segments = blk_rq_nr_discard_segments(req);
117 	unsigned short n = 0;
118 	struct virtio_blk_discard_write_zeroes *range;
119 	struct bio *bio;
120 	u32 flags = 0;
121 
122 	if (unmap)
123 		flags |= VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP;
124 
125 	range = kmalloc_array(segments, sizeof(*range), GFP_ATOMIC);
126 	if (!range)
127 		return -ENOMEM;
128 
129 	/*
130 	 * Single max discard segment means multi-range discard isn't
131 	 * supported, and block layer only runs contiguity merge like
132 	 * normal RW request. So we can't reply on bio for retrieving
133 	 * each range info.
134 	 */
135 	if (queue_max_discard_segments(req->q) == 1) {
136 		range[0].flags = cpu_to_le32(flags);
137 		range[0].num_sectors = cpu_to_le32(blk_rq_sectors(req));
138 		range[0].sector = cpu_to_le64(blk_rq_pos(req));
139 		n = 1;
140 	} else {
141 		__rq_for_each_bio(bio, req) {
142 			u64 sector = bio->bi_iter.bi_sector;
143 			u32 num_sectors = bio->bi_iter.bi_size >> SECTOR_SHIFT;
144 
145 			range[n].flags = cpu_to_le32(flags);
146 			range[n].num_sectors = cpu_to_le32(num_sectors);
147 			range[n].sector = cpu_to_le64(sector);
148 			n++;
149 		}
150 	}
151 
152 	WARN_ON_ONCE(n != segments);
153 
154 	req->special_vec.bv_page = virt_to_page(range);
155 	req->special_vec.bv_offset = offset_in_page(range);
156 	req->special_vec.bv_len = sizeof(*range) * segments;
157 	req->rq_flags |= RQF_SPECIAL_PAYLOAD;
158 
159 	return 0;
160 }
161 
virtblk_request_done(struct request * req)162 static inline void virtblk_request_done(struct request *req)
163 {
164 	struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
165 
166 	if (req->rq_flags & RQF_SPECIAL_PAYLOAD) {
167 		kfree(page_address(req->special_vec.bv_page) +
168 		      req->special_vec.bv_offset);
169 	}
170 
171 	blk_mq_end_request(req, virtblk_result(vbr));
172 }
173 
virtblk_done(struct virtqueue * vq)174 static void virtblk_done(struct virtqueue *vq)
175 {
176 	struct virtio_blk *vblk = vq->vdev->priv;
177 	bool req_done = false;
178 	int qid = vq->index;
179 	struct virtblk_req *vbr;
180 	unsigned long flags;
181 	unsigned int len;
182 
183 	spin_lock_irqsave(&vblk->vqs[qid].lock, flags);
184 	do {
185 		virtqueue_disable_cb(vq);
186 		while ((vbr = virtqueue_get_buf(vblk->vqs[qid].vq, &len)) != NULL) {
187 			struct request *req = blk_mq_rq_from_pdu(vbr);
188 
189 			if (likely(!blk_should_fake_timeout(req->q)))
190 				blk_mq_complete_request(req);
191 			req_done = true;
192 		}
193 		if (unlikely(virtqueue_is_broken(vq)))
194 			break;
195 	} while (!virtqueue_enable_cb(vq));
196 
197 	/* In case queue is stopped waiting for more buffers. */
198 	if (req_done)
199 		blk_mq_start_stopped_hw_queues(vblk->disk->queue, true);
200 	spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
201 }
202 
virtio_commit_rqs(struct blk_mq_hw_ctx * hctx)203 static void virtio_commit_rqs(struct blk_mq_hw_ctx *hctx)
204 {
205 	struct virtio_blk *vblk = hctx->queue->queuedata;
206 	struct virtio_blk_vq *vq = &vblk->vqs[hctx->queue_num];
207 	bool kick;
208 
209 	spin_lock_irq(&vq->lock);
210 	kick = virtqueue_kick_prepare(vq->vq);
211 	spin_unlock_irq(&vq->lock);
212 
213 	if (kick)
214 		virtqueue_notify(vq->vq);
215 }
216 
virtio_queue_rq(struct blk_mq_hw_ctx * hctx,const struct blk_mq_queue_data * bd)217 static blk_status_t virtio_queue_rq(struct blk_mq_hw_ctx *hctx,
218 			   const struct blk_mq_queue_data *bd)
219 {
220 	struct virtio_blk *vblk = hctx->queue->queuedata;
221 	struct request *req = bd->rq;
222 	struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
223 	unsigned long flags;
224 	unsigned int num;
225 	int qid = hctx->queue_num;
226 	int err;
227 	bool notify = false;
228 	bool unmap = false;
229 	u32 type;
230 
231 	switch (req_op(req)) {
232 	case REQ_OP_READ:
233 	case REQ_OP_WRITE:
234 		type = 0;
235 		break;
236 	case REQ_OP_FLUSH:
237 		type = VIRTIO_BLK_T_FLUSH;
238 		break;
239 	case REQ_OP_DISCARD:
240 		type = VIRTIO_BLK_T_DISCARD;
241 		break;
242 	case REQ_OP_WRITE_ZEROES:
243 		type = VIRTIO_BLK_T_WRITE_ZEROES;
244 		unmap = !(req->cmd_flags & REQ_NOUNMAP);
245 		break;
246 	case REQ_OP_DRV_IN:
247 		type = VIRTIO_BLK_T_GET_ID;
248 		break;
249 	default:
250 		WARN_ON_ONCE(1);
251 		return BLK_STS_IOERR;
252 	}
253 
254 	BUG_ON(type != VIRTIO_BLK_T_DISCARD &&
255 	       type != VIRTIO_BLK_T_WRITE_ZEROES &&
256 	       (req->nr_phys_segments + 2 > vblk->sg_elems));
257 
258 	vbr->out_hdr.type = cpu_to_virtio32(vblk->vdev, type);
259 	vbr->out_hdr.sector = type ?
260 		0 : cpu_to_virtio64(vblk->vdev, blk_rq_pos(req));
261 	vbr->out_hdr.ioprio = cpu_to_virtio32(vblk->vdev, req_get_ioprio(req));
262 
263 	blk_mq_start_request(req);
264 
265 	if (type == VIRTIO_BLK_T_DISCARD || type == VIRTIO_BLK_T_WRITE_ZEROES) {
266 		err = virtblk_setup_discard_write_zeroes(req, unmap);
267 		if (err)
268 			return BLK_STS_RESOURCE;
269 	}
270 
271 	num = blk_rq_map_sg(hctx->queue, req, vbr->sg);
272 	if (num) {
273 		if (rq_data_dir(req) == WRITE)
274 			vbr->out_hdr.type |= cpu_to_virtio32(vblk->vdev, VIRTIO_BLK_T_OUT);
275 		else
276 			vbr->out_hdr.type |= cpu_to_virtio32(vblk->vdev, VIRTIO_BLK_T_IN);
277 	}
278 
279 	spin_lock_irqsave(&vblk->vqs[qid].lock, flags);
280 	err = virtblk_add_req(vblk->vqs[qid].vq, vbr, vbr->sg, num);
281 	if (err) {
282 		virtqueue_kick(vblk->vqs[qid].vq);
283 		/* Don't stop the queue if -ENOMEM: we may have failed to
284 		 * bounce the buffer due to global resource outage.
285 		 */
286 		if (err == -ENOSPC)
287 			blk_mq_stop_hw_queue(hctx);
288 		spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
289 		switch (err) {
290 		case -ENOSPC:
291 			return BLK_STS_DEV_RESOURCE;
292 		case -ENOMEM:
293 			return BLK_STS_RESOURCE;
294 		default:
295 			return BLK_STS_IOERR;
296 		}
297 	}
298 
299 	if (bd->last && virtqueue_kick_prepare(vblk->vqs[qid].vq))
300 		notify = true;
301 	spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
302 
303 	if (notify)
304 		virtqueue_notify(vblk->vqs[qid].vq);
305 	return BLK_STS_OK;
306 }
307 
308 /* return id (s/n) string for *disk to *id_str
309  */
virtblk_get_id(struct gendisk * disk,char * id_str)310 static int virtblk_get_id(struct gendisk *disk, char *id_str)
311 {
312 	struct virtio_blk *vblk = disk->private_data;
313 	struct request_queue *q = vblk->disk->queue;
314 	struct request *req;
315 	int err;
316 
317 	req = blk_get_request(q, REQ_OP_DRV_IN, 0);
318 	if (IS_ERR(req))
319 		return PTR_ERR(req);
320 
321 	err = blk_rq_map_kern(q, req, id_str, VIRTIO_BLK_ID_BYTES, GFP_KERNEL);
322 	if (err)
323 		goto out;
324 
325 	blk_execute_rq(vblk->disk->queue, vblk->disk, req, false);
326 	err = blk_status_to_errno(virtblk_result(blk_mq_rq_to_pdu(req)));
327 out:
328 	blk_put_request(req);
329 	return err;
330 }
331 
virtblk_get(struct virtio_blk * vblk)332 static void virtblk_get(struct virtio_blk *vblk)
333 {
334 	refcount_inc(&vblk->refs);
335 }
336 
virtblk_put(struct virtio_blk * vblk)337 static void virtblk_put(struct virtio_blk *vblk)
338 {
339 	if (refcount_dec_and_test(&vblk->refs)) {
340 		ida_simple_remove(&vd_index_ida, vblk->index);
341 		mutex_destroy(&vblk->vdev_mutex);
342 		kfree(vblk);
343 	}
344 }
345 
virtblk_open(struct block_device * bd,fmode_t mode)346 static int virtblk_open(struct block_device *bd, fmode_t mode)
347 {
348 	struct virtio_blk *vblk = bd->bd_disk->private_data;
349 	int ret = 0;
350 
351 	mutex_lock(&vblk->vdev_mutex);
352 
353 	if (vblk->vdev)
354 		virtblk_get(vblk);
355 	else
356 		ret = -ENXIO;
357 
358 	mutex_unlock(&vblk->vdev_mutex);
359 	return ret;
360 }
361 
virtblk_release(struct gendisk * disk,fmode_t mode)362 static void virtblk_release(struct gendisk *disk, fmode_t mode)
363 {
364 	struct virtio_blk *vblk = disk->private_data;
365 
366 	virtblk_put(vblk);
367 }
368 
369 /* We provide getgeo only to please some old bootloader/partitioning tools */
virtblk_getgeo(struct block_device * bd,struct hd_geometry * geo)370 static int virtblk_getgeo(struct block_device *bd, struct hd_geometry *geo)
371 {
372 	struct virtio_blk *vblk = bd->bd_disk->private_data;
373 	int ret = 0;
374 
375 	mutex_lock(&vblk->vdev_mutex);
376 
377 	if (!vblk->vdev) {
378 		ret = -ENXIO;
379 		goto out;
380 	}
381 
382 	/* see if the host passed in geometry config */
383 	if (virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_GEOMETRY)) {
384 		virtio_cread(vblk->vdev, struct virtio_blk_config,
385 			     geometry.cylinders, &geo->cylinders);
386 		virtio_cread(vblk->vdev, struct virtio_blk_config,
387 			     geometry.heads, &geo->heads);
388 		virtio_cread(vblk->vdev, struct virtio_blk_config,
389 			     geometry.sectors, &geo->sectors);
390 	} else {
391 		/* some standard values, similar to sd */
392 		geo->heads = 1 << 6;
393 		geo->sectors = 1 << 5;
394 		geo->cylinders = get_capacity(bd->bd_disk) >> 11;
395 	}
396 out:
397 	mutex_unlock(&vblk->vdev_mutex);
398 	return ret;
399 }
400 
401 static const struct block_device_operations virtblk_fops = {
402 	.owner  = THIS_MODULE,
403 	.open = virtblk_open,
404 	.release = virtblk_release,
405 	.getgeo = virtblk_getgeo,
406 };
407 
index_to_minor(int index)408 static int index_to_minor(int index)
409 {
410 	return index << PART_BITS;
411 }
412 
minor_to_index(int minor)413 static int minor_to_index(int minor)
414 {
415 	return minor >> PART_BITS;
416 }
417 
serial_show(struct device * dev,struct device_attribute * attr,char * buf)418 static ssize_t serial_show(struct device *dev,
419 			   struct device_attribute *attr, char *buf)
420 {
421 	struct gendisk *disk = dev_to_disk(dev);
422 	int err;
423 
424 	/* sysfs gives us a PAGE_SIZE buffer */
425 	BUILD_BUG_ON(PAGE_SIZE < VIRTIO_BLK_ID_BYTES);
426 
427 	buf[VIRTIO_BLK_ID_BYTES] = '\0';
428 	err = virtblk_get_id(disk, buf);
429 	if (!err)
430 		return strlen(buf);
431 
432 	if (err == -EIO) /* Unsupported? Make it empty. */
433 		return 0;
434 
435 	return err;
436 }
437 
438 static DEVICE_ATTR_RO(serial);
439 
440 /* The queue's logical block size must be set before calling this */
virtblk_update_capacity(struct virtio_blk * vblk,bool resize)441 static void virtblk_update_capacity(struct virtio_blk *vblk, bool resize)
442 {
443 	struct virtio_device *vdev = vblk->vdev;
444 	struct request_queue *q = vblk->disk->queue;
445 	char cap_str_2[10], cap_str_10[10];
446 	unsigned long long nblocks;
447 	u64 capacity;
448 
449 	/* Host must always specify the capacity. */
450 	virtio_cread(vdev, struct virtio_blk_config, capacity, &capacity);
451 
452 	/* If capacity is too big, truncate with warning. */
453 	if ((sector_t)capacity != capacity) {
454 		dev_warn(&vdev->dev, "Capacity %llu too large: truncating\n",
455 			 (unsigned long long)capacity);
456 		capacity = (sector_t)-1;
457 	}
458 
459 	nblocks = DIV_ROUND_UP_ULL(capacity, queue_logical_block_size(q) >> 9);
460 
461 	string_get_size(nblocks, queue_logical_block_size(q),
462 			STRING_UNITS_2, cap_str_2, sizeof(cap_str_2));
463 	string_get_size(nblocks, queue_logical_block_size(q),
464 			STRING_UNITS_10, cap_str_10, sizeof(cap_str_10));
465 
466 	dev_notice(&vdev->dev,
467 		   "[%s] %s%llu %d-byte logical blocks (%s/%s)\n",
468 		   vblk->disk->disk_name,
469 		   resize ? "new size: " : "",
470 		   nblocks,
471 		   queue_logical_block_size(q),
472 		   cap_str_10,
473 		   cap_str_2);
474 
475 	set_capacity_revalidate_and_notify(vblk->disk, capacity, true);
476 }
477 
virtblk_config_changed_work(struct work_struct * work)478 static void virtblk_config_changed_work(struct work_struct *work)
479 {
480 	struct virtio_blk *vblk =
481 		container_of(work, struct virtio_blk, config_work);
482 
483 	virtblk_update_capacity(vblk, true);
484 }
485 
virtblk_config_changed(struct virtio_device * vdev)486 static void virtblk_config_changed(struct virtio_device *vdev)
487 {
488 	struct virtio_blk *vblk = vdev->priv;
489 
490 	queue_work(virtblk_wq, &vblk->config_work);
491 }
492 
init_vq(struct virtio_blk * vblk)493 static int init_vq(struct virtio_blk *vblk)
494 {
495 	int err;
496 	int i;
497 	vq_callback_t **callbacks;
498 	const char **names;
499 	struct virtqueue **vqs;
500 	unsigned short num_vqs;
501 	struct virtio_device *vdev = vblk->vdev;
502 	struct irq_affinity desc = { 0, };
503 
504 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_MQ,
505 				   struct virtio_blk_config, num_queues,
506 				   &num_vqs);
507 	if (err)
508 		num_vqs = 1;
509 
510 	num_vqs = min_t(unsigned int, nr_cpu_ids, num_vqs);
511 
512 	vblk->vqs = kmalloc_array(num_vqs, sizeof(*vblk->vqs), GFP_KERNEL);
513 	if (!vblk->vqs)
514 		return -ENOMEM;
515 
516 	names = kmalloc_array(num_vqs, sizeof(*names), GFP_KERNEL);
517 	callbacks = kmalloc_array(num_vqs, sizeof(*callbacks), GFP_KERNEL);
518 	vqs = kmalloc_array(num_vqs, sizeof(*vqs), GFP_KERNEL);
519 	if (!names || !callbacks || !vqs) {
520 		err = -ENOMEM;
521 		goto out;
522 	}
523 
524 	for (i = 0; i < num_vqs; i++) {
525 		callbacks[i] = virtblk_done;
526 		snprintf(vblk->vqs[i].name, VQ_NAME_LEN, "req.%d", i);
527 		names[i] = vblk->vqs[i].name;
528 	}
529 
530 	/* Discover virtqueues and write information to configuration.  */
531 	err = virtio_find_vqs(vdev, num_vqs, vqs, callbacks, names, &desc);
532 	if (err)
533 		goto out;
534 
535 	for (i = 0; i < num_vqs; i++) {
536 		spin_lock_init(&vblk->vqs[i].lock);
537 		vblk->vqs[i].vq = vqs[i];
538 	}
539 	vblk->num_vqs = num_vqs;
540 
541 out:
542 	kfree(vqs);
543 	kfree(callbacks);
544 	kfree(names);
545 	if (err)
546 		kfree(vblk->vqs);
547 	return err;
548 }
549 
550 /*
551  * Legacy naming scheme used for virtio devices.  We are stuck with it for
552  * virtio blk but don't ever use it for any new driver.
553  */
virtblk_name_format(char * prefix,int index,char * buf,int buflen)554 static int virtblk_name_format(char *prefix, int index, char *buf, int buflen)
555 {
556 	const int base = 'z' - 'a' + 1;
557 	char *begin = buf + strlen(prefix);
558 	char *end = buf + buflen;
559 	char *p;
560 	int unit;
561 
562 	p = end - 1;
563 	*p = '\0';
564 	unit = base;
565 	do {
566 		if (p == begin)
567 			return -EINVAL;
568 		*--p = 'a' + (index % unit);
569 		index = (index / unit) - 1;
570 	} while (index >= 0);
571 
572 	memmove(begin, p, end - p);
573 	memcpy(buf, prefix, strlen(prefix));
574 
575 	return 0;
576 }
577 
virtblk_get_cache_mode(struct virtio_device * vdev)578 static int virtblk_get_cache_mode(struct virtio_device *vdev)
579 {
580 	u8 writeback;
581 	int err;
582 
583 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE,
584 				   struct virtio_blk_config, wce,
585 				   &writeback);
586 
587 	/*
588 	 * If WCE is not configurable and flush is not available,
589 	 * assume no writeback cache is in use.
590 	 */
591 	if (err)
592 		writeback = virtio_has_feature(vdev, VIRTIO_BLK_F_FLUSH);
593 
594 	return writeback;
595 }
596 
virtblk_update_cache_mode(struct virtio_device * vdev)597 static void virtblk_update_cache_mode(struct virtio_device *vdev)
598 {
599 	u8 writeback = virtblk_get_cache_mode(vdev);
600 	struct virtio_blk *vblk = vdev->priv;
601 
602 	blk_queue_write_cache(vblk->disk->queue, writeback, false);
603 	revalidate_disk_size(vblk->disk, true);
604 }
605 
606 static const char *const virtblk_cache_types[] = {
607 	"write through", "write back"
608 };
609 
610 static ssize_t
cache_type_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)611 cache_type_store(struct device *dev, struct device_attribute *attr,
612 		 const char *buf, size_t count)
613 {
614 	struct gendisk *disk = dev_to_disk(dev);
615 	struct virtio_blk *vblk = disk->private_data;
616 	struct virtio_device *vdev = vblk->vdev;
617 	int i;
618 
619 	BUG_ON(!virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_CONFIG_WCE));
620 	i = sysfs_match_string(virtblk_cache_types, buf);
621 	if (i < 0)
622 		return i;
623 
624 	virtio_cwrite8(vdev, offsetof(struct virtio_blk_config, wce), i);
625 	virtblk_update_cache_mode(vdev);
626 	return count;
627 }
628 
629 static ssize_t
cache_type_show(struct device * dev,struct device_attribute * attr,char * buf)630 cache_type_show(struct device *dev, struct device_attribute *attr, char *buf)
631 {
632 	struct gendisk *disk = dev_to_disk(dev);
633 	struct virtio_blk *vblk = disk->private_data;
634 	u8 writeback = virtblk_get_cache_mode(vblk->vdev);
635 
636 	BUG_ON(writeback >= ARRAY_SIZE(virtblk_cache_types));
637 	return snprintf(buf, 40, "%s\n", virtblk_cache_types[writeback]);
638 }
639 
640 static DEVICE_ATTR_RW(cache_type);
641 
642 static struct attribute *virtblk_attrs[] = {
643 	&dev_attr_serial.attr,
644 	&dev_attr_cache_type.attr,
645 	NULL,
646 };
647 
virtblk_attrs_are_visible(struct kobject * kobj,struct attribute * a,int n)648 static umode_t virtblk_attrs_are_visible(struct kobject *kobj,
649 		struct attribute *a, int n)
650 {
651 	struct device *dev = kobj_to_dev(kobj);
652 	struct gendisk *disk = dev_to_disk(dev);
653 	struct virtio_blk *vblk = disk->private_data;
654 	struct virtio_device *vdev = vblk->vdev;
655 
656 	if (a == &dev_attr_cache_type.attr &&
657 	    !virtio_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE))
658 		return S_IRUGO;
659 
660 	return a->mode;
661 }
662 
663 static const struct attribute_group virtblk_attr_group = {
664 	.attrs = virtblk_attrs,
665 	.is_visible = virtblk_attrs_are_visible,
666 };
667 
668 static const struct attribute_group *virtblk_attr_groups[] = {
669 	&virtblk_attr_group,
670 	NULL,
671 };
672 
virtblk_init_request(struct blk_mq_tag_set * set,struct request * rq,unsigned int hctx_idx,unsigned int numa_node)673 static int virtblk_init_request(struct blk_mq_tag_set *set, struct request *rq,
674 		unsigned int hctx_idx, unsigned int numa_node)
675 {
676 	struct virtio_blk *vblk = set->driver_data;
677 	struct virtblk_req *vbr = blk_mq_rq_to_pdu(rq);
678 
679 	sg_init_table(vbr->sg, vblk->sg_elems);
680 	return 0;
681 }
682 
virtblk_map_queues(struct blk_mq_tag_set * set)683 static int virtblk_map_queues(struct blk_mq_tag_set *set)
684 {
685 	struct virtio_blk *vblk = set->driver_data;
686 
687 	return blk_mq_virtio_map_queues(&set->map[HCTX_TYPE_DEFAULT],
688 					vblk->vdev, 0);
689 }
690 
691 static const struct blk_mq_ops virtio_mq_ops = {
692 	.queue_rq	= virtio_queue_rq,
693 	.commit_rqs	= virtio_commit_rqs,
694 	.complete	= virtblk_request_done,
695 	.init_request	= virtblk_init_request,
696 	.map_queues	= virtblk_map_queues,
697 };
698 
699 static unsigned int virtblk_queue_depth;
700 module_param_named(queue_depth, virtblk_queue_depth, uint, 0444);
701 
virtblk_probe(struct virtio_device * vdev)702 static int virtblk_probe(struct virtio_device *vdev)
703 {
704 	struct virtio_blk *vblk;
705 	struct request_queue *q;
706 	int err, index;
707 
708 	u32 v, blk_size, max_size, sg_elems, opt_io_size;
709 	u16 min_io_size;
710 	u8 physical_block_exp, alignment_offset;
711 
712 	if (!vdev->config->get) {
713 		dev_err(&vdev->dev, "%s failure: config access disabled\n",
714 			__func__);
715 		return -EINVAL;
716 	}
717 
718 	err = ida_simple_get(&vd_index_ida, 0, minor_to_index(1 << MINORBITS),
719 			     GFP_KERNEL);
720 	if (err < 0)
721 		goto out;
722 	index = err;
723 
724 	/* We need to know how many segments before we allocate. */
725 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SEG_MAX,
726 				   struct virtio_blk_config, seg_max,
727 				   &sg_elems);
728 
729 	/* We need at least one SG element, whatever they say. */
730 	if (err || !sg_elems)
731 		sg_elems = 1;
732 
733 	/* We need an extra sg elements at head and tail. */
734 	sg_elems += 2;
735 	vdev->priv = vblk = kmalloc(sizeof(*vblk), GFP_KERNEL);
736 	if (!vblk) {
737 		err = -ENOMEM;
738 		goto out_free_index;
739 	}
740 
741 	/* This reference is dropped in virtblk_remove(). */
742 	refcount_set(&vblk->refs, 1);
743 	mutex_init(&vblk->vdev_mutex);
744 
745 	vblk->vdev = vdev;
746 	vblk->sg_elems = sg_elems;
747 
748 	INIT_WORK(&vblk->config_work, virtblk_config_changed_work);
749 
750 	err = init_vq(vblk);
751 	if (err)
752 		goto out_free_vblk;
753 
754 	/* FIXME: How many partitions?  How long is a piece of string? */
755 	vblk->disk = alloc_disk(1 << PART_BITS);
756 	if (!vblk->disk) {
757 		err = -ENOMEM;
758 		goto out_free_vq;
759 	}
760 
761 	/* Default queue sizing is to fill the ring. */
762 	if (!virtblk_queue_depth) {
763 		virtblk_queue_depth = vblk->vqs[0].vq->num_free;
764 		/* ... but without indirect descs, we use 2 descs per req */
765 		if (!virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC))
766 			virtblk_queue_depth /= 2;
767 	}
768 
769 	memset(&vblk->tag_set, 0, sizeof(vblk->tag_set));
770 	vblk->tag_set.ops = &virtio_mq_ops;
771 	vblk->tag_set.queue_depth = virtblk_queue_depth;
772 	vblk->tag_set.numa_node = NUMA_NO_NODE;
773 	vblk->tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
774 	vblk->tag_set.cmd_size =
775 		sizeof(struct virtblk_req) +
776 		sizeof(struct scatterlist) * sg_elems;
777 	vblk->tag_set.driver_data = vblk;
778 	vblk->tag_set.nr_hw_queues = vblk->num_vqs;
779 
780 	err = blk_mq_alloc_tag_set(&vblk->tag_set);
781 	if (err)
782 		goto out_put_disk;
783 
784 	q = blk_mq_init_queue(&vblk->tag_set);
785 	if (IS_ERR(q)) {
786 		err = -ENOMEM;
787 		goto out_free_tags;
788 	}
789 	vblk->disk->queue = q;
790 
791 	q->queuedata = vblk;
792 
793 	virtblk_name_format("vd", index, vblk->disk->disk_name, DISK_NAME_LEN);
794 
795 	vblk->disk->major = major;
796 	vblk->disk->first_minor = index_to_minor(index);
797 	vblk->disk->private_data = vblk;
798 	vblk->disk->fops = &virtblk_fops;
799 	vblk->disk->flags |= GENHD_FL_EXT_DEVT;
800 	vblk->index = index;
801 
802 	/* configure queue flush support */
803 	virtblk_update_cache_mode(vdev);
804 
805 	/* If disk is read-only in the host, the guest should obey */
806 	if (virtio_has_feature(vdev, VIRTIO_BLK_F_RO))
807 		set_disk_ro(vblk->disk, 1);
808 
809 	/* We can handle whatever the host told us to handle. */
810 	blk_queue_max_segments(q, vblk->sg_elems-2);
811 
812 	/* No real sector limit. */
813 	blk_queue_max_hw_sectors(q, -1U);
814 
815 	max_size = virtio_max_dma_size(vdev);
816 
817 	/* Host can optionally specify maximum segment size and number of
818 	 * segments. */
819 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SIZE_MAX,
820 				   struct virtio_blk_config, size_max, &v);
821 	if (!err)
822 		max_size = min(max_size, v);
823 
824 	blk_queue_max_segment_size(q, max_size);
825 
826 	/* Host can optionally specify the block size of the device */
827 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_BLK_SIZE,
828 				   struct virtio_blk_config, blk_size,
829 				   &blk_size);
830 	if (!err) {
831 		err = blk_validate_block_size(blk_size);
832 		if (err) {
833 			dev_err(&vdev->dev,
834 				"virtio_blk: invalid block size: 0x%x\n",
835 				blk_size);
836 			goto out_cleanup_disk;
837 		}
838 
839 		blk_queue_logical_block_size(q, blk_size);
840 	} else
841 		blk_size = queue_logical_block_size(q);
842 
843 	/* Use topology information if available */
844 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
845 				   struct virtio_blk_config, physical_block_exp,
846 				   &physical_block_exp);
847 	if (!err && physical_block_exp)
848 		blk_queue_physical_block_size(q,
849 				blk_size * (1 << physical_block_exp));
850 
851 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
852 				   struct virtio_blk_config, alignment_offset,
853 				   &alignment_offset);
854 	if (!err && alignment_offset)
855 		blk_queue_alignment_offset(q, blk_size * alignment_offset);
856 
857 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
858 				   struct virtio_blk_config, min_io_size,
859 				   &min_io_size);
860 	if (!err && min_io_size)
861 		blk_queue_io_min(q, blk_size * min_io_size);
862 
863 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
864 				   struct virtio_blk_config, opt_io_size,
865 				   &opt_io_size);
866 	if (!err && opt_io_size)
867 		blk_queue_io_opt(q, blk_size * opt_io_size);
868 
869 	if (virtio_has_feature(vdev, VIRTIO_BLK_F_DISCARD)) {
870 		virtio_cread(vdev, struct virtio_blk_config,
871 			     discard_sector_alignment, &v);
872 		if (v)
873 			q->limits.discard_granularity = v << SECTOR_SHIFT;
874 		else
875 			q->limits.discard_granularity = blk_size;
876 
877 		virtio_cread(vdev, struct virtio_blk_config,
878 			     max_discard_sectors, &v);
879 		blk_queue_max_discard_sectors(q, v ? v : UINT_MAX);
880 
881 		virtio_cread(vdev, struct virtio_blk_config, max_discard_seg,
882 			     &v);
883 
884 		/*
885 		 * max_discard_seg == 0 is out of spec but we always
886 		 * handled it.
887 		 */
888 		if (!v)
889 			v = sg_elems - 2;
890 		blk_queue_max_discard_segments(q,
891 					       min(v, MAX_DISCARD_SEGMENTS));
892 
893 		blk_queue_flag_set(QUEUE_FLAG_DISCARD, q);
894 	}
895 
896 	if (virtio_has_feature(vdev, VIRTIO_BLK_F_WRITE_ZEROES)) {
897 		virtio_cread(vdev, struct virtio_blk_config,
898 			     max_write_zeroes_sectors, &v);
899 		blk_queue_max_write_zeroes_sectors(q, v ? v : UINT_MAX);
900 	}
901 
902 	virtblk_update_capacity(vblk, false);
903 	virtio_device_ready(vdev);
904 
905 	device_add_disk(&vdev->dev, vblk->disk, virtblk_attr_groups);
906 	return 0;
907 
908 out_cleanup_disk:
909 	blk_cleanup_queue(vblk->disk->queue);
910 out_free_tags:
911 	blk_mq_free_tag_set(&vblk->tag_set);
912 out_put_disk:
913 	put_disk(vblk->disk);
914 out_free_vq:
915 	vdev->config->del_vqs(vdev);
916 	kfree(vblk->vqs);
917 out_free_vblk:
918 	kfree(vblk);
919 out_free_index:
920 	ida_simple_remove(&vd_index_ida, index);
921 out:
922 	return err;
923 }
924 
virtblk_remove(struct virtio_device * vdev)925 static void virtblk_remove(struct virtio_device *vdev)
926 {
927 	struct virtio_blk *vblk = vdev->priv;
928 
929 	/* Make sure no work handler is accessing the device. */
930 	flush_work(&vblk->config_work);
931 
932 	del_gendisk(vblk->disk);
933 	blk_cleanup_queue(vblk->disk->queue);
934 
935 	blk_mq_free_tag_set(&vblk->tag_set);
936 
937 	mutex_lock(&vblk->vdev_mutex);
938 
939 	/* Stop all the virtqueues. */
940 	vdev->config->reset(vdev);
941 
942 	/* Virtqueues are stopped, nothing can use vblk->vdev anymore. */
943 	vblk->vdev = NULL;
944 
945 	put_disk(vblk->disk);
946 	vdev->config->del_vqs(vdev);
947 	kfree(vblk->vqs);
948 
949 	mutex_unlock(&vblk->vdev_mutex);
950 
951 	virtblk_put(vblk);
952 }
953 
954 #ifdef CONFIG_PM_SLEEP
virtblk_freeze(struct virtio_device * vdev)955 static int virtblk_freeze(struct virtio_device *vdev)
956 {
957 	struct virtio_blk *vblk = vdev->priv;
958 
959 	/* Ensure we don't receive any more interrupts */
960 	vdev->config->reset(vdev);
961 
962 	/* Make sure no work handler is accessing the device. */
963 	flush_work(&vblk->config_work);
964 
965 	blk_mq_quiesce_queue(vblk->disk->queue);
966 
967 	vdev->config->del_vqs(vdev);
968 	kfree(vblk->vqs);
969 
970 	return 0;
971 }
972 
virtblk_restore(struct virtio_device * vdev)973 static int virtblk_restore(struct virtio_device *vdev)
974 {
975 	struct virtio_blk *vblk = vdev->priv;
976 	int ret;
977 
978 	ret = init_vq(vdev->priv);
979 	if (ret)
980 		return ret;
981 
982 	virtio_device_ready(vdev);
983 
984 	blk_mq_unquiesce_queue(vblk->disk->queue);
985 	return 0;
986 }
987 #endif
988 
989 static const struct virtio_device_id id_table[] = {
990 	{ VIRTIO_ID_BLOCK, VIRTIO_DEV_ANY_ID },
991 	{ 0 },
992 };
993 
994 static unsigned int features_legacy[] = {
995 	VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_F_SIZE_MAX, VIRTIO_BLK_F_GEOMETRY,
996 	VIRTIO_BLK_F_RO, VIRTIO_BLK_F_BLK_SIZE,
997 	VIRTIO_BLK_F_FLUSH, VIRTIO_BLK_F_TOPOLOGY, VIRTIO_BLK_F_CONFIG_WCE,
998 	VIRTIO_BLK_F_MQ, VIRTIO_BLK_F_DISCARD, VIRTIO_BLK_F_WRITE_ZEROES,
999 }
1000 ;
1001 static unsigned int features[] = {
1002 	VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_F_SIZE_MAX, VIRTIO_BLK_F_GEOMETRY,
1003 	VIRTIO_BLK_F_RO, VIRTIO_BLK_F_BLK_SIZE,
1004 	VIRTIO_BLK_F_FLUSH, VIRTIO_BLK_F_TOPOLOGY, VIRTIO_BLK_F_CONFIG_WCE,
1005 	VIRTIO_BLK_F_MQ, VIRTIO_BLK_F_DISCARD, VIRTIO_BLK_F_WRITE_ZEROES,
1006 };
1007 
1008 static struct virtio_driver virtio_blk = {
1009 	.feature_table			= features,
1010 	.feature_table_size		= ARRAY_SIZE(features),
1011 	.feature_table_legacy		= features_legacy,
1012 	.feature_table_size_legacy	= ARRAY_SIZE(features_legacy),
1013 	.driver.name			= KBUILD_MODNAME,
1014 	.driver.owner			= THIS_MODULE,
1015 	.id_table			= id_table,
1016 	.probe				= virtblk_probe,
1017 	.remove				= virtblk_remove,
1018 	.config_changed			= virtblk_config_changed,
1019 #ifdef CONFIG_PM_SLEEP
1020 	.freeze				= virtblk_freeze,
1021 	.restore			= virtblk_restore,
1022 #endif
1023 };
1024 
init(void)1025 static int __init init(void)
1026 {
1027 	int error;
1028 
1029 	virtblk_wq = alloc_workqueue("virtio-blk", 0, 0);
1030 	if (!virtblk_wq)
1031 		return -ENOMEM;
1032 
1033 	major = register_blkdev(0, "virtblk");
1034 	if (major < 0) {
1035 		error = major;
1036 		goto out_destroy_workqueue;
1037 	}
1038 
1039 	error = register_virtio_driver(&virtio_blk);
1040 	if (error)
1041 		goto out_unregister_blkdev;
1042 	return 0;
1043 
1044 out_unregister_blkdev:
1045 	unregister_blkdev(major, "virtblk");
1046 out_destroy_workqueue:
1047 	destroy_workqueue(virtblk_wq);
1048 	return error;
1049 }
1050 
fini(void)1051 static void __exit fini(void)
1052 {
1053 	unregister_virtio_driver(&virtio_blk);
1054 	unregister_blkdev(major, "virtblk");
1055 	destroy_workqueue(virtblk_wq);
1056 }
1057 module_init(init);
1058 module_exit(fini);
1059 
1060 MODULE_DEVICE_TABLE(virtio, id_table);
1061 MODULE_DESCRIPTION("Virtio block driver");
1062 MODULE_LICENSE("GPL");
1063