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