2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2011 NetApp, Inc.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
34 #include <sys/param.h>
35 #include <sys/linker_set.h>
36 #include <sys/select.h>
38 #include <sys/ioctl.h>
39 #include <machine/vmm_snapshot.h>
40 #include <net/ethernet.h>
41 #include <net/if.h> /* IFNAMSIZ */
54 #include <pthread_np.h>
61 #include "net_utils.h"
62 #include "net_backends.h"
65 #define VTNET_RINGSZ 1024
67 #define VTNET_MAXSEGS 256
69 #define VTNET_MAX_PKT_LEN (65536 + 64)
71 #define VTNET_MIN_MTU ETHERMIN
72 #define VTNET_MAX_MTU 65535
74 #define VTNET_S_HOSTCAPS \
75 ( VIRTIO_NET_F_MAC | VIRTIO_NET_F_STATUS | \
76 VIRTIO_F_NOTIFY_ON_EMPTY | VIRTIO_RING_F_INDIRECT_DESC)
79 * PCI config-space "registers"
81 struct virtio_net_config {
84 uint16_t max_virtqueue_pairs;
93 #define VTNET_CTLQ 2 /* NB: not yet supported */
100 static int pci_vtnet_debug;
101 #define DPRINTF(params) if (pci_vtnet_debug) PRINTLN params
102 #define WPRINTF(params) PRINTLN params
107 struct pci_vtnet_softc {
108 struct virtio_softc vsc_vs;
109 struct vqueue_info vsc_queues[VTNET_MAXQ - 1];
110 pthread_mutex_t vsc_mtx;
112 net_backend_t *vsc_be;
114 int resetting; /* protected by tx_mtx */
116 uint64_t vsc_features; /* negotiated features */
118 pthread_mutex_t rx_mtx;
119 int rx_merge; /* merged rx bufs in use */
122 pthread_mutex_t tx_mtx;
123 pthread_cond_t tx_cond;
129 struct virtio_net_config vsc_config;
130 struct virtio_consts vsc_consts;
133 static void pci_vtnet_reset(void *);
134 /* static void pci_vtnet_notify(void *, struct vqueue_info *); */
135 static int pci_vtnet_cfgread(void *, int, int, uint32_t *);
136 static int pci_vtnet_cfgwrite(void *, int, int, uint32_t);
137 static void pci_vtnet_neg_features(void *, uint64_t);
138 #ifdef BHYVE_SNAPSHOT
139 static void pci_vtnet_pause(void *);
140 static void pci_vtnet_resume(void *);
141 static int pci_vtnet_snapshot(void *, struct vm_snapshot_meta *);
144 static struct virtio_consts vtnet_vi_consts = {
145 "vtnet", /* our name */
146 VTNET_MAXQ - 1, /* we currently support 2 virtqueues */
147 sizeof(struct virtio_net_config), /* config reg size */
148 pci_vtnet_reset, /* reset */
149 NULL, /* device-wide qnotify -- not used */
150 pci_vtnet_cfgread, /* read PCI config */
151 pci_vtnet_cfgwrite, /* write PCI config */
152 pci_vtnet_neg_features, /* apply negotiated features */
153 VTNET_S_HOSTCAPS, /* our capabilities */
154 #ifdef BHYVE_SNAPSHOT
155 pci_vtnet_pause, /* pause rx/tx threads */
156 pci_vtnet_resume, /* resume rx/tx threads */
157 pci_vtnet_snapshot, /* save / restore device state */
162 pci_vtnet_reset(void *vsc)
164 struct pci_vtnet_softc *sc = vsc;
166 DPRINTF(("vtnet: device reset requested !"));
168 /* Acquire the RX lock to block RX processing. */
169 pthread_mutex_lock(&sc->rx_mtx);
172 * Make sure receive operation is disabled at least until we
173 * re-negotiate the features, since receive operation depends
174 * on the value of sc->rx_merge and the header length, which
175 * are both set in pci_vtnet_neg_features().
176 * Receive operation will be enabled again once the guest adds
177 * the first receive buffers and kicks us.
179 netbe_rx_disable(sc->vsc_be);
181 /* Set sc->resetting and give a chance to the TX thread to stop. */
182 pthread_mutex_lock(&sc->tx_mtx);
184 while (sc->tx_in_progress) {
185 pthread_mutex_unlock(&sc->tx_mtx);
187 pthread_mutex_lock(&sc->tx_mtx);
191 * Now reset rings, MSI-X vectors, and negotiated capabilities.
192 * Do that with the TX lock held, since we need to reset
195 vi_reset_dev(&sc->vsc_vs);
198 pthread_mutex_unlock(&sc->tx_mtx);
199 pthread_mutex_unlock(&sc->rx_mtx);
202 static __inline struct iovec *
203 iov_trim_hdr(struct iovec *iov, int *iovcnt, unsigned int hlen)
207 if (iov[0].iov_len < hlen) {
209 * Not enough header space in the first fragment.
210 * That's not ok for us.
215 iov[0].iov_len -= hlen;
216 if (iov[0].iov_len == 0) {
220 * Only space for the header. That's not
227 iov[0].iov_base = (void *)((uintptr_t)iov[0].iov_base + hlen);
234 struct virtio_mrg_rxbuf_info {
241 pci_vtnet_rx(struct pci_vtnet_softc *sc)
243 int prepend_hdr_len = sc->vhdrlen - sc->be_vhdrlen;
244 struct virtio_mrg_rxbuf_info info[VTNET_MAXSEGS];
245 struct iovec iov[VTNET_MAXSEGS + 1];
246 struct vqueue_info *vq;
248 vq = &sc->vsc_queues[VTNET_RXQ];
250 struct virtio_net_rxhdr *hdr;
259 plen = netbe_peek_recvlen(sc->vsc_be);
262 * No more packets (plen == 0), or backend errored
263 * (plen < 0). Interrupt if needed and stop.
265 vq_endchains(vq, /*used_all_avail=*/0);
268 plen += prepend_hdr_len;
271 * Get a descriptor chain to store the next ingress
272 * packet. In case of mergeable rx buffers, get as
273 * many chains as necessary in order to make room
281 int n = vq_getchain(vq, &info[n_chains].idx, riov,
282 VTNET_MAXSEGS - riov_len, NULL);
286 * No rx buffers. Enable RX kicks and double
290 if (!vq_has_descs(vq)) {
292 * Still no buffers. Return the unused
293 * chains (if any), interrupt if needed
294 * (including for NOTIFY_ON_EMPTY), and
295 * disable the backend until the next
298 vq_retchains(vq, n_chains);
299 vq_endchains(vq, /*used_all_avail=*/1);
300 netbe_rx_disable(sc->vsc_be);
304 /* More rx buffers found, so keep going. */
308 assert(n >= 1 && riov_len + n <= VTNET_MAXSEGS);
314 info[n_chains].len = (uint32_t)count_iov(riov, n);
315 riov_bytes += info[n_chains].len;
318 } while (riov_bytes < plen && riov_len < VTNET_MAXSEGS);
321 hdr = riov[0].iov_base;
322 if (prepend_hdr_len > 0) {
324 * The frontend uses a virtio-net header, but the
325 * backend does not. We need to prepend a zeroed
328 riov = iov_trim_hdr(riov, &riov_len, prepend_hdr_len);
331 * The first collected chain is nonsensical,
332 * as it is not even enough to store the
333 * virtio-net header. Just drop it.
335 vq_relchain(vq, info[0].idx, 0);
336 vq_retchains(vq, n_chains - 1);
339 memset(hdr, 0, prepend_hdr_len);
342 rlen = netbe_recv(sc->vsc_be, riov, riov_len);
343 if (rlen != plen - prepend_hdr_len) {
345 * If this happens it means there is something
346 * wrong with the backend (e.g., some other
347 * process is stealing our packets).
349 WPRINTF(("netbe_recv: expected %zd bytes, "
350 "got %zd", plen - prepend_hdr_len, rlen));
351 vq_retchains(vq, n_chains);
355 ulen = (uint32_t)plen;
358 * Publish the used buffers to the guest, reporting the
359 * number of bytes that we wrote.
362 vq_relchain(vq, info[0].idx, ulen);
372 vq_relchain_prepare(vq, info[i].idx, iolen);
378 vq_relchain_publish(vq);
379 assert(i == n_chains);
386 * Called when there is read activity on the backend file descriptor.
387 * Each buffer posted by the guest is assumed to be able to contain
388 * an entire ethernet frame + rx header.
391 pci_vtnet_rx_callback(int fd, enum ev_type type, void *param)
393 struct pci_vtnet_softc *sc = param;
395 pthread_mutex_lock(&sc->rx_mtx);
397 pthread_mutex_unlock(&sc->rx_mtx);
401 /* Called on RX kick. */
403 pci_vtnet_ping_rxq(void *vsc, struct vqueue_info *vq)
405 struct pci_vtnet_softc *sc = vsc;
408 * A qnotify means that the rx process can now begin.
410 pthread_mutex_lock(&sc->rx_mtx);
412 netbe_rx_enable(sc->vsc_be);
413 pthread_mutex_unlock(&sc->rx_mtx);
416 /* TX virtqueue processing, called by the TX thread. */
418 pci_vtnet_proctx(struct pci_vtnet_softc *sc, struct vqueue_info *vq)
420 struct iovec iov[VTNET_MAXSEGS + 1];
421 struct iovec *siov = iov;
427 * Obtain chain of descriptors. The first descriptor also
428 * contains the virtio-net header.
430 n = vq_getchain(vq, &idx, iov, VTNET_MAXSEGS, NULL);
431 assert(n >= 1 && n <= VTNET_MAXSEGS);
433 if (sc->vhdrlen != sc->be_vhdrlen) {
435 * The frontend uses a virtio-net header, but the backend
436 * does not. We simply strip the header and ignore it, as
437 * it should be zero-filled.
439 siov = iov_trim_hdr(siov, &n, sc->vhdrlen);
443 /* The chain is nonsensical. Just drop it. */
446 len = netbe_send(sc->vsc_be, siov, n);
449 * If send failed, report that 0 bytes
457 * Return the processed chain to the guest, reporting
458 * the number of bytes that we read.
460 vq_relchain(vq, idx, len);
463 /* Called on TX kick. */
465 pci_vtnet_ping_txq(void *vsc, struct vqueue_info *vq)
467 struct pci_vtnet_softc *sc = vsc;
470 * Any ring entries to process?
472 if (!vq_has_descs(vq))
475 /* Signal the tx thread for processing */
476 pthread_mutex_lock(&sc->tx_mtx);
478 if (sc->tx_in_progress == 0)
479 pthread_cond_signal(&sc->tx_cond);
480 pthread_mutex_unlock(&sc->tx_mtx);
484 * Thread which will handle processing of TX desc
487 pci_vtnet_tx_thread(void *param)
489 struct pci_vtnet_softc *sc = param;
490 struct vqueue_info *vq;
493 vq = &sc->vsc_queues[VTNET_TXQ];
496 * Let us wait till the tx queue pointers get initialised &
499 pthread_mutex_lock(&sc->tx_mtx);
500 error = pthread_cond_wait(&sc->tx_cond, &sc->tx_mtx);
504 /* note - tx mutex is locked here */
505 while (sc->resetting || !vq_has_descs(vq)) {
507 if (!sc->resetting && vq_has_descs(vq))
510 sc->tx_in_progress = 0;
511 error = pthread_cond_wait(&sc->tx_cond, &sc->tx_mtx);
515 sc->tx_in_progress = 1;
516 pthread_mutex_unlock(&sc->tx_mtx);
520 * Run through entries, placing them into
521 * iovecs and sending when an end-of-packet
524 pci_vtnet_proctx(sc, vq);
525 } while (vq_has_descs(vq));
528 * Generate an interrupt if needed.
530 vq_endchains(vq, /*used_all_avail=*/1);
532 pthread_mutex_lock(&sc->tx_mtx);
538 pci_vtnet_ping_ctlq(void *vsc, struct vqueue_info *vq)
541 DPRINTF(("vtnet: control qnotify!"));
546 pci_vtnet_init(struct vmctx *ctx, struct pci_devinst *pi, char *opts)
548 struct pci_vtnet_softc *sc;
549 char tname[MAXCOMLEN + 1];
552 unsigned long mtu = ETHERMTU;
555 * Allocate data structures for further virtio initializations.
556 * sc also contains a copy of vtnet_vi_consts, since capabilities
557 * change depending on the backend.
559 sc = calloc(1, sizeof(struct pci_vtnet_softc));
561 sc->vsc_consts = vtnet_vi_consts;
562 pthread_mutex_init(&sc->vsc_mtx, NULL);
564 sc->vsc_queues[VTNET_RXQ].vq_qsize = VTNET_RINGSZ;
565 sc->vsc_queues[VTNET_RXQ].vq_notify = pci_vtnet_ping_rxq;
566 sc->vsc_queues[VTNET_TXQ].vq_qsize = VTNET_RINGSZ;
567 sc->vsc_queues[VTNET_TXQ].vq_notify = pci_vtnet_ping_txq;
569 sc->vsc_queues[VTNET_CTLQ].vq_qsize = VTNET_RINGSZ;
570 sc->vsc_queues[VTNET_CTLQ].vq_notify = pci_vtnet_ping_ctlq;
574 * Attempt to open the backend device and read the MAC address
584 /* Get the device name. */
585 optscopy = vtopts = strdup(opts);
586 (void) strsep(&vtopts, ",");
589 * Parse the list of options in the form
590 * key1=value1,...,keyN=valueN.
592 while (vtopts != NULL) {
593 char *value = vtopts;
596 key = strsep(&value, "=");
600 (void) strsep(&vtopts, ",");
602 if (strcmp(key, "mac") == 0) {
603 err = net_parsemac(value, sc->vsc_config.mac);
607 } else if (strcmp(key, "mtu") == 0) {
608 err = net_parsemtu(value, &mtu);
612 if (mtu < VTNET_MIN_MTU || mtu > VTNET_MAX_MTU) {
628 err = netbe_init(&sc->vsc_be, opts, pci_vtnet_rx_callback,
635 sc->vsc_consts.vc_hv_caps |= VIRTIO_NET_F_MRG_RXBUF |
636 netbe_get_cap(sc->vsc_be);
640 net_genmac(pi, sc->vsc_config.mac);
643 sc->vsc_config.mtu = mtu;
645 sc->vsc_consts.vc_hv_caps |= VIRTIO_NET_F_MTU;
649 * Since we do not actually support multiqueue,
650 * set the maximum virtqueue pairs to 1.
652 sc->vsc_config.max_virtqueue_pairs = 1;
654 /* initialize config space */
655 pci_set_cfgdata16(pi, PCIR_DEVICE, VIRTIO_DEV_NET);
656 pci_set_cfgdata16(pi, PCIR_VENDOR, VIRTIO_VENDOR);
657 pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_NETWORK);
658 pci_set_cfgdata16(pi, PCIR_SUBDEV_0, VIRTIO_TYPE_NET);
659 pci_set_cfgdata16(pi, PCIR_SUBVEND_0, VIRTIO_VENDOR);
661 /* Link is up if we managed to open backend device. */
662 sc->vsc_config.status = (opts == NULL || sc->vsc_be);
664 vi_softc_linkup(&sc->vsc_vs, &sc->vsc_consts, sc, pi, sc->vsc_queues);
665 sc->vsc_vs.vs_mtx = &sc->vsc_mtx;
667 /* use BAR 1 to map MSI-X table and PBA, if we're using MSI-X */
668 if (vi_intr_init(&sc->vsc_vs, 1, fbsdrun_virtio_msix())) {
673 /* use BAR 0 to map config regs in IO space */
674 vi_set_io_bar(&sc->vsc_vs, 0);
679 sc->vhdrlen = sizeof(struct virtio_net_rxhdr) - 2;
680 pthread_mutex_init(&sc->rx_mtx, NULL);
683 * Initialize tx semaphore & spawn TX processing thread.
684 * As of now, only one thread for TX desc processing is
687 sc->tx_in_progress = 0;
688 pthread_mutex_init(&sc->tx_mtx, NULL);
689 pthread_cond_init(&sc->tx_cond, NULL);
690 pthread_create(&sc->tx_tid, NULL, pci_vtnet_tx_thread, (void *)sc);
691 snprintf(tname, sizeof(tname), "vtnet-%d:%d tx", pi->pi_slot,
693 pthread_set_name_np(sc->tx_tid, tname);
699 pci_vtnet_cfgwrite(void *vsc, int offset, int size, uint32_t value)
701 struct pci_vtnet_softc *sc = vsc;
704 if (offset < (int)sizeof(sc->vsc_config.mac)) {
705 assert(offset + size <= (int)sizeof(sc->vsc_config.mac));
707 * The driver is allowed to change the MAC address
709 ptr = &sc->vsc_config.mac[offset];
710 memcpy(ptr, &value, size);
712 /* silently ignore other writes */
713 DPRINTF(("vtnet: write to readonly reg %d", offset));
720 pci_vtnet_cfgread(void *vsc, int offset, int size, uint32_t *retval)
722 struct pci_vtnet_softc *sc = vsc;
725 ptr = (uint8_t *)&sc->vsc_config + offset;
726 memcpy(retval, ptr, size);
731 pci_vtnet_neg_features(void *vsc, uint64_t negotiated_features)
733 struct pci_vtnet_softc *sc = vsc;
735 sc->vsc_features = negotiated_features;
737 if (negotiated_features & VIRTIO_NET_F_MRG_RXBUF) {
738 sc->vhdrlen = sizeof(struct virtio_net_rxhdr);
742 * Without mergeable rx buffers, virtio-net header is 2
743 * bytes shorter than sizeof(struct virtio_net_rxhdr).
745 sc->vhdrlen = sizeof(struct virtio_net_rxhdr) - 2;
749 /* Tell the backend to enable some capabilities it has advertised. */
750 netbe_set_cap(sc->vsc_be, negotiated_features, sc->vhdrlen);
751 sc->be_vhdrlen = netbe_get_vnet_hdr_len(sc->vsc_be);
752 assert(sc->be_vhdrlen == 0 || sc->be_vhdrlen == sc->vhdrlen);
755 #ifdef BHYVE_SNAPSHOT
757 pci_vtnet_pause(void *vsc)
759 struct pci_vtnet_softc *sc = vsc;
761 DPRINTF(("vtnet: device pause requested !\n"));
763 /* Acquire the RX lock to block RX processing. */
764 pthread_mutex_lock(&sc->rx_mtx);
766 /* Wait for the transmit thread to finish its processing. */
767 pthread_mutex_lock(&sc->tx_mtx);
768 while (sc->tx_in_progress) {
769 pthread_mutex_unlock(&sc->tx_mtx);
771 pthread_mutex_lock(&sc->tx_mtx);
776 pci_vtnet_resume(void *vsc)
778 struct pci_vtnet_softc *sc = vsc;
780 DPRINTF(("vtnet: device resume requested !\n"));
782 pthread_mutex_unlock(&sc->tx_mtx);
783 /* The RX lock should have been acquired in vtnet_pause. */
784 pthread_mutex_unlock(&sc->rx_mtx);
788 pci_vtnet_snapshot(void *vsc, struct vm_snapshot_meta *meta)
791 struct pci_vtnet_softc *sc = vsc;
793 DPRINTF(("vtnet: device snapshot requested !\n"));
796 * Queues and consts should have been saved by the more generic
797 * vi_pci_snapshot function. We need to save only our features and
801 SNAPSHOT_VAR_OR_LEAVE(sc->vsc_features, meta, ret, done);
803 /* Force reapply negociated features at restore time */
804 if (meta->op == VM_SNAPSHOT_RESTORE) {
805 pci_vtnet_neg_features(sc, sc->vsc_features);
806 netbe_rx_enable(sc->vsc_be);
809 SNAPSHOT_VAR_OR_LEAVE(sc->vsc_config, meta, ret, done);
810 SNAPSHOT_VAR_OR_LEAVE(sc->rx_merge, meta, ret, done);
812 SNAPSHOT_VAR_OR_LEAVE(sc->vhdrlen, meta, ret, done);
813 SNAPSHOT_VAR_OR_LEAVE(sc->be_vhdrlen, meta, ret, done);
820 static struct pci_devemu pci_de_vnet = {
821 .pe_emu = "virtio-net",
822 .pe_init = pci_vtnet_init,
823 .pe_barwrite = vi_pci_write,
824 .pe_barread = vi_pci_read,
825 #ifdef BHYVE_SNAPSHOT
826 .pe_snapshot = vi_pci_snapshot,
827 .pe_pause = vi_pci_pause,
828 .pe_resume = vi_pci_resume,
831 PCI_EMUL_SET(pci_de_vnet);