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