1221828Sgrehan/*-
2221828Sgrehan * Copyright (c) 2011 NetApp, Inc.
3221828Sgrehan * All rights reserved.
4221828Sgrehan *
5221828Sgrehan * Redistribution and use in source and binary forms, with or without
6221828Sgrehan * modification, are permitted provided that the following conditions
7221828Sgrehan * are met:
8221828Sgrehan * 1. Redistributions of source code must retain the above copyright
9221828Sgrehan *    notice, this list of conditions and the following disclaimer.
10221828Sgrehan * 2. Redistributions in binary form must reproduce the above copyright
11221828Sgrehan *    notice, this list of conditions and the following disclaimer in the
12221828Sgrehan *    documentation and/or other materials provided with the distribution.
13221828Sgrehan *
14221828Sgrehan * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
15221828Sgrehan * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16221828Sgrehan * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17221828Sgrehan * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
18221828Sgrehan * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19221828Sgrehan * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20221828Sgrehan * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21221828Sgrehan * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22221828Sgrehan * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23221828Sgrehan * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24221828Sgrehan * SUCH DAMAGE.
25221828Sgrehan *
26221828Sgrehan * $FreeBSD: releng/11.0/usr.sbin/bhyve/pci_virtio_block.c 299675 2016-05-13 14:38:04Z pfg $
27221828Sgrehan */
28221828Sgrehan
29221828Sgrehan#include <sys/cdefs.h>
30221828Sgrehan__FBSDID("$FreeBSD: releng/11.0/usr.sbin/bhyve/pci_virtio_block.c 299675 2016-05-13 14:38:04Z pfg $");
31221828Sgrehan
32221828Sgrehan#include <sys/param.h>
33221828Sgrehan#include <sys/linker_set.h>
34221828Sgrehan#include <sys/stat.h>
35221828Sgrehan#include <sys/uio.h>
36221828Sgrehan#include <sys/ioctl.h>
37244013Sgrehan#include <sys/disk.h>
38221828Sgrehan
39221828Sgrehan#include <errno.h>
40221828Sgrehan#include <fcntl.h>
41221828Sgrehan#include <stdio.h>
42221828Sgrehan#include <stdlib.h>
43221828Sgrehan#include <stdint.h>
44221828Sgrehan#include <string.h>
45221828Sgrehan#include <strings.h>
46221828Sgrehan#include <unistd.h>
47221828Sgrehan#include <assert.h>
48221828Sgrehan#include <pthread.h>
49256389Sgrehan#include <md5.h>
50221828Sgrehan
51244167Sgrehan#include "bhyverun.h"
52221828Sgrehan#include "pci_emul.h"
53221828Sgrehan#include "virtio.h"
54280037Smav#include "block_if.h"
55221828Sgrehan
56221828Sgrehan#define VTBLK_RINGSZ	64
57221828Sgrehan
58221828Sgrehan#define VTBLK_S_OK	0
59221828Sgrehan#define VTBLK_S_IOERR	1
60256389Sgrehan#define	VTBLK_S_UNSUPP	2
61221828Sgrehan
62256389Sgrehan#define	VTBLK_BLK_ID_BYTES	20
63256389Sgrehan
64257005Sgrehan/* Capability bits */
65257005Sgrehan#define	VTBLK_F_SEG_MAX		(1 << 2)	/* Maximum request segments */
66279652Smav#define	VTBLK_F_BLK_SIZE	(1 << 6)	/* cfg block size valid */
67280154Smav#define	VTBLK_F_FLUSH		(1 << 9)	/* Cache flush support */
68279652Smav#define	VTBLK_F_TOPOLOGY	(1 << 10)	/* Optimal I/O alignment */
69257005Sgrehan
70221828Sgrehan/*
71221828Sgrehan * Host capabilities
72221828Sgrehan */
73221828Sgrehan#define VTBLK_S_HOSTCAPS      \
74257005Sgrehan  ( VTBLK_F_SEG_MAX  |						    \
75257005Sgrehan    VTBLK_F_BLK_SIZE |						    \
76280154Smav    VTBLK_F_FLUSH    |						    \
77279652Smav    VTBLK_F_TOPOLOGY |						    \
78253440Sgrehan    VIRTIO_RING_F_INDIRECT_DESC )	/* indirect descriptors */
79221828Sgrehan
80221828Sgrehan/*
81253440Sgrehan * Config space "registers"
82221828Sgrehan */
83221828Sgrehanstruct vtblk_config {
84221828Sgrehan	uint64_t	vbc_capacity;
85221828Sgrehan	uint32_t	vbc_size_max;
86221828Sgrehan	uint32_t	vbc_seg_max;
87279652Smav	struct {
88279652Smav		uint16_t cylinders;
89279652Smav		uint8_t heads;
90279652Smav		uint8_t sectors;
91279652Smav	} vbc_geometry;
92221828Sgrehan	uint32_t	vbc_blk_size;
93279652Smav	struct {
94279652Smav		uint8_t physical_block_exp;
95279652Smav		uint8_t alignment_offset;
96279652Smav		uint16_t min_io_size;
97279652Smav		uint32_t opt_io_size;
98279652Smav	} vbc_topology;
99279652Smav	uint8_t		vbc_writeback;
100221828Sgrehan} __packed;
101221828Sgrehan
102221828Sgrehan/*
103221828Sgrehan * Fixed-size block header
104221828Sgrehan */
105221828Sgrehanstruct virtio_blk_hdr {
106247342Sneel#define	VBH_OP_READ		0
107247342Sneel#define	VBH_OP_WRITE		1
108272710Sneel#define	VBH_OP_FLUSH		4
109272710Sneel#define	VBH_OP_FLUSH_OUT	5
110256389Sgrehan#define	VBH_OP_IDENT		8
111247342Sneel#define	VBH_FLAG_BARRIER	0x80000000	/* OR'ed into vbh_type */
112221828Sgrehan	uint32_t       	vbh_type;
113221828Sgrehan	uint32_t	vbh_ioprio;
114221828Sgrehan	uint64_t	vbh_sector;
115221828Sgrehan} __packed;
116221828Sgrehan
117221828Sgrehan/*
118221828Sgrehan * Debug printf
119221828Sgrehan */
120221828Sgrehanstatic int pci_vtblk_debug;
121221828Sgrehan#define DPRINTF(params) if (pci_vtblk_debug) printf params
122221828Sgrehan#define WPRINTF(params) printf params
123221828Sgrehan
124280037Smavstruct pci_vtblk_ioreq {
125280037Smav	struct blockif_req		io_req;
126280037Smav	struct pci_vtblk_softc	       *io_sc;
127280037Smav	uint8_t			       *io_status;
128280037Smav	uint16_t			io_idx;
129280037Smav};
130280037Smav
131221828Sgrehan/*
132221828Sgrehan * Per-device softc
133221828Sgrehan */
134221828Sgrehanstruct pci_vtblk_softc {
135253440Sgrehan	struct virtio_softc vbsc_vs;
136261268Sjhb	pthread_mutex_t vsc_mtx;
137253440Sgrehan	struct vqueue_info vbsc_vq;
138280037Smav	struct vtblk_config vbsc_cfg;
139280037Smav	struct blockif_ctxt *bc;
140256389Sgrehan	char vbsc_ident[VTBLK_BLK_ID_BYTES];
141280037Smav	struct pci_vtblk_ioreq vbsc_ios[VTBLK_RINGSZ];
142221828Sgrehan};
143221828Sgrehan
144253440Sgrehanstatic void pci_vtblk_reset(void *);
145253440Sgrehanstatic void pci_vtblk_notify(void *, struct vqueue_info *);
146253440Sgrehanstatic int pci_vtblk_cfgread(void *, int, int, uint32_t *);
147253440Sgrehanstatic int pci_vtblk_cfgwrite(void *, int, int, uint32_t);
148246214Sneel
149253440Sgrehanstatic struct virtio_consts vtblk_vi_consts = {
150253440Sgrehan	"vtblk",		/* our name */
151253440Sgrehan	1,			/* we support 1 virtqueue */
152253440Sgrehan	sizeof(struct vtblk_config), /* config reg size */
153253440Sgrehan	pci_vtblk_reset,	/* reset */
154253440Sgrehan	pci_vtblk_notify,	/* device-wide qnotify */
155253440Sgrehan	pci_vtblk_cfgread,	/* read PCI config */
156253440Sgrehan	pci_vtblk_cfgwrite,	/* write PCI config */
157271299Sgrehan	NULL,			/* apply negotiated features */
158253440Sgrehan	VTBLK_S_HOSTCAPS,	/* our capabilities */
159253440Sgrehan};
160246214Sneel
161221828Sgrehanstatic void
162253440Sgrehanpci_vtblk_reset(void *vsc)
163221828Sgrehan{
164253440Sgrehan	struct pci_vtblk_softc *sc = vsc;
165221828Sgrehan
166253440Sgrehan	DPRINTF(("vtblk: device reset requested !\n"));
167253440Sgrehan	vi_reset_dev(&sc->vbsc_vs);
168221828Sgrehan}
169221828Sgrehan
170221828Sgrehanstatic void
171280037Smavpci_vtblk_done(struct blockif_req *br, int err)
172280037Smav{
173280037Smav	struct pci_vtblk_ioreq *io = br->br_param;
174280037Smav	struct pci_vtblk_softc *sc = io->io_sc;
175280037Smav
176280037Smav	/* convert errno into a virtio block error return */
177280037Smav	if (err == EOPNOTSUPP || err == ENOSYS)
178280037Smav		*io->io_status = VTBLK_S_UNSUPP;
179280037Smav	else if (err != 0)
180280037Smav		*io->io_status = VTBLK_S_IOERR;
181280037Smav	else
182280037Smav		*io->io_status = VTBLK_S_OK;
183280037Smav
184280037Smav	/*
185280037Smav	 * Return the descriptor back to the host.
186280037Smav	 * We wrote 1 byte (our status) to host.
187280037Smav	 */
188280037Smav	pthread_mutex_lock(&sc->vsc_mtx);
189280037Smav	vq_relchain(&sc->vbsc_vq, io->io_idx, 1);
190280037Smav	vq_endchains(&sc->vbsc_vq, 0);
191280037Smav	pthread_mutex_unlock(&sc->vsc_mtx);
192280037Smav}
193280037Smav
194280037Smavstatic void
195253440Sgrehanpci_vtblk_proc(struct pci_vtblk_softc *sc, struct vqueue_info *vq)
196221828Sgrehan{
197221828Sgrehan	struct virtio_blk_hdr *vbh;
198280037Smav	struct pci_vtblk_ioreq *io;
199253440Sgrehan	int i, n;
200221828Sgrehan	int err;
201281700Smav	ssize_t iolen;
202253440Sgrehan	int writeop, type;
203280133Smav	struct iovec iov[BLOCKIF_IOV_MAX + 2];
204280133Smav	uint16_t idx, flags[BLOCKIF_IOV_MAX + 2];
205221828Sgrehan
206280133Smav	n = vq_getchain(vq, &idx, iov, BLOCKIF_IOV_MAX + 2, flags);
207221828Sgrehan
208253440Sgrehan	/*
209253440Sgrehan	 * The first descriptor will be the read-only fixed header,
210253440Sgrehan	 * and the last is for status (hence +2 above and below).
211253440Sgrehan	 * The remaining iov's are the actual data I/O vectors.
212253440Sgrehan	 *
213253440Sgrehan	 * XXX - note - this fails on crash dump, which does a
214253440Sgrehan	 * VIRTIO_BLK_T_FLUSH with a zero transfer length
215253440Sgrehan	 */
216280133Smav	assert(n >= 2 && n <= BLOCKIF_IOV_MAX + 2);
217221828Sgrehan
218280037Smav	io = &sc->vbsc_ios[idx];
219253440Sgrehan	assert((flags[0] & VRING_DESC_F_WRITE) == 0);
220253440Sgrehan	assert(iov[0].iov_len == sizeof(struct virtio_blk_hdr));
221253440Sgrehan	vbh = iov[0].iov_base;
222280037Smav	memcpy(&io->io_req.br_iov, &iov[1], sizeof(struct iovec) * (n - 2));
223280037Smav	io->io_req.br_iovcnt = n - 2;
224280037Smav	io->io_req.br_offset = vbh->vbh_sector * DEV_BSIZE;
225280037Smav	io->io_status = iov[--n].iov_base;
226253440Sgrehan	assert(iov[n].iov_len == 1);
227253440Sgrehan	assert(flags[n] & VRING_DESC_F_WRITE);
228221828Sgrehan
229221828Sgrehan	/*
230247342Sneel	 * XXX
231247342Sneel	 * The guest should not be setting the BARRIER flag because
232247342Sneel	 * we don't advertise the capability.
233247342Sneel	 */
234247342Sneel	type = vbh->vbh_type & ~VBH_FLAG_BARRIER;
235247342Sneel	writeop = (type == VBH_OP_WRITE);
236221828Sgrehan
237253440Sgrehan	iolen = 0;
238253440Sgrehan	for (i = 1; i < n; i++) {
239221828Sgrehan		/*
240221828Sgrehan		 * - write op implies read-only descriptor,
241256389Sgrehan		 * - read/ident op implies write-only descriptor,
242221828Sgrehan		 * therefore test the inverse of the descriptor bit
243221828Sgrehan		 * to the op.
244221828Sgrehan		 */
245253440Sgrehan		assert(((flags[i] & VRING_DESC_F_WRITE) == 0) == writeop);
246253440Sgrehan		iolen += iov[i].iov_len;
247221828Sgrehan	}
248281700Smav	io->io_req.br_resid = iolen;
249221828Sgrehan
250281700Smav	DPRINTF(("virtio-block: %s op, %zd bytes, %d segs, offset %ld\n\r",
251299675Spfg		 writeop ? "write" : "read/ident", iolen, i - 1,
252299675Spfg		 io->io_req.br_offset));
253221828Sgrehan
254256389Sgrehan	switch (type) {
255280037Smav	case VBH_OP_READ:
256280037Smav		err = blockif_read(sc->bc, &io->io_req);
257280037Smav		break;
258256389Sgrehan	case VBH_OP_WRITE:
259280037Smav		err = blockif_write(sc->bc, &io->io_req);
260256389Sgrehan		break;
261280037Smav	case VBH_OP_FLUSH:
262280037Smav	case VBH_OP_FLUSH_OUT:
263280037Smav		err = blockif_flush(sc->bc, &io->io_req);
264256389Sgrehan		break;
265256389Sgrehan	case VBH_OP_IDENT:
266256389Sgrehan		/* Assume a single buffer */
267280044Smav		/* S/n equal to buffer is not zero-terminated. */
268280044Smav		memset(iov[1].iov_base, 0, iov[1].iov_len);
269280044Smav		strncpy(iov[1].iov_base, sc->vbsc_ident,
270266935Sneel		    MIN(iov[1].iov_len, sizeof(sc->vbsc_ident)));
271280037Smav		pci_vtblk_done(&io->io_req, 0);
272280037Smav		return;
273256389Sgrehan	default:
274280037Smav		pci_vtblk_done(&io->io_req, EOPNOTSUPP);
275280037Smav		return;
276256389Sgrehan	}
277280037Smav	assert(err == 0);
278221828Sgrehan}
279221828Sgrehan
280221828Sgrehanstatic void
281253440Sgrehanpci_vtblk_notify(void *vsc, struct vqueue_info *vq)
282249813Sneel{
283253440Sgrehan	struct pci_vtblk_softc *sc = vsc;
284249813Sneel
285253440Sgrehan	while (vq_has_descs(vq))
286253440Sgrehan		pci_vtblk_proc(sc, vq);
287249813Sneel}
288249813Sneel
289221828Sgrehanstatic int
290221828Sgrehanpci_vtblk_init(struct vmctx *ctx, struct pci_devinst *pi, char *opts)
291221828Sgrehan{
292280037Smav	char bident[sizeof("XX:X:X")];
293280037Smav	struct blockif_ctxt *bctxt;
294256389Sgrehan	MD5_CTX mdctx;
295256389Sgrehan	u_char digest[16];
296221828Sgrehan	struct pci_vtblk_softc *sc;
297280037Smav	off_t size;
298280037Smav	int i, sectsz, sts, sto;
299221828Sgrehan
300221828Sgrehan	if (opts == NULL) {
301221828Sgrehan		printf("virtio-block: backing device required\n");
302221828Sgrehan		return (1);
303221828Sgrehan	}
304221828Sgrehan
305221828Sgrehan	/*
306221828Sgrehan	 * The supplied backing file has to exist
307221828Sgrehan	 */
308280037Smav	snprintf(bident, sizeof(bident), "%d:%d", pi->pi_slot, pi->pi_func);
309280037Smav	bctxt = blockif_open(opts, bident);
310280037Smav	if (bctxt == NULL) {
311221828Sgrehan		perror("Could not open backing file");
312221828Sgrehan		return (1);
313221828Sgrehan	}
314221828Sgrehan
315280037Smav	size = blockif_size(bctxt);
316280037Smav	sectsz = blockif_sectsz(bctxt);
317280037Smav	blockif_psectsz(bctxt, &sts, &sto);
318244013Sgrehan
319264770Sdelphij	sc = calloc(1, sizeof(struct pci_vtblk_softc));
320280037Smav	sc->bc = bctxt;
321280037Smav	for (i = 0; i < VTBLK_RINGSZ; i++) {
322280037Smav		struct pci_vtblk_ioreq *io = &sc->vbsc_ios[i];
323280037Smav		io->io_req.br_callback = pci_vtblk_done;
324280037Smav		io->io_req.br_param = io;
325280037Smav		io->io_sc = sc;
326280037Smav		io->io_idx = i;
327280037Smav	}
328221828Sgrehan
329261268Sjhb	pthread_mutex_init(&sc->vsc_mtx, NULL);
330261268Sjhb
331253440Sgrehan	/* init virtio softc and virtqueues */
332253440Sgrehan	vi_softc_linkup(&sc->vbsc_vs, &vtblk_vi_consts, sc, pi, &sc->vbsc_vq);
333261268Sjhb	sc->vbsc_vs.vs_mtx = &sc->vsc_mtx;
334261268Sjhb
335253440Sgrehan	sc->vbsc_vq.vq_qsize = VTBLK_RINGSZ;
336253440Sgrehan	/* sc->vbsc_vq.vq_notify = we have no per-queue notify */
337253440Sgrehan
338256389Sgrehan	/*
339256389Sgrehan	 * Create an identifier for the backing file. Use parts of the
340256389Sgrehan	 * md5 sum of the filename
341256389Sgrehan	 */
342256389Sgrehan	MD5Init(&mdctx);
343256389Sgrehan	MD5Update(&mdctx, opts, strlen(opts));
344256389Sgrehan	MD5Final(digest, &mdctx);
345256389Sgrehan	sprintf(sc->vbsc_ident, "BHYVE-%02X%02X-%02X%02X-%02X%02X",
346256389Sgrehan	    digest[0], digest[1], digest[2], digest[3], digest[4], digest[5]);
347256389Sgrehan
348221828Sgrehan	/* setup virtio block config space */
349257005Sgrehan	sc->vbsc_cfg.vbc_capacity = size / DEV_BSIZE; /* 512-byte units */
350279652Smav	sc->vbsc_cfg.vbc_size_max = 0;	/* not negotiated */
351280133Smav	sc->vbsc_cfg.vbc_seg_max = BLOCKIF_IOV_MAX;
352279652Smav	sc->vbsc_cfg.vbc_geometry.cylinders = 0;	/* no geometry */
353279652Smav	sc->vbsc_cfg.vbc_geometry.heads = 0;
354279652Smav	sc->vbsc_cfg.vbc_geometry.sectors = 0;
355244013Sgrehan	sc->vbsc_cfg.vbc_blk_size = sectsz;
356279652Smav	sc->vbsc_cfg.vbc_topology.physical_block_exp =
357279652Smav	    (sts > sectsz) ? (ffsll(sts / sectsz) - 1) : 0;
358279652Smav	sc->vbsc_cfg.vbc_topology.alignment_offset =
359279652Smav	    (sto != 0) ? ((sts - sto) / sectsz) : 0;
360279652Smav	sc->vbsc_cfg.vbc_topology.min_io_size = 0;
361279652Smav	sc->vbsc_cfg.vbc_topology.opt_io_size = 0;
362279652Smav	sc->vbsc_cfg.vbc_writeback = 0;
363221828Sgrehan
364253440Sgrehan	/*
365253440Sgrehan	 * Should we move some of this into virtio.c?  Could
366253440Sgrehan	 * have the device, class, and subdev_0 as fields in
367253440Sgrehan	 * the virtio constants structure.
368253440Sgrehan	 */
369221828Sgrehan	pci_set_cfgdata16(pi, PCIR_DEVICE, VIRTIO_DEV_BLOCK);
370221828Sgrehan	pci_set_cfgdata16(pi, PCIR_VENDOR, VIRTIO_VENDOR);
371221828Sgrehan	pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_STORAGE);
372221828Sgrehan	pci_set_cfgdata16(pi, PCIR_SUBDEV_0, VIRTIO_TYPE_BLOCK);
373282865Sgrehan	pci_set_cfgdata16(pi, PCIR_SUBVEND_0, VIRTIO_VENDOR);
374246214Sneel
375280037Smav	if (vi_intr_init(&sc->vbsc_vs, 1, fbsdrun_virtio_msix())) {
376280037Smav		blockif_close(sc->bc);
377280037Smav		free(sc);
378253440Sgrehan		return (1);
379280037Smav	}
380253440Sgrehan	vi_set_io_bar(&sc->vbsc_vs, 0);
381221828Sgrehan	return (0);
382221828Sgrehan}
383221828Sgrehan
384253440Sgrehanstatic int
385253440Sgrehanpci_vtblk_cfgwrite(void *vsc, int offset, int size, uint32_t value)
386246214Sneel{
387246214Sneel
388253440Sgrehan	DPRINTF(("vtblk: write to readonly reg %d\n\r", offset));
389253440Sgrehan	return (1);
390246214Sneel}
391246214Sneel
392253440Sgrehanstatic int
393253440Sgrehanpci_vtblk_cfgread(void *vsc, int offset, int size, uint32_t *retval)
394221828Sgrehan{
395253440Sgrehan	struct pci_vtblk_softc *sc = vsc;
396222830Sgrehan	void *ptr;
397221828Sgrehan
398253440Sgrehan	/* our caller has already verified offset and size */
399253440Sgrehan	ptr = (uint8_t *)&sc->vbsc_cfg + offset;
400253440Sgrehan	memcpy(retval, ptr, size);
401253440Sgrehan	return (0);
402221828Sgrehan}
403221828Sgrehan
404221828Sgrehanstruct pci_devemu pci_de_vblk = {
405241744Sgrehan	.pe_emu =	"virtio-blk",
406241744Sgrehan	.pe_init =	pci_vtblk_init,
407253440Sgrehan	.pe_barwrite =	vi_pci_write,
408253440Sgrehan	.pe_barread =	vi_pci_read
409221828Sgrehan};
410221828SgrehanPCI_EMUL_SET(pci_de_vblk);
411