1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2011 NetApp, Inc.
5  * All rights reserved.
6  * Copyright 2020-2021 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 /*
30  * This file and its contents are supplied under the terms of the
31  * Common Development and Distribution License ("CDDL"), version 1.0.
32  * You may only use this file in accordance with the terms of version
33  * 1.0 of the CDDL.
34  *
35  * A full copy of the text of the CDDL should have accompanied this
36  * source.  A copy of the CDDL is also available via the Internet at
37  * http://www.illumos.org/license/CDDL.
38  *
39  * Copyright 2014 Pluribus Networks Inc.
40  */
41 
42 #include <sys/cdefs.h>
43 
44 #include <sys/param.h>
45 #include <sys/linker_set.h>
46 #include <sys/stat.h>
47 #include <sys/uio.h>
48 #include <sys/ioctl.h>
49 #include <sys/disk.h>
50 
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <stdint.h>
56 #include <string.h>
57 #include <strings.h>
58 #include <unistd.h>
59 #include <assert.h>
60 #include <pthread.h>
61 #include <md5.h>
62 
63 #include "bhyverun.h"
64 #include "config.h"
65 #include "debug.h"
66 #include "pci_emul.h"
67 #include "virtio.h"
68 #include "block_if.h"
69 
70 #define	VTBLK_BSIZE	512
71 #define	VTBLK_RINGSZ	128
72 
73 _Static_assert(VTBLK_RINGSZ <= BLOCKIF_RING_MAX, "Each ring entry must be able to queue a request");
74 
75 #define	VTBLK_S_OK	0
76 #define	VTBLK_S_IOERR	1
77 #define	VTBLK_S_UNSUPP	2
78 
79 #define	VTBLK_BLK_ID_BYTES	20 + 1
80 
81 /* Capability bits */
82 #define	VTBLK_F_BARRIER		(1 << 0)	/* Does host support barriers? */
83 #define	VTBLK_F_SIZE_MAX	(1 << 1)	/* Indicates maximum segment size */
84 #define	VTBLK_F_SEG_MAX		(1 << 2)	/* Indicates maximum # of segments */
85 #define	VTBLK_F_GEOMETRY	(1 << 4)	/* Legacy geometry available  */
86 #define	VTBLK_F_RO		(1 << 5)	/* Disk is read-only */
87 #define	VTBLK_F_BLK_SIZE	(1 << 6)	/* Block size of disk is available*/
88 #define	VTBLK_F_SCSI		(1 << 7)	/* Supports scsi command passthru */
89 #define	VTBLK_F_FLUSH		(1 << 9)	/* Writeback mode enabled after reset */
90 #define	VTBLK_F_WCE		(1 << 9)	/* Legacy alias for FLUSH */
91 #define	VTBLK_F_TOPOLOGY	(1 << 10)	/* Topology information is available */
92 #define	VTBLK_F_CONFIG_WCE	(1 << 11)	/* Writeback mode available in config */
93 #define	VTBLK_F_MQ		(1 << 12)	/* Multi-Queue */
94 #define	VTBLK_F_DISCARD		(1 << 13)	/* Trim blocks */
95 #define	VTBLK_F_WRITE_ZEROES	(1 << 14)	/* Write zeros */
96 
97 /*
98  * Host capabilities
99  */
100 #define	VTBLK_S_HOSTCAPS      \
101   ( VTBLK_F_SEG_MAX  |						    \
102     VTBLK_F_BLK_SIZE |						    \
103     VTBLK_F_FLUSH    |						    \
104     VTBLK_F_TOPOLOGY |						    \
105     VIRTIO_RING_F_INDIRECT_DESC )	/* indirect descriptors */
106 
107 /*
108  * The current blockif_delete() interface only allows a single delete
109  * request at a time.
110  */
111 #define	VTBLK_MAX_DISCARD_SEG	1
112 
113 /*
114  * An arbitrary limit to prevent excessive latency due to large
115  * delete requests.
116  */
117 #define	VTBLK_MAX_DISCARD_SECT	((16 << 20) / VTBLK_BSIZE)	/* 16 MiB */
118 
119 /*
120  * Config space "registers"
121  */
122 struct vtblk_config {
123 	uint64_t	vbc_capacity;
124 	uint32_t	vbc_size_max;
125 	uint32_t	vbc_seg_max;
126 	struct {
127 		uint16_t cylinders;
128 		uint8_t heads;
129 		uint8_t sectors;
130 	} vbc_geometry;
131 	uint32_t	vbc_blk_size;
132 	struct {
133 		uint8_t physical_block_exp;
134 		uint8_t alignment_offset;
135 		uint16_t min_io_size;
136 		uint32_t opt_io_size;
137 	} vbc_topology;
138 	uint8_t		vbc_writeback;
139 	uint8_t		unused0[1];
140 	uint16_t	num_queues;
141 	uint32_t	max_discard_sectors;
142 	uint32_t	max_discard_seg;
143 	uint32_t	discard_sector_alignment;
144 	uint32_t	max_write_zeroes_sectors;
145 	uint32_t	max_write_zeroes_seg;
146 	uint8_t		write_zeroes_may_unmap;
147 	uint8_t		unused1[3];
148 } __packed;
149 
150 /*
151  * Fixed-size block header
152  */
153 struct virtio_blk_hdr {
154 #define	VBH_OP_READ		0
155 #define	VBH_OP_WRITE		1
156 #define	VBH_OP_SCSI_CMD		2
157 #define	VBH_OP_SCSI_CMD_OUT	3
158 #define	VBH_OP_FLUSH		4
159 #define	VBH_OP_FLUSH_OUT	5
160 #define	VBH_OP_IDENT		8
161 #define	VBH_OP_DISCARD		11
162 #define	VBH_OP_WRITE_ZEROES	13
163 
164 #define	VBH_FLAG_BARRIER	0x80000000	/* OR'ed into vbh_type */
165 	uint32_t	vbh_type;
166 	uint32_t	vbh_ioprio;
167 	uint64_t	vbh_sector;
168 } __packed;
169 
170 /*
171  * Debug printf
172  */
173 static int pci_vtblk_debug;
174 #define	DPRINTF(params) if (pci_vtblk_debug) PRINTLN params
175 #define	WPRINTF(params) PRINTLN params
176 
177 struct pci_vtblk_ioreq {
178 	struct blockif_req		io_req;
179 	struct pci_vtblk_softc		*io_sc;
180 	uint8_t				*io_status;
181 	uint16_t			io_idx;
182 };
183 
184 struct virtio_blk_discard_write_zeroes {
185 	uint64_t	sector;
186 	uint32_t	num_sectors;
187 	struct {
188 		uint32_t unmap:1;
189 		uint32_t reserved:31;
190 	} flags;
191 };
192 
193 /*
194  * Per-device softc
195  */
196 struct pci_vtblk_softc {
197 	struct virtio_softc vbsc_vs;
198 	pthread_mutex_t vsc_mtx;
199 	struct vqueue_info vbsc_vq;
200 	struct vtblk_config vbsc_cfg;
201 	struct virtio_consts vbsc_consts;
202 	struct blockif_ctxt *bc;
203 #ifndef __FreeBSD__
204 	int vbsc_wce;
205 #endif
206 	char vbsc_ident[VTBLK_BLK_ID_BYTES];
207 	struct pci_vtblk_ioreq vbsc_ios[VTBLK_RINGSZ];
208 };
209 
210 static void pci_vtblk_reset(void *);
211 static void pci_vtblk_notify(void *, struct vqueue_info *);
212 static int pci_vtblk_cfgread(void *, int, int, uint32_t *);
213 static int pci_vtblk_cfgwrite(void *, int, int, uint32_t);
214 #ifndef __FreeBSD__
215 static void pci_vtblk_apply_feats(void *, uint64_t);
216 #endif
217 
218 static struct virtio_consts vtblk_vi_consts = {
219 	.vc_name =	"vtblk",
220 	.vc_nvq =	1,
221 	.vc_cfgsize =	sizeof(struct vtblk_config),
222 	.vc_reset =	pci_vtblk_reset,
223 	.vc_qnotify =	pci_vtblk_notify,
224 	.vc_cfgread =	pci_vtblk_cfgread,
225 	.vc_cfgwrite =	pci_vtblk_cfgwrite,
226 #ifndef __FreeBSD__
227 	.vc_apply_features = pci_vtblk_apply_feats,
228 #else
229 	.vc_apply_features = NULL,
230 #endif
231 	.vc_hv_caps =	VTBLK_S_HOSTCAPS,
232 };
233 
234 static void
pci_vtblk_reset(void * vsc)235 pci_vtblk_reset(void *vsc)
236 {
237 	struct pci_vtblk_softc *sc = vsc;
238 
239 	DPRINTF(("vtblk: device reset requested !"));
240 	vi_reset_dev(&sc->vbsc_vs);
241 #ifndef __FreeBSD__
242 	/* Disable write cache until FLUSH feature is negotiated */
243 	(void) blockif_set_wce(sc->bc, 0);
244 	sc->vbsc_wce = 0;
245 #endif
246 }
247 
248 static void
pci_vtblk_done_locked(struct pci_vtblk_ioreq * io,int err)249 pci_vtblk_done_locked(struct pci_vtblk_ioreq *io, int err)
250 {
251 	struct pci_vtblk_softc *sc = io->io_sc;
252 
253 	/* convert errno into a virtio block error return */
254 	if (err == EOPNOTSUPP || err == ENOSYS)
255 		*io->io_status = VTBLK_S_UNSUPP;
256 	else if (err != 0)
257 		*io->io_status = VTBLK_S_IOERR;
258 	else
259 		*io->io_status = VTBLK_S_OK;
260 
261 	/*
262 	 * Return the descriptor back to the host.
263 	 * We wrote 1 byte (our status) to host.
264 	 */
265 	vq_relchain(&sc->vbsc_vq, io->io_idx, 1);
266 	vq_endchains(&sc->vbsc_vq, 0);
267 }
268 
269 static void
pci_vtblk_done(struct blockif_req * br,int err)270 pci_vtblk_done(struct blockif_req *br, int err)
271 {
272 	struct pci_vtblk_ioreq *io = br->br_param;
273 	struct pci_vtblk_softc *sc = io->io_sc;
274 
275 	pthread_mutex_lock(&sc->vsc_mtx);
276 	pci_vtblk_done_locked(io, err);
277 	pthread_mutex_unlock(&sc->vsc_mtx);
278 }
279 
280 static void
pci_vtblk_proc(struct pci_vtblk_softc * sc,struct vqueue_info * vq)281 pci_vtblk_proc(struct pci_vtblk_softc *sc, struct vqueue_info *vq)
282 {
283 	struct virtio_blk_hdr *vbh;
284 	struct pci_vtblk_ioreq *io;
285 	int i, n;
286 	int err;
287 	ssize_t iolen;
288 	int writeop, type;
289 	struct vi_req req;
290 	struct iovec iov[BLOCKIF_IOV_MAX + 2];
291 	struct virtio_blk_discard_write_zeroes *discard;
292 
293 	n = vq_getchain(vq, iov, BLOCKIF_IOV_MAX + 2, &req);
294 
295 	/*
296 	 * The first descriptor will be the read-only fixed header,
297 	 * and the last is for status (hence +2 above and below).
298 	 * The remaining iov's are the actual data I/O vectors.
299 	 *
300 	 * XXX - note - this fails on crash dump, which does a
301 	 * VIRTIO_BLK_T_FLUSH with a zero transfer length
302 	 */
303 	assert(n >= 2 && n <= BLOCKIF_IOV_MAX + 2);
304 
305 	io = &sc->vbsc_ios[req.idx];
306 	assert(req.readable != 0);
307 	assert(iov[0].iov_len == sizeof(struct virtio_blk_hdr));
308 	vbh = (struct virtio_blk_hdr *)iov[0].iov_base;
309 	memcpy(&io->io_req.br_iov, &iov[1], sizeof(struct iovec) * (n - 2));
310 	io->io_req.br_iovcnt = n - 2;
311 	io->io_req.br_offset = vbh->vbh_sector * VTBLK_BSIZE;
312 	io->io_status = (uint8_t *)iov[--n].iov_base;
313 	assert(req.writable != 0);
314 	assert(iov[n].iov_len == 1);
315 
316 	/*
317 	 * XXX
318 	 * The guest should not be setting the BARRIER flag because
319 	 * we don't advertise the capability.
320 	 */
321 	type = vbh->vbh_type & ~VBH_FLAG_BARRIER;
322 	writeop = (type == VBH_OP_WRITE || type == VBH_OP_DISCARD);
323 	/*
324 	 * - Write op implies read-only descriptor
325 	 * - Read/ident op implies write-only descriptor
326 	 *
327 	 * By taking away either the read-only fixed header or the write-only
328 	 * status iovec, the following condition should hold true.
329 	 */
330 	assert(n == (writeop ? req.readable : req.writable));
331 
332 	iolen = 0;
333 	for (i = 1; i < n; i++) {
334 		iolen += iov[i].iov_len;
335 	}
336 	io->io_req.br_resid = iolen;
337 
338 	DPRINTF(("virtio-block: %s op, %zd bytes, %d segs, offset %ld",
339 		 writeop ? "write/discard" : "read/ident", iolen, i - 1,
340 		 io->io_req.br_offset));
341 
342 	switch (type) {
343 	case VBH_OP_READ:
344 		err = blockif_read(sc->bc, &io->io_req);
345 		break;
346 	case VBH_OP_WRITE:
347 		err = blockif_write(sc->bc, &io->io_req);
348 		break;
349 	case VBH_OP_DISCARD:
350 		/*
351 		 * We currently only support a single request, if the guest
352 		 * has submitted a request that doesn't conform to the
353 		 * requirements, we return a error.
354 		 */
355 		if (iov[1].iov_len != sizeof (*discard)) {
356 			pci_vtblk_done_locked(io, EINVAL);
357 			return;
358 		}
359 
360 		/* The segments to discard are provided rather than data */
361 		discard = (struct virtio_blk_discard_write_zeroes *)
362 		    iov[1].iov_base;
363 
364 		/*
365 		 * virtio v1.1 5.2.6.2:
366 		 * The device MUST set the status byte to VIRTIO_BLK_S_UNSUPP
367 		 * for discard and write zeroes commands if any unknown flag is
368 		 * set. Furthermore, the device MUST set the status byte to
369 		 * VIRTIO_BLK_S_UNSUPP for discard commands if the unmap flag
370 		 * is set.
371 		 *
372 		 * Currently there are no known flags for a DISCARD request.
373 		 */
374 		if (discard->flags.unmap != 0 || discard->flags.reserved != 0) {
375 			pci_vtblk_done_locked(io, ENOTSUP);
376 			return;
377 		}
378 
379 		/* Make sure the request doesn't exceed our size limit */
380 		if (discard->num_sectors > VTBLK_MAX_DISCARD_SECT) {
381 			pci_vtblk_done_locked(io, EINVAL);
382 			return;
383 		}
384 
385 		io->io_req.br_offset = discard->sector * VTBLK_BSIZE;
386 		io->io_req.br_resid = discard->num_sectors * VTBLK_BSIZE;
387 		err = blockif_delete(sc->bc, &io->io_req);
388 		break;
389 	case VBH_OP_FLUSH:
390 	case VBH_OP_FLUSH_OUT:
391 		err = blockif_flush(sc->bc, &io->io_req);
392 		break;
393 	case VBH_OP_IDENT:
394 		/* Assume a single buffer */
395 		/* S/n equal to buffer is not zero-terminated. */
396 		memset(iov[1].iov_base, 0, iov[1].iov_len);
397 		strncpy(iov[1].iov_base, sc->vbsc_ident,
398 		    MIN(iov[1].iov_len, sizeof(sc->vbsc_ident)));
399 		pci_vtblk_done_locked(io, 0);
400 		return;
401 	default:
402 		pci_vtblk_done_locked(io, EOPNOTSUPP);
403 		return;
404 	}
405 	assert(err == 0);
406 }
407 
408 static void
pci_vtblk_notify(void * vsc,struct vqueue_info * vq)409 pci_vtblk_notify(void *vsc, struct vqueue_info *vq)
410 {
411 	struct pci_vtblk_softc *sc = vsc;
412 
413 	while (vq_has_descs(vq))
414 		pci_vtblk_proc(sc, vq);
415 }
416 
417 static void
pci_vtblk_resized(struct blockif_ctxt * bctxt __unused,void * arg,size_t new_size)418 pci_vtblk_resized(struct blockif_ctxt *bctxt __unused, void *arg,
419     size_t new_size)
420 {
421 	struct pci_vtblk_softc *sc;
422 
423 	sc = arg;
424 
425 	sc->vbsc_cfg.vbc_capacity = new_size / VTBLK_BSIZE; /* 512-byte units */
426 	vi_interrupt(&sc->vbsc_vs, VIRTIO_PCI_ISR_CONFIG,
427 	    sc->vbsc_vs.vs_msix_cfg_idx);
428 }
429 
430 static int
pci_vtblk_init(struct pci_devinst * pi,nvlist_t * nvl)431 pci_vtblk_init(struct pci_devinst *pi, nvlist_t *nvl)
432 {
433 	char bident[sizeof("XXX:XXX")];
434 	struct blockif_ctxt *bctxt;
435 	const char *path, *serial;
436 	MD5_CTX mdctx;
437 	u_char digest[16];
438 	struct pci_vtblk_softc *sc;
439 	off_t size;
440 	int i, sectsz, sts, sto;
441 
442 	/*
443 	 * The supplied backing file has to exist
444 	 */
445 	snprintf(bident, sizeof(bident), "%u:%u", pi->pi_slot, pi->pi_func);
446 	bctxt = blockif_open(nvl, bident);
447 	if (bctxt == NULL) {
448 		perror("Could not open backing file");
449 		return (1);
450 	}
451 
452 	if (blockif_add_boot_device(pi, bctxt)) {
453 		perror("Invalid boot device");
454 		return (1);
455 	}
456 
457 	size = blockif_size(bctxt);
458 	sectsz = blockif_sectsz(bctxt);
459 	blockif_psectsz(bctxt, &sts, &sto);
460 
461 	sc = calloc(1, sizeof(struct pci_vtblk_softc));
462 	sc->bc = bctxt;
463 	for (i = 0; i < VTBLK_RINGSZ; i++) {
464 		struct pci_vtblk_ioreq *io = &sc->vbsc_ios[i];
465 		io->io_req.br_callback = pci_vtblk_done;
466 		io->io_req.br_param = io;
467 		io->io_sc = sc;
468 		io->io_idx = i;
469 	}
470 
471 	bcopy(&vtblk_vi_consts, &sc->vbsc_consts, sizeof (vtblk_vi_consts));
472 	if (blockif_candelete(sc->bc))
473 		sc->vbsc_consts.vc_hv_caps |= VTBLK_F_DISCARD;
474 
475 #ifndef __FreeBSD__
476 	/* Disable write cache until FLUSH feature is negotiated */
477 	(void) blockif_set_wce(sc->bc, 0);
478 	sc->vbsc_wce = 0;
479 #endif
480 
481 	pthread_mutex_init(&sc->vsc_mtx, NULL);
482 
483 	/* init virtio softc and virtqueues */
484 	vi_softc_linkup(&sc->vbsc_vs, &sc->vbsc_consts, sc, pi, &sc->vbsc_vq);
485 	sc->vbsc_vs.vs_mtx = &sc->vsc_mtx;
486 
487 	sc->vbsc_vq.vq_qsize = VTBLK_RINGSZ;
488 	/* sc->vbsc_vq.vq_notify = we have no per-queue notify */
489 
490 	/*
491 	 * If an explicit identifier is not given, create an
492 	 * identifier using parts of the md5 sum of the filename.
493 	 */
494 	bzero(sc->vbsc_ident, VTBLK_BLK_ID_BYTES);
495 	if ((serial = get_config_value_node(nvl, "serial")) != NULL ||
496 	    (serial = get_config_value_node(nvl, "ser")) != NULL) {
497 		strlcpy(sc->vbsc_ident, serial, VTBLK_BLK_ID_BYTES);
498 	} else {
499 		path = get_config_value_node(nvl, "path");
500 		MD5Init(&mdctx);
501 		MD5Update(&mdctx, path, strlen(path));
502 		MD5Final(digest, &mdctx);
503 		snprintf(sc->vbsc_ident, VTBLK_BLK_ID_BYTES,
504 		    "BHYVE-%02X%02X-%02X%02X-%02X%02X",
505 		    digest[0], digest[1], digest[2], digest[3], digest[4],
506 		    digest[5]);
507 	}
508 
509 	/* setup virtio block config space */
510 	sc->vbsc_cfg.vbc_capacity = size / VTBLK_BSIZE; /* 512-byte units */
511 	sc->vbsc_cfg.vbc_size_max = 0;	/* not negotiated */
512 
513 	/*
514 	 * If Linux is presented with a seg_max greater than the virtio queue
515 	 * size, it can stumble into situations where it violates its own
516 	 * invariants and panics.  For safety, we keep seg_max clamped, paying
517 	 * heed to the two extra descriptors needed for the header and status
518 	 * of a request.
519 	 */
520 	sc->vbsc_cfg.vbc_seg_max = MIN(VTBLK_RINGSZ - 2, BLOCKIF_IOV_MAX);
521 	sc->vbsc_cfg.vbc_geometry.cylinders = 0;	/* no geometry */
522 	sc->vbsc_cfg.vbc_geometry.heads = 0;
523 	sc->vbsc_cfg.vbc_geometry.sectors = 0;
524 	sc->vbsc_cfg.vbc_blk_size = sectsz;
525 	sc->vbsc_cfg.vbc_topology.physical_block_exp =
526 	    (sts > sectsz) ? (ffsll(sts / sectsz) - 1) : 0;
527 	sc->vbsc_cfg.vbc_topology.alignment_offset =
528 	    (sto != 0) ? ((sts - sto) / sectsz) : 0;
529 	sc->vbsc_cfg.vbc_topology.min_io_size = 0;
530 	sc->vbsc_cfg.vbc_topology.opt_io_size = 0;
531 	sc->vbsc_cfg.vbc_writeback = 0;
532 	sc->vbsc_cfg.max_discard_sectors = VTBLK_MAX_DISCARD_SECT;
533 	sc->vbsc_cfg.max_discard_seg = VTBLK_MAX_DISCARD_SEG;
534 	sc->vbsc_cfg.discard_sector_alignment = MAX(sectsz, sts) / VTBLK_BSIZE;
535 
536 	/*
537 	 * Should we move some of this into virtio.c?  Could
538 	 * have the device, class, and subdev_0 as fields in
539 	 * the virtio constants structure.
540 	 */
541 	pci_set_cfgdata16(pi, PCIR_DEVICE, VIRTIO_DEV_BLOCK);
542 	pci_set_cfgdata16(pi, PCIR_VENDOR, VIRTIO_VENDOR);
543 	pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_STORAGE);
544 	pci_set_cfgdata16(pi, PCIR_SUBDEV_0, VIRTIO_ID_BLOCK);
545 	pci_set_cfgdata16(pi, PCIR_SUBVEND_0, VIRTIO_VENDOR);
546 
547 	if (vi_intr_init(&sc->vbsc_vs, 1, fbsdrun_virtio_msix())) {
548 		blockif_close(sc->bc);
549 		free(sc);
550 		return (1);
551 	}
552 	vi_set_io_bar(&sc->vbsc_vs, 0);
553 	blockif_register_resize_callback(sc->bc, pci_vtblk_resized, sc);
554 	return (0);
555 }
556 
557 static int
pci_vtblk_cfgwrite(void * vsc __unused,int offset,int size __unused,uint32_t value __unused)558 pci_vtblk_cfgwrite(void *vsc __unused, int offset, int size __unused,
559     uint32_t value __unused)
560 {
561 
562 	DPRINTF(("vtblk: write to readonly reg %d", offset));
563 	return (1);
564 }
565 
566 static int
pci_vtblk_cfgread(void * vsc,int offset,int size,uint32_t * retval)567 pci_vtblk_cfgread(void *vsc, int offset, int size, uint32_t *retval)
568 {
569 	struct pci_vtblk_softc *sc = vsc;
570 	void *ptr;
571 
572 	/* our caller has already verified offset and size */
573 	ptr = (uint8_t *)&sc->vbsc_cfg + offset;
574 	memcpy(retval, ptr, size);
575 	return (0);
576 }
577 
578 #ifndef __FreeBSD__
579 void
pci_vtblk_apply_feats(void * vsc,uint64_t caps)580 pci_vtblk_apply_feats(void *vsc, uint64_t caps)
581 {
582 	struct pci_vtblk_softc *sc = vsc;
583 	const int wce_next = ((caps & VTBLK_F_FLUSH) != 0) ? 1 : 0;
584 
585 	if (sc->vbsc_wce != wce_next) {
586 		(void) blockif_set_wce(sc->bc, wce_next);
587 		sc->vbsc_wce = wce_next;
588 	}
589 }
590 #endif /* __FreeBSD__ */
591 
592 static const struct pci_devemu pci_de_vblk = {
593 	.pe_emu =	"virtio-blk",
594 	.pe_init =	pci_vtblk_init,
595 	.pe_legacy_config = blockif_legacy_config,
596 	.pe_barwrite =	vi_pci_write,
597 	.pe_barread =	vi_pci_read,
598 };
599 PCI_EMUL_SET(pci_de_vblk);
600