xref: /freebsd/usr.sbin/bhyve/pci_virtio_block.c (revision 6b129086dcee14496517fae085b448e3edc69bc7)
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 
55 #define VTBLK_RINGSZ	64
56 
57 #define VTBLK_MAXSEGS	32
58 
59 #define VTBLK_S_OK	0
60 #define VTBLK_S_IOERR	1
61 #define	VTBLK_S_UNSUPP	2
62 
63 #define	VTBLK_BLK_ID_BYTES	20
64 
65 /* Capability bits */
66 #define	VTBLK_F_SEG_MAX		(1 << 2)	/* Maximum request segments */
67 #define	VTBLK_F_BLK_SIZE       	(1 << 6)	/* cfg block size valid */
68 
69 /*
70  * Host capabilities
71  */
72 #define VTBLK_S_HOSTCAPS      \
73   ( VTBLK_F_SEG_MAX  |						    \
74     VTBLK_F_BLK_SIZE |						    \
75     VIRTIO_RING_F_INDIRECT_DESC )	/* indirect descriptors */
76 
77 /*
78  * Config space "registers"
79  */
80 struct vtblk_config {
81 	uint64_t	vbc_capacity;
82 	uint32_t	vbc_size_max;
83 	uint32_t	vbc_seg_max;
84 	uint16_t	vbc_geom_c;
85 	uint8_t		vbc_geom_h;
86 	uint8_t		vbc_geom_s;
87 	uint32_t	vbc_blk_size;
88 	uint32_t	vbc_sectors_max;
89 } __packed;
90 
91 /*
92  * Fixed-size block header
93  */
94 struct virtio_blk_hdr {
95 #define	VBH_OP_READ		0
96 #define	VBH_OP_WRITE		1
97 #define	VBH_OP_FLUSH		4
98 #define	VBH_OP_FLUSH_OUT	5
99 #define	VBH_OP_IDENT		8
100 #define	VBH_FLAG_BARRIER	0x80000000	/* OR'ed into vbh_type */
101 	uint32_t       	vbh_type;
102 	uint32_t	vbh_ioprio;
103 	uint64_t	vbh_sector;
104 } __packed;
105 
106 /*
107  * Debug printf
108  */
109 static int pci_vtblk_debug;
110 #define DPRINTF(params) if (pci_vtblk_debug) printf params
111 #define WPRINTF(params) printf params
112 
113 /*
114  * Per-device softc
115  */
116 struct pci_vtblk_softc {
117 	struct virtio_softc vbsc_vs;
118 	pthread_mutex_t vsc_mtx;
119 	struct vqueue_info vbsc_vq;
120 	int		vbsc_fd;
121 	struct vtblk_config vbsc_cfg;
122 	char vbsc_ident[VTBLK_BLK_ID_BYTES];
123 };
124 
125 static void pci_vtblk_reset(void *);
126 static void pci_vtblk_notify(void *, struct vqueue_info *);
127 static int pci_vtblk_cfgread(void *, int, int, uint32_t *);
128 static int pci_vtblk_cfgwrite(void *, int, int, uint32_t);
129 
130 static struct virtio_consts vtblk_vi_consts = {
131 	"vtblk",		/* our name */
132 	1,			/* we support 1 virtqueue */
133 	sizeof(struct vtblk_config), /* config reg size */
134 	pci_vtblk_reset,	/* reset */
135 	pci_vtblk_notify,	/* device-wide qnotify */
136 	pci_vtblk_cfgread,	/* read PCI config */
137 	pci_vtblk_cfgwrite,	/* write PCI config */
138 	NULL,			/* apply negotiated features */
139 	VTBLK_S_HOSTCAPS,	/* our capabilities */
140 };
141 
142 static void
143 pci_vtblk_reset(void *vsc)
144 {
145 	struct pci_vtblk_softc *sc = vsc;
146 
147 	DPRINTF(("vtblk: device reset requested !\n"));
148 	vi_reset_dev(&sc->vbsc_vs);
149 }
150 
151 static void
152 pci_vtblk_proc(struct pci_vtblk_softc *sc, struct vqueue_info *vq)
153 {
154 	struct virtio_blk_hdr *vbh;
155 	uint8_t *status;
156 	int i, n;
157 	int err;
158 	int iolen;
159 	int writeop, type;
160 	off_t offset;
161 	struct iovec iov[VTBLK_MAXSEGS + 2];
162 	uint16_t flags[VTBLK_MAXSEGS + 2];
163 
164 	n = vq_getchain(vq, iov, VTBLK_MAXSEGS + 2, flags);
165 
166 	/*
167 	 * The first descriptor will be the read-only fixed header,
168 	 * and the last is for status (hence +2 above and below).
169 	 * The remaining iov's are the actual data I/O vectors.
170 	 *
171 	 * XXX - note - this fails on crash dump, which does a
172 	 * VIRTIO_BLK_T_FLUSH with a zero transfer length
173 	 */
174 	assert(n >= 2 && n <= VTBLK_MAXSEGS + 2);
175 
176 	assert((flags[0] & VRING_DESC_F_WRITE) == 0);
177 	assert(iov[0].iov_len == sizeof(struct virtio_blk_hdr));
178 	vbh = iov[0].iov_base;
179 
180 	status = iov[--n].iov_base;
181 	assert(iov[n].iov_len == 1);
182 	assert(flags[n] & VRING_DESC_F_WRITE);
183 
184 	/*
185 	 * XXX
186 	 * The guest should not be setting the BARRIER flag because
187 	 * we don't advertise the capability.
188 	 */
189 	type = vbh->vbh_type & ~VBH_FLAG_BARRIER;
190 	writeop = (type == VBH_OP_WRITE);
191 
192 	offset = vbh->vbh_sector * DEV_BSIZE;
193 
194 	iolen = 0;
195 	for (i = 1; i < n; i++) {
196 		/*
197 		 * - write op implies read-only descriptor,
198 		 * - read/ident op implies write-only descriptor,
199 		 * therefore test the inverse of the descriptor bit
200 		 * to the op.
201 		 */
202 		assert(((flags[i] & VRING_DESC_F_WRITE) == 0) == writeop);
203 		iolen += iov[i].iov_len;
204 	}
205 
206 	DPRINTF(("virtio-block: %s op, %d bytes, %d segs, offset %ld\n\r",
207 		 writeop ? "write" : "read/ident", iolen, i - 1, offset));
208 
209 	switch (type) {
210 	case VBH_OP_WRITE:
211 		err = pwritev(sc->vbsc_fd, iov + 1, i - 1, offset);
212 		break;
213 	case VBH_OP_READ:
214 		err = preadv(sc->vbsc_fd, iov + 1, i - 1, offset);
215 		break;
216 	case VBH_OP_IDENT:
217 		/* Assume a single buffer */
218 		strlcpy(iov[1].iov_base, sc->vbsc_ident,
219 		    MIN(iov[1].iov_len, sizeof(sc->vbsc_ident)));
220 		err = 0;
221 		break;
222 	case VBH_OP_FLUSH:
223 	case VBH_OP_FLUSH_OUT:
224 		err = fsync(sc->vbsc_fd);
225 		break;
226 	default:
227 		err = -ENOSYS;
228 		break;
229 	}
230 
231 	/* convert errno into a virtio block error return */
232 	if (err < 0) {
233 		if (err == -ENOSYS)
234 			*status = VTBLK_S_UNSUPP;
235 		else
236 			*status = VTBLK_S_IOERR;
237 	} else
238 		*status = VTBLK_S_OK;
239 
240 	/*
241 	 * Return the descriptor back to the host.
242 	 * We wrote 1 byte (our status) to host.
243 	 */
244 	vq_relchain(vq, 1);
245 }
246 
247 static void
248 pci_vtblk_notify(void *vsc, struct vqueue_info *vq)
249 {
250 	struct pci_vtblk_softc *sc = vsc;
251 
252 	vq_startchains(vq);
253 	while (vq_has_descs(vq))
254 		pci_vtblk_proc(sc, vq);
255 	vq_endchains(vq, 1);	/* Generate interrupt if appropriate. */
256 }
257 
258 static int
259 pci_vtblk_init(struct vmctx *ctx, struct pci_devinst *pi, char *opts)
260 {
261 	struct stat sbuf;
262 	MD5_CTX mdctx;
263 	u_char digest[16];
264 	struct pci_vtblk_softc *sc;
265 	off_t size;
266 	int fd;
267 	int sectsz;
268 
269 	if (opts == NULL) {
270 		printf("virtio-block: backing device required\n");
271 		return (1);
272 	}
273 
274 	/*
275 	 * The supplied backing file has to exist
276 	 */
277 	fd = open(opts, O_RDWR);
278 	if (fd < 0) {
279 		perror("Could not open backing file");
280 		return (1);
281 	}
282 
283 	if (fstat(fd, &sbuf) < 0) {
284 		perror("Could not stat backing file");
285 		close(fd);
286 		return (1);
287 	}
288 
289 	/*
290 	 * Deal with raw devices
291 	 */
292 	size = sbuf.st_size;
293 	sectsz = DEV_BSIZE;
294 	if (S_ISCHR(sbuf.st_mode)) {
295 		if (ioctl(fd, DIOCGMEDIASIZE, &size) < 0 ||
296 		    ioctl(fd, DIOCGSECTORSIZE, &sectsz)) {
297 			perror("Could not fetch dev blk/sector size");
298 			close(fd);
299 			return (1);
300 		}
301 		assert(size != 0);
302 		assert(sectsz != 0);
303 	}
304 
305 	sc = calloc(1, sizeof(struct pci_vtblk_softc));
306 
307 	/* record fd of storage device/file */
308 	sc->vbsc_fd = fd;
309 
310 	pthread_mutex_init(&sc->vsc_mtx, NULL);
311 
312 	/* init virtio softc and virtqueues */
313 	vi_softc_linkup(&sc->vbsc_vs, &vtblk_vi_consts, sc, pi, &sc->vbsc_vq);
314 	sc->vbsc_vs.vs_mtx = &sc->vsc_mtx;
315 
316 	sc->vbsc_vq.vq_qsize = VTBLK_RINGSZ;
317 	/* sc->vbsc_vq.vq_notify = we have no per-queue notify */
318 
319 	/*
320 	 * Create an identifier for the backing file. Use parts of the
321 	 * md5 sum of the filename
322 	 */
323 	MD5Init(&mdctx);
324 	MD5Update(&mdctx, opts, strlen(opts));
325 	MD5Final(digest, &mdctx);
326 	sprintf(sc->vbsc_ident, "BHYVE-%02X%02X-%02X%02X-%02X%02X",
327 	    digest[0], digest[1], digest[2], digest[3], digest[4], digest[5]);
328 
329 	/* setup virtio block config space */
330 	sc->vbsc_cfg.vbc_capacity = size / DEV_BSIZE; /* 512-byte units */
331 	sc->vbsc_cfg.vbc_seg_max = VTBLK_MAXSEGS;
332 	sc->vbsc_cfg.vbc_blk_size = sectsz;
333 	sc->vbsc_cfg.vbc_size_max = 0;	/* not negotiated */
334 	sc->vbsc_cfg.vbc_geom_c = 0;	/* no geometry */
335 	sc->vbsc_cfg.vbc_geom_h = 0;
336 	sc->vbsc_cfg.vbc_geom_s = 0;
337 	sc->vbsc_cfg.vbc_sectors_max = 0;
338 
339 	/*
340 	 * Should we move some of this into virtio.c?  Could
341 	 * have the device, class, and subdev_0 as fields in
342 	 * the virtio constants structure.
343 	 */
344 	pci_set_cfgdata16(pi, PCIR_DEVICE, VIRTIO_DEV_BLOCK);
345 	pci_set_cfgdata16(pi, PCIR_VENDOR, VIRTIO_VENDOR);
346 	pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_STORAGE);
347 	pci_set_cfgdata16(pi, PCIR_SUBDEV_0, VIRTIO_TYPE_BLOCK);
348 
349 	pci_lintr_request(pi);
350 
351 	if (vi_intr_init(&sc->vbsc_vs, 1, fbsdrun_virtio_msix()))
352 		return (1);
353 	vi_set_io_bar(&sc->vbsc_vs, 0);
354 	return (0);
355 }
356 
357 static int
358 pci_vtblk_cfgwrite(void *vsc, int offset, int size, uint32_t value)
359 {
360 
361 	DPRINTF(("vtblk: write to readonly reg %d\n\r", offset));
362 	return (1);
363 }
364 
365 static int
366 pci_vtblk_cfgread(void *vsc, int offset, int size, uint32_t *retval)
367 {
368 	struct pci_vtblk_softc *sc = vsc;
369 	void *ptr;
370 
371 	/* our caller has already verified offset and size */
372 	ptr = (uint8_t *)&sc->vbsc_cfg + offset;
373 	memcpy(retval, ptr, size);
374 	return (0);
375 }
376 
377 struct pci_devemu pci_de_vblk = {
378 	.pe_emu =	"virtio-blk",
379 	.pe_init =	pci_vtblk_init,
380 	.pe_barwrite =	vi_pci_write,
381 	.pe_barread =	vi_pci_read
382 };
383 PCI_EMUL_SET(pci_de_vblk);
384