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