2 * Copyright (c) 2004-2006 Kip Macy
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``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 THE AUTHOR 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
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
31 #include "opt_inet6.h"
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/sockio.h>
36 #include <sys/limits.h>
38 #include <sys/malloc.h>
39 #include <sys/module.h>
40 #include <sys/kernel.h>
41 #include <sys/socket.h>
42 #include <sys/sysctl.h>
43 #include <sys/queue.h>
48 #include <net/if_var.h>
49 #include <net/if_arp.h>
50 #include <net/ethernet.h>
51 #include <net/if_dl.h>
52 #include <net/if_media.h>
56 #include <net/if_types.h>
58 #include <netinet/in_systm.h>
59 #include <netinet/in.h>
60 #include <netinet/ip.h>
61 #include <netinet/if_ether.h>
62 #if __FreeBSD_version >= 700000
63 #include <netinet/tcp.h>
64 #include <netinet/tcp_lro.h>
70 #include <machine/clock.h> /* for DELAY */
71 #include <machine/bus.h>
72 #include <machine/resource.h>
73 #include <machine/frame.h>
74 #include <machine/vmparam.h>
79 #include <machine/intr_machdep.h>
81 #include <xen/xen-os.h>
82 #include <xen/hypervisor.h>
83 #include <xen/xen_intr.h>
84 #include <xen/gnttab.h>
85 #include <xen/interface/memory.h>
86 #include <xen/interface/io/netif.h>
87 #include <xen/xenbus/xenbusvar.h>
89 #include <machine/xen/xenvar.h>
91 #include "xenbus_if.h"
93 /* Features supported by all backends. TSO and LRO can be negotiated */
94 #define XN_CSUM_FEATURES (CSUM_TCP | CSUM_UDP)
96 #define NET_TX_RING_SIZE __RING_SIZE((netif_tx_sring_t *)0, PAGE_SIZE)
97 #define NET_RX_RING_SIZE __RING_SIZE((netif_rx_sring_t *)0, PAGE_SIZE)
99 #if __FreeBSD_version >= 700000
101 * Should the driver do LRO on the RX end
102 * this can be toggled on the fly, but the
103 * interface must be reset (down/up) for it
106 static int xn_enable_lro = 1;
107 TUNABLE_INT("hw.xn.enable_lro", &xn_enable_lro);
116 static int MODPARM_rx_copy = 0;
117 module_param_named(rx_copy, MODPARM_rx_copy, bool, 0);
118 MODULE_PARM_DESC(rx_copy, "Copy packets from network card (rather than flip)");
119 static int MODPARM_rx_flip = 0;
120 module_param_named(rx_flip, MODPARM_rx_flip, bool, 0);
121 MODULE_PARM_DESC(rx_flip, "Flip packets from network card (rather than copy)");
123 static const int MODPARM_rx_copy = 1;
124 static const int MODPARM_rx_flip = 0;
128 * \brief The maximum allowed data fragments in a single transmit
131 * This limit is imposed by the backend driver. We assume here that
132 * we are dealing with a Linux driver domain and have set our limit
133 * to mirror the Linux MAX_SKB_FRAGS constant.
135 #define MAX_TX_REQ_FRAGS (65536 / PAGE_SIZE + 2)
137 #define RX_COPY_THRESHOLD 256
139 #define net_ratelimit() 0
141 struct netfront_info;
142 struct netfront_rx_info;
144 static void xn_txeof(struct netfront_info *);
145 static void xn_rxeof(struct netfront_info *);
146 static void network_alloc_rx_buffers(struct netfront_info *);
148 static void xn_tick_locked(struct netfront_info *);
149 static void xn_tick(void *);
151 static void xn_intr(void *);
152 static inline int xn_count_frags(struct mbuf *m);
153 static int xn_assemble_tx_request(struct netfront_info *sc,
154 struct mbuf *m_head);
155 static void xn_start_locked(struct ifnet *);
156 static void xn_start(struct ifnet *);
157 static int xn_ioctl(struct ifnet *, u_long, caddr_t);
158 static void xn_ifinit_locked(struct netfront_info *);
159 static void xn_ifinit(void *);
160 static void xn_stop(struct netfront_info *);
161 static void xn_query_features(struct netfront_info *np);
162 static int xn_configure_features(struct netfront_info *np);
164 static void xn_watchdog(struct ifnet *);
168 static void netfront_closing(device_t dev);
170 static void netif_free(struct netfront_info *info);
171 static int netfront_detach(device_t dev);
173 static int talk_to_backend(device_t dev, struct netfront_info *info);
174 static int create_netdev(device_t dev);
175 static void netif_disconnect_backend(struct netfront_info *info);
176 static int setup_device(device_t dev, struct netfront_info *info);
177 static void free_ring(int *ref, void *ring_ptr_ref);
179 static int xn_ifmedia_upd(struct ifnet *ifp);
180 static void xn_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr);
182 /* Xenolinux helper functions */
183 int network_connect(struct netfront_info *);
185 static void xn_free_rx_ring(struct netfront_info *);
187 static void xn_free_tx_ring(struct netfront_info *);
189 static int xennet_get_responses(struct netfront_info *np,
190 struct netfront_rx_info *rinfo, RING_IDX rp, RING_IDX *cons,
191 struct mbuf **list, int *pages_flipped_p);
193 #define virt_to_mfn(x) (vtomach(x) >> PAGE_SHIFT)
195 #define INVALID_P2M_ENTRY (~0UL)
198 * Mbuf pointers. We need these to keep track of the virtual addresses
199 * of our mbuf chains since we can only convert from virtual to physical,
200 * not the other way around. The size must track the free index arrays.
202 struct xn_chain_data {
203 struct mbuf *xn_tx_chain[NET_TX_RING_SIZE+1];
205 struct mbuf *xn_rx_chain[NET_RX_RING_SIZE+1];
208 struct net_device_stats
210 u_long rx_packets; /* total packets received */
211 u_long tx_packets; /* total packets transmitted */
212 u_long rx_bytes; /* total bytes received */
213 u_long tx_bytes; /* total bytes transmitted */
214 u_long rx_errors; /* bad packets received */
215 u_long tx_errors; /* packet transmit problems */
216 u_long rx_dropped; /* no space in linux buffers */
217 u_long tx_dropped; /* no space available in linux */
218 u_long multicast; /* multicast packets received */
221 /* detailed rx_errors: */
222 u_long rx_length_errors;
223 u_long rx_over_errors; /* receiver ring buff overflow */
224 u_long rx_crc_errors; /* recved pkt with crc error */
225 u_long rx_frame_errors; /* recv'd frame alignment error */
226 u_long rx_fifo_errors; /* recv'r fifo overrun */
227 u_long rx_missed_errors; /* receiver missed packet */
229 /* detailed tx_errors */
230 u_long tx_aborted_errors;
231 u_long tx_carrier_errors;
232 u_long tx_fifo_errors;
233 u_long tx_heartbeat_errors;
234 u_long tx_window_errors;
237 u_long rx_compressed;
238 u_long tx_compressed;
241 struct netfront_info {
242 struct ifnet *xn_ifp;
243 #if __FreeBSD_version >= 700000
244 struct lro_ctrl xn_lro;
247 struct net_device_stats stats;
250 netif_tx_front_ring_t tx;
251 netif_rx_front_ring_t rx;
257 xen_intr_handle_t xen_intr_handle;
258 u_int copying_receiver;
262 /* Receive-ring batched refills. */
263 #define RX_MIN_TARGET 32
264 #define RX_MAX_TARGET NET_RX_RING_SIZE
269 grant_ref_t gref_tx_head;
270 grant_ref_t grant_tx_ref[NET_TX_RING_SIZE + 1];
271 grant_ref_t gref_rx_head;
272 grant_ref_t grant_rx_ref[NET_TX_RING_SIZE + 1];
277 uint8_t mac[ETHER_ADDR_LEN];
278 struct xn_chain_data xn_cdata; /* mbufs */
279 struct mbufq xn_rx_batch; /* batch queue */
282 struct callout xn_stat_ch;
284 u_long rx_pfn_array[NET_RX_RING_SIZE];
285 multicall_entry_t rx_mcl[NET_RX_RING_SIZE+1];
286 mmu_update_t rx_mmu[NET_RX_RING_SIZE];
287 struct ifmedia sc_media;
290 #define rx_mbufs xn_cdata.xn_rx_chain
291 #define tx_mbufs xn_cdata.xn_tx_chain
293 #define XN_LOCK_INIT(_sc, _name) \
294 mtx_init(&(_sc)->tx_lock, #_name"_tx", "network transmit lock", MTX_DEF); \
295 mtx_init(&(_sc)->rx_lock, #_name"_rx", "network receive lock", MTX_DEF); \
296 mtx_init(&(_sc)->sc_lock, #_name"_sc", "netfront softc lock", MTX_DEF)
298 #define XN_RX_LOCK(_sc) mtx_lock(&(_sc)->rx_lock)
299 #define XN_RX_UNLOCK(_sc) mtx_unlock(&(_sc)->rx_lock)
301 #define XN_TX_LOCK(_sc) mtx_lock(&(_sc)->tx_lock)
302 #define XN_TX_UNLOCK(_sc) mtx_unlock(&(_sc)->tx_lock)
304 #define XN_LOCK(_sc) mtx_lock(&(_sc)->sc_lock);
305 #define XN_UNLOCK(_sc) mtx_unlock(&(_sc)->sc_lock);
307 #define XN_LOCK_ASSERT(_sc) mtx_assert(&(_sc)->sc_lock, MA_OWNED);
308 #define XN_RX_LOCK_ASSERT(_sc) mtx_assert(&(_sc)->rx_lock, MA_OWNED);
309 #define XN_TX_LOCK_ASSERT(_sc) mtx_assert(&(_sc)->tx_lock, MA_OWNED);
310 #define XN_LOCK_DESTROY(_sc) mtx_destroy(&(_sc)->rx_lock); \
311 mtx_destroy(&(_sc)->tx_lock); \
312 mtx_destroy(&(_sc)->sc_lock);
314 struct netfront_rx_info {
315 struct netif_rx_response rx;
316 struct netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX - 1];
319 #define netfront_carrier_on(netif) ((netif)->carrier = 1)
320 #define netfront_carrier_off(netif) ((netif)->carrier = 0)
321 #define netfront_carrier_ok(netif) ((netif)->carrier)
323 /* Access macros for acquiring freeing slots in xn_free_{tx,rx}_idxs[]. */
326 add_id_to_freelist(struct mbuf **list, uintptr_t id)
329 ("%s: the head item (0) must always be free.", __func__));
331 list[0] = (struct mbuf *)id;
334 static inline unsigned short
335 get_id_from_freelist(struct mbuf **list)
339 id = (uintptr_t)list[0];
341 ("%s: the head item (0) must always remain free.", __func__));
347 xennet_rxidx(RING_IDX idx)
349 return idx & (NET_RX_RING_SIZE - 1);
352 static inline struct mbuf *
353 xennet_get_rx_mbuf(struct netfront_info *np, RING_IDX ri)
355 int i = xennet_rxidx(ri);
359 np->rx_mbufs[i] = NULL;
363 static inline grant_ref_t
364 xennet_get_rx_ref(struct netfront_info *np, RING_IDX ri)
366 int i = xennet_rxidx(ri);
367 grant_ref_t ref = np->grant_rx_ref[i];
368 KASSERT(ref != GRANT_REF_INVALID, ("Invalid grant reference!\n"));
369 np->grant_rx_ref[i] = GRANT_REF_INVALID;
373 #define IPRINTK(fmt, args...) \
374 printf("[XEN] " fmt, ##args)
376 #define WPRINTK(fmt, args...) \
377 printf("[XEN] " fmt, ##args)
379 #define WPRINTK(fmt, args...)
382 #define DPRINTK(fmt, args...) \
383 printf("[XEN] %s: " fmt, __func__, ##args)
385 #define DPRINTK(fmt, args...)
389 * Read the 'mac' node at the given device's node in the store, and parse that
390 * as colon-separated octets, placing result the given mac array. mac must be
391 * a preallocated array of length ETH_ALEN (as declared in linux/if_ether.h).
392 * Return 0 on success, or errno on error.
395 xen_net_read_mac(device_t dev, uint8_t mac[])
398 char *s, *e, *macstr;
401 path = xenbus_get_node(dev);
402 error = xs_read(XST_NIL, path, "mac", NULL, (void **) &macstr);
403 if (error == ENOENT) {
405 * Deal with missing mac XenStore nodes on devices with
406 * HVM emulation (the 'ioemu' configuration attribute)
409 * The HVM emulator may execute in a stub device model
410 * domain which lacks the permission, only given to Dom0,
411 * to update the guest's XenStore tree. For this reason,
412 * the HVM emulator doesn't even attempt to write the
413 * front-side mac node, even when operating in Dom0.
414 * However, there should always be a mac listed in the
415 * backend tree. Fallback to this version if our query
416 * of the front side XenStore location doesn't find
419 path = xenbus_get_otherend_path(dev);
420 error = xs_read(XST_NIL, path, "mac", NULL, (void **) &macstr);
423 xenbus_dev_fatal(dev, error, "parsing %s/mac", path);
428 for (i = 0; i < ETHER_ADDR_LEN; i++) {
429 mac[i] = strtoul(s, &e, 16);
430 if (s == e || (e[0] != ':' && e[0] != 0)) {
431 free(macstr, M_XENBUS);
436 free(macstr, M_XENBUS);
441 * Entry point to this code when a new device is created. Allocate the basic
442 * structures and the ring buffers for communication with the backend, and
443 * inform the backend of the appropriate details for those. Switch to
447 netfront_probe(device_t dev)
450 if (!strcmp(xenbus_get_type(dev), "vif")) {
451 device_set_desc(dev, "Virtual Network Interface");
459 netfront_attach(device_t dev)
463 err = create_netdev(dev);
465 xenbus_dev_fatal(dev, err, "creating netdev");
469 #if __FreeBSD_version >= 700000
470 SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
471 SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
472 OID_AUTO, "enable_lro", CTLFLAG_RW,
473 &xn_enable_lro, 0, "Large Receive Offload");
480 netfront_suspend(device_t dev)
482 struct netfront_info *info = device_get_softc(dev);
486 netfront_carrier_off(info);
493 * We are reconnecting to the backend, due to a suspend/resume, or a backend
494 * driver restart. We tear down our netif structure and recreate it, but
495 * leave the device-layer structures intact so that this is transparent to the
496 * rest of the kernel.
499 netfront_resume(device_t dev)
501 struct netfront_info *info = device_get_softc(dev);
503 netif_disconnect_backend(info);
507 /* Common code used when first setting up, and when resuming. */
509 talk_to_backend(device_t dev, struct netfront_info *info)
512 struct xs_transaction xst;
513 const char *node = xenbus_get_node(dev);
516 err = xen_net_read_mac(dev, info->mac);
518 xenbus_dev_fatal(dev, err, "parsing %s/mac", node);
522 /* Create shared ring, alloc event channel. */
523 err = setup_device(dev, info);
528 err = xs_transaction_start(&xst);
530 xenbus_dev_fatal(dev, err, "starting transaction");
533 err = xs_printf(xst, node, "tx-ring-ref","%u",
536 message = "writing tx ring-ref";
537 goto abort_transaction;
539 err = xs_printf(xst, node, "rx-ring-ref","%u",
542 message = "writing rx ring-ref";
543 goto abort_transaction;
545 err = xs_printf(xst, node,
546 "event-channel", "%u",
547 xen_intr_port(info->xen_intr_handle));
549 message = "writing event-channel";
550 goto abort_transaction;
552 err = xs_printf(xst, node, "request-rx-copy", "%u",
553 info->copying_receiver);
555 message = "writing request-rx-copy";
556 goto abort_transaction;
558 err = xs_printf(xst, node, "feature-rx-notify", "%d", 1);
560 message = "writing feature-rx-notify";
561 goto abort_transaction;
563 err = xs_printf(xst, node, "feature-sg", "%d", 1);
565 message = "writing feature-sg";
566 goto abort_transaction;
568 #if __FreeBSD_version >= 700000
569 err = xs_printf(xst, node, "feature-gso-tcpv4", "%d", 1);
571 message = "writing feature-gso-tcpv4";
572 goto abort_transaction;
576 err = xs_transaction_end(xst, 0);
580 xenbus_dev_fatal(dev, err, "completing transaction");
587 xs_transaction_end(xst, 1);
588 xenbus_dev_fatal(dev, err, "%s", message);
596 setup_device(device_t dev, struct netfront_info *info)
598 netif_tx_sring_t *txs;
599 netif_rx_sring_t *rxs;
605 info->tx_ring_ref = GRANT_REF_INVALID;
606 info->rx_ring_ref = GRANT_REF_INVALID;
607 info->rx.sring = NULL;
608 info->tx.sring = NULL;
610 txs = (netif_tx_sring_t *)malloc(PAGE_SIZE, M_DEVBUF, M_NOWAIT|M_ZERO);
613 xenbus_dev_fatal(dev, error, "allocating tx ring page");
616 SHARED_RING_INIT(txs);
617 FRONT_RING_INIT(&info->tx, txs, PAGE_SIZE);
618 error = xenbus_grant_ring(dev, virt_to_mfn(txs), &info->tx_ring_ref);
622 rxs = (netif_rx_sring_t *)malloc(PAGE_SIZE, M_DEVBUF, M_NOWAIT|M_ZERO);
625 xenbus_dev_fatal(dev, error, "allocating rx ring page");
628 SHARED_RING_INIT(rxs);
629 FRONT_RING_INIT(&info->rx, rxs, PAGE_SIZE);
631 error = xenbus_grant_ring(dev, virt_to_mfn(rxs), &info->rx_ring_ref);
635 error = xen_intr_alloc_and_bind_local_port(dev,
636 xenbus_get_otherend_id(dev), /*filter*/NULL, xn_intr, info,
637 INTR_TYPE_NET | INTR_MPSAFE | INTR_ENTROPY, &info->xen_intr_handle);
640 xenbus_dev_fatal(dev, error,
641 "xen_intr_alloc_and_bind_local_port failed");
654 * If this interface has an ipv4 address, send an arp for it. This
655 * helps to get the network going again after migrating hosts.
658 netfront_send_fake_arp(device_t dev, struct netfront_info *info)
664 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
665 if (ifa->ifa_addr->sa_family == AF_INET) {
666 arp_ifinit(ifp, ifa);
673 * Callback received when the backend's state changes.
676 netfront_backend_changed(device_t dev, XenbusState newstate)
678 struct netfront_info *sc = device_get_softc(dev);
680 DPRINTK("newstate=%d\n", newstate);
683 case XenbusStateInitialising:
684 case XenbusStateInitialised:
685 case XenbusStateConnected:
686 case XenbusStateUnknown:
687 case XenbusStateClosed:
688 case XenbusStateReconfigured:
689 case XenbusStateReconfiguring:
691 case XenbusStateInitWait:
692 if (xenbus_get_state(dev) != XenbusStateInitialising)
694 if (network_connect(sc) != 0)
696 xenbus_set_state(dev, XenbusStateConnected);
698 netfront_send_fake_arp(dev, sc);
701 case XenbusStateClosing:
702 xenbus_set_state(dev, XenbusStateClosed);
708 xn_free_rx_ring(struct netfront_info *sc)
713 for (i = 0; i < NET_RX_RING_SIZE; i++) {
714 if (sc->xn_cdata.rx_mbufs[i] != NULL) {
715 m_freem(sc->rx_mbufs[i]);
716 sc->rx_mbufs[i] = NULL;
721 sc->xn_rx_if->req_prod = 0;
722 sc->xn_rx_if->event = sc->rx.rsp_cons ;
727 xn_free_tx_ring(struct netfront_info *sc)
732 for (i = 0; i < NET_TX_RING_SIZE; i++) {
733 if (sc->tx_mbufs[i] != NULL) {
734 m_freem(sc->tx_mbufs[i]);
735 sc->xn_cdata.xn_tx_chain[i] = NULL;
744 * \brief Verify that there is sufficient space in the Tx ring
745 * buffer for a maximally sized request to be enqueued.
747 * A transmit request requires a transmit descriptor for each packet
748 * fragment, plus up to 2 entries for "options" (e.g. TSO).
751 xn_tx_slot_available(struct netfront_info *np)
753 return (RING_FREE_REQUESTS(&np->tx) > (MAX_TX_REQ_FRAGS + 2));
757 netif_release_tx_bufs(struct netfront_info *np)
761 for (i = 1; i <= NET_TX_RING_SIZE; i++) {
767 * We assume that no kernel addresses are
768 * less than NET_TX_RING_SIZE. Any entry
769 * in the table that is below this number
770 * must be an index from free-list tracking.
772 if (((uintptr_t)m) <= NET_TX_RING_SIZE)
774 gnttab_end_foreign_access_ref(np->grant_tx_ref[i]);
775 gnttab_release_grant_reference(&np->gref_tx_head,
776 np->grant_tx_ref[i]);
777 np->grant_tx_ref[i] = GRANT_REF_INVALID;
778 add_id_to_freelist(np->tx_mbufs, i);
779 np->xn_cdata.xn_tx_chain_cnt--;
780 if (np->xn_cdata.xn_tx_chain_cnt < 0) {
781 panic("%s: tx_chain_cnt must be >= 0", __func__);
788 network_alloc_rx_buffers(struct netfront_info *sc)
790 int otherend_id = xenbus_get_otherend_id(sc->xbdev);
793 int i, batch_target, notify;
795 struct xen_memory_reservation reservation;
798 netif_rx_request_t *req;
802 req_prod = sc->rx.req_prod_pvt;
804 if (__predict_false(sc->carrier == 0))
808 * Allocate mbufs greedily, even though we batch updates to the
809 * receive ring. This creates a less bursty demand on the memory
810 * allocator, and so should reduce the chance of failed allocation
811 * requests both for ourself and for other kernel subsystems.
813 * Here we attempt to maintain rx_target buffers in flight, counting
814 * buffers that we have yet to process in the receive ring.
816 batch_target = sc->rx_target - (req_prod - sc->rx.rsp_cons);
817 for (i = mbufq_len(&sc->xn_rx_batch); i < batch_target; i++) {
818 MGETHDR(m_new, M_NOWAIT, MT_DATA);
820 printf("%s: MGETHDR failed\n", __func__);
824 if (m_cljget(m_new, M_NOWAIT, MJUMPAGESIZE) == NULL) {
825 printf("%s: m_cljget failed\n", __func__);
836 m_new->m_len = m_new->m_pkthdr.len = MJUMPAGESIZE;
838 /* queue the mbufs allocated */
839 (void )mbufq_enqueue(&sc->xn_rx_batch, m_new);
843 * If we've allocated at least half of our target number of entries,
844 * submit them to the backend - we have enough to make the overhead
845 * of submission worthwhile. Otherwise wait for more mbufs and
846 * request entries to become available.
848 if (i < (sc->rx_target/2)) {
849 if (req_prod >sc->rx.sring->req_prod)
855 * Double floating fill target if we risked having the backend
856 * run out of empty buffers for receive traffic. We define "running
857 * low" as having less than a fourth of our target buffers free
858 * at the time we refilled the queue.
860 if ((req_prod - sc->rx.sring->rsp_prod) < (sc->rx_target / 4)) {
862 if (sc->rx_target > sc->rx_max_target)
863 sc->rx_target = sc->rx_max_target;
867 for (nr_flips = i = 0; ; i++) {
868 if ((m_new = mbufq_dequeue(&sc->xn_rx_batch)) == NULL)
871 m_new->m_ext.ext_arg1 = (vm_paddr_t *)(uintptr_t)(
872 vtophys(m_new->m_ext.ext_buf) >> PAGE_SHIFT);
874 id = xennet_rxidx(req_prod + i);
876 KASSERT(sc->rx_mbufs[id] == NULL, ("non-NULL xm_rx_chain"));
877 sc->rx_mbufs[id] = m_new;
879 ref = gnttab_claim_grant_reference(&sc->gref_rx_head);
880 KASSERT(ref != GNTTAB_LIST_END,
881 ("reserved grant references exhuasted"));
882 sc->grant_rx_ref[id] = ref;
884 vaddr = mtod(m_new, vm_offset_t);
885 pfn = vtophys(vaddr) >> PAGE_SHIFT;
886 req = RING_GET_REQUEST(&sc->rx, req_prod + i);
888 if (sc->copying_receiver == 0) {
889 gnttab_grant_foreign_transfer_ref(ref,
891 sc->rx_pfn_array[nr_flips] = PFNTOMFN(pfn);
892 if (!xen_feature(XENFEAT_auto_translated_physmap)) {
893 /* Remove this page before passing
896 set_phys_to_machine(pfn, INVALID_P2M_ENTRY);
897 MULTI_update_va_mapping(&sc->rx_mcl[i],
902 gnttab_grant_foreign_access_ref(ref,
909 sc->rx_pfn_array[i] =
910 vtomach(mtod(m_new,vm_offset_t)) >> PAGE_SHIFT;
913 KASSERT(i, ("no mbufs processed")); /* should have returned earlier */
914 KASSERT(mbufq_len(&sc->xn_rx_batch) == 0, ("not all mbufs processed"));
916 * We may have allocated buffers which have entries outstanding
917 * in the page * update queue -- make sure we flush those first!
922 /* Tell the ballon driver what is going on. */
923 balloon_update_driver_allowance(i);
925 set_xen_guest_handle(reservation.extent_start, sc->rx_pfn_array);
926 reservation.nr_extents = i;
927 reservation.extent_order = 0;
928 reservation.address_bits = 0;
929 reservation.domid = DOMID_SELF;
931 if (!xen_feature(XENFEAT_auto_translated_physmap)) {
932 /* After all PTEs have been zapped, flush the TLB. */
933 sc->rx_mcl[i-1].args[MULTI_UVMFLAGS_INDEX] =
934 UVMF_TLB_FLUSH|UVMF_ALL;
936 /* Give away a batch of pages. */
937 sc->rx_mcl[i].op = __HYPERVISOR_memory_op;
938 sc->rx_mcl[i].args[0] = XENMEM_decrease_reservation;
939 sc->rx_mcl[i].args[1] = (u_long)&reservation;
940 /* Zap PTEs and give away pages in one big multicall. */
941 (void)HYPERVISOR_multicall(sc->rx_mcl, i+1);
943 if (__predict_false(sc->rx_mcl[i].result != i ||
944 HYPERVISOR_memory_op(XENMEM_decrease_reservation,
946 panic("%s: unable to reduce memory "
947 "reservation\n", __func__);
953 /* Above is a suitable barrier to ensure backend will see requests. */
954 sc->rx.req_prod_pvt = req_prod + i;
956 RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&sc->rx, notify);
958 xen_intr_signal(sc->xen_intr_handle);
962 xn_rxeof(struct netfront_info *np)
965 #if __FreeBSD_version >= 700000 && (defined(INET) || defined(INET6))
966 struct lro_ctrl *lro = &np->xn_lro;
967 struct lro_entry *queued;
969 struct netfront_rx_info rinfo;
970 struct netif_rx_response *rx = &rinfo.rx;
971 struct netif_extra_info *extras = rinfo.extras;
973 multicall_entry_t *mcl;
975 struct mbufq rxq, errq;
976 int err, pages_flipped = 0, work_to_do;
979 XN_RX_LOCK_ASSERT(np);
980 if (!netfront_carrier_ok(np))
983 /* XXX: there should be some sane limit. */
984 mbufq_init(&errq, INT_MAX);
985 mbufq_init(&rxq, INT_MAX);
989 rp = np->rx.sring->rsp_prod;
990 rmb(); /* Ensure we see queued responses up to 'rp'. */
994 memcpy(rx, RING_GET_RESPONSE(&np->rx, i), sizeof(*rx));
995 memset(extras, 0, sizeof(rinfo.extras));
998 err = xennet_get_responses(np, &rinfo, rp, &i, &m,
1001 if (__predict_false(err)) {
1003 (void )mbufq_enqueue(&errq, m);
1004 np->stats.rx_errors++;
1008 m->m_pkthdr.rcvif = ifp;
1009 if ( rx->flags & NETRXF_data_validated ) {
1010 /* Tell the stack the checksums are okay */
1012 * XXX this isn't necessarily the case - need to add
1016 m->m_pkthdr.csum_flags |=
1017 (CSUM_IP_CHECKED | CSUM_IP_VALID | CSUM_DATA_VALID
1019 m->m_pkthdr.csum_data = 0xffff;
1022 np->stats.rx_packets++;
1023 np->stats.rx_bytes += m->m_pkthdr.len;
1025 (void )mbufq_enqueue(&rxq, m);
1026 np->rx.rsp_cons = i;
1029 if (pages_flipped) {
1030 /* Some pages are no longer absent... */
1032 balloon_update_driver_allowance(-pages_flipped);
1034 /* Do all the remapping work, and M->P updates, in one big
1037 if (!!xen_feature(XENFEAT_auto_translated_physmap)) {
1038 mcl = np->rx_mcl + pages_flipped;
1039 mcl->op = __HYPERVISOR_mmu_update;
1040 mcl->args[0] = (u_long)np->rx_mmu;
1041 mcl->args[1] = pages_flipped;
1043 mcl->args[3] = DOMID_SELF;
1044 (void)HYPERVISOR_multicall(np->rx_mcl,
1052 * Process all the mbufs after the remapping is complete.
1053 * Break the mbuf chain first though.
1055 while ((m = mbufq_dequeue(&rxq)) != NULL) {
1056 if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
1059 * Do we really need to drop the rx lock?
1062 #if __FreeBSD_version >= 700000 && (defined(INET) || defined(INET6))
1063 /* Use LRO if possible */
1064 if ((ifp->if_capenable & IFCAP_LRO) == 0 ||
1065 lro->lro_cnt == 0 || tcp_lro_rx(lro, m, 0)) {
1067 * If LRO fails, pass up to the stack
1070 (*ifp->if_input)(ifp, m);
1073 (*ifp->if_input)(ifp, m);
1078 np->rx.rsp_cons = i;
1080 #if __FreeBSD_version >= 700000 && (defined(INET) || defined(INET6))
1082 * Flush any outstanding LRO work
1084 while (!SLIST_EMPTY(&lro->lro_active)) {
1085 queued = SLIST_FIRST(&lro->lro_active);
1086 SLIST_REMOVE_HEAD(&lro->lro_active, next);
1087 tcp_lro_flush(lro, queued);
1092 /* If we get a callback with very few responses, reduce fill target. */
1093 /* NB. Note exponential increase, linear decrease. */
1094 if (((np->rx.req_prod_pvt - np->rx.sring->rsp_prod) >
1095 ((3*np->rx_target) / 4)) && (--np->rx_target < np->rx_min_target))
1096 np->rx_target = np->rx_min_target;
1099 network_alloc_rx_buffers(np);
1101 RING_FINAL_CHECK_FOR_RESPONSES(&np->rx, work_to_do);
1102 } while (work_to_do);
1106 xn_txeof(struct netfront_info *np)
1111 netif_tx_response_t *txr;
1114 XN_TX_LOCK_ASSERT(np);
1116 if (!netfront_carrier_ok(np))
1122 prod = np->tx.sring->rsp_prod;
1123 rmb(); /* Ensure we see responses up to 'rp'. */
1125 for (i = np->tx.rsp_cons; i != prod; i++) {
1126 txr = RING_GET_RESPONSE(&np->tx, i);
1127 if (txr->status == NETIF_RSP_NULL)
1130 if (txr->status != NETIF_RSP_OKAY) {
1131 printf("%s: WARNING: response is %d!\n",
1132 __func__, txr->status);
1135 m = np->tx_mbufs[id];
1136 KASSERT(m != NULL, ("mbuf not found in xn_tx_chain"));
1137 KASSERT((uintptr_t)m > NET_TX_RING_SIZE,
1138 ("mbuf already on the free list, but we're "
1139 "trying to free it again!"));
1143 * Increment packet count if this is the last
1144 * mbuf of the chain.
1147 if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1148 if (__predict_false(gnttab_query_foreign_access(
1149 np->grant_tx_ref[id]) != 0)) {
1150 panic("%s: grant id %u still in use by the "
1151 "backend", __func__, id);
1153 gnttab_end_foreign_access_ref(
1154 np->grant_tx_ref[id]);
1155 gnttab_release_grant_reference(
1156 &np->gref_tx_head, np->grant_tx_ref[id]);
1157 np->grant_tx_ref[id] = GRANT_REF_INVALID;
1159 np->tx_mbufs[id] = NULL;
1160 add_id_to_freelist(np->tx_mbufs, id);
1161 np->xn_cdata.xn_tx_chain_cnt--;
1163 /* Only mark the queue active if we've freed up at least one slot to try */
1164 ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1166 np->tx.rsp_cons = prod;
1169 * Set a new event, then check for race with update of
1170 * tx_cons. Note that it is essential to schedule a
1171 * callback, no matter how few buffers are pending. Even if
1172 * there is space in the transmit ring, higher layers may
1173 * be blocked because too much data is outstanding: in such
1174 * cases notification from Xen is likely to be the only kick
1177 np->tx.sring->rsp_event =
1178 prod + ((np->tx.sring->req_prod - prod) >> 1) + 1;
1181 } while (prod != np->tx.sring->rsp_prod);
1184 ((np->tx.sring->req_prod - prod) < NET_TX_RING_SIZE)) {
1187 if (np->user_state == UST_OPEN)
1188 netif_wake_queue(dev);
1196 struct netfront_info *np = xsc;
1197 struct ifnet *ifp = np->xn_ifp;
1200 if (!(np->rx.rsp_cons != np->rx.sring->rsp_prod &&
1201 likely(netfront_carrier_ok(np)) &&
1202 ifp->if_drv_flags & IFF_DRV_RUNNING))
1205 if (RING_HAS_UNCONSUMED_RESPONSES(&np->tx)) {
1215 if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
1216 !IFQ_DRV_IS_EMPTY(&ifp->if_snd))
1221 xennet_move_rx_slot(struct netfront_info *np, struct mbuf *m,
1224 int new = xennet_rxidx(np->rx.req_prod_pvt);
1226 KASSERT(np->rx_mbufs[new] == NULL, ("rx_mbufs != NULL"));
1227 np->rx_mbufs[new] = m;
1228 np->grant_rx_ref[new] = ref;
1229 RING_GET_REQUEST(&np->rx, np->rx.req_prod_pvt)->id = new;
1230 RING_GET_REQUEST(&np->rx, np->rx.req_prod_pvt)->gref = ref;
1231 np->rx.req_prod_pvt++;
1235 xennet_get_extras(struct netfront_info *np,
1236 struct netif_extra_info *extras, RING_IDX rp, RING_IDX *cons)
1238 struct netif_extra_info *extra;
1246 if (__predict_false(*cons + 1 == rp)) {
1248 if (net_ratelimit())
1249 WPRINTK("Missing extra info\n");
1255 extra = (struct netif_extra_info *)
1256 RING_GET_RESPONSE(&np->rx, ++(*cons));
1258 if (__predict_false(!extra->type ||
1259 extra->type >= XEN_NETIF_EXTRA_TYPE_MAX)) {
1261 if (net_ratelimit())
1262 WPRINTK("Invalid extra type: %d\n",
1267 memcpy(&extras[extra->type - 1], extra, sizeof(*extra));
1270 m = xennet_get_rx_mbuf(np, *cons);
1271 ref = xennet_get_rx_ref(np, *cons);
1272 xennet_move_rx_slot(np, m, ref);
1273 } while (extra->flags & XEN_NETIF_EXTRA_FLAG_MORE);
1279 xennet_get_responses(struct netfront_info *np,
1280 struct netfront_rx_info *rinfo, RING_IDX rp, RING_IDX *cons,
1282 int *pages_flipped_p)
1284 int pages_flipped = *pages_flipped_p;
1285 struct mmu_update *mmu;
1286 struct multicall_entry *mcl;
1287 struct netif_rx_response *rx = &rinfo->rx;
1288 struct netif_extra_info *extras = rinfo->extras;
1289 struct mbuf *m, *m0, *m_prev;
1290 grant_ref_t ref = xennet_get_rx_ref(np, *cons);
1291 RING_IDX ref_cons = *cons;
1296 m0 = m = m_prev = xennet_get_rx_mbuf(np, *cons);
1298 if (rx->flags & NETRXF_extra_info) {
1299 err = xennet_get_extras(np, extras, rp, cons);
1303 m0->m_pkthdr.len = 0;
1311 DPRINTK("rx->status=%hd rx->offset=%hu frags=%u\n",
1312 rx->status, rx->offset, frags);
1314 if (__predict_false(rx->status < 0 ||
1315 rx->offset + rx->status > PAGE_SIZE)) {
1318 if (net_ratelimit())
1319 WPRINTK("rx->offset: %x, size: %u\n",
1320 rx->offset, rx->status);
1322 xennet_move_rx_slot(np, m, ref);
1327 goto next_skip_queue;
1331 * This definitely indicates a bug, either in this driver or in
1332 * the backend driver. In future this should flag the bad
1333 * situation to the system controller to reboot the backed.
1335 if (ref == GRANT_REF_INVALID) {
1338 if (net_ratelimit())
1339 WPRINTK("Bad rx response id %d.\n", rx->id);
1341 printf("%s: Bad rx response id %d.\n", __func__,rx->id);
1346 if (!np->copying_receiver) {
1347 /* Memory pressure, insufficient buffer
1350 if (!(mfn = gnttab_end_foreign_transfer_ref(ref))) {
1351 WPRINTK("Unfulfilled rx req (id=%d, st=%d).\n",
1352 rx->id, rx->status);
1353 xennet_move_rx_slot(np, m, ref);
1358 if (!xen_feature( XENFEAT_auto_translated_physmap)) {
1359 /* Remap the page. */
1360 void *vaddr = mtod(m, void *);
1363 mcl = np->rx_mcl + pages_flipped;
1364 mmu = np->rx_mmu + pages_flipped;
1366 MULTI_update_va_mapping(mcl, (u_long)vaddr,
1367 (((vm_paddr_t)mfn) << PAGE_SHIFT) | PG_RW |
1368 PG_V | PG_M | PG_A, 0);
1369 pfn = (uintptr_t)m->m_ext.ext_arg1;
1370 mmu->ptr = ((vm_paddr_t)mfn << PAGE_SHIFT) |
1371 MMU_MACHPHYS_UPDATE;
1374 set_phys_to_machine(pfn, mfn);
1378 ret = gnttab_end_foreign_access_ref(ref);
1379 KASSERT(ret, ("ret != 0"));
1382 gnttab_release_grant_reference(&np->gref_rx_head, ref);
1388 m->m_len = rx->status;
1389 m->m_data += rx->offset;
1390 m0->m_pkthdr.len += rx->status;
1393 if (!(rx->flags & NETRXF_more_data))
1396 if (*cons + frags == rp) {
1397 if (net_ratelimit())
1398 WPRINTK("Need more frags\n");
1400 printf("%s: cons %u frags %u rp %u, not enough frags\n",
1401 __func__, *cons, frags, rp);
1405 * Note that m can be NULL, if rx->status < 0 or if
1406 * rx->offset + rx->status > PAGE_SIZE above.
1410 rx = RING_GET_RESPONSE(&np->rx, *cons + frags);
1411 m = xennet_get_rx_mbuf(np, *cons + frags);
1414 * m_prev == NULL can happen if rx->status < 0 or if
1415 * rx->offset + * rx->status > PAGE_SIZE above.
1421 * m0 can be NULL if rx->status < 0 or if * rx->offset +
1422 * rx->status > PAGE_SIZE above.
1427 ref = xennet_get_rx_ref(np, *cons + frags);
1428 ref_cons = *cons + frags;
1433 *pages_flipped_p = pages_flipped;
1439 xn_tick_locked(struct netfront_info *sc)
1441 XN_RX_LOCK_ASSERT(sc);
1442 callout_reset(&sc->xn_stat_ch, hz, xn_tick, sc);
1444 /* XXX placeholder for printing debug information */
1450 struct netfront_info *sc;
1459 * \brief Count the number of fragments in an mbuf chain.
1461 * Surprisingly, there isn't an M* macro for this.
1464 xn_count_frags(struct mbuf *m)
1468 for (nfrags = 0; m != NULL; m = m->m_next)
1475 * Given an mbuf chain, make sure we have enough room and then push
1476 * it onto the transmit ring.
1479 xn_assemble_tx_request(struct netfront_info *sc, struct mbuf *m_head)
1484 netif_extra_info_t *extra;
1490 * Defragment the mbuf if necessary.
1492 nfrags = xn_count_frags(m_head);
1495 * Check to see whether this request is longer than netback
1496 * can handle, and try to defrag it.
1499 * It is a bit lame, but the netback driver in Linux can't
1500 * deal with nfrags > MAX_TX_REQ_FRAGS, which is a quirk of
1501 * the Linux network stack.
1503 if (nfrags > sc->maxfrags) {
1504 m = m_defrag(m_head, M_NOWAIT);
1507 * Defrag failed, so free the mbuf and
1508 * therefore drop the packet.
1516 /* Determine how many fragments now exist */
1517 nfrags = xn_count_frags(m_head);
1520 * Check to see whether the defragmented packet has too many
1521 * segments for the Linux netback driver.
1524 * The FreeBSD TCP stack, with TSO enabled, can produce a chain
1525 * of mbufs longer than Linux can handle. Make sure we don't
1526 * pass a too-long chain over to the other side by dropping the
1527 * packet. It doesn't look like there is currently a way to
1528 * tell the TCP stack to generate a shorter chain of packets.
1530 if (nfrags > MAX_TX_REQ_FRAGS) {
1532 printf("%s: nfrags %d > MAX_TX_REQ_FRAGS %d, netback "
1533 "won't be able to handle it, dropping\n",
1534 __func__, nfrags, MAX_TX_REQ_FRAGS);
1541 * This check should be redundant. We've already verified that we
1542 * have enough slots in the ring to handle a packet of maximum
1543 * size, and that our packet is less than the maximum size. Keep
1544 * it in here as an assert for now just to make certain that
1545 * xn_tx_chain_cnt is accurate.
1547 KASSERT((sc->xn_cdata.xn_tx_chain_cnt + nfrags) <= NET_TX_RING_SIZE,
1548 ("%s: xn_tx_chain_cnt (%d) + nfrags (%d) > NET_TX_RING_SIZE "
1549 "(%d)!", __func__, (int) sc->xn_cdata.xn_tx_chain_cnt,
1550 (int) nfrags, (int) NET_TX_RING_SIZE));
1553 * Start packing the mbufs in this chain into
1554 * the fragment pointers. Stop when we run out
1555 * of fragments or hit the end of the mbuf chain.
1559 otherend_id = xenbus_get_otherend_id(sc->xbdev);
1560 for (m = m_head; m; m = m->m_next) {
1561 netif_tx_request_t *tx;
1564 u_long mfn; /* XXX Wrong type? */
1566 tx = RING_GET_REQUEST(&sc->tx, sc->tx.req_prod_pvt);
1567 id = get_id_from_freelist(sc->tx_mbufs);
1569 panic("%s: was allocated the freelist head!\n",
1571 sc->xn_cdata.xn_tx_chain_cnt++;
1572 if (sc->xn_cdata.xn_tx_chain_cnt > NET_TX_RING_SIZE)
1573 panic("%s: tx_chain_cnt must be <= NET_TX_RING_SIZE\n",
1575 sc->tx_mbufs[id] = m;
1577 ref = gnttab_claim_grant_reference(&sc->gref_tx_head);
1578 KASSERT((short)ref >= 0, ("Negative ref"));
1579 mfn = virt_to_mfn(mtod(m, vm_offset_t));
1580 gnttab_grant_foreign_access_ref(ref, otherend_id,
1581 mfn, GNTMAP_readonly);
1582 tx->gref = sc->grant_tx_ref[id] = ref;
1583 tx->offset = mtod(m, vm_offset_t) & (PAGE_SIZE - 1);
1587 * The first fragment has the entire packet
1588 * size, subsequent fragments have just the
1589 * fragment size. The backend works out the
1590 * true size of the first fragment by
1591 * subtracting the sizes of the other
1594 tx->size = m->m_pkthdr.len;
1597 * The first fragment contains the checksum flags
1598 * and is optionally followed by extra data for
1602 * CSUM_TSO requires checksum offloading.
1603 * Some versions of FreeBSD fail to
1604 * set CSUM_TCP in the CSUM_TSO case,
1605 * so we have to test for CSUM_TSO
1608 if (m->m_pkthdr.csum_flags
1609 & (CSUM_DELAY_DATA | CSUM_TSO)) {
1610 tx->flags |= (NETTXF_csum_blank
1611 | NETTXF_data_validated);
1613 #if __FreeBSD_version >= 700000
1614 if (m->m_pkthdr.csum_flags & CSUM_TSO) {
1615 struct netif_extra_info *gso =
1616 (struct netif_extra_info *)
1617 RING_GET_REQUEST(&sc->tx,
1618 ++sc->tx.req_prod_pvt);
1620 tx->flags |= NETTXF_extra_info;
1622 gso->u.gso.size = m->m_pkthdr.tso_segsz;
1624 XEN_NETIF_GSO_TYPE_TCPV4;
1626 gso->u.gso.features = 0;
1628 gso->type = XEN_NETIF_EXTRA_TYPE_GSO;
1633 tx->size = m->m_len;
1636 tx->flags |= NETTXF_more_data;
1638 sc->tx.req_prod_pvt++;
1640 BPF_MTAP(ifp, m_head);
1642 sc->stats.tx_bytes += m_head->m_pkthdr.len;
1643 sc->stats.tx_packets++;
1649 xn_start_locked(struct ifnet *ifp)
1651 struct netfront_info *sc;
1652 struct mbuf *m_head;
1657 if (!netfront_carrier_ok(sc))
1661 * While we have enough transmit slots available for at least one
1662 * maximum-sized packet, pull mbufs off the queue and put them on
1663 * the transmit ring.
1665 while (xn_tx_slot_available(sc)) {
1666 IF_DEQUEUE(&ifp->if_snd, m_head);
1670 if (xn_assemble_tx_request(sc, m_head) != 0)
1674 RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&sc->tx, notify);
1676 xen_intr_signal(sc->xen_intr_handle);
1678 if (RING_FULL(&sc->tx)) {
1681 netif_stop_queue(dev);
1687 xn_start(struct ifnet *ifp)
1689 struct netfront_info *sc;
1692 xn_start_locked(ifp);
1696 /* equivalent of network_open() in Linux */
1698 xn_ifinit_locked(struct netfront_info *sc)
1706 if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1711 network_alloc_rx_buffers(sc);
1712 sc->rx.sring->rsp_event = sc->rx.rsp_cons + 1;
1714 ifp->if_drv_flags |= IFF_DRV_RUNNING;
1715 ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1716 if_link_state_change(ifp, LINK_STATE_UP);
1718 callout_reset(&sc->xn_stat_ch, hz, xn_tick, sc);
1722 xn_ifinit(void *xsc)
1724 struct netfront_info *sc = xsc;
1727 xn_ifinit_locked(sc);
1732 xn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1734 struct netfront_info *sc = ifp->if_softc;
1735 struct ifreq *ifr = (struct ifreq *) data;
1737 struct ifaddr *ifa = (struct ifaddr *)data;
1740 int mask, error = 0;
1745 if (ifa->ifa_addr->sa_family == AF_INET) {
1746 ifp->if_flags |= IFF_UP;
1747 if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
1748 xn_ifinit_locked(sc);
1749 arp_ifinit(ifp, ifa);
1754 error = ether_ioctl(ifp, cmd, data);
1760 /* XXX can we alter the MTU on a VN ?*/
1762 if (ifr->ifr_mtu > XN_JUMBO_MTU)
1767 ifp->if_mtu = ifr->ifr_mtu;
1768 ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1774 if (ifp->if_flags & IFF_UP) {
1776 * If only the state of the PROMISC flag changed,
1777 * then just use the 'set promisc mode' command
1778 * instead of reinitializing the entire NIC. Doing
1779 * a full re-init means reloading the firmware and
1780 * waiting for it to start up, which may take a
1784 /* No promiscuous mode with Xen */
1785 if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
1786 ifp->if_flags & IFF_PROMISC &&
1787 !(sc->xn_if_flags & IFF_PROMISC)) {
1788 XN_SETBIT(sc, XN_RX_MODE,
1789 XN_RXMODE_RX_PROMISC);
1790 } else if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
1791 !(ifp->if_flags & IFF_PROMISC) &&
1792 sc->xn_if_flags & IFF_PROMISC) {
1793 XN_CLRBIT(sc, XN_RX_MODE,
1794 XN_RXMODE_RX_PROMISC);
1797 xn_ifinit_locked(sc);
1799 if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1803 sc->xn_if_flags = ifp->if_flags;
1808 mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1809 if (mask & IFCAP_TXCSUM) {
1810 if (IFCAP_TXCSUM & ifp->if_capenable) {
1811 ifp->if_capenable &= ~(IFCAP_TXCSUM|IFCAP_TSO4);
1812 ifp->if_hwassist &= ~(CSUM_TCP | CSUM_UDP
1813 | CSUM_IP | CSUM_TSO);
1815 ifp->if_capenable |= IFCAP_TXCSUM;
1816 ifp->if_hwassist |= (CSUM_TCP | CSUM_UDP
1820 if (mask & IFCAP_RXCSUM) {
1821 ifp->if_capenable ^= IFCAP_RXCSUM;
1823 #if __FreeBSD_version >= 700000
1824 if (mask & IFCAP_TSO4) {
1825 if (IFCAP_TSO4 & ifp->if_capenable) {
1826 ifp->if_capenable &= ~IFCAP_TSO4;
1827 ifp->if_hwassist &= ~CSUM_TSO;
1828 } else if (IFCAP_TXCSUM & ifp->if_capenable) {
1829 ifp->if_capenable |= IFCAP_TSO4;
1830 ifp->if_hwassist |= CSUM_TSO;
1832 IPRINTK("Xen requires tx checksum offload"
1833 " be enabled to use TSO\n");
1837 if (mask & IFCAP_LRO) {
1838 ifp->if_capenable ^= IFCAP_LRO;
1847 if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1857 error = ifmedia_ioctl(ifp, ifr, &sc->sc_media, cmd);
1860 error = ether_ioctl(ifp, cmd, data);
1867 xn_stop(struct netfront_info *sc)
1875 callout_stop(&sc->xn_stat_ch);
1877 xn_free_rx_ring(sc);
1878 xn_free_tx_ring(sc);
1880 ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
1881 if_link_state_change(ifp, LINK_STATE_DOWN);
1884 /* START of Xenolinux helper functions adapted to FreeBSD */
1886 network_connect(struct netfront_info *np)
1888 int i, requeue_idx, error;
1890 netif_rx_request_t *req;
1891 u_int feature_rx_copy, feature_rx_flip;
1893 error = xs_scanf(XST_NIL, xenbus_get_otherend_path(np->xbdev),
1894 "feature-rx-copy", NULL, "%u", &feature_rx_copy);
1896 feature_rx_copy = 0;
1897 error = xs_scanf(XST_NIL, xenbus_get_otherend_path(np->xbdev),
1898 "feature-rx-flip", NULL, "%u", &feature_rx_flip);
1900 feature_rx_flip = 1;
1903 * Copy packets on receive path if:
1904 * (a) This was requested by user, and the backend supports it; or
1905 * (b) Flipping was requested, but this is unsupported by the backend.
1907 np->copying_receiver = ((MODPARM_rx_copy && feature_rx_copy) ||
1908 (MODPARM_rx_flip && !feature_rx_flip));
1910 /* Recovery procedure: */
1911 error = talk_to_backend(np->xbdev, np);
1915 /* Step 1: Reinitialise variables. */
1916 xn_query_features(np);
1917 xn_configure_features(np);
1918 netif_release_tx_bufs(np);
1920 /* Step 2: Rebuild the RX buffer freelist and the RX ring itself. */
1921 for (requeue_idx = 0, i = 0; i < NET_RX_RING_SIZE; i++) {
1925 if (np->rx_mbufs[i] == NULL)
1928 m = np->rx_mbufs[requeue_idx] = xennet_get_rx_mbuf(np, i);
1929 ref = np->grant_rx_ref[requeue_idx] = xennet_get_rx_ref(np, i);
1931 req = RING_GET_REQUEST(&np->rx, requeue_idx);
1932 pfn = vtophys(mtod(m, vm_offset_t)) >> PAGE_SHIFT;
1934 if (!np->copying_receiver) {
1935 gnttab_grant_foreign_transfer_ref(ref,
1936 xenbus_get_otherend_id(np->xbdev),
1939 gnttab_grant_foreign_access_ref(ref,
1940 xenbus_get_otherend_id(np->xbdev),
1944 req->id = requeue_idx;
1949 np->rx.req_prod_pvt = requeue_idx;
1951 /* Step 3: All public and private state should now be sane. Get
1952 * ready to start sending and receiving packets and give the driver
1953 * domain a kick because we've probably just requeued some
1956 netfront_carrier_on(np);
1957 xen_intr_signal(np->xen_intr_handle);
1961 network_alloc_rx_buffers(np);
1967 xn_query_features(struct netfront_info *np)
1971 device_printf(np->xbdev, "backend features:");
1973 if (xs_scanf(XST_NIL, xenbus_get_otherend_path(np->xbdev),
1974 "feature-sg", NULL, "%d", &val) < 0)
1979 np->maxfrags = MAX_TX_REQ_FRAGS;
1980 printf(" feature-sg");
1983 if (xs_scanf(XST_NIL, xenbus_get_otherend_path(np->xbdev),
1984 "feature-gso-tcpv4", NULL, "%d", &val) < 0)
1987 np->xn_ifp->if_capabilities &= ~(IFCAP_TSO4|IFCAP_LRO);
1989 np->xn_ifp->if_capabilities |= IFCAP_TSO4|IFCAP_LRO;
1990 printf(" feature-gso-tcp4");
1997 xn_configure_features(struct netfront_info *np)
2002 #if __FreeBSD_version >= 700000 && (defined(INET) || defined(INET6))
2003 if ((np->xn_ifp->if_capenable & IFCAP_LRO) != 0)
2004 tcp_lro_free(&np->xn_lro);
2006 np->xn_ifp->if_capenable =
2007 np->xn_ifp->if_capabilities & ~(IFCAP_LRO|IFCAP_TSO4);
2008 np->xn_ifp->if_hwassist &= ~CSUM_TSO;
2009 #if __FreeBSD_version >= 700000 && (defined(INET) || defined(INET6))
2010 if (xn_enable_lro && (np->xn_ifp->if_capabilities & IFCAP_LRO) != 0) {
2011 err = tcp_lro_init(&np->xn_lro);
2013 device_printf(np->xbdev, "LRO initialization failed\n");
2015 np->xn_lro.ifp = np->xn_ifp;
2016 np->xn_ifp->if_capenable |= IFCAP_LRO;
2019 if ((np->xn_ifp->if_capabilities & IFCAP_TSO4) != 0) {
2020 np->xn_ifp->if_capenable |= IFCAP_TSO4;
2021 np->xn_ifp->if_hwassist |= CSUM_TSO;
2028 * Create a network device.
2029 * @param dev Newbus device representing this virtual NIC.
2032 create_netdev(device_t dev)
2035 struct netfront_info *np;
2039 np = device_get_softc(dev);
2043 XN_LOCK_INIT(np, xennetif);
2045 ifmedia_init(&np->sc_media, 0, xn_ifmedia_upd, xn_ifmedia_sts);
2046 ifmedia_add(&np->sc_media, IFM_ETHER|IFM_MANUAL, 0, NULL);
2047 ifmedia_set(&np->sc_media, IFM_ETHER|IFM_MANUAL);
2049 np->rx_target = RX_MIN_TARGET;
2050 np->rx_min_target = RX_MIN_TARGET;
2051 np->rx_max_target = RX_MAX_TARGET;
2053 /* Initialise {tx,rx}_skbs to be a free chain containing every entry. */
2054 for (i = 0; i <= NET_TX_RING_SIZE; i++) {
2055 np->tx_mbufs[i] = (void *) ((u_long) i+1);
2056 np->grant_tx_ref[i] = GRANT_REF_INVALID;
2058 np->tx_mbufs[NET_TX_RING_SIZE] = (void *)0;
2060 for (i = 0; i <= NET_RX_RING_SIZE; i++) {
2062 np->rx_mbufs[i] = NULL;
2063 np->grant_rx_ref[i] = GRANT_REF_INVALID;
2065 /* A grant for every tx ring slot */
2066 if (gnttab_alloc_grant_references(NET_TX_RING_SIZE,
2067 &np->gref_tx_head) != 0) {
2068 IPRINTK("#### netfront can't alloc tx grant refs\n");
2072 /* A grant for every rx ring slot */
2073 if (gnttab_alloc_grant_references(RX_MAX_TARGET,
2074 &np->gref_rx_head) != 0) {
2075 WPRINTK("#### netfront can't alloc rx grant refs\n");
2076 gnttab_free_grant_references(np->gref_tx_head);
2081 err = xen_net_read_mac(dev, np->mac);
2085 /* Set up ifnet structure */
2086 ifp = np->xn_ifp = if_alloc(IFT_ETHER);
2088 if_initname(ifp, "xn", device_get_unit(dev));
2089 ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
2090 ifp->if_ioctl = xn_ioctl;
2091 ifp->if_output = ether_output;
2092 ifp->if_start = xn_start;
2094 ifp->if_watchdog = xn_watchdog;
2096 ifp->if_init = xn_ifinit;
2097 ifp->if_snd.ifq_maxlen = NET_TX_RING_SIZE - 1;
2099 ifp->if_hwassist = XN_CSUM_FEATURES;
2100 ifp->if_capabilities = IFCAP_HWCSUM;
2101 ifp->if_hw_tsomax = 65536 - (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
2102 ifp->if_hw_tsomaxsegcount = MAX_TX_REQ_FRAGS;
2103 ifp->if_hw_tsomaxsegsize = PAGE_SIZE;
2105 ether_ifattach(ifp, np->mac);
2106 callout_init(&np->xn_stat_ch, CALLOUT_MPSAFE);
2107 netfront_carrier_off(np);
2112 gnttab_free_grant_references(np->gref_tx_head);
2118 * Handle the change of state of the backend to Closing. We must delete our
2119 * device-layer structures now, to ensure that writes are flushed through to
2120 * the backend. Once is this done, we can switch to Closed in
2125 netfront_closing(device_t dev)
2128 struct netfront_info *info = dev->dev_driver_data;
2130 DPRINTK("netfront_closing: %s removed\n", dev->nodename);
2134 xenbus_switch_state(dev, XenbusStateClosed);
2139 netfront_detach(device_t dev)
2141 struct netfront_info *info = device_get_softc(dev);
2143 DPRINTK("%s\n", xenbus_get_node(dev));
2151 netif_free(struct netfront_info *info)
2156 callout_drain(&info->xn_stat_ch);
2157 netif_disconnect_backend(info);
2158 if (info->xn_ifp != NULL) {
2159 ether_ifdetach(info->xn_ifp);
2160 if_free(info->xn_ifp);
2161 info->xn_ifp = NULL;
2163 ifmedia_removeall(&info->sc_media);
2167 netif_disconnect_backend(struct netfront_info *info)
2171 netfront_carrier_off(info);
2175 free_ring(&info->tx_ring_ref, &info->tx.sring);
2176 free_ring(&info->rx_ring_ref, &info->rx.sring);
2178 xen_intr_unbind(&info->xen_intr_handle);
2182 free_ring(int *ref, void *ring_ptr_ref)
2184 void **ring_ptr_ptr = ring_ptr_ref;
2186 if (*ref != GRANT_REF_INVALID) {
2187 /* This API frees the associated storage. */
2188 gnttab_end_foreign_access(*ref, *ring_ptr_ptr);
2189 *ref = GRANT_REF_INVALID;
2191 *ring_ptr_ptr = NULL;
2195 xn_ifmedia_upd(struct ifnet *ifp)
2201 xn_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
2203 ifmr->ifm_status = IFM_AVALID|IFM_ACTIVE;
2204 ifmr->ifm_active = IFM_ETHER|IFM_MANUAL;
2207 /* ** Driver registration ** */
2208 static device_method_t netfront_methods[] = {
2209 /* Device interface */
2210 DEVMETHOD(device_probe, netfront_probe),
2211 DEVMETHOD(device_attach, netfront_attach),
2212 DEVMETHOD(device_detach, netfront_detach),
2213 DEVMETHOD(device_shutdown, bus_generic_shutdown),
2214 DEVMETHOD(device_suspend, netfront_suspend),
2215 DEVMETHOD(device_resume, netfront_resume),
2217 /* Xenbus interface */
2218 DEVMETHOD(xenbus_otherend_changed, netfront_backend_changed),
2223 static driver_t netfront_driver = {
2226 sizeof(struct netfront_info),
2228 devclass_t netfront_devclass;
2230 DRIVER_MODULE(xe, xenbusb_front, netfront_driver, netfront_devclass, NULL,