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 <net/ethernet.h>
40 #include <net/if.h> /* IFNAMSIZ */
53 #include <pthread_np.h>
60 #include "net_utils.h"
61 #include "net_backends.h"
64 #define VTNET_RINGSZ 1024
66 #define VTNET_MAXSEGS 256
68 #define VTNET_MAX_PKT_LEN (65536 + 64)
70 #define VTNET_S_HOSTCAPS \
71 ( VIRTIO_NET_F_MAC | VIRTIO_NET_F_STATUS | \
72 VIRTIO_F_NOTIFY_ON_EMPTY | VIRTIO_RING_F_INDIRECT_DESC)
75 * PCI config-space "registers"
77 struct virtio_net_config {
87 #define VTNET_CTLQ 2 /* NB: not yet supported */
94 static int pci_vtnet_debug;
95 #define DPRINTF(params) if (pci_vtnet_debug) PRINTLN params
96 #define WPRINTF(params) PRINTLN params
101 struct pci_vtnet_softc {
102 struct virtio_softc vsc_vs;
103 struct vqueue_info vsc_queues[VTNET_MAXQ - 1];
104 pthread_mutex_t vsc_mtx;
106 net_backend_t *vsc_be;
108 int resetting; /* protected by tx_mtx */
110 uint64_t vsc_features; /* negotiated features */
112 pthread_mutex_t rx_mtx;
113 int rx_merge; /* merged rx bufs in use */
116 pthread_mutex_t tx_mtx;
117 pthread_cond_t tx_cond;
123 struct virtio_net_config vsc_config;
124 struct virtio_consts vsc_consts;
127 static void pci_vtnet_reset(void *);
128 /* static void pci_vtnet_notify(void *, struct vqueue_info *); */
129 static int pci_vtnet_cfgread(void *, int, int, uint32_t *);
130 static int pci_vtnet_cfgwrite(void *, int, int, uint32_t);
131 static void pci_vtnet_neg_features(void *, uint64_t);
133 static struct virtio_consts vtnet_vi_consts = {
134 "vtnet", /* our name */
135 VTNET_MAXQ - 1, /* we currently support 2 virtqueues */
136 sizeof(struct virtio_net_config), /* config reg size */
137 pci_vtnet_reset, /* reset */
138 NULL, /* device-wide qnotify -- not used */
139 pci_vtnet_cfgread, /* read PCI config */
140 pci_vtnet_cfgwrite, /* write PCI config */
141 pci_vtnet_neg_features, /* apply negotiated features */
142 VTNET_S_HOSTCAPS, /* our capabilities */
146 pci_vtnet_reset(void *vsc)
148 struct pci_vtnet_softc *sc = vsc;
150 DPRINTF(("vtnet: device reset requested !"));
152 /* Acquire the RX lock to block RX processing. */
153 pthread_mutex_lock(&sc->rx_mtx);
156 * Make sure receive operation is disabled at least until we
157 * re-negotiate the features, since receive operation depends
158 * on the value of sc->rx_merge and the header length, which
159 * are both set in pci_vtnet_neg_features().
160 * Receive operation will be enabled again once the guest adds
161 * the first receive buffers and kicks us.
163 netbe_rx_disable(sc->vsc_be);
165 /* Set sc->resetting and give a chance to the TX thread to stop. */
166 pthread_mutex_lock(&sc->tx_mtx);
168 while (sc->tx_in_progress) {
169 pthread_mutex_unlock(&sc->tx_mtx);
171 pthread_mutex_lock(&sc->tx_mtx);
175 * Now reset rings, MSI-X vectors, and negotiated capabilities.
176 * Do that with the TX lock held, since we need to reset
179 vi_reset_dev(&sc->vsc_vs);
182 pthread_mutex_unlock(&sc->tx_mtx);
183 pthread_mutex_unlock(&sc->rx_mtx);
186 static __inline struct iovec *
187 iov_trim_hdr(struct iovec *iov, int *iovcnt, unsigned int hlen)
191 if (iov[0].iov_len < hlen) {
193 * Not enough header space in the first fragment.
194 * That's not ok for us.
199 iov[0].iov_len -= hlen;
200 if (iov[0].iov_len == 0) {
204 * Only space for the header. That's not
211 iov[0].iov_base = (void *)((uintptr_t)iov[0].iov_base + hlen);
218 struct virtio_mrg_rxbuf_info {
225 pci_vtnet_rx(struct pci_vtnet_softc *sc)
227 int prepend_hdr_len = sc->vhdrlen - sc->be_vhdrlen;
228 struct virtio_mrg_rxbuf_info info[VTNET_MAXSEGS];
229 struct iovec iov[VTNET_MAXSEGS + 1];
230 struct vqueue_info *vq;
238 vq = &sc->vsc_queues[VTNET_RXQ];
240 struct virtio_net_rxhdr *hdr;
243 * Get a descriptor chain to store the next ingress
244 * packet. In case of mergeable rx buffers, get as
245 * many chains as necessary in order to make room
246 * for a maximum sized LRO packet.
253 int n = vq_getchain(vq, &info[n_chains].idx, riov,
254 VTNET_MAXSEGS - riov_len, NULL);
258 * No rx buffers. Enable RX kicks and double
262 if (!vq_has_descs(vq)) {
264 * Still no buffers. Return the unused
265 * chains (if any), interrupt if needed
266 * (including for NOTIFY_ON_EMPTY), and
267 * disable the backend until the next
270 vq_retchains(vq, n_chains);
271 vq_endchains(vq, /*used_all_avail=*/1);
272 netbe_rx_disable(sc->vsc_be);
276 /* More rx buffers found, so keep going. */
280 assert(n >= 1 && riov_len + n <= VTNET_MAXSEGS);
286 info[n_chains].len = (uint32_t)count_iov(riov, n);
287 riov_bytes += info[n_chains].len;
290 } while (riov_bytes < VTNET_MAX_PKT_LEN &&
291 riov_len < VTNET_MAXSEGS);
294 hdr = riov[0].iov_base;
295 if (prepend_hdr_len > 0) {
297 * The frontend uses a virtio-net header, but the
298 * backend does not. We need to prepend a zeroed
301 riov = iov_trim_hdr(riov, &riov_len, prepend_hdr_len);
304 * The first collected chain is nonsensical,
305 * as it is not even enough to store the
306 * virtio-net header. Just drop it.
308 vq_relchain(vq, info[0].idx, 0);
309 vq_retchains(vq, n_chains - 1);
312 memset(hdr, 0, prepend_hdr_len);
315 len = netbe_recv(sc->vsc_be, riov, riov_len);
319 * No more packets (len == 0), or backend errored
320 * (err < 0). Return unused available buffers
323 vq_retchains(vq, n_chains);
324 /* Interrupt if needed/appropriate and stop. */
325 vq_endchains(vq, /*used_all_avail=*/0);
329 ulen = (uint32_t)(len + prepend_hdr_len);
332 * Publish the used buffers to the guest, reporting the
333 * number of bytes that we wrote.
336 vq_relchain(vq, info[0].idx, ulen);
346 vq_relchain_prepare(vq, info[i].idx, iolen);
349 assert(i <= n_chains);
353 vq_relchain_publish(vq);
354 vq_retchains(vq, n_chains - i);
361 * Called when there is read activity on the backend file descriptor.
362 * Each buffer posted by the guest is assumed to be able to contain
363 * an entire ethernet frame + rx header.
366 pci_vtnet_rx_callback(int fd, enum ev_type type, void *param)
368 struct pci_vtnet_softc *sc = param;
370 pthread_mutex_lock(&sc->rx_mtx);
372 pthread_mutex_unlock(&sc->rx_mtx);
376 /* Called on RX kick. */
378 pci_vtnet_ping_rxq(void *vsc, struct vqueue_info *vq)
380 struct pci_vtnet_softc *sc = vsc;
383 * A qnotify means that the rx process can now begin.
385 pthread_mutex_lock(&sc->rx_mtx);
387 netbe_rx_enable(sc->vsc_be);
388 pthread_mutex_unlock(&sc->rx_mtx);
391 /* TX virtqueue processing, called by the TX thread. */
393 pci_vtnet_proctx(struct pci_vtnet_softc *sc, struct vqueue_info *vq)
395 struct iovec iov[VTNET_MAXSEGS + 1];
396 struct iovec *siov = iov;
402 * Obtain chain of descriptors. The first descriptor also
403 * contains the virtio-net header.
405 n = vq_getchain(vq, &idx, iov, VTNET_MAXSEGS, NULL);
406 assert(n >= 1 && n <= VTNET_MAXSEGS);
408 if (sc->vhdrlen != sc->be_vhdrlen) {
410 * The frontend uses a virtio-net header, but the backend
411 * does not. We simply strip the header and ignore it, as
412 * it should be zero-filled.
414 siov = iov_trim_hdr(siov, &n, sc->vhdrlen);
418 /* The chain is nonsensical. Just drop it. */
421 len = netbe_send(sc->vsc_be, siov, n);
424 * If send failed, report that 0 bytes
432 * Return the processed chain to the guest, reporting
433 * the number of bytes that we read.
435 vq_relchain(vq, idx, len);
438 /* Called on TX kick. */
440 pci_vtnet_ping_txq(void *vsc, struct vqueue_info *vq)
442 struct pci_vtnet_softc *sc = vsc;
445 * Any ring entries to process?
447 if (!vq_has_descs(vq))
450 /* Signal the tx thread for processing */
451 pthread_mutex_lock(&sc->tx_mtx);
453 if (sc->tx_in_progress == 0)
454 pthread_cond_signal(&sc->tx_cond);
455 pthread_mutex_unlock(&sc->tx_mtx);
459 * Thread which will handle processing of TX desc
462 pci_vtnet_tx_thread(void *param)
464 struct pci_vtnet_softc *sc = param;
465 struct vqueue_info *vq;
468 vq = &sc->vsc_queues[VTNET_TXQ];
471 * Let us wait till the tx queue pointers get initialised &
474 pthread_mutex_lock(&sc->tx_mtx);
475 error = pthread_cond_wait(&sc->tx_cond, &sc->tx_mtx);
479 /* note - tx mutex is locked here */
480 while (sc->resetting || !vq_has_descs(vq)) {
482 if (!sc->resetting && vq_has_descs(vq))
485 sc->tx_in_progress = 0;
486 error = pthread_cond_wait(&sc->tx_cond, &sc->tx_mtx);
490 sc->tx_in_progress = 1;
491 pthread_mutex_unlock(&sc->tx_mtx);
495 * Run through entries, placing them into
496 * iovecs and sending when an end-of-packet
499 pci_vtnet_proctx(sc, vq);
500 } while (vq_has_descs(vq));
503 * Generate an interrupt if needed.
505 vq_endchains(vq, /*used_all_avail=*/1);
507 pthread_mutex_lock(&sc->tx_mtx);
513 pci_vtnet_ping_ctlq(void *vsc, struct vqueue_info *vq)
516 DPRINTF(("vtnet: control qnotify!"));
521 pci_vtnet_init(struct vmctx *ctx, struct pci_devinst *pi, char *opts)
523 struct pci_vtnet_softc *sc;
524 char tname[MAXCOMLEN + 1];
528 * Allocate data structures for further virtio initializations.
529 * sc also contains a copy of vtnet_vi_consts, since capabilities
530 * change depending on the backend.
532 sc = calloc(1, sizeof(struct pci_vtnet_softc));
534 sc->vsc_consts = vtnet_vi_consts;
535 pthread_mutex_init(&sc->vsc_mtx, NULL);
537 sc->vsc_queues[VTNET_RXQ].vq_qsize = VTNET_RINGSZ;
538 sc->vsc_queues[VTNET_RXQ].vq_notify = pci_vtnet_ping_rxq;
539 sc->vsc_queues[VTNET_TXQ].vq_qsize = VTNET_RINGSZ;
540 sc->vsc_queues[VTNET_TXQ].vq_notify = pci_vtnet_ping_txq;
542 sc->vsc_queues[VTNET_CTLQ].vq_qsize = VTNET_RINGSZ;
543 sc->vsc_queues[VTNET_CTLQ].vq_notify = pci_vtnet_ping_ctlq;
547 * Attempt to open the backend device and read the MAC address
556 /* Get the device name. */
557 devname = vtopts = strdup(opts);
558 (void) strsep(&vtopts, ",");
561 * Parse the list of options in the form
562 * key1=value1,...,keyN=valueN.
564 while (vtopts != NULL) {
565 char *value = vtopts;
568 key = strsep(&value, "=");
572 (void) strsep(&vtopts, ",");
574 if (strcmp(key, "mac") == 0) {
575 err = net_parsemac(value, sc->vsc_config.mac);
588 err = netbe_init(&sc->vsc_be, devname, pci_vtnet_rx_callback,
595 sc->vsc_consts.vc_hv_caps |= netbe_get_cap(sc->vsc_be);
599 net_genmac(pi, sc->vsc_config.mac);
602 /* initialize config space */
603 pci_set_cfgdata16(pi, PCIR_DEVICE, VIRTIO_DEV_NET);
604 pci_set_cfgdata16(pi, PCIR_VENDOR, VIRTIO_VENDOR);
605 pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_NETWORK);
606 pci_set_cfgdata16(pi, PCIR_SUBDEV_0, VIRTIO_TYPE_NET);
607 pci_set_cfgdata16(pi, PCIR_SUBVEND_0, VIRTIO_VENDOR);
609 /* Link is up if we managed to open backend device. */
610 sc->vsc_config.status = (opts == NULL || sc->vsc_be);
612 vi_softc_linkup(&sc->vsc_vs, &sc->vsc_consts, sc, pi, sc->vsc_queues);
613 sc->vsc_vs.vs_mtx = &sc->vsc_mtx;
615 /* use BAR 1 to map MSI-X table and PBA, if we're using MSI-X */
616 if (vi_intr_init(&sc->vsc_vs, 1, fbsdrun_virtio_msix())) {
621 /* use BAR 0 to map config regs in IO space */
622 vi_set_io_bar(&sc->vsc_vs, 0);
627 sc->vhdrlen = sizeof(struct virtio_net_rxhdr) - 2;
628 pthread_mutex_init(&sc->rx_mtx, NULL);
631 * Initialize tx semaphore & spawn TX processing thread.
632 * As of now, only one thread for TX desc processing is
635 sc->tx_in_progress = 0;
636 pthread_mutex_init(&sc->tx_mtx, NULL);
637 pthread_cond_init(&sc->tx_cond, NULL);
638 pthread_create(&sc->tx_tid, NULL, pci_vtnet_tx_thread, (void *)sc);
639 snprintf(tname, sizeof(tname), "vtnet-%d:%d tx", pi->pi_slot,
641 pthread_set_name_np(sc->tx_tid, tname);
647 pci_vtnet_cfgwrite(void *vsc, int offset, int size, uint32_t value)
649 struct pci_vtnet_softc *sc = vsc;
652 if (offset < (int)sizeof(sc->vsc_config.mac)) {
653 assert(offset + size <= (int)sizeof(sc->vsc_config.mac));
655 * The driver is allowed to change the MAC address
657 ptr = &sc->vsc_config.mac[offset];
658 memcpy(ptr, &value, size);
660 /* silently ignore other writes */
661 DPRINTF(("vtnet: write to readonly reg %d", offset));
668 pci_vtnet_cfgread(void *vsc, int offset, int size, uint32_t *retval)
670 struct pci_vtnet_softc *sc = vsc;
673 ptr = (uint8_t *)&sc->vsc_config + offset;
674 memcpy(retval, ptr, size);
679 pci_vtnet_neg_features(void *vsc, uint64_t negotiated_features)
681 struct pci_vtnet_softc *sc = vsc;
683 sc->vsc_features = negotiated_features;
685 if (negotiated_features & VIRTIO_NET_F_MRG_RXBUF) {
686 sc->vhdrlen = sizeof(struct virtio_net_rxhdr);
690 * Without mergeable rx buffers, virtio-net header is 2
691 * bytes shorter than sizeof(struct virtio_net_rxhdr).
693 sc->vhdrlen = sizeof(struct virtio_net_rxhdr) - 2;
697 /* Tell the backend to enable some capabilities it has advertised. */
698 netbe_set_cap(sc->vsc_be, negotiated_features, sc->vhdrlen);
699 sc->be_vhdrlen = netbe_get_vnet_hdr_len(sc->vsc_be);
700 assert(sc->be_vhdrlen == 0 || sc->be_vhdrlen == sc->vhdrlen);
703 static struct pci_devemu pci_de_vnet = {
704 .pe_emu = "virtio-net",
705 .pe_init = pci_vtnet_init,
706 .pe_barwrite = vi_pci_write,
707 .pe_barread = vi_pci_read
709 PCI_EMUL_SET(pci_de_vnet);