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