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