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/10.3/usr.sbin/bhyve/pci_virtio_block.c 284900 2015-06-28 03:22:26Z neel $
27221828Sgrehan */
28221828Sgrehan
29221828Sgrehan#include <sys/cdefs.h>
30221828Sgrehan__FBSDID("$FreeBSD: releng/10.3/usr.sbin/bhyve/pci_virtio_block.c 284900 2015-06-28 03:22:26Z neel $");
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>
49256390Sgrehan#include <md5.h>
50221828Sgrehan
51244167Sgrehan#include "bhyverun.h"
52221828Sgrehan#include "pci_emul.h"
53221828Sgrehan#include "virtio.h"
54280744Smav#include "block_if.h"
55221828Sgrehan
56221828Sgrehan#define VTBLK_RINGSZ	64
57221828Sgrehan
58221828Sgrehan#define VTBLK_S_OK	0
59221828Sgrehan#define VTBLK_S_IOERR	1
60256390Sgrehan#define	VTBLK_S_UNSUPP	2
61221828Sgrehan
62256390Sgrehan#define	VTBLK_BLK_ID_BYTES	20
63256390Sgrehan
64257128Sgrehan/* Capability bits */
65257128Sgrehan#define	VTBLK_F_SEG_MAX		(1 << 2)	/* Maximum request segments */
66280243Smav#define	VTBLK_F_BLK_SIZE	(1 << 6)	/* cfg block size valid */
67280750Smav#define	VTBLK_F_FLUSH		(1 << 9)	/* Cache flush support */
68280243Smav#define	VTBLK_F_TOPOLOGY	(1 << 10)	/* Optimal I/O alignment */
69257128Sgrehan
70221828Sgrehan/*
71221828Sgrehan * Host capabilities
72221828Sgrehan */
73221828Sgrehan#define VTBLK_S_HOSTCAPS      \
74257128Sgrehan  ( VTBLK_F_SEG_MAX  |						    \
75257128Sgrehan    VTBLK_F_BLK_SIZE |						    \
76280750Smav    VTBLK_F_FLUSH    |						    \
77280243Smav    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;
87280243Smav	struct {
88280243Smav		uint16_t cylinders;
89280243Smav		uint8_t heads;
90280243Smav		uint8_t sectors;
91280243Smav	} vbc_geometry;
92221828Sgrehan	uint32_t	vbc_blk_size;
93280243Smav	struct {
94280243Smav		uint8_t physical_block_exp;
95280243Smav		uint8_t alignment_offset;
96280243Smav		uint16_t min_io_size;
97280243Smav		uint32_t opt_io_size;
98280243Smav	} vbc_topology;
99280243Smav	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
108276349Sneel#define	VBH_OP_FLUSH		4
109276349Sneel#define	VBH_OP_FLUSH_OUT	5
110256390Sgrehan#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
124280744Smavstruct pci_vtblk_ioreq {
125280744Smav	struct blockif_req		io_req;
126280744Smav	struct pci_vtblk_softc	       *io_sc;
127280744Smav	uint8_t			       *io_status;
128280744Smav	uint16_t			io_idx;
129280744Smav};
130280744Smav
131221828Sgrehan/*
132221828Sgrehan * Per-device softc
133221828Sgrehan */
134221828Sgrehanstruct pci_vtblk_softc {
135253440Sgrehan	struct virtio_softc vbsc_vs;
136267393Sjhb	pthread_mutex_t vsc_mtx;
137253440Sgrehan	struct vqueue_info vbsc_vq;
138280744Smav	struct vtblk_config vbsc_cfg;
139280744Smav	struct blockif_ctxt *bc;
140256390Sgrehan	char vbsc_ident[VTBLK_BLK_ID_BYTES];
141280744Smav	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 */
157271685Sgrehan	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
171280744Smavpci_vtblk_done(struct blockif_req *br, int err)
172280744Smav{
173280744Smav	struct pci_vtblk_ioreq *io = br->br_param;
174280744Smav	struct pci_vtblk_softc *sc = io->io_sc;
175280744Smav
176280744Smav	/* convert errno into a virtio block error return */
177280744Smav	if (err == EOPNOTSUPP || err == ENOSYS)
178280744Smav		*io->io_status = VTBLK_S_UNSUPP;
179280744Smav	else if (err != 0)
180280744Smav		*io->io_status = VTBLK_S_IOERR;
181280744Smav	else
182280744Smav		*io->io_status = VTBLK_S_OK;
183280744Smav
184280744Smav	/*
185280744Smav	 * Return the descriptor back to the host.
186280744Smav	 * We wrote 1 byte (our status) to host.
187280744Smav	 */
188280744Smav	pthread_mutex_lock(&sc->vsc_mtx);
189280744Smav	vq_relchain(&sc->vbsc_vq, io->io_idx, 1);
190280744Smav	vq_endchains(&sc->vbsc_vq, 0);
191280744Smav	pthread_mutex_unlock(&sc->vsc_mtx);
192280744Smav}
193280744Smav
194280744Smavstatic void
195253440Sgrehanpci_vtblk_proc(struct pci_vtblk_softc *sc, struct vqueue_info *vq)
196221828Sgrehan{
197221828Sgrehan	struct virtio_blk_hdr *vbh;
198280744Smav	struct pci_vtblk_ioreq *io;
199253440Sgrehan	int i, n;
200221828Sgrehan	int err;
201282307Smav	ssize_t iolen;
202253440Sgrehan	int writeop, type;
203221828Sgrehan	off_t offset;
204280749Smav	struct iovec iov[BLOCKIF_IOV_MAX + 2];
205280749Smav	uint16_t idx, flags[BLOCKIF_IOV_MAX + 2];
206221828Sgrehan
207280749Smav	n = vq_getchain(vq, &idx, iov, BLOCKIF_IOV_MAX + 2, flags);
208221828Sgrehan
209253440Sgrehan	/*
210253440Sgrehan	 * The first descriptor will be the read-only fixed header,
211253440Sgrehan	 * and the last is for status (hence +2 above and below).
212253440Sgrehan	 * The remaining iov's are the actual data I/O vectors.
213253440Sgrehan	 *
214253440Sgrehan	 * XXX - note - this fails on crash dump, which does a
215253440Sgrehan	 * VIRTIO_BLK_T_FLUSH with a zero transfer length
216253440Sgrehan	 */
217280749Smav	assert(n >= 2 && n <= BLOCKIF_IOV_MAX + 2);
218221828Sgrehan
219280744Smav	io = &sc->vbsc_ios[idx];
220253440Sgrehan	assert((flags[0] & VRING_DESC_F_WRITE) == 0);
221253440Sgrehan	assert(iov[0].iov_len == sizeof(struct virtio_blk_hdr));
222253440Sgrehan	vbh = iov[0].iov_base;
223280744Smav	memcpy(&io->io_req.br_iov, &iov[1], sizeof(struct iovec) * (n - 2));
224280744Smav	io->io_req.br_iovcnt = n - 2;
225280744Smav	io->io_req.br_offset = vbh->vbh_sector * DEV_BSIZE;
226280744Smav	io->io_status = iov[--n].iov_base;
227253440Sgrehan	assert(iov[n].iov_len == 1);
228253440Sgrehan	assert(flags[n] & VRING_DESC_F_WRITE);
229221828Sgrehan
230221828Sgrehan	/*
231247342Sneel	 * XXX
232247342Sneel	 * The guest should not be setting the BARRIER flag because
233247342Sneel	 * we don't advertise the capability.
234247342Sneel	 */
235247342Sneel	type = vbh->vbh_type & ~VBH_FLAG_BARRIER;
236247342Sneel	writeop = (type == VBH_OP_WRITE);
237221828Sgrehan
238253440Sgrehan	iolen = 0;
239253440Sgrehan	for (i = 1; i < n; i++) {
240221828Sgrehan		/*
241221828Sgrehan		 * - write op implies read-only descriptor,
242256390Sgrehan		 * - read/ident op implies write-only descriptor,
243221828Sgrehan		 * therefore test the inverse of the descriptor bit
244221828Sgrehan		 * to the op.
245221828Sgrehan		 */
246253440Sgrehan		assert(((flags[i] & VRING_DESC_F_WRITE) == 0) == writeop);
247253440Sgrehan		iolen += iov[i].iov_len;
248221828Sgrehan	}
249282307Smav	io->io_req.br_resid = iolen;
250221828Sgrehan
251282307Smav	DPRINTF(("virtio-block: %s op, %zd bytes, %d segs, offset %ld\n\r",
252256390Sgrehan		 writeop ? "write" : "read/ident", iolen, i - 1, offset));
253221828Sgrehan
254256390Sgrehan	switch (type) {
255280744Smav	case VBH_OP_READ:
256280744Smav		err = blockif_read(sc->bc, &io->io_req);
257280744Smav		break;
258256390Sgrehan	case VBH_OP_WRITE:
259280744Smav		err = blockif_write(sc->bc, &io->io_req);
260256390Sgrehan		break;
261280744Smav	case VBH_OP_FLUSH:
262280744Smav	case VBH_OP_FLUSH_OUT:
263280744Smav		err = blockif_flush(sc->bc, &io->io_req);
264256390Sgrehan		break;
265256390Sgrehan	case VBH_OP_IDENT:
266256390Sgrehan		/* Assume a single buffer */
267280747Smav		/* S/n equal to buffer is not zero-terminated. */
268280747Smav		memset(iov[1].iov_base, 0, iov[1].iov_len);
269280747Smav		strncpy(iov[1].iov_base, sc->vbsc_ident,
270268976Sjhb		    MIN(iov[1].iov_len, sizeof(sc->vbsc_ident)));
271280744Smav		pci_vtblk_done(&io->io_req, 0);
272280744Smav		return;
273256390Sgrehan	default:
274280744Smav		pci_vtblk_done(&io->io_req, EOPNOTSUPP);
275280744Smav		return;
276256390Sgrehan	}
277280744Smav	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{
292280744Smav	char bident[sizeof("XX:X:X")];
293280744Smav	struct blockif_ctxt *bctxt;
294256390Sgrehan	MD5_CTX mdctx;
295256390Sgrehan	u_char digest[16];
296221828Sgrehan	struct pci_vtblk_softc *sc;
297280744Smav	off_t size;
298280744Smav	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	 */
308280744Smav	snprintf(bident, sizeof(bident), "%d:%d", pi->pi_slot, pi->pi_func);
309280744Smav	bctxt = blockif_open(opts, bident);
310280744Smav	if (bctxt == NULL) {
311221828Sgrehan		perror("Could not open backing file");
312221828Sgrehan		return (1);
313221828Sgrehan	}
314221828Sgrehan
315280744Smav	size = blockif_size(bctxt);
316280744Smav	sectsz = blockif_sectsz(bctxt);
317280744Smav	blockif_psectsz(bctxt, &sts, &sto);
318244013Sgrehan
319268953Sjhb	sc = calloc(1, sizeof(struct pci_vtblk_softc));
320280744Smav	sc->bc = bctxt;
321280744Smav	for (i = 0; i < VTBLK_RINGSZ; i++) {
322280744Smav		struct pci_vtblk_ioreq *io = &sc->vbsc_ios[i];
323280744Smav		io->io_req.br_callback = pci_vtblk_done;
324280744Smav		io->io_req.br_param = io;
325280744Smav		io->io_sc = sc;
326280744Smav		io->io_idx = i;
327280744Smav	}
328221828Sgrehan
329267393Sjhb	pthread_mutex_init(&sc->vsc_mtx, NULL);
330267393Sjhb
331253440Sgrehan	/* init virtio softc and virtqueues */
332253440Sgrehan	vi_softc_linkup(&sc->vbsc_vs, &vtblk_vi_consts, sc, pi, &sc->vbsc_vq);
333267393Sjhb	sc->vbsc_vs.vs_mtx = &sc->vsc_mtx;
334267393Sjhb
335253440Sgrehan	sc->vbsc_vq.vq_qsize = VTBLK_RINGSZ;
336253440Sgrehan	/* sc->vbsc_vq.vq_notify = we have no per-queue notify */
337253440Sgrehan
338256390Sgrehan	/*
339256390Sgrehan	 * Create an identifier for the backing file. Use parts of the
340256390Sgrehan	 * md5 sum of the filename
341256390Sgrehan	 */
342256390Sgrehan	MD5Init(&mdctx);
343256390Sgrehan	MD5Update(&mdctx, opts, strlen(opts));
344256390Sgrehan	MD5Final(digest, &mdctx);
345256390Sgrehan	sprintf(sc->vbsc_ident, "BHYVE-%02X%02X-%02X%02X-%02X%02X",
346256390Sgrehan	    digest[0], digest[1], digest[2], digest[3], digest[4], digest[5]);
347256390Sgrehan
348221828Sgrehan	/* setup virtio block config space */
349257128Sgrehan	sc->vbsc_cfg.vbc_capacity = size / DEV_BSIZE; /* 512-byte units */
350280243Smav	sc->vbsc_cfg.vbc_size_max = 0;	/* not negotiated */
351280749Smav	sc->vbsc_cfg.vbc_seg_max = BLOCKIF_IOV_MAX;
352280243Smav	sc->vbsc_cfg.vbc_geometry.cylinders = 0;	/* no geometry */
353280243Smav	sc->vbsc_cfg.vbc_geometry.heads = 0;
354280243Smav	sc->vbsc_cfg.vbc_geometry.sectors = 0;
355244013Sgrehan	sc->vbsc_cfg.vbc_blk_size = sectsz;
356280243Smav	sc->vbsc_cfg.vbc_topology.physical_block_exp =
357280243Smav	    (sts > sectsz) ? (ffsll(sts / sectsz) - 1) : 0;
358280243Smav	sc->vbsc_cfg.vbc_topology.alignment_offset =
359280243Smav	    (sto != 0) ? ((sts - sto) / sectsz) : 0;
360280243Smav	sc->vbsc_cfg.vbc_topology.min_io_size = 0;
361280243Smav	sc->vbsc_cfg.vbc_topology.opt_io_size = 0;
362280243Smav	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);
373284900Sneel	pci_set_cfgdata16(pi, PCIR_SUBVEND_0, VIRTIO_VENDOR);
374246214Sneel
375280744Smav	if (vi_intr_init(&sc->vbsc_vs, 1, fbsdrun_virtio_msix())) {
376280744Smav		blockif_close(sc->bc);
377280744Smav		free(sc);
378253440Sgrehan		return (1);
379280744Smav	}
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