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>
37 #include <sys/malloc.h>
38 #include <sys/module.h>
39 #include <sys/kernel.h>
40 #include <sys/socket.h>
41 #include <sys/sysctl.h>
42 #include <sys/queue.h>
47 #include <net/if_var.h>
48 #include <net/if_arp.h>
49 #include <net/ethernet.h>
50 #include <net/if_dl.h>
51 #include <net/if_media.h>
55 #include <net/if_types.h>
57 #include <netinet/in_systm.h>
58 #include <netinet/in.h>
59 #include <netinet/ip.h>
60 #include <netinet/if_ether.h>
61 #if __FreeBSD_version >= 700000
62 #include <netinet/tcp.h>
63 #include <netinet/tcp_lro.h>
69 #include <machine/clock.h> /* for DELAY */
70 #include <machine/bus.h>
71 #include <machine/resource.h>
72 #include <machine/frame.h>
73 #include <machine/vmparam.h>
78 #include <machine/intr_machdep.h>
80 #include <xen/xen-os.h>
81 #include <xen/hypervisor.h>
82 #include <xen/xen_intr.h>
83 #include <xen/gnttab.h>
84 #include <xen/interface/memory.h>
85 #include <xen/interface/io/netif.h>
86 #include <xen/xenbus/xenbusvar.h>
88 #include <machine/xen/xenvar.h>
90 #include <dev/xen/netfront/mbufq.h>
92 #include "xenbus_if.h"
94 /* Features supported by all backends. TSO and LRO can be negotiated */
95 #define XN_CSUM_FEATURES (CSUM_TCP | CSUM_UDP)
97 #define NET_TX_RING_SIZE __RING_SIZE((netif_tx_sring_t *)0, PAGE_SIZE)
98 #define NET_RX_RING_SIZE __RING_SIZE((netif_rx_sring_t *)0, PAGE_SIZE)
100 #if __FreeBSD_version >= 700000
102 * Should the driver do LRO on the RX end
103 * this can be toggled on the fly, but the
104 * interface must be reset (down/up) for it
107 static int xn_enable_lro = 1;
108 TUNABLE_INT("hw.xn.enable_lro", &xn_enable_lro);
117 static int MODPARM_rx_copy = 0;
118 module_param_named(rx_copy, MODPARM_rx_copy, bool, 0);
119 MODULE_PARM_DESC(rx_copy, "Copy packets from network card (rather than flip)");
120 static int MODPARM_rx_flip = 0;
121 module_param_named(rx_flip, MODPARM_rx_flip, bool, 0);
122 MODULE_PARM_DESC(rx_flip, "Flip packets from network card (rather than copy)");
124 static const int MODPARM_rx_copy = 1;
125 static const int MODPARM_rx_flip = 0;
129 * \brief The maximum allowed data fragments in a single transmit
132 * This limit is imposed by the backend driver. We assume here that
133 * we are dealing with a Linux driver domain and have set our limit
134 * to mirror the Linux MAX_SKB_FRAGS constant.
136 #define MAX_TX_REQ_FRAGS (65536 / PAGE_SIZE + 2)
138 #define RX_COPY_THRESHOLD 256
140 #define net_ratelimit() 0
142 struct netfront_info;
143 struct netfront_rx_info;
145 static void xn_txeof(struct netfront_info *);
146 static void xn_rxeof(struct netfront_info *);
147 static void network_alloc_rx_buffers(struct netfront_info *);
149 static void xn_tick_locked(struct netfront_info *);
150 static void xn_tick(void *);
152 static void xn_intr(void *);
153 static inline int xn_count_frags(struct mbuf *m);
154 static int xn_assemble_tx_request(struct netfront_info *sc,
155 struct mbuf *m_head);
156 static void xn_start_locked(struct ifnet *);
157 static void xn_start(struct ifnet *);
158 static int xn_ioctl(struct ifnet *, u_long, caddr_t);
159 static void xn_ifinit_locked(struct netfront_info *);
160 static void xn_ifinit(void *);
161 static void xn_stop(struct netfront_info *);
162 static void xn_query_features(struct netfront_info *np);
163 static int xn_configure_features(struct netfront_info *np);
165 static void xn_watchdog(struct ifnet *);
169 static void netfront_closing(device_t dev);
171 static void netif_free(struct netfront_info *info);
172 static int netfront_detach(device_t dev);
174 static int talk_to_backend(device_t dev, struct netfront_info *info);
175 static int create_netdev(device_t dev);
176 static void netif_disconnect_backend(struct netfront_info *info);
177 static int setup_device(device_t dev, struct netfront_info *info);
178 static void free_ring(int *ref, void *ring_ptr_ref);
180 static int xn_ifmedia_upd(struct ifnet *ifp);
181 static void xn_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr);
183 /* Xenolinux helper functions */
184 int network_connect(struct netfront_info *);
186 static void xn_free_rx_ring(struct netfront_info *);
188 static void xn_free_tx_ring(struct netfront_info *);
190 static int xennet_get_responses(struct netfront_info *np,
191 struct netfront_rx_info *rinfo, RING_IDX rp, RING_IDX *cons,
192 struct mbuf **list, int *pages_flipped_p);
194 #define virt_to_mfn(x) (vtomach(x) >> PAGE_SHIFT)
196 #define INVALID_P2M_ENTRY (~0UL)
199 * Mbuf pointers. We need these to keep track of the virtual addresses
200 * of our mbuf chains since we can only convert from virtual to physical,
201 * not the other way around. The size must track the free index arrays.
203 struct xn_chain_data {
204 struct mbuf *xn_tx_chain[NET_TX_RING_SIZE+1];
206 struct mbuf *xn_rx_chain[NET_RX_RING_SIZE+1];
209 struct net_device_stats
211 u_long rx_packets; /* total packets received */
212 u_long tx_packets; /* total packets transmitted */
213 u_long rx_bytes; /* total bytes received */
214 u_long tx_bytes; /* total bytes transmitted */
215 u_long rx_errors; /* bad packets received */
216 u_long tx_errors; /* packet transmit problems */
217 u_long rx_dropped; /* no space in linux buffers */
218 u_long tx_dropped; /* no space available in linux */
219 u_long multicast; /* multicast packets received */
222 /* detailed rx_errors: */
223 u_long rx_length_errors;
224 u_long rx_over_errors; /* receiver ring buff overflow */
225 u_long rx_crc_errors; /* recved pkt with crc error */
226 u_long rx_frame_errors; /* recv'd frame alignment error */
227 u_long rx_fifo_errors; /* recv'r fifo overrun */
228 u_long rx_missed_errors; /* receiver missed packet */
230 /* detailed tx_errors */
231 u_long tx_aborted_errors;
232 u_long tx_carrier_errors;
233 u_long tx_fifo_errors;
234 u_long tx_heartbeat_errors;
235 u_long tx_window_errors;
238 u_long rx_compressed;
239 u_long tx_compressed;
242 struct netfront_info {
243 struct ifnet *xn_ifp;
244 #if __FreeBSD_version >= 700000
245 struct lro_ctrl xn_lro;
248 struct net_device_stats stats;
251 netif_tx_front_ring_t tx;
252 netif_rx_front_ring_t rx;
258 xen_intr_handle_t xen_intr_handle;
259 u_int copying_receiver;
263 /* Receive-ring batched refills. */
264 #define RX_MIN_TARGET 32
265 #define RX_MAX_TARGET NET_RX_RING_SIZE
270 grant_ref_t gref_tx_head;
271 grant_ref_t grant_tx_ref[NET_TX_RING_SIZE + 1];
272 grant_ref_t gref_rx_head;
273 grant_ref_t grant_rx_ref[NET_TX_RING_SIZE + 1];
278 uint8_t mac[ETHER_ADDR_LEN];
279 struct xn_chain_data xn_cdata; /* mbufs */
280 struct mbuf_head xn_rx_batch; /* head of the batch queue */
283 struct callout xn_stat_ch;
285 u_long rx_pfn_array[NET_RX_RING_SIZE];
286 multicall_entry_t rx_mcl[NET_RX_RING_SIZE+1];
287 mmu_update_t rx_mmu[NET_RX_RING_SIZE];
288 struct ifmedia sc_media;
291 #define rx_mbufs xn_cdata.xn_rx_chain
292 #define tx_mbufs xn_cdata.xn_tx_chain
294 #define XN_LOCK_INIT(_sc, _name) \
295 mtx_init(&(_sc)->tx_lock, #_name"_tx", "network transmit lock", MTX_DEF); \
296 mtx_init(&(_sc)->rx_lock, #_name"_rx", "network receive lock", MTX_DEF); \
297 mtx_init(&(_sc)->sc_lock, #_name"_sc", "netfront softc lock", MTX_DEF)
299 #define XN_RX_LOCK(_sc) mtx_lock(&(_sc)->rx_lock)
300 #define XN_RX_UNLOCK(_sc) mtx_unlock(&(_sc)->rx_lock)
302 #define XN_TX_LOCK(_sc) mtx_lock(&(_sc)->tx_lock)
303 #define XN_TX_UNLOCK(_sc) mtx_unlock(&(_sc)->tx_lock)
305 #define XN_LOCK(_sc) mtx_lock(&(_sc)->sc_lock);
306 #define XN_UNLOCK(_sc) mtx_unlock(&(_sc)->sc_lock);
308 #define XN_LOCK_ASSERT(_sc) mtx_assert(&(_sc)->sc_lock, MA_OWNED);
309 #define XN_RX_LOCK_ASSERT(_sc) mtx_assert(&(_sc)->rx_lock, MA_OWNED);
310 #define XN_TX_LOCK_ASSERT(_sc) mtx_assert(&(_sc)->tx_lock, MA_OWNED);
311 #define XN_LOCK_DESTROY(_sc) mtx_destroy(&(_sc)->rx_lock); \
312 mtx_destroy(&(_sc)->tx_lock); \
313 mtx_destroy(&(_sc)->sc_lock);
315 struct netfront_rx_info {
316 struct netif_rx_response rx;
317 struct netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX - 1];
320 #define netfront_carrier_on(netif) ((netif)->carrier = 1)
321 #define netfront_carrier_off(netif) ((netif)->carrier = 0)
322 #define netfront_carrier_ok(netif) ((netif)->carrier)
324 /* Access macros for acquiring freeing slots in xn_free_{tx,rx}_idxs[]. */
327 add_id_to_freelist(struct mbuf **list, uintptr_t id)
330 ("%s: the head item (0) must always be free.", __func__));
332 list[0] = (struct mbuf *)id;
335 static inline unsigned short
336 get_id_from_freelist(struct mbuf **list)
340 id = (uintptr_t)list[0];
342 ("%s: the head item (0) must always remain free.", __func__));
348 xennet_rxidx(RING_IDX idx)
350 return idx & (NET_RX_RING_SIZE - 1);
353 static inline struct mbuf *
354 xennet_get_rx_mbuf(struct netfront_info *np, RING_IDX ri)
356 int i = xennet_rxidx(ri);
360 np->rx_mbufs[i] = NULL;
364 static inline grant_ref_t
365 xennet_get_rx_ref(struct netfront_info *np, RING_IDX ri)
367 int i = xennet_rxidx(ri);
368 grant_ref_t ref = np->grant_rx_ref[i];
369 KASSERT(ref != GRANT_REF_INVALID, ("Invalid grant reference!\n"));
370 np->grant_rx_ref[i] = GRANT_REF_INVALID;
374 #define IPRINTK(fmt, args...) \
375 printf("[XEN] " fmt, ##args)
377 #define WPRINTK(fmt, args...) \
378 printf("[XEN] " fmt, ##args)
380 #define WPRINTK(fmt, args...)
383 #define DPRINTK(fmt, args...) \
384 printf("[XEN] %s: " fmt, __func__, ##args)
386 #define DPRINTK(fmt, args...)
390 * Read the 'mac' node at the given device's node in the store, and parse that
391 * as colon-separated octets, placing result the given mac array. mac must be
392 * a preallocated array of length ETH_ALEN (as declared in linux/if_ether.h).
393 * Return 0 on success, or errno on error.
396 xen_net_read_mac(device_t dev, uint8_t mac[])
399 char *s, *e, *macstr;
402 path = xenbus_get_node(dev);
403 error = xs_read(XST_NIL, path, "mac", NULL, (void **) &macstr);
404 if (error == ENOENT) {
406 * Deal with missing mac XenStore nodes on devices with
407 * HVM emulation (the 'ioemu' configuration attribute)
410 * The HVM emulator may execute in a stub device model
411 * domain which lacks the permission, only given to Dom0,
412 * to update the guest's XenStore tree. For this reason,
413 * the HVM emulator doesn't even attempt to write the
414 * front-side mac node, even when operating in Dom0.
415 * However, there should always be a mac listed in the
416 * backend tree. Fallback to this version if our query
417 * of the front side XenStore location doesn't find
420 path = xenbus_get_otherend_path(dev);
421 error = xs_read(XST_NIL, path, "mac", NULL, (void **) &macstr);
424 xenbus_dev_fatal(dev, error, "parsing %s/mac", path);
429 for (i = 0; i < ETHER_ADDR_LEN; i++) {
430 mac[i] = strtoul(s, &e, 16);
431 if (s == e || (e[0] != ':' && e[0] != 0)) {
432 free(macstr, M_XENBUS);
437 free(macstr, M_XENBUS);
442 * Entry point to this code when a new device is created. Allocate the basic
443 * structures and the ring buffers for communication with the backend, and
444 * inform the backend of the appropriate details for those. Switch to
448 netfront_probe(device_t dev)
451 if (!strcmp(xenbus_get_type(dev), "vif")) {
452 device_set_desc(dev, "Virtual Network Interface");
460 netfront_attach(device_t dev)
464 err = create_netdev(dev);
466 xenbus_dev_fatal(dev, err, "creating netdev");
470 #if __FreeBSD_version >= 700000
471 SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
472 SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
473 OID_AUTO, "enable_lro", CTLFLAG_RW,
474 &xn_enable_lro, 0, "Large Receive Offload");
481 netfront_suspend(device_t dev)
483 struct netfront_info *info = device_get_softc(dev);
487 netfront_carrier_off(info);
494 * We are reconnecting to the backend, due to a suspend/resume, or a backend
495 * driver restart. We tear down our netif structure and recreate it, but
496 * leave the device-layer structures intact so that this is transparent to the
497 * rest of the kernel.
500 netfront_resume(device_t dev)
502 struct netfront_info *info = device_get_softc(dev);
504 netif_disconnect_backend(info);
508 /* Common code used when first setting up, and when resuming. */
510 talk_to_backend(device_t dev, struct netfront_info *info)
513 struct xs_transaction xst;
514 const char *node = xenbus_get_node(dev);
517 err = xen_net_read_mac(dev, info->mac);
519 xenbus_dev_fatal(dev, err, "parsing %s/mac", node);
523 /* Create shared ring, alloc event channel. */
524 err = setup_device(dev, info);
529 err = xs_transaction_start(&xst);
531 xenbus_dev_fatal(dev, err, "starting transaction");
534 err = xs_printf(xst, node, "tx-ring-ref","%u",
537 message = "writing tx ring-ref";
538 goto abort_transaction;
540 err = xs_printf(xst, node, "rx-ring-ref","%u",
543 message = "writing rx ring-ref";
544 goto abort_transaction;
546 err = xs_printf(xst, node,
547 "event-channel", "%u",
548 xen_intr_port(info->xen_intr_handle));
550 message = "writing event-channel";
551 goto abort_transaction;
553 err = xs_printf(xst, node, "request-rx-copy", "%u",
554 info->copying_receiver);
556 message = "writing request-rx-copy";
557 goto abort_transaction;
559 err = xs_printf(xst, node, "feature-rx-notify", "%d", 1);
561 message = "writing feature-rx-notify";
562 goto abort_transaction;
564 err = xs_printf(xst, node, "feature-sg", "%d", 1);
566 message = "writing feature-sg";
567 goto abort_transaction;
569 #if __FreeBSD_version >= 700000
570 err = xs_printf(xst, node, "feature-gso-tcpv4", "%d", 1);
572 message = "writing feature-gso-tcpv4";
573 goto abort_transaction;
577 err = xs_transaction_end(xst, 0);
581 xenbus_dev_fatal(dev, err, "completing transaction");
588 xs_transaction_end(xst, 1);
589 xenbus_dev_fatal(dev, err, "%s", message);
597 setup_device(device_t dev, struct netfront_info *info)
599 netif_tx_sring_t *txs;
600 netif_rx_sring_t *rxs;
606 info->tx_ring_ref = GRANT_REF_INVALID;
607 info->rx_ring_ref = GRANT_REF_INVALID;
608 info->rx.sring = NULL;
609 info->tx.sring = NULL;
611 txs = (netif_tx_sring_t *)malloc(PAGE_SIZE, M_DEVBUF, M_NOWAIT|M_ZERO);
614 xenbus_dev_fatal(dev, error, "allocating tx ring page");
617 SHARED_RING_INIT(txs);
618 FRONT_RING_INIT(&info->tx, txs, PAGE_SIZE);
619 error = xenbus_grant_ring(dev, virt_to_mfn(txs), &info->tx_ring_ref);
623 rxs = (netif_rx_sring_t *)malloc(PAGE_SIZE, M_DEVBUF, M_NOWAIT|M_ZERO);
626 xenbus_dev_fatal(dev, error, "allocating rx ring page");
629 SHARED_RING_INIT(rxs);
630 FRONT_RING_INIT(&info->rx, rxs, PAGE_SIZE);
632 error = xenbus_grant_ring(dev, virt_to_mfn(rxs), &info->rx_ring_ref);
636 error = xen_intr_alloc_and_bind_local_port(dev,
637 xenbus_get_otherend_id(dev), /*filter*/NULL, xn_intr, info,
638 INTR_TYPE_NET | INTR_MPSAFE | INTR_ENTROPY, &info->xen_intr_handle);
641 xenbus_dev_fatal(dev, error,
642 "xen_intr_alloc_and_bind_local_port failed");
655 * If this interface has an ipv4 address, send an arp for it. This
656 * helps to get the network going again after migrating hosts.
659 netfront_send_fake_arp(device_t dev, struct netfront_info *info)
665 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
666 if (ifa->ifa_addr->sa_family == AF_INET) {
667 arp_ifinit(ifp, ifa);
674 * Callback received when the backend's state changes.
677 netfront_backend_changed(device_t dev, XenbusState newstate)
679 struct netfront_info *sc = device_get_softc(dev);
681 DPRINTK("newstate=%d\n", newstate);
684 case XenbusStateInitialising:
685 case XenbusStateInitialised:
686 case XenbusStateConnected:
687 case XenbusStateUnknown:
688 case XenbusStateClosed:
689 case XenbusStateReconfigured:
690 case XenbusStateReconfiguring:
692 case XenbusStateInitWait:
693 if (xenbus_get_state(dev) != XenbusStateInitialising)
695 if (network_connect(sc) != 0)
697 xenbus_set_state(dev, XenbusStateConnected);
699 netfront_send_fake_arp(dev, sc);
702 case XenbusStateClosing:
703 xenbus_set_state(dev, XenbusStateClosed);
709 xn_free_rx_ring(struct netfront_info *sc)
714 for (i = 0; i < NET_RX_RING_SIZE; i++) {
715 if (sc->xn_cdata.rx_mbufs[i] != NULL) {
716 m_freem(sc->rx_mbufs[i]);
717 sc->rx_mbufs[i] = NULL;
722 sc->xn_rx_if->req_prod = 0;
723 sc->xn_rx_if->event = sc->rx.rsp_cons ;
728 xn_free_tx_ring(struct netfront_info *sc)
733 for (i = 0; i < NET_TX_RING_SIZE; i++) {
734 if (sc->tx_mbufs[i] != NULL) {
735 m_freem(sc->tx_mbufs[i]);
736 sc->xn_cdata.xn_tx_chain[i] = NULL;
745 * \brief Verify that there is sufficient space in the Tx ring
746 * buffer for a maximally sized request to be enqueued.
748 * A transmit request requires a transmit descriptor for each packet
749 * fragment, plus up to 2 entries for "options" (e.g. TSO).
752 xn_tx_slot_available(struct netfront_info *np)
754 return (RING_FREE_REQUESTS(&np->tx) > (MAX_TX_REQ_FRAGS + 2));
758 netif_release_tx_bufs(struct netfront_info *np)
762 for (i = 1; i <= NET_TX_RING_SIZE; i++) {
768 * We assume that no kernel addresses are
769 * less than NET_TX_RING_SIZE. Any entry
770 * in the table that is below this number
771 * must be an index from free-list tracking.
773 if (((uintptr_t)m) <= NET_TX_RING_SIZE)
775 gnttab_end_foreign_access_ref(np->grant_tx_ref[i]);
776 gnttab_release_grant_reference(&np->gref_tx_head,
777 np->grant_tx_ref[i]);
778 np->grant_tx_ref[i] = GRANT_REF_INVALID;
779 add_id_to_freelist(np->tx_mbufs, i);
780 np->xn_cdata.xn_tx_chain_cnt--;
781 if (np->xn_cdata.xn_tx_chain_cnt < 0) {
782 panic("%s: tx_chain_cnt must be >= 0", __func__);
789 network_alloc_rx_buffers(struct netfront_info *sc)
791 int otherend_id = xenbus_get_otherend_id(sc->xbdev);
794 int i, batch_target, notify;
796 struct xen_memory_reservation reservation;
799 netif_rx_request_t *req;
803 req_prod = sc->rx.req_prod_pvt;
805 if (__predict_false(sc->carrier == 0))
809 * Allocate mbufs greedily, even though we batch updates to the
810 * receive ring. This creates a less bursty demand on the memory
811 * allocator, and so should reduce the chance of failed allocation
812 * requests both for ourself and for other kernel subsystems.
814 * Here we attempt to maintain rx_target buffers in flight, counting
815 * buffers that we have yet to process in the receive ring.
817 batch_target = sc->rx_target - (req_prod - sc->rx.rsp_cons);
818 for (i = mbufq_len(&sc->xn_rx_batch); i < batch_target; i++) {
819 MGETHDR(m_new, M_NOWAIT, MT_DATA);
821 printf("%s: MGETHDR failed\n", __func__);
825 m_cljget(m_new, M_NOWAIT, MJUMPAGESIZE);
826 if ((m_new->m_flags & M_EXT) == 0) {
827 printf("%s: m_cljget failed\n", __func__);
838 m_new->m_len = m_new->m_pkthdr.len = MJUMPAGESIZE;
840 /* queue the mbufs allocated */
841 mbufq_tail(&sc->xn_rx_batch, m_new);
845 * If we've allocated at least half of our target number of entries,
846 * submit them to the backend - we have enough to make the overhead
847 * of submission worthwhile. Otherwise wait for more mbufs and
848 * request entries to become available.
850 if (i < (sc->rx_target/2)) {
851 if (req_prod >sc->rx.sring->req_prod)
857 * Double floating fill target if we risked having the backend
858 * run out of empty buffers for receive traffic. We define "running
859 * low" as having less than a fourth of our target buffers free
860 * at the time we refilled the queue.
862 if ((req_prod - sc->rx.sring->rsp_prod) < (sc->rx_target / 4)) {
864 if (sc->rx_target > sc->rx_max_target)
865 sc->rx_target = sc->rx_max_target;
869 for (nr_flips = i = 0; ; i++) {
870 if ((m_new = mbufq_dequeue(&sc->xn_rx_batch)) == NULL)
873 m_new->m_ext.ext_arg1 = (vm_paddr_t *)(uintptr_t)(
874 vtophys(m_new->m_ext.ext_buf) >> PAGE_SHIFT);
876 id = xennet_rxidx(req_prod + i);
878 KASSERT(sc->rx_mbufs[id] == NULL, ("non-NULL xm_rx_chain"));
879 sc->rx_mbufs[id] = m_new;
881 ref = gnttab_claim_grant_reference(&sc->gref_rx_head);
882 KASSERT(ref != GNTTAB_LIST_END,
883 ("reserved grant references exhuasted"));
884 sc->grant_rx_ref[id] = ref;
886 vaddr = mtod(m_new, vm_offset_t);
887 pfn = vtophys(vaddr) >> PAGE_SHIFT;
888 req = RING_GET_REQUEST(&sc->rx, req_prod + i);
890 if (sc->copying_receiver == 0) {
891 gnttab_grant_foreign_transfer_ref(ref,
893 sc->rx_pfn_array[nr_flips] = PFNTOMFN(pfn);
894 if (!xen_feature(XENFEAT_auto_translated_physmap)) {
895 /* Remove this page before passing
898 set_phys_to_machine(pfn, INVALID_P2M_ENTRY);
899 MULTI_update_va_mapping(&sc->rx_mcl[i],
904 gnttab_grant_foreign_access_ref(ref,
911 sc->rx_pfn_array[i] =
912 vtomach(mtod(m_new,vm_offset_t)) >> PAGE_SHIFT;
915 KASSERT(i, ("no mbufs processed")); /* should have returned earlier */
916 KASSERT(mbufq_len(&sc->xn_rx_batch) == 0, ("not all mbufs processed"));
918 * We may have allocated buffers which have entries outstanding
919 * in the page * update queue -- make sure we flush those first!
924 /* Tell the ballon driver what is going on. */
925 balloon_update_driver_allowance(i);
927 set_xen_guest_handle(reservation.extent_start, sc->rx_pfn_array);
928 reservation.nr_extents = i;
929 reservation.extent_order = 0;
930 reservation.address_bits = 0;
931 reservation.domid = DOMID_SELF;
933 if (!xen_feature(XENFEAT_auto_translated_physmap)) {
934 /* After all PTEs have been zapped, flush the TLB. */
935 sc->rx_mcl[i-1].args[MULTI_UVMFLAGS_INDEX] =
936 UVMF_TLB_FLUSH|UVMF_ALL;
938 /* Give away a batch of pages. */
939 sc->rx_mcl[i].op = __HYPERVISOR_memory_op;
940 sc->rx_mcl[i].args[0] = XENMEM_decrease_reservation;
941 sc->rx_mcl[i].args[1] = (u_long)&reservation;
942 /* Zap PTEs and give away pages in one big multicall. */
943 (void)HYPERVISOR_multicall(sc->rx_mcl, i+1);
945 if (__predict_false(sc->rx_mcl[i].result != i ||
946 HYPERVISOR_memory_op(XENMEM_decrease_reservation,
948 panic("%s: unable to reduce memory "
949 "reservation\n", __func__);
955 /* Above is a suitable barrier to ensure backend will see requests. */
956 sc->rx.req_prod_pvt = req_prod + i;
958 RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&sc->rx, notify);
960 xen_intr_signal(sc->xen_intr_handle);
964 xn_rxeof(struct netfront_info *np)
967 #if __FreeBSD_version >= 700000 && (defined(INET) || defined(INET6))
968 struct lro_ctrl *lro = &np->xn_lro;
969 struct lro_entry *queued;
971 struct netfront_rx_info rinfo;
972 struct netif_rx_response *rx = &rinfo.rx;
973 struct netif_extra_info *extras = rinfo.extras;
975 multicall_entry_t *mcl;
977 struct mbuf_head rxq, errq;
978 int err, pages_flipped = 0, work_to_do;
981 XN_RX_LOCK_ASSERT(np);
982 if (!netfront_carrier_ok(np))
990 rp = np->rx.sring->rsp_prod;
991 rmb(); /* Ensure we see queued responses up to 'rp'. */
995 memcpy(rx, RING_GET_RESPONSE(&np->rx, i), sizeof(*rx));
996 memset(extras, 0, sizeof(rinfo.extras));
999 err = xennet_get_responses(np, &rinfo, rp, &i, &m,
1002 if (__predict_false(err)) {
1004 mbufq_tail(&errq, m);
1005 np->stats.rx_errors++;
1009 m->m_pkthdr.rcvif = ifp;
1010 if ( rx->flags & NETRXF_data_validated ) {
1011 /* Tell the stack the checksums are okay */
1013 * XXX this isn't necessarily the case - need to add
1017 m->m_pkthdr.csum_flags |=
1018 (CSUM_IP_CHECKED | CSUM_IP_VALID | CSUM_DATA_VALID
1020 m->m_pkthdr.csum_data = 0xffff;
1023 np->stats.rx_packets++;
1024 np->stats.rx_bytes += m->m_pkthdr.len;
1026 mbufq_tail(&rxq, m);
1027 np->rx.rsp_cons = i;
1030 if (pages_flipped) {
1031 /* Some pages are no longer absent... */
1033 balloon_update_driver_allowance(-pages_flipped);
1035 /* Do all the remapping work, and M->P updates, in one big
1038 if (!!xen_feature(XENFEAT_auto_translated_physmap)) {
1039 mcl = np->rx_mcl + pages_flipped;
1040 mcl->op = __HYPERVISOR_mmu_update;
1041 mcl->args[0] = (u_long)np->rx_mmu;
1042 mcl->args[1] = pages_flipped;
1044 mcl->args[3] = DOMID_SELF;
1045 (void)HYPERVISOR_multicall(np->rx_mcl,
1050 while ((m = mbufq_dequeue(&errq)))
1054 * Process all the mbufs after the remapping is complete.
1055 * Break the mbuf chain first though.
1057 while ((m = mbufq_dequeue(&rxq)) != NULL) {
1058 if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
1061 * Do we really need to drop the rx lock?
1064 #if __FreeBSD_version >= 700000 && (defined(INET) || defined(INET6))
1065 /* Use LRO if possible */
1066 if ((ifp->if_capenable & IFCAP_LRO) == 0 ||
1067 lro->lro_cnt == 0 || tcp_lro_rx(lro, m, 0)) {
1069 * If LRO fails, pass up to the stack
1072 (*ifp->if_input)(ifp, m);
1075 (*ifp->if_input)(ifp, m);
1080 np->rx.rsp_cons = i;
1082 #if __FreeBSD_version >= 700000 && (defined(INET) || defined(INET6))
1084 * Flush any outstanding LRO work
1086 while (!SLIST_EMPTY(&lro->lro_active)) {
1087 queued = SLIST_FIRST(&lro->lro_active);
1088 SLIST_REMOVE_HEAD(&lro->lro_active, next);
1089 tcp_lro_flush(lro, queued);
1094 /* If we get a callback with very few responses, reduce fill target. */
1095 /* NB. Note exponential increase, linear decrease. */
1096 if (((np->rx.req_prod_pvt - np->rx.sring->rsp_prod) >
1097 ((3*np->rx_target) / 4)) && (--np->rx_target < np->rx_min_target))
1098 np->rx_target = np->rx_min_target;
1101 network_alloc_rx_buffers(np);
1103 RING_FINAL_CHECK_FOR_RESPONSES(&np->rx, work_to_do);
1104 } while (work_to_do);
1108 xn_txeof(struct netfront_info *np)
1113 netif_tx_response_t *txr;
1116 XN_TX_LOCK_ASSERT(np);
1118 if (!netfront_carrier_ok(np))
1124 prod = np->tx.sring->rsp_prod;
1125 rmb(); /* Ensure we see responses up to 'rp'. */
1127 for (i = np->tx.rsp_cons; i != prod; i++) {
1128 txr = RING_GET_RESPONSE(&np->tx, i);
1129 if (txr->status == NETIF_RSP_NULL)
1132 if (txr->status != NETIF_RSP_OKAY) {
1133 printf("%s: WARNING: response is %d!\n",
1134 __func__, txr->status);
1137 m = np->tx_mbufs[id];
1138 KASSERT(m != NULL, ("mbuf not found in xn_tx_chain"));
1139 KASSERT((uintptr_t)m > NET_TX_RING_SIZE,
1140 ("mbuf already on the free list, but we're "
1141 "trying to free it again!"));
1145 * Increment packet count if this is the last
1146 * mbuf of the chain.
1149 if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1150 if (__predict_false(gnttab_query_foreign_access(
1151 np->grant_tx_ref[id]) != 0)) {
1152 panic("%s: grant id %u still in use by the "
1153 "backend", __func__, id);
1155 gnttab_end_foreign_access_ref(
1156 np->grant_tx_ref[id]);
1157 gnttab_release_grant_reference(
1158 &np->gref_tx_head, np->grant_tx_ref[id]);
1159 np->grant_tx_ref[id] = GRANT_REF_INVALID;
1161 np->tx_mbufs[id] = NULL;
1162 add_id_to_freelist(np->tx_mbufs, id);
1163 np->xn_cdata.xn_tx_chain_cnt--;
1165 /* Only mark the queue active if we've freed up at least one slot to try */
1166 ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1168 np->tx.rsp_cons = prod;
1171 * Set a new event, then check for race with update of
1172 * tx_cons. Note that it is essential to schedule a
1173 * callback, no matter how few buffers are pending. Even if
1174 * there is space in the transmit ring, higher layers may
1175 * be blocked because too much data is outstanding: in such
1176 * cases notification from Xen is likely to be the only kick
1179 np->tx.sring->rsp_event =
1180 prod + ((np->tx.sring->req_prod - prod) >> 1) + 1;
1183 } while (prod != np->tx.sring->rsp_prod);
1186 ((np->tx.sring->req_prod - prod) < NET_TX_RING_SIZE)) {
1189 if (np->user_state == UST_OPEN)
1190 netif_wake_queue(dev);
1198 struct netfront_info *np = xsc;
1199 struct ifnet *ifp = np->xn_ifp;
1202 if (!(np->rx.rsp_cons != np->rx.sring->rsp_prod &&
1203 likely(netfront_carrier_ok(np)) &&
1204 ifp->if_drv_flags & IFF_DRV_RUNNING))
1207 if (RING_HAS_UNCONSUMED_RESPONSES(&np->tx)) {
1217 if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
1218 !IFQ_DRV_IS_EMPTY(&ifp->if_snd))
1223 xennet_move_rx_slot(struct netfront_info *np, struct mbuf *m,
1226 int new = xennet_rxidx(np->rx.req_prod_pvt);
1228 KASSERT(np->rx_mbufs[new] == NULL, ("rx_mbufs != NULL"));
1229 np->rx_mbufs[new] = m;
1230 np->grant_rx_ref[new] = ref;
1231 RING_GET_REQUEST(&np->rx, np->rx.req_prod_pvt)->id = new;
1232 RING_GET_REQUEST(&np->rx, np->rx.req_prod_pvt)->gref = ref;
1233 np->rx.req_prod_pvt++;
1237 xennet_get_extras(struct netfront_info *np,
1238 struct netif_extra_info *extras, RING_IDX rp, RING_IDX *cons)
1240 struct netif_extra_info *extra;
1248 if (__predict_false(*cons + 1 == rp)) {
1250 if (net_ratelimit())
1251 WPRINTK("Missing extra info\n");
1257 extra = (struct netif_extra_info *)
1258 RING_GET_RESPONSE(&np->rx, ++(*cons));
1260 if (__predict_false(!extra->type ||
1261 extra->type >= XEN_NETIF_EXTRA_TYPE_MAX)) {
1263 if (net_ratelimit())
1264 WPRINTK("Invalid extra type: %d\n",
1269 memcpy(&extras[extra->type - 1], extra, sizeof(*extra));
1272 m = xennet_get_rx_mbuf(np, *cons);
1273 ref = xennet_get_rx_ref(np, *cons);
1274 xennet_move_rx_slot(np, m, ref);
1275 } while (extra->flags & XEN_NETIF_EXTRA_FLAG_MORE);
1281 xennet_get_responses(struct netfront_info *np,
1282 struct netfront_rx_info *rinfo, RING_IDX rp, RING_IDX *cons,
1284 int *pages_flipped_p)
1286 int pages_flipped = *pages_flipped_p;
1287 struct mmu_update *mmu;
1288 struct multicall_entry *mcl;
1289 struct netif_rx_response *rx = &rinfo->rx;
1290 struct netif_extra_info *extras = rinfo->extras;
1291 struct mbuf *m, *m0, *m_prev;
1292 grant_ref_t ref = xennet_get_rx_ref(np, *cons);
1293 RING_IDX ref_cons = *cons;
1298 m0 = m = m_prev = xennet_get_rx_mbuf(np, *cons);
1300 if (rx->flags & NETRXF_extra_info) {
1301 err = xennet_get_extras(np, extras, rp, cons);
1305 m0->m_pkthdr.len = 0;
1313 DPRINTK("rx->status=%hd rx->offset=%hu frags=%u\n",
1314 rx->status, rx->offset, frags);
1316 if (__predict_false(rx->status < 0 ||
1317 rx->offset + rx->status > PAGE_SIZE)) {
1320 if (net_ratelimit())
1321 WPRINTK("rx->offset: %x, size: %u\n",
1322 rx->offset, rx->status);
1324 xennet_move_rx_slot(np, m, ref);
1329 goto next_skip_queue;
1333 * This definitely indicates a bug, either in this driver or in
1334 * the backend driver. In future this should flag the bad
1335 * situation to the system controller to reboot the backed.
1337 if (ref == GRANT_REF_INVALID) {
1340 if (net_ratelimit())
1341 WPRINTK("Bad rx response id %d.\n", rx->id);
1343 printf("%s: Bad rx response id %d.\n", __func__,rx->id);
1348 if (!np->copying_receiver) {
1349 /* Memory pressure, insufficient buffer
1352 if (!(mfn = gnttab_end_foreign_transfer_ref(ref))) {
1353 WPRINTK("Unfulfilled rx req (id=%d, st=%d).\n",
1354 rx->id, rx->status);
1355 xennet_move_rx_slot(np, m, ref);
1360 if (!xen_feature( XENFEAT_auto_translated_physmap)) {
1361 /* Remap the page. */
1362 void *vaddr = mtod(m, void *);
1365 mcl = np->rx_mcl + pages_flipped;
1366 mmu = np->rx_mmu + pages_flipped;
1368 MULTI_update_va_mapping(mcl, (u_long)vaddr,
1369 (((vm_paddr_t)mfn) << PAGE_SHIFT) | PG_RW |
1370 PG_V | PG_M | PG_A, 0);
1371 pfn = (uintptr_t)m->m_ext.ext_arg1;
1372 mmu->ptr = ((vm_paddr_t)mfn << PAGE_SHIFT) |
1373 MMU_MACHPHYS_UPDATE;
1376 set_phys_to_machine(pfn, mfn);
1380 ret = gnttab_end_foreign_access_ref(ref);
1381 KASSERT(ret, ("ret != 0"));
1384 gnttab_release_grant_reference(&np->gref_rx_head, ref);
1390 m->m_len = rx->status;
1391 m->m_data += rx->offset;
1392 m0->m_pkthdr.len += rx->status;
1395 if (!(rx->flags & NETRXF_more_data))
1398 if (*cons + frags == rp) {
1399 if (net_ratelimit())
1400 WPRINTK("Need more frags\n");
1402 printf("%s: cons %u frags %u rp %u, not enough frags\n",
1403 __func__, *cons, frags, rp);
1407 * Note that m can be NULL, if rx->status < 0 or if
1408 * rx->offset + rx->status > PAGE_SIZE above.
1412 rx = RING_GET_RESPONSE(&np->rx, *cons + frags);
1413 m = xennet_get_rx_mbuf(np, *cons + frags);
1416 * m_prev == NULL can happen if rx->status < 0 or if
1417 * rx->offset + * rx->status > PAGE_SIZE above.
1423 * m0 can be NULL if rx->status < 0 or if * rx->offset +
1424 * rx->status > PAGE_SIZE above.
1429 ref = xennet_get_rx_ref(np, *cons + frags);
1430 ref_cons = *cons + frags;
1435 *pages_flipped_p = pages_flipped;
1441 xn_tick_locked(struct netfront_info *sc)
1443 XN_RX_LOCK_ASSERT(sc);
1444 callout_reset(&sc->xn_stat_ch, hz, xn_tick, sc);
1446 /* XXX placeholder for printing debug information */
1452 struct netfront_info *sc;
1461 * \brief Count the number of fragments in an mbuf chain.
1463 * Surprisingly, there isn't an M* macro for this.
1466 xn_count_frags(struct mbuf *m)
1470 for (nfrags = 0; m != NULL; m = m->m_next)
1477 * Given an mbuf chain, make sure we have enough room and then push
1478 * it onto the transmit ring.
1481 xn_assemble_tx_request(struct netfront_info *sc, struct mbuf *m_head)
1486 netif_extra_info_t *extra;
1492 * Defragment the mbuf if necessary.
1494 nfrags = xn_count_frags(m_head);
1497 * Check to see whether this request is longer than netback
1498 * can handle, and try to defrag it.
1501 * It is a bit lame, but the netback driver in Linux can't
1502 * deal with nfrags > MAX_TX_REQ_FRAGS, which is a quirk of
1503 * the Linux network stack.
1505 if (nfrags > sc->maxfrags) {
1506 m = m_defrag(m_head, M_NOWAIT);
1509 * Defrag failed, so free the mbuf and
1510 * therefore drop the packet.
1518 /* Determine how many fragments now exist */
1519 nfrags = xn_count_frags(m_head);
1522 * Check to see whether the defragmented packet has too many
1523 * segments for the Linux netback driver.
1526 * The FreeBSD TCP stack, with TSO enabled, can produce a chain
1527 * of mbufs longer than Linux can handle. Make sure we don't
1528 * pass a too-long chain over to the other side by dropping the
1529 * packet. It doesn't look like there is currently a way to
1530 * tell the TCP stack to generate a shorter chain of packets.
1532 if (nfrags > MAX_TX_REQ_FRAGS) {
1534 printf("%s: nfrags %d > MAX_TX_REQ_FRAGS %d, netback "
1535 "won't be able to handle it, dropping\n",
1536 __func__, nfrags, MAX_TX_REQ_FRAGS);
1543 * This check should be redundant. We've already verified that we
1544 * have enough slots in the ring to handle a packet of maximum
1545 * size, and that our packet is less than the maximum size. Keep
1546 * it in here as an assert for now just to make certain that
1547 * xn_tx_chain_cnt is accurate.
1549 KASSERT((sc->xn_cdata.xn_tx_chain_cnt + nfrags) <= NET_TX_RING_SIZE,
1550 ("%s: xn_tx_chain_cnt (%d) + nfrags (%d) > NET_TX_RING_SIZE "
1551 "(%d)!", __func__, (int) sc->xn_cdata.xn_tx_chain_cnt,
1552 (int) nfrags, (int) NET_TX_RING_SIZE));
1555 * Start packing the mbufs in this chain into
1556 * the fragment pointers. Stop when we run out
1557 * of fragments or hit the end of the mbuf chain.
1561 otherend_id = xenbus_get_otherend_id(sc->xbdev);
1562 for (m = m_head; m; m = m->m_next) {
1563 netif_tx_request_t *tx;
1566 u_long mfn; /* XXX Wrong type? */
1568 tx = RING_GET_REQUEST(&sc->tx, sc->tx.req_prod_pvt);
1569 id = get_id_from_freelist(sc->tx_mbufs);
1571 panic("%s: was allocated the freelist head!\n",
1573 sc->xn_cdata.xn_tx_chain_cnt++;
1574 if (sc->xn_cdata.xn_tx_chain_cnt > NET_TX_RING_SIZE)
1575 panic("%s: tx_chain_cnt must be <= NET_TX_RING_SIZE\n",
1577 sc->tx_mbufs[id] = m;
1579 ref = gnttab_claim_grant_reference(&sc->gref_tx_head);
1580 KASSERT((short)ref >= 0, ("Negative ref"));
1581 mfn = virt_to_mfn(mtod(m, vm_offset_t));
1582 gnttab_grant_foreign_access_ref(ref, otherend_id,
1583 mfn, GNTMAP_readonly);
1584 tx->gref = sc->grant_tx_ref[id] = ref;
1585 tx->offset = mtod(m, vm_offset_t) & (PAGE_SIZE - 1);
1589 * The first fragment has the entire packet
1590 * size, subsequent fragments have just the
1591 * fragment size. The backend works out the
1592 * true size of the first fragment by
1593 * subtracting the sizes of the other
1596 tx->size = m->m_pkthdr.len;
1599 * The first fragment contains the checksum flags
1600 * and is optionally followed by extra data for
1604 * CSUM_TSO requires checksum offloading.
1605 * Some versions of FreeBSD fail to
1606 * set CSUM_TCP in the CSUM_TSO case,
1607 * so we have to test for CSUM_TSO
1610 if (m->m_pkthdr.csum_flags
1611 & (CSUM_DELAY_DATA | CSUM_TSO)) {
1612 tx->flags |= (NETTXF_csum_blank
1613 | NETTXF_data_validated);
1615 #if __FreeBSD_version >= 700000
1616 if (m->m_pkthdr.csum_flags & CSUM_TSO) {
1617 struct netif_extra_info *gso =
1618 (struct netif_extra_info *)
1619 RING_GET_REQUEST(&sc->tx,
1620 ++sc->tx.req_prod_pvt);
1622 tx->flags |= NETTXF_extra_info;
1624 gso->u.gso.size = m->m_pkthdr.tso_segsz;
1626 XEN_NETIF_GSO_TYPE_TCPV4;
1628 gso->u.gso.features = 0;
1630 gso->type = XEN_NETIF_EXTRA_TYPE_GSO;
1635 tx->size = m->m_len;
1638 tx->flags |= NETTXF_more_data;
1640 sc->tx.req_prod_pvt++;
1642 BPF_MTAP(ifp, m_head);
1644 sc->stats.tx_bytes += m_head->m_pkthdr.len;
1645 sc->stats.tx_packets++;
1651 xn_start_locked(struct ifnet *ifp)
1653 struct netfront_info *sc;
1654 struct mbuf *m_head;
1659 if (!netfront_carrier_ok(sc))
1663 * While we have enough transmit slots available for at least one
1664 * maximum-sized packet, pull mbufs off the queue and put them on
1665 * the transmit ring.
1667 while (xn_tx_slot_available(sc)) {
1668 IF_DEQUEUE(&ifp->if_snd, m_head);
1672 if (xn_assemble_tx_request(sc, m_head) != 0)
1676 RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&sc->tx, notify);
1678 xen_intr_signal(sc->xen_intr_handle);
1680 if (RING_FULL(&sc->tx)) {
1683 netif_stop_queue(dev);
1689 xn_start(struct ifnet *ifp)
1691 struct netfront_info *sc;
1694 xn_start_locked(ifp);
1698 /* equivalent of network_open() in Linux */
1700 xn_ifinit_locked(struct netfront_info *sc)
1708 if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1713 network_alloc_rx_buffers(sc);
1714 sc->rx.sring->rsp_event = sc->rx.rsp_cons + 1;
1716 ifp->if_drv_flags |= IFF_DRV_RUNNING;
1717 ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1718 if_link_state_change(ifp, LINK_STATE_UP);
1720 callout_reset(&sc->xn_stat_ch, hz, xn_tick, sc);
1724 xn_ifinit(void *xsc)
1726 struct netfront_info *sc = xsc;
1729 xn_ifinit_locked(sc);
1734 xn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1736 struct netfront_info *sc = ifp->if_softc;
1737 struct ifreq *ifr = (struct ifreq *) data;
1739 struct ifaddr *ifa = (struct ifaddr *)data;
1742 int mask, error = 0;
1748 if (ifa->ifa_addr->sa_family == AF_INET) {
1749 ifp->if_flags |= IFF_UP;
1750 if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
1751 xn_ifinit_locked(sc);
1752 arp_ifinit(ifp, ifa);
1757 error = ether_ioctl(ifp, cmd, data);
1763 /* XXX can we alter the MTU on a VN ?*/
1765 if (ifr->ifr_mtu > XN_JUMBO_MTU)
1770 ifp->if_mtu = ifr->ifr_mtu;
1771 ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1777 if (ifp->if_flags & IFF_UP) {
1779 * If only the state of the PROMISC flag changed,
1780 * then just use the 'set promisc mode' command
1781 * instead of reinitializing the entire NIC. Doing
1782 * a full re-init means reloading the firmware and
1783 * waiting for it to start up, which may take a
1787 /* No promiscuous mode with Xen */
1788 if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
1789 ifp->if_flags & IFF_PROMISC &&
1790 !(sc->xn_if_flags & IFF_PROMISC)) {
1791 XN_SETBIT(sc, XN_RX_MODE,
1792 XN_RXMODE_RX_PROMISC);
1793 } else if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
1794 !(ifp->if_flags & IFF_PROMISC) &&
1795 sc->xn_if_flags & IFF_PROMISC) {
1796 XN_CLRBIT(sc, XN_RX_MODE,
1797 XN_RXMODE_RX_PROMISC);
1800 xn_ifinit_locked(sc);
1802 if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1806 sc->xn_if_flags = ifp->if_flags;
1811 mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1812 if (mask & IFCAP_TXCSUM) {
1813 if (IFCAP_TXCSUM & ifp->if_capenable) {
1814 ifp->if_capenable &= ~(IFCAP_TXCSUM|IFCAP_TSO4);
1815 ifp->if_hwassist &= ~(CSUM_TCP | CSUM_UDP
1816 | CSUM_IP | CSUM_TSO);
1818 ifp->if_capenable |= IFCAP_TXCSUM;
1819 ifp->if_hwassist |= (CSUM_TCP | CSUM_UDP
1823 if (mask & IFCAP_RXCSUM) {
1824 ifp->if_capenable ^= IFCAP_RXCSUM;
1826 #if __FreeBSD_version >= 700000
1827 if (mask & IFCAP_TSO4) {
1828 if (IFCAP_TSO4 & ifp->if_capenable) {
1829 ifp->if_capenable &= ~IFCAP_TSO4;
1830 ifp->if_hwassist &= ~CSUM_TSO;
1831 } else if (IFCAP_TXCSUM & ifp->if_capenable) {
1832 ifp->if_capenable |= IFCAP_TSO4;
1833 ifp->if_hwassist |= CSUM_TSO;
1835 IPRINTK("Xen requires tx checksum offload"
1836 " be enabled to use TSO\n");
1840 if (mask & IFCAP_LRO) {
1841 ifp->if_capenable ^= IFCAP_LRO;
1850 if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1860 error = ifmedia_ioctl(ifp, ifr, &sc->sc_media, cmd);
1863 error = ether_ioctl(ifp, cmd, data);
1870 xn_stop(struct netfront_info *sc)
1878 callout_stop(&sc->xn_stat_ch);
1880 xn_free_rx_ring(sc);
1881 xn_free_tx_ring(sc);
1883 ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
1884 if_link_state_change(ifp, LINK_STATE_DOWN);
1887 /* START of Xenolinux helper functions adapted to FreeBSD */
1889 network_connect(struct netfront_info *np)
1891 int i, requeue_idx, error;
1893 netif_rx_request_t *req;
1894 u_int feature_rx_copy, feature_rx_flip;
1896 error = xs_scanf(XST_NIL, xenbus_get_otherend_path(np->xbdev),
1897 "feature-rx-copy", NULL, "%u", &feature_rx_copy);
1899 feature_rx_copy = 0;
1900 error = xs_scanf(XST_NIL, xenbus_get_otherend_path(np->xbdev),
1901 "feature-rx-flip", NULL, "%u", &feature_rx_flip);
1903 feature_rx_flip = 1;
1906 * Copy packets on receive path if:
1907 * (a) This was requested by user, and the backend supports it; or
1908 * (b) Flipping was requested, but this is unsupported by the backend.
1910 np->copying_receiver = ((MODPARM_rx_copy && feature_rx_copy) ||
1911 (MODPARM_rx_flip && !feature_rx_flip));
1913 /* Recovery procedure: */
1914 error = talk_to_backend(np->xbdev, np);
1918 /* Step 1: Reinitialise variables. */
1919 xn_query_features(np);
1920 xn_configure_features(np);
1921 netif_release_tx_bufs(np);
1923 /* Step 2: Rebuild the RX buffer freelist and the RX ring itself. */
1924 for (requeue_idx = 0, i = 0; i < NET_RX_RING_SIZE; i++) {
1928 if (np->rx_mbufs[i] == NULL)
1931 m = np->rx_mbufs[requeue_idx] = xennet_get_rx_mbuf(np, i);
1932 ref = np->grant_rx_ref[requeue_idx] = xennet_get_rx_ref(np, i);
1934 req = RING_GET_REQUEST(&np->rx, requeue_idx);
1935 pfn = vtophys(mtod(m, vm_offset_t)) >> PAGE_SHIFT;
1937 if (!np->copying_receiver) {
1938 gnttab_grant_foreign_transfer_ref(ref,
1939 xenbus_get_otherend_id(np->xbdev),
1942 gnttab_grant_foreign_access_ref(ref,
1943 xenbus_get_otherend_id(np->xbdev),
1947 req->id = requeue_idx;
1952 np->rx.req_prod_pvt = requeue_idx;
1954 /* Step 3: All public and private state should now be sane. Get
1955 * ready to start sending and receiving packets and give the driver
1956 * domain a kick because we've probably just requeued some
1959 netfront_carrier_on(np);
1960 xen_intr_signal(np->xen_intr_handle);
1964 network_alloc_rx_buffers(np);
1970 xn_query_features(struct netfront_info *np)
1974 device_printf(np->xbdev, "backend features:");
1976 if (xs_scanf(XST_NIL, xenbus_get_otherend_path(np->xbdev),
1977 "feature-sg", NULL, "%d", &val) < 0)
1982 np->maxfrags = MAX_TX_REQ_FRAGS;
1983 printf(" feature-sg");
1986 if (xs_scanf(XST_NIL, xenbus_get_otherend_path(np->xbdev),
1987 "feature-gso-tcpv4", NULL, "%d", &val) < 0)
1990 np->xn_ifp->if_capabilities &= ~(IFCAP_TSO4|IFCAP_LRO);
1992 np->xn_ifp->if_capabilities |= IFCAP_TSO4|IFCAP_LRO;
1993 printf(" feature-gso-tcp4");
2000 xn_configure_features(struct netfront_info *np)
2005 #if __FreeBSD_version >= 700000 && (defined(INET) || defined(INET6))
2006 if ((np->xn_ifp->if_capenable & IFCAP_LRO) != 0)
2007 tcp_lro_free(&np->xn_lro);
2009 np->xn_ifp->if_capenable =
2010 np->xn_ifp->if_capabilities & ~(IFCAP_LRO|IFCAP_TSO4);
2011 np->xn_ifp->if_hwassist &= ~CSUM_TSO;
2012 #if __FreeBSD_version >= 700000 && (defined(INET) || defined(INET6))
2013 if (xn_enable_lro && (np->xn_ifp->if_capabilities & IFCAP_LRO) != 0) {
2014 err = tcp_lro_init(&np->xn_lro);
2016 device_printf(np->xbdev, "LRO initialization failed\n");
2018 np->xn_lro.ifp = np->xn_ifp;
2019 np->xn_ifp->if_capenable |= IFCAP_LRO;
2022 if ((np->xn_ifp->if_capabilities & IFCAP_TSO4) != 0) {
2023 np->xn_ifp->if_capenable |= IFCAP_TSO4;
2024 np->xn_ifp->if_hwassist |= CSUM_TSO;
2031 * Create a network device.
2032 * @param dev Newbus device representing this virtual NIC.
2035 create_netdev(device_t dev)
2038 struct netfront_info *np;
2042 np = device_get_softc(dev);
2046 XN_LOCK_INIT(np, xennetif);
2048 ifmedia_init(&np->sc_media, 0, xn_ifmedia_upd, xn_ifmedia_sts);
2049 ifmedia_add(&np->sc_media, IFM_ETHER|IFM_MANUAL, 0, NULL);
2050 ifmedia_set(&np->sc_media, IFM_ETHER|IFM_MANUAL);
2052 np->rx_target = RX_MIN_TARGET;
2053 np->rx_min_target = RX_MIN_TARGET;
2054 np->rx_max_target = RX_MAX_TARGET;
2056 /* Initialise {tx,rx}_skbs to be a free chain containing every entry. */
2057 for (i = 0; i <= NET_TX_RING_SIZE; i++) {
2058 np->tx_mbufs[i] = (void *) ((u_long) i+1);
2059 np->grant_tx_ref[i] = GRANT_REF_INVALID;
2061 np->tx_mbufs[NET_TX_RING_SIZE] = (void *)0;
2063 for (i = 0; i <= NET_RX_RING_SIZE; i++) {
2065 np->rx_mbufs[i] = NULL;
2066 np->grant_rx_ref[i] = GRANT_REF_INVALID;
2068 /* A grant for every tx ring slot */
2069 if (gnttab_alloc_grant_references(NET_TX_RING_SIZE,
2070 &np->gref_tx_head) != 0) {
2071 IPRINTK("#### netfront can't alloc tx grant refs\n");
2075 /* A grant for every rx ring slot */
2076 if (gnttab_alloc_grant_references(RX_MAX_TARGET,
2077 &np->gref_rx_head) != 0) {
2078 WPRINTK("#### netfront can't alloc rx grant refs\n");
2079 gnttab_free_grant_references(np->gref_tx_head);
2084 err = xen_net_read_mac(dev, np->mac);
2088 /* Set up ifnet structure */
2089 ifp = np->xn_ifp = if_alloc(IFT_ETHER);
2091 if_initname(ifp, "xn", device_get_unit(dev));
2092 ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
2093 ifp->if_ioctl = xn_ioctl;
2094 ifp->if_output = ether_output;
2095 ifp->if_start = xn_start;
2097 ifp->if_watchdog = xn_watchdog;
2099 ifp->if_init = xn_ifinit;
2100 ifp->if_snd.ifq_maxlen = NET_TX_RING_SIZE - 1;
2102 ifp->if_hwassist = XN_CSUM_FEATURES;
2103 ifp->if_capabilities = IFCAP_HWCSUM;
2104 ifp->if_hw_tsomax = 65536 - (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
2105 ifp->if_hw_tsomaxsegcount = MAX_TX_REQ_FRAGS;
2106 ifp->if_hw_tsomaxsegsize = PAGE_SIZE;
2108 ether_ifattach(ifp, np->mac);
2109 callout_init(&np->xn_stat_ch, CALLOUT_MPSAFE);
2110 netfront_carrier_off(np);
2115 gnttab_free_grant_references(np->gref_tx_head);
2121 * Handle the change of state of the backend to Closing. We must delete our
2122 * device-layer structures now, to ensure that writes are flushed through to
2123 * the backend. Once is this done, we can switch to Closed in
2128 netfront_closing(device_t dev)
2131 struct netfront_info *info = dev->dev_driver_data;
2133 DPRINTK("netfront_closing: %s removed\n", dev->nodename);
2137 xenbus_switch_state(dev, XenbusStateClosed);
2142 netfront_detach(device_t dev)
2144 struct netfront_info *info = device_get_softc(dev);
2146 DPRINTK("%s\n", xenbus_get_node(dev));
2154 netif_free(struct netfront_info *info)
2159 callout_drain(&info->xn_stat_ch);
2160 netif_disconnect_backend(info);
2161 if (info->xn_ifp != NULL) {
2162 ether_ifdetach(info->xn_ifp);
2163 if_free(info->xn_ifp);
2164 info->xn_ifp = NULL;
2166 ifmedia_removeall(&info->sc_media);
2170 netif_disconnect_backend(struct netfront_info *info)
2174 netfront_carrier_off(info);
2178 free_ring(&info->tx_ring_ref, &info->tx.sring);
2179 free_ring(&info->rx_ring_ref, &info->rx.sring);
2181 xen_intr_unbind(&info->xen_intr_handle);
2185 free_ring(int *ref, void *ring_ptr_ref)
2187 void **ring_ptr_ptr = ring_ptr_ref;
2189 if (*ref != GRANT_REF_INVALID) {
2190 /* This API frees the associated storage. */
2191 gnttab_end_foreign_access(*ref, *ring_ptr_ptr);
2192 *ref = GRANT_REF_INVALID;
2194 *ring_ptr_ptr = NULL;
2198 xn_ifmedia_upd(struct ifnet *ifp)
2204 xn_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
2206 ifmr->ifm_status = IFM_AVALID|IFM_ACTIVE;
2207 ifmr->ifm_active = IFM_ETHER|IFM_MANUAL;
2210 /* ** Driver registration ** */
2211 static device_method_t netfront_methods[] = {
2212 /* Device interface */
2213 DEVMETHOD(device_probe, netfront_probe),
2214 DEVMETHOD(device_attach, netfront_attach),
2215 DEVMETHOD(device_detach, netfront_detach),
2216 DEVMETHOD(device_shutdown, bus_generic_shutdown),
2217 DEVMETHOD(device_suspend, netfront_suspend),
2218 DEVMETHOD(device_resume, netfront_resume),
2220 /* Xenbus interface */
2221 DEVMETHOD(xenbus_otherend_changed, netfront_backend_changed),
2226 static driver_t netfront_driver = {
2229 sizeof(struct netfront_info),
2231 devclass_t netfront_devclass;
2233 DRIVER_MODULE(xe, xenbusb_front, netfront_driver, netfront_devclass, NULL,