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