xref: /freebsd/usr.sbin/bhyve/pci_virtio_block.c (revision ad6fc754f3d0dc2047171b41cb4d6e13da3deb98)
1 /*-
2  * Copyright (c) 2011 NetApp, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/linker_set.h>
34 #include <sys/stat.h>
35 #include <sys/uio.h>
36 #include <sys/ioctl.h>
37 #include <sys/disk.h>
38 
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <stdint.h>
44 #include <string.h>
45 #include <strings.h>
46 #include <unistd.h>
47 #include <assert.h>
48 #include <pthread.h>
49 #include <md5.h>
50 
51 #include "bhyverun.h"
52 #include "pci_emul.h"
53 #include "virtio.h"
54 #include "block_if.h"
55 
56 #define VTBLK_RINGSZ	64
57 
58 #define VTBLK_MAXSEGS	32
59 
60 #define VTBLK_S_OK	0
61 #define VTBLK_S_IOERR	1
62 #define	VTBLK_S_UNSUPP	2
63 
64 #define	VTBLK_BLK_ID_BYTES	20
65 
66 /* Capability bits */
67 #define	VTBLK_F_SEG_MAX		(1 << 2)	/* Maximum request segments */
68 #define	VTBLK_F_BLK_SIZE	(1 << 6)	/* cfg block size valid */
69 #define	VTBLK_F_TOPOLOGY	(1 << 10)	/* Optimal I/O alignment */
70 
71 /*
72  * Host capabilities
73  */
74 #define VTBLK_S_HOSTCAPS      \
75   ( VTBLK_F_SEG_MAX  |						    \
76     VTBLK_F_BLK_SIZE |						    \
77     VTBLK_F_TOPOLOGY |						    \
78     VIRTIO_RING_F_INDIRECT_DESC )	/* indirect descriptors */
79 
80 /*
81  * Config space "registers"
82  */
83 struct vtblk_config {
84 	uint64_t	vbc_capacity;
85 	uint32_t	vbc_size_max;
86 	uint32_t	vbc_seg_max;
87 	struct {
88 		uint16_t cylinders;
89 		uint8_t heads;
90 		uint8_t sectors;
91 	} vbc_geometry;
92 	uint32_t	vbc_blk_size;
93 	struct {
94 		uint8_t physical_block_exp;
95 		uint8_t alignment_offset;
96 		uint16_t min_io_size;
97 		uint32_t opt_io_size;
98 	} vbc_topology;
99 	uint8_t		vbc_writeback;
100 } __packed;
101 
102 /*
103  * Fixed-size block header
104  */
105 struct virtio_blk_hdr {
106 #define	VBH_OP_READ		0
107 #define	VBH_OP_WRITE		1
108 #define	VBH_OP_FLUSH		4
109 #define	VBH_OP_FLUSH_OUT	5
110 #define	VBH_OP_IDENT		8
111 #define	VBH_FLAG_BARRIER	0x80000000	/* OR'ed into vbh_type */
112 	uint32_t       	vbh_type;
113 	uint32_t	vbh_ioprio;
114 	uint64_t	vbh_sector;
115 } __packed;
116 
117 /*
118  * Debug printf
119  */
120 static int pci_vtblk_debug;
121 #define DPRINTF(params) if (pci_vtblk_debug) printf params
122 #define WPRINTF(params) printf params
123 
124 struct pci_vtblk_ioreq {
125 	struct blockif_req		io_req;
126 	struct pci_vtblk_softc	       *io_sc;
127 	uint8_t			       *io_status;
128 	uint16_t			io_idx;
129 };
130 
131 /*
132  * Per-device softc
133  */
134 struct pci_vtblk_softc {
135 	struct virtio_softc vbsc_vs;
136 	pthread_mutex_t vsc_mtx;
137 	struct vqueue_info vbsc_vq;
138 	struct vtblk_config vbsc_cfg;
139 	struct blockif_ctxt *bc;
140 	char vbsc_ident[VTBLK_BLK_ID_BYTES];
141 	struct pci_vtblk_ioreq vbsc_ios[VTBLK_RINGSZ];
142 };
143 
144 static void pci_vtblk_reset(void *);
145 static void pci_vtblk_notify(void *, struct vqueue_info *);
146 static int pci_vtblk_cfgread(void *, int, int, uint32_t *);
147 static int pci_vtblk_cfgwrite(void *, int, int, uint32_t);
148 
149 static struct virtio_consts vtblk_vi_consts = {
150 	"vtblk",		/* our name */
151 	1,			/* we support 1 virtqueue */
152 	sizeof(struct vtblk_config), /* config reg size */
153 	pci_vtblk_reset,	/* reset */
154 	pci_vtblk_notify,	/* device-wide qnotify */
155 	pci_vtblk_cfgread,	/* read PCI config */
156 	pci_vtblk_cfgwrite,	/* write PCI config */
157 	NULL,			/* apply negotiated features */
158 	VTBLK_S_HOSTCAPS,	/* our capabilities */
159 };
160 
161 static void
162 pci_vtblk_reset(void *vsc)
163 {
164 	struct pci_vtblk_softc *sc = vsc;
165 
166 	DPRINTF(("vtblk: device reset requested !\n"));
167 	vi_reset_dev(&sc->vbsc_vs);
168 }
169 
170 static void
171 pci_vtblk_done(struct blockif_req *br, int err)
172 {
173 	struct pci_vtblk_ioreq *io = br->br_param;
174 	struct pci_vtblk_softc *sc = io->io_sc;
175 
176 	/* convert errno into a virtio block error return */
177 	if (err == EOPNOTSUPP || err == ENOSYS)
178 		*io->io_status = VTBLK_S_UNSUPP;
179 	else if (err != 0)
180 		*io->io_status = VTBLK_S_IOERR;
181 	else
182 		*io->io_status = VTBLK_S_OK;
183 
184 	/*
185 	 * Return the descriptor back to the host.
186 	 * We wrote 1 byte (our status) to host.
187 	 */
188 	pthread_mutex_lock(&sc->vsc_mtx);
189 	vq_relchain(&sc->vbsc_vq, io->io_idx, 1);
190 	vq_endchains(&sc->vbsc_vq, 0);
191 	pthread_mutex_unlock(&sc->vsc_mtx);
192 }
193 
194 static void
195 pci_vtblk_proc(struct pci_vtblk_softc *sc, struct vqueue_info *vq)
196 {
197 	struct virtio_blk_hdr *vbh;
198 	struct pci_vtblk_ioreq *io;
199 	int i, n;
200 	int err;
201 	int iolen;
202 	int writeop, type;
203 	off_t offset;
204 	struct iovec iov[VTBLK_MAXSEGS + 2];
205 	uint16_t idx, flags[VTBLK_MAXSEGS + 2];
206 
207 	n = vq_getchain(vq, &idx, iov, VTBLK_MAXSEGS + 2, flags);
208 
209 	/*
210 	 * The first descriptor will be the read-only fixed header,
211 	 * and the last is for status (hence +2 above and below).
212 	 * The remaining iov's are the actual data I/O vectors.
213 	 *
214 	 * XXX - note - this fails on crash dump, which does a
215 	 * VIRTIO_BLK_T_FLUSH with a zero transfer length
216 	 */
217 	assert(n >= 2 && n <= VTBLK_MAXSEGS + 2);
218 
219 	io = &sc->vbsc_ios[idx];
220 	assert((flags[0] & VRING_DESC_F_WRITE) == 0);
221 	assert(iov[0].iov_len == sizeof(struct virtio_blk_hdr));
222 	vbh = iov[0].iov_base;
223 	memcpy(&io->io_req.br_iov, &iov[1], sizeof(struct iovec) * (n - 2));
224 	io->io_req.br_iovcnt = n - 2;
225 	io->io_req.br_offset = vbh->vbh_sector * DEV_BSIZE;
226 	io->io_status = iov[--n].iov_base;
227 	assert(iov[n].iov_len == 1);
228 	assert(flags[n] & VRING_DESC_F_WRITE);
229 
230 	/*
231 	 * XXX
232 	 * The guest should not be setting the BARRIER flag because
233 	 * we don't advertise the capability.
234 	 */
235 	type = vbh->vbh_type & ~VBH_FLAG_BARRIER;
236 	writeop = (type == VBH_OP_WRITE);
237 
238 	iolen = 0;
239 	for (i = 1; i < n; i++) {
240 		/*
241 		 * - write op implies read-only descriptor,
242 		 * - read/ident op implies write-only descriptor,
243 		 * therefore test the inverse of the descriptor bit
244 		 * to the op.
245 		 */
246 		assert(((flags[i] & VRING_DESC_F_WRITE) == 0) == writeop);
247 		iolen += iov[i].iov_len;
248 	}
249 
250 	DPRINTF(("virtio-block: %s op, %d bytes, %d segs, offset %ld\n\r",
251 		 writeop ? "write" : "read/ident", iolen, i - 1, offset));
252 
253 	switch (type) {
254 	case VBH_OP_READ:
255 		err = blockif_read(sc->bc, &io->io_req);
256 		break;
257 	case VBH_OP_WRITE:
258 		err = blockif_write(sc->bc, &io->io_req);
259 		break;
260 	case VBH_OP_FLUSH:
261 	case VBH_OP_FLUSH_OUT:
262 		err = blockif_flush(sc->bc, &io->io_req);
263 		break;
264 	case VBH_OP_IDENT:
265 		/* Assume a single buffer */
266 		/* S/n equal to buffer is not zero-terminated. */
267 		memset(iov[1].iov_base, 0, iov[1].iov_len);
268 		strncpy(iov[1].iov_base, sc->vbsc_ident,
269 		    MIN(iov[1].iov_len, sizeof(sc->vbsc_ident)));
270 		pci_vtblk_done(&io->io_req, 0);
271 		return;
272 	default:
273 		pci_vtblk_done(&io->io_req, EOPNOTSUPP);
274 		return;
275 	}
276 	assert(err == 0);
277 }
278 
279 static void
280 pci_vtblk_notify(void *vsc, struct vqueue_info *vq)
281 {
282 	struct pci_vtblk_softc *sc = vsc;
283 
284 	while (vq_has_descs(vq))
285 		pci_vtblk_proc(sc, vq);
286 }
287 
288 static int
289 pci_vtblk_init(struct vmctx *ctx, struct pci_devinst *pi, char *opts)
290 {
291 	char bident[sizeof("XX:X:X")];
292 	struct blockif_ctxt *bctxt;
293 	MD5_CTX mdctx;
294 	u_char digest[16];
295 	struct pci_vtblk_softc *sc;
296 	off_t size;
297 	int i, sectsz, sts, sto;
298 
299 	if (opts == NULL) {
300 		printf("virtio-block: backing device required\n");
301 		return (1);
302 	}
303 
304 	/*
305 	 * The supplied backing file has to exist
306 	 */
307 	snprintf(bident, sizeof(bident), "%d:%d", pi->pi_slot, pi->pi_func);
308 	bctxt = blockif_open(opts, bident);
309 	if (bctxt == NULL) {
310 		perror("Could not open backing file");
311 		return (1);
312 	}
313 
314 	size = blockif_size(bctxt);
315 	sectsz = blockif_sectsz(bctxt);
316 	blockif_psectsz(bctxt, &sts, &sto);
317 
318 	sc = calloc(1, sizeof(struct pci_vtblk_softc));
319 	sc->bc = bctxt;
320 	for (i = 0; i < VTBLK_RINGSZ; i++) {
321 		struct pci_vtblk_ioreq *io = &sc->vbsc_ios[i];
322 		io->io_req.br_callback = pci_vtblk_done;
323 		io->io_req.br_param = io;
324 		io->io_sc = sc;
325 		io->io_idx = i;
326 	}
327 
328 	pthread_mutex_init(&sc->vsc_mtx, NULL);
329 
330 	/* init virtio softc and virtqueues */
331 	vi_softc_linkup(&sc->vbsc_vs, &vtblk_vi_consts, sc, pi, &sc->vbsc_vq);
332 	sc->vbsc_vs.vs_mtx = &sc->vsc_mtx;
333 
334 	sc->vbsc_vq.vq_qsize = VTBLK_RINGSZ;
335 	/* sc->vbsc_vq.vq_notify = we have no per-queue notify */
336 
337 	/*
338 	 * Create an identifier for the backing file. Use parts of the
339 	 * md5 sum of the filename
340 	 */
341 	MD5Init(&mdctx);
342 	MD5Update(&mdctx, opts, strlen(opts));
343 	MD5Final(digest, &mdctx);
344 	sprintf(sc->vbsc_ident, "BHYVE-%02X%02X-%02X%02X-%02X%02X",
345 	    digest[0], digest[1], digest[2], digest[3], digest[4], digest[5]);
346 
347 	/* setup virtio block config space */
348 	sc->vbsc_cfg.vbc_capacity = size / DEV_BSIZE; /* 512-byte units */
349 	sc->vbsc_cfg.vbc_size_max = 0;	/* not negotiated */
350 	sc->vbsc_cfg.vbc_seg_max = VTBLK_MAXSEGS;
351 	sc->vbsc_cfg.vbc_geometry.cylinders = 0;	/* no geometry */
352 	sc->vbsc_cfg.vbc_geometry.heads = 0;
353 	sc->vbsc_cfg.vbc_geometry.sectors = 0;
354 	sc->vbsc_cfg.vbc_blk_size = sectsz;
355 	sc->vbsc_cfg.vbc_topology.physical_block_exp =
356 	    (sts > sectsz) ? (ffsll(sts / sectsz) - 1) : 0;
357 	sc->vbsc_cfg.vbc_topology.alignment_offset =
358 	    (sto != 0) ? ((sts - sto) / sectsz) : 0;
359 	sc->vbsc_cfg.vbc_topology.min_io_size = 0;
360 	sc->vbsc_cfg.vbc_topology.opt_io_size = 0;
361 	sc->vbsc_cfg.vbc_writeback = 0;
362 
363 	/*
364 	 * Should we move some of this into virtio.c?  Could
365 	 * have the device, class, and subdev_0 as fields in
366 	 * the virtio constants structure.
367 	 */
368 	pci_set_cfgdata16(pi, PCIR_DEVICE, VIRTIO_DEV_BLOCK);
369 	pci_set_cfgdata16(pi, PCIR_VENDOR, VIRTIO_VENDOR);
370 	pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_STORAGE);
371 	pci_set_cfgdata16(pi, PCIR_SUBDEV_0, VIRTIO_TYPE_BLOCK);
372 
373 	pci_lintr_request(pi);
374 
375 	if (vi_intr_init(&sc->vbsc_vs, 1, fbsdrun_virtio_msix())) {
376 		blockif_close(sc->bc);
377 		free(sc);
378 		return (1);
379 	}
380 	vi_set_io_bar(&sc->vbsc_vs, 0);
381 	return (0);
382 }
383 
384 static int
385 pci_vtblk_cfgwrite(void *vsc, int offset, int size, uint32_t value)
386 {
387 
388 	DPRINTF(("vtblk: write to readonly reg %d\n\r", offset));
389 	return (1);
390 }
391 
392 static int
393 pci_vtblk_cfgread(void *vsc, int offset, int size, uint32_t *retval)
394 {
395 	struct pci_vtblk_softc *sc = vsc;
396 	void *ptr;
397 
398 	/* our caller has already verified offset and size */
399 	ptr = (uint8_t *)&sc->vbsc_cfg + offset;
400 	memcpy(retval, ptr, size);
401 	return (0);
402 }
403 
404 struct pci_devemu pci_de_vblk = {
405 	.pe_emu =	"virtio-blk",
406 	.pe_init =	pci_vtblk_init,
407 	.pe_barwrite =	vi_pci_write,
408 	.pe_barread =	vi_pci_read
409 };
410 PCI_EMUL_SET(pci_de_vblk);
411