netmap-release/sys/net/000755 000423 000000 00000000000 12076103424 015621 5ustar00luigiwheel000000 000000 netmap-release/sys/net/netmap_user.h000644 000423 000000 00000007165 12064657240 020334 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2011 Matteo Landi, Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * 3. Neither the name of the authors nor the names of their contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY MATTEO LANDI AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTEO LANDI OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ /* * $FreeBSD: head/sys/net/netmap_user.h 241166 2012-10-03 21:41:20Z emaste $ * $Id: netmap_user.h 11966 2012-12-20 18:46:47Z luigi $ * * This header contains the macros used to manipulate netmap structures * and packets in userspace. See netmap(4) for more information. * * The address of the struct netmap_if, say nifp, is computed from the * value returned from ioctl(.., NIOCREG, ...) and the mmap region: * ioctl(fd, NIOCREG, &req); * mem = mmap(0, ... ); * nifp = NETMAP_IF(mem, req.nr_nifp); * (so simple, we could just do it manually) * * From there: * struct netmap_ring *NETMAP_TXRING(nifp, index) * struct netmap_ring *NETMAP_RXRING(nifp, index) * we can access ring->nr_cur, ring->nr_avail, ring->nr_flags * * ring->slot[i] gives us the i-th slot (we can access * directly plen, flags, bufindex) * * char *buf = NETMAP_BUF(ring, index) returns a pointer to * the i-th buffer * * Since rings are circular, we have macros to compute the next index * i = NETMAP_RING_NEXT(ring, i); */ #ifndef _NET_NETMAP_USER_H_ #define _NET_NETMAP_USER_H_ #define _NETMAP_OFFSET(type, ptr, offset) \ ((type)(void *)((char *)(ptr) + (offset))) #define NETMAP_IF(b, o) _NETMAP_OFFSET(struct netmap_if *, b, o) #define NETMAP_TXRING(nifp, index) _NETMAP_OFFSET(struct netmap_ring *, \ nifp, (nifp)->ring_ofs[index] ) #define NETMAP_RXRING(nifp, index) _NETMAP_OFFSET(struct netmap_ring *, \ nifp, (nifp)->ring_ofs[index + (nifp)->ni_tx_rings + 1] ) #define NETMAP_BUF(ring, index) \ ((char *)(ring) + (ring)->buf_ofs + ((index)*(ring)->nr_buf_size)) #define NETMAP_BUF_IDX(ring, buf) \ ( ((char *)(buf) - ((char *)(ring) + (ring)->buf_ofs) ) / \ (ring)->nr_buf_size ) #define NETMAP_RING_NEXT(r, i) \ ((i)+1 == (r)->num_slots ? 0 : (i) + 1 ) #define NETMAP_RING_FIRST_RESERVED(r) \ ( (r)->cur < (r)->reserved ? \ (r)->cur + (r)->num_slots - (r)->reserved : \ (r)->cur - (r)->reserved ) /* * Return 1 if the given tx ring is empty. */ #define NETMAP_TX_RING_EMPTY(r) ((r)->avail >= (r)->num_slots - 1) #endif /* _NET_NETMAP_USER_H_ */ netmap-release/sys/net/netmap.h000644 000423 000000 00000032276 12076103424 017270 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2011 Matteo Landi, Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * 3. Neither the name of the authors nor the names of their contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY MATTEO LANDI AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTEO LANDI OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ /* * $FreeBSD: head/sys/net/netmap.h 234227 2012-04-13 16:03:07Z luigi $ * $Id: netmap.h 11997 2013-01-17 21:59:12Z luigi $ * * Definitions of constants and the structures used by the netmap * framework, for the part visible to both kernel and userspace. * Detailed info on netmap is available with "man netmap" or at * * http://info.iet.unipi.it/~luigi/netmap/ */ #ifndef _NET_NETMAP_H_ #define _NET_NETMAP_H_ /* * --- Netmap data structures --- * * The data structures used by netmap are shown below. Those in * capital letters are in an mmapp()ed area shared with userspace, * while others are private to the kernel. * Shared structures do not contain pointers but only memory * offsets, so that addressing is portable between kernel and userspace. softc +----------------+ | standard fields| | if_pspare[0] ----------+ +----------------+ | | +----------------+<------+ |(netmap_adapter)| | | netmap_kring | tx_rings *--------------------------------->+---------------+ | | netmap_kring | ring *---------. | rx_rings *--------->+---------------+ | nr_hwcur | | +----------------+ | ring *--------. | nr_hwavail | V | nr_hwcur | | | selinfo | | | nr_hwavail | | +---------------+ . | selinfo | | | ... | . +---------------+ | |(ntx+1 entries)| | .... | | | | |(nrx+1 entries)| | +---------------+ | | | KERNEL +---------------+ | | ==================================================================== | USERSPACE | NETMAP_RING +---->+-------------+ / | cur | NETMAP_IF (nifp, one per file desc.) / | avail | +---------------+ / | buf_ofs | | ni_tx_rings | / +=============+ | ni_rx_rings | / | buf_idx | slot[0] | | / | len, flags | | | / +-------------+ +===============+ / | buf_idx | slot[1] | txring_ofs[0] | (rel.to nifp)--' | len, flags | | txring_ofs[1] | +-------------+ (num_rings+1 entries) (nr_num_slots entries) | txring_ofs[n] | | buf_idx | slot[n-1] +---------------+ | len, flags | | rxring_ofs[0] | +-------------+ | rxring_ofs[1] | (num_rings+1 entries) | txring_ofs[n] | +---------------+ * The private descriptor ('softc' or 'adapter') of each interface * is extended with a "struct netmap_adapter" containing netmap-related * info (see description in dev/netmap/netmap_kernel.h. * Among other things, tx_rings and rx_rings point to the arrays of * "struct netmap_kring" which in turn reache the various * "struct netmap_ring", shared with userspace. * The NETMAP_RING is the userspace-visible replica of the NIC ring. * Each slot has the index of a buffer, its length and some flags. * In user space, the buffer address is computed as * (char *)ring + buf_ofs + index*NETMAP_BUF_SIZE * In the kernel, buffers do not necessarily need to be contiguous, * and the virtual and physical addresses are derived through * a lookup table. * * struct netmap_slot: * * buf_idx is the index of the buffer associated to the slot. * len is the length of the payload * NS_BUF_CHANGED must be set whenever userspace wants * to change buf_idx (it might be necessary to * reprogram the NIC slot) * NS_REPORT must be set if we want the NIC to generate an interrupt * when this slot is used. Leaving it to 0 improves * performance. * NS_FORWARD if set on a receive ring, and the device is in * transparent mode, buffers released with the flag set * will be forwarded to the 'other' side (host stack * or NIC, respectively) on the next select() or ioctl() * NS_NO_LEARN on a VALE switch, do not 'learn' the source port for * this packet. * NS_PORT_MASK the high 8 bits of the flag, if not zero, indicate the * destination port for the VALE switch, overriding * the lookup table. */ struct netmap_slot { uint32_t buf_idx; /* buffer index */ uint16_t len; /* packet length, to be copied to/from the hw ring */ uint16_t flags; /* buf changed, etc. */ #define NS_BUF_CHANGED 0x0001 /* must resync the map, buffer changed */ #define NS_REPORT 0x0002 /* ask the hardware to report results * e.g. by generating an interrupt */ #define NS_FORWARD 0x0004 /* pass packet to the other endpoint * (host stack or device) */ #define NS_NO_LEARN 0x0008 #define NS_PORT_SHIFT 8 #define NS_PORT_MASK (0xff << NS_PORT_SHIFT) }; /* * Netmap representation of a TX or RX ring (also known as "queue"). * This is a queue implemented as a fixed-size circular array. * At the software level, two fields are important: avail and cur. * * In TX rings: * avail indicates the number of slots available for transmission. * It is updated by the kernel after every netmap system call. * It MUST BE decremented by the application when it appends a * packet. * cur indicates the slot to use for the next packet * to send (i.e. the "tail" of the queue). * It MUST BE incremented by the application before * netmap system calls to reflect the number of newly * sent packets. * It is checked by the kernel on netmap system calls * (normally unmodified by the kernel unless invalid). * * The kernel side of netmap uses two additional fields in its own * private ring structure, netmap_kring: * nr_hwcur is a copy of nr_cur on an NIOCTXSYNC. * nr_hwavail is the number of slots known as available by the * hardware. It is updated on an INTR (inc by the * number of packets sent) and on a NIOCTXSYNC * (decrease by nr_cur - nr_hwcur) * A special case, nr_hwavail is -1 if the transmit * side is idle (no pending transmits). * * In RX rings: * avail is the number of packets available (possibly 0). * It MUST BE decremented by the application when it consumes * a packet, and it is updated to nr_hwavail on a NIOCRXSYNC * cur indicates the first slot that contains a packet not * processed yet (the "head" of the queue). * It MUST BE incremented by the software when it consumes * a packet. * reserved indicates the number of buffers before 'cur' * that the application has still in use. Normally 0, * it MUST BE incremented by the application when it * does not return the buffer immediately, and decremented * when the buffer is finally freed. * * The kernel side of netmap uses two additional fields in the kring: * nr_hwcur is a copy of nr_cur on an NIOCRXSYNC * nr_hwavail is the number of packets available. It is updated * on INTR (inc by the number of new packets arrived) * and on NIOCRXSYNC (decreased by nr_cur - nr_hwcur). * * DATA OWNERSHIP/LOCKING: * The netmap_ring is owned by the user program and it is only * accessed or modified in the upper half of the kernel during * a system call. * * The netmap_kring is only modified by the upper half of the kernel. * * FLAGS * NR_TIMESTAMP updates the 'ts' field on each syscall. This is * a global timestamp for all packets. * NR_RX_TSTMP if set, the last 64 byte in each buffer will * contain a timestamp for the frame supplied by * the hardware (if supported) * NR_FORWARD if set, the NS_FORWARD flag in each slot of the * RX ring is checked, and if set the packet is * passed to the other side (host stack or device, * respectively). This permits bpf-like behaviour * or transparency for selected packets. */ struct netmap_ring { /* * nr_buf_base_ofs is meant to be used through macros. * It contains the offset of the buffer region from this * descriptor. */ const ssize_t buf_ofs; const uint32_t num_slots; /* number of slots in the ring. */ uint32_t avail; /* number of usable slots */ uint32_t cur; /* 'current' r/w position */ uint32_t reserved; /* not refilled before current */ const uint16_t nr_buf_size; uint16_t flags; #define NR_TIMESTAMP 0x0002 /* set timestamp on *sync() */ #define NR_FORWARD 0x0004 /* enable NS_FORWARD for ring */ #define NR_RX_TSTMP 0x0008 /* set rx timestamp in slots */ struct timeval ts; /* time of last *sync() */ /* the slots follow. This struct has variable size */ struct netmap_slot slot[0]; /* array of slots. */ }; /* * Netmap representation of an interface and its queue(s). * There is one netmap_if for each file descriptor on which we want * to select/poll. We assume that on each interface has the same number * of receive and transmit queues. * select/poll operates on one or all pairs depending on the value of * nmr_queueid passed on the ioctl. */ struct netmap_if { char ni_name[IFNAMSIZ]; /* name of the interface. */ const u_int ni_version; /* API version, currently unused */ const u_int ni_rx_rings; /* number of rx rings */ const u_int ni_tx_rings; /* if zero, same as ni_rx_rings */ /* * The following array contains the offset of each netmap ring * from this structure. The first ni_tx_queues+1 entries refer * to the tx rings, the next ni_rx_queues+1 refer to the rx rings * (the last entry in each block refers to the host stack rings). * The area is filled up by the kernel on NIOCREG, * and then only read by userspace code. */ const ssize_t ring_ofs[0]; }; #ifndef NIOCREGIF /* * ioctl names and related fields * * NIOCGINFO takes a struct ifreq, the interface name is the input, * the outputs are number of queues and number of descriptor * for each queue (useful to set number of threads etc.). * * NIOCREGIF takes an interface name within a struct ifreq, * and activates netmap mode on the interface (if possible). * * NIOCUNREGIF unregisters the interface associated to the fd. * * NIOCTXSYNC, NIOCRXSYNC synchronize tx or rx queues, * whose identity is set in NIOCREGIF through nr_ringid */ /* * struct nmreq overlays a struct ifreq */ struct nmreq { char nr_name[IFNAMSIZ]; uint32_t nr_version; /* API version */ #define NETMAP_API 3 /* current version */ uint32_t nr_offset; /* nifp offset in the shared region */ uint32_t nr_memsize; /* size of the shared region */ uint32_t nr_tx_slots; /* slots in tx rings */ uint32_t nr_rx_slots; /* slots in rx rings */ uint16_t nr_tx_rings; /* number of tx rings */ uint16_t nr_rx_rings; /* number of rx rings */ uint16_t nr_ringid; /* ring(s) we care about */ #define NETMAP_HW_RING 0x4000 /* low bits indicate one hw ring */ #define NETMAP_SW_RING 0x2000 /* process the sw ring */ #define NETMAP_NO_TX_POLL 0x1000 /* no automatic txsync on poll */ #define NETMAP_RING_MASK 0xfff /* the ring number */ uint16_t spare1; uint32_t spare2[4]; }; /* * FreeBSD uses the size value embedded in the _IOWR to determine * how much to copy in/out. So we need it to match the actual * data structure we pass. We put some spares in the structure * to ease compatibility with other versions */ #define NIOCGINFO _IOWR('i', 145, struct nmreq) /* return IF info */ #define NIOCREGIF _IOWR('i', 146, struct nmreq) /* interface register */ #define NIOCUNREGIF _IO('i', 147) /* interface unregister */ #define NIOCTXSYNC _IO('i', 148) /* sync tx queues */ #define NIOCRXSYNC _IO('i', 149) /* sync rx queues */ #endif /* !NIOCREGIF */ #endif /* _NET_NETMAP_H_ */ netmap-release/sys/dev/000755 000423 000000 00000000000 12073110505 015604 5ustar00luigiwheel000000 000000 netmap-release/sys/dev/netmap/000755 000423 000000 00000000000 12110024375 017071 5ustar00luigiwheel000000 000000 netmap-release/sys/dev/netmap/cxgbe_netmap.h000644 000423 000000 00000030037 12076103424 021705 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2012 Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $FreeBSD$ * $Id: cxgbe_netmap.h 9520 2011-10-24 14:11:01Z svn_landi $ * * netmap modifications for cxgbe 20120120 t4_sge seems to be the main file for processing. the device has several queues iq ingress queue (messages posted ?) fl freelist queue buffers are in sd->cl interrupts are serviced by t4_intr*() which does a atomic_cmpset_int() to run only one instance of the driver (service_iq()) and then clears the flag at the end. The dispatches in there makes a list (iql) of postponed work. Handlers are cpl_handler[] per packet type. received packets are t4_eth_rx() the main transmit routine is t4_main.c :: cxgbe_transmit() which ends into t4_sge.c :: t4_eth_tx() and eventually write_txpkt_wr() refill_fl() is called under lock X_RSPD_TYPE_FLBUF is a data packet, perhaps */ #include #include // #include // #include /* vtophys ? */ #include static int cxgbe_netmap_reg(struct ifnet *, int onoff); static int cxgbe_netmap_txsync(void *, u_int, int); static int cxgbe_netmap_rxsync(void *, u_int, int); static void cxgbe_netmap_lock_wrapper(void *, int, u_int); SYSCTL_NODE(_dev, OID_AUTO, cxgbe, CTLFLAG_RW, 0, "cxgbe card"); static void cxgbe_netmap_attach(struct port_info *pi) { struct netmap_adapter na; bzero(&na, sizeof(na)); na.ifp = pi->ifp; na.separate_locks = 1; na.num_tx_desc = 0; // qsize pi->num_tx_desc; na.num_rx_desc = 0; // XXX qsize pi->num_rx_desc; na.nm_txsync = cxgbe_netmap_txsync; na.nm_rxsync = cxgbe_netmap_rxsync; na.nm_lock = cxgbe_netmap_lock_wrapper; na.nm_register = cxgbe_netmap_reg; /* * adapter->rx_mbuf_sz is set by SIOCSETMTU, but in netmap mode * we allocate the buffers on the first register. So we must * disallow a SIOCSETMTU when if_capenable & IFCAP_NETMAP is set. */ na.buff_size = NETMAP_BUF_SIZE; netmap_attach(&na, pi->ntxq); } /* * wrapper to export locks to the generic code */ static void cxgbe_netmap_lock_wrapper(void *_a, int what, u_int queueid) { #if 0 struct adapter *adapter = _a; ASSERT(queueid < adapter->num_queues); switch (what) { case NETMAP_CORE_LOCK: IXGBE_CORE_LOCK(adapter); break; case NETMAP_CORE_UNLOCK: IXGBE_CORE_UNLOCK(adapter); break; case NETMAP_TX_LOCK: IXGBE_TX_LOCK(&adapter->tx_rings[queueid]); break; case NETMAP_TX_UNLOCK: IXGBE_TX_UNLOCK(&adapter->tx_rings[queueid]); break; case NETMAP_RX_LOCK: IXGBE_RX_LOCK(&adapter->rx_rings[queueid]); break; case NETMAP_RX_UNLOCK: IXGBE_RX_UNLOCK(&adapter->rx_rings[queueid]); break; } #endif } /* * support for netmap register/unregisted. We are already under core lock. * only called on the first init or the last unregister. */ static int cxgbe_netmap_reg(struct ifnet *ifp, int onoff) { struct adapter *adapter = ifp->if_softc; struct netmap_adapter *na = NA(ifp); int error = 0; if (!na) return EINVAL; #if 0 ixgbe_disable_intr(adapter); /* Tell the stack that the interface is no longer active */ ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); if (onoff) { ifp->if_capenable |= IFCAP_NETMAP; /* save if_transmit to restore it later */ na->if_transmit = ifp->if_transmit; ifp->if_transmit = netmap_start; ixgbe_init_locked(adapter); if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) == 0) { error = ENOMEM; goto fail; } } else { fail: /* restore if_transmit */ ifp->if_transmit = na->if_transmit; ifp->if_capenable &= ~IFCAP_NETMAP; ixgbe_init_locked(adapter); /* also enables intr */ } #endif return (error); } /* * Reconcile kernel and user view of the transmit ring. * * Userspace has filled tx slots up to cur (excluded). * The last unused slot previously known to the kernel was nr_hwcur, * and the last interrupt reported nr_hwavail slots available * (using the special value -1 to indicate idle transmit ring). * The function must first update avail to what the kernel * knows, subtract the newly used slots (cur - nr_hwcur) * from both avail and nr_hwavail, and set nr_hwcur = cur * issuing a dmamap_sync on all slots. * * Check parameters in the struct netmap_ring. * We don't use avail, only check for bogus values. * Make sure cur is valid, and same goes for buffer indexes and lengths. * To avoid races, read the values once, and never use those from * the ring afterwards. */ static int cxgbe_netmap_txsync(void *a, u_int ring_nr, int do_lock) { #if 0 struct adapter *adapter = a; struct tx_ring *txr = &adapter->tx_rings[ring_nr]; struct netmap_adapter *na = NA(adapter->ifp); struct netmap_kring *kring = &na->tx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; int j, k, n = 0, lim = kring->nkr_num_slots - 1; /* generate an interrupt approximately every half ring */ int report_frequency = kring->nkr_num_slots >> 1; k = ring->cur; /* ring is not protected by any lock */ if ( (kring->nr_kflags & NR_REINIT) || k > lim) return netmap_ring_reinit(kring); if (do_lock) IXGBE_TX_LOCK(txr); bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map, BUS_DMASYNC_POSTREAD); /* update avail to what the kernel knows */ ring->avail = kring->nr_hwavail; j = kring->nr_hwcur; if (j != k) { /* we have new packets to send */ while (j != k) { struct netmap_slot *slot = &ring->slot[j]; struct ixgbe_tx_buf *txbuf = &txr->tx_buffers[j]; union ixgbe_adv_tx_desc *curr = &txr->tx_base[j]; void *addr = NMB(slot); int flags = ((slot->flags & NS_REPORT) || j == 0 || j == report_frequency) ? IXGBE_TXD_CMD_RS : 0; int len = slot->len; if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) { if (do_lock) IXGBE_TX_UNLOCK(txr); return netmap_ring_reinit(kring); } slot->flags &= ~NS_REPORT; curr->read.buffer_addr = htole64(vtophys(addr)); curr->read.olinfo_status = 0; curr->read.cmd_type_len = htole32(txr->txd_cmd | len | (IXGBE_ADVTXD_DTYP_DATA | IXGBE_ADVTXD_DCMD_IFCS | IXGBE_TXD_CMD_EOP | flags) ); if (slot->flags & NS_BUF_CHANGED) { /* buffer has changed, unload and reload map */ netmap_reload_map(txr->txtag, txbuf->map, addr, na->buff_size); slot->flags &= ~NS_BUF_CHANGED; } bus_dmamap_sync(txr->txtag, txbuf->map, BUS_DMASYNC_PREWRITE); j = (j == lim) ? 0 : j + 1; n++; } kring->nr_hwcur = k; /* the saved ring->cur */ ring->avail -= n; // XXX see others kring->nr_hwavail = ring->avail; bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE); IXGBE_WRITE_REG(&adapter->hw, IXGBE_TDT(txr->me), k); } if (n == 0 || kring->nr_hwavail < 1) { /* record completed transmissions. TODO * * The datasheet discourages the use of TDH to find out the * number of sent packets; the right way to do so, is to check * the DD bit inside the status of a packet descriptor. On the * other hand, we avoid to set the `report status' bit for * *all* outgoing packets (kind of interrupt mitigation), * consequently the DD bit is not guaranteed to be set for all * the packets: thats way, for the moment we continue to use * TDH. */ j = IXGBE_READ_REG(&adapter->hw, IXGBE_TDH(ring_nr)); if (j >= kring->nkr_num_slots) { /* XXX can happen */ D("TDH wrap %d", j); j -= kring->nkr_num_slots; } int delta = j - txr->next_to_clean; if (delta) { /* new transmissions were completed, increment ring->nr_hwavail. */ if (delta < 0) delta += kring->nkr_num_slots; txr->next_to_clean = j; kring->nr_hwavail += delta; ring->avail = kring->nr_hwavail; } } if (do_lock) IXGBE_TX_UNLOCK(txr); #endif return 0; } /* * Reconcile kernel and user view of the receive ring. * * Userspace has read rx slots up to cur (excluded). * The last unread slot previously known to the kernel was nr_hwcur, * and the last interrupt reported nr_hwavail slots available. * We must subtract the newly consumed slots (cur - nr_hwcur) * from nr_hwavail, clearing the descriptors for the next * read, tell the hardware that they are available, * and set nr_hwcur = cur and avail = nr_hwavail. * issuing a dmamap_sync on all slots. */ static int cxgbe_netmap_rxsync(void *a, u_int ring_nr, int do_lock) { #if 0 struct adapter *adapter = a; struct rx_ring *rxr = &adapter->rx_rings[ring_nr]; struct netmap_adapter *na = NA(adapter->ifp); struct netmap_kring *kring = &na->rx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; int j, k, n, lim = kring->nkr_num_slots - 1; k = ring->cur; /* ring is not protected by any lock */ if ( (kring->nr_kflags & NR_REINIT) || k > lim) return netmap_ring_reinit(kring); if (do_lock) IXGBE_RX_LOCK(rxr); /* XXX check sync modes */ bus_dmamap_sync(rxr->rxdma.dma_tag, rxr->rxdma.dma_map, BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE); j = rxr->next_to_check; for (n = 0; ; n++) { union ixgbe_adv_rx_desc *curr = &rxr->rx_base[j]; uint32_t staterr = le32toh(curr->wb.upper.status_error); if ((staterr & IXGBE_RXD_STAT_DD) == 0) break; ring->slot[j].len = le16toh(curr->wb.upper.length); ring->slot[j].flags = kring->nkr_slot_flags; bus_dmamap_sync(rxr->ptag, rxr->rx_buffers[j].pmap, BUS_DMASYNC_POSTREAD); j = (j == lim) ? 0 : j + 1; } if (n) { rxr->next_to_check = j; kring->nr_hwavail += n; if (kring->nr_hwavail >= lim - 10) { ND("rx ring %d almost full %d", ring_nr, kring->nr_hwavail); } } /* skip past packets that userspace has already processed, * making them available for reception. * advance nr_hwcur and issue a bus_dmamap_sync on the * buffers so it is safe to write to them. * Also increase nr_hwavail */ j = kring->nr_hwcur; if (j != k) { /* userspace has read some packets. */ n = 0; while (j != k) { struct netmap_slot *slot = ring->slot + j; union ixgbe_adv_rx_desc *curr = &rxr->rx_base[j]; struct ixgbe_rx_buf *rxbuf = rxr->rx_buffers + j; void *addr = NMB(slot); if (addr == netmap_buffer_base) { /* bad buf */ if (do_lock) IXGBE_RX_UNLOCK(rxr); return netmap_ring_reinit(kring); } curr->wb.upper.status_error = 0; curr->read.pkt_addr = htole64(vtophys(addr)); if (slot->flags & NS_BUF_CHANGED) { netmap_reload_map(rxr->ptag, rxbuf->pmap, addr, na->buff_size); slot->flags &= ~NS_BUF_CHANGED; } bus_dmamap_sync(rxr->ptag, rxbuf->pmap, BUS_DMASYNC_PREREAD); j = (j == lim) ? 0 : j + 1; n++; } kring->nr_hwavail -= n; kring->nr_hwcur = ring->cur; bus_dmamap_sync(rxr->rxdma.dma_tag, rxr->rxdma.dma_map, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE); /* IMPORTANT: we must leave one free slot in the ring, * so move j back by one unit */ j = (j == 0) ? lim : j - 1; IXGBE_WRITE_REG(&adapter->hw, IXGBE_RDT(rxr->me), j); } /* tell userspace that there are new packets */ ring->avail = kring->nr_hwavail ; if (do_lock) IXGBE_RX_UNLOCK(rxr); #endif return 0; } netmap-release/sys/dev/netmap/if_bge_netmap.h000644 000423 000000 00000027646 12076103424 022044 0ustar00luigiwheel000000 000000 /*- * (C) 2011 Luigi Rizzo - Universita` di Pisa * * BSD copyright * * $FreeBSD$ * $Id: if_bge_netmap.h 11996 2013-01-17 20:12:33Z luigi $ * * netmap support for if_bge.c * see ixgbe_netmap.h for details on the structure of the * various functions. */ #include #include #include #include /* vtophys ? */ #include /* * wrapper to export locks to the generic code * bge does not have separate tx/rx locks */ static void bge_netmap_lock_wrapper(void *_a, int what, u_int queueid) { struct bge_softc *adapter = _a; switch (what) { case NETMAP_CORE_LOCK: BGE_LOCK(adapter); break; case NETMAP_CORE_UNLOCK: BGE_UNLOCK(adapter); break; case NETMAP_TX_LOCK: case NETMAP_RX_LOCK: case NETMAP_TX_UNLOCK: case NETMAP_RX_UNLOCK: D("invalid lock call %d, no tx/rx locks here", what); break; } } /* * support for netmap register/unregisted. We are already under core lock. * only called on the first register or the last unregister. */ static int bge_netmap_reg(struct ifnet *ifp, int onoff) { struct bge_softc *adapter = ifp->if_softc; struct netmap_adapter *na = NA(ifp); int error = 0; if (!na) return (EINVAL); /* not attached */ /* Tell the stack that the interface is no longer active */ ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); bge_stop(adapter); if (onoff) { ifp->if_capenable |= IFCAP_NETMAP; /* save if_transmit and restore it */ na->if_transmit = ifp->if_transmit; /* XXX if_start and if_qflush ??? */ ifp->if_transmit = netmap_start; bge_init_locked(adapter); if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) == 0) { error = ENOMEM; goto fail; } } else { fail: /* restore if_transmit */ ifp->if_transmit = na->if_transmit; ifp->if_capenable &= ~IFCAP_NETMAP; bge_init_locked(adapter); /* also enables intr */ } return (error); } /* * Reconcile kernel and user view of the transmit ring. */ static int bge_netmap_txsync(void *a, u_int ring_nr, int do_lock) { struct bge_softc *sc = a; struct netmap_adapter *na = NA(sc->bge_ifp); struct netmap_kring *kring = &na->tx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; int delta, j, k, l, lim = kring->nkr_num_slots - 1; k = ring->cur; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) BGE_LOCK(sc); /* bge_tx_cons_idx is the equivalent of TDH on intel cards, * i.e. the index of the tx frame most recently completed. */ l = sc->bge_ldata.bge_status_block->bge_idx[0].bge_tx_cons_idx; /* Sync the TX descriptor list */ bus_dmamap_sync(sc->bge_cdata.bge_tx_ring_tag, sc->bge_cdata.bge_tx_ring_map, BUS_DMASYNC_POSTWRITE); /* record completed transmissions */ delta = l - sc->bge_tx_saved_considx; if (delta < 0) /* wrap around */ delta += BGE_TX_RING_CNT; if (delta > 0) { /* some tx completed */ sc->bge_tx_saved_considx = l; sc->bge_txcnt -= delta; kring->nr_hwavail += delta; } /* update avail to what the kernel knows */ ring->avail = kring->nr_hwavail; j = kring->nr_hwcur; if (j != k) { /* we have new packets to send */ bus_dmamap_t *txmap = sc->bge_cdata.bge_tx_dmamap; int n = 0; l = sc->bge_tx_prodidx; while (j != k) { struct netmap_slot *slot = &ring->slot[j]; struct bge_tx_bd *d = &sc->bge_ldata.bge_tx_ring[l]; void *addr = NMB(slot); int len = slot->len; if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) { if (do_lock) BGE_UNLOCK(sc); return netmap_ring_reinit(kring); } if (slot->flags & NS_BUF_CHANGED) { uint64_t paddr = vtophys(addr); d->bge_addr.bge_addr_lo = BGE_ADDR_LO(paddr); d->bge_addr.bge_addr_hi = BGE_ADDR_HI(paddr); /* buffer has changed, unload and reload map */ netmap_reload_map(sc->bge_cdata.bge_tx_mtag, txmap[l], addr, na->buff_size); slot->flags &= ~NS_BUF_CHANGED; } slot->flags &= ~NS_REPORT; d->bge_len = len; d->bge_flags = BGE_TXBDFLAG_END; bus_dmamap_sync(sc->bge_cdata.bge_tx_mtag, txmap[l], BUS_DMASYNC_PREWRITE); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; n++; } kring->nr_hwcur = k; /* the saved ring->cur */ sc->bge_tx_prodidx = l; ring->avail -= n; kring->nr_hwavail = ring->avail; // XXX see others /* now repeat the last part of bge_start_locked() */ bus_dmamap_sync(sc->bge_cdata.bge_tx_ring_tag, sc->bge_cdata.bge_tx_ring_map, BUS_DMASYNC_PREWRITE); /* Transmit. */ bge_writembx(sc, BGE_MBX_TX_HOST_PROD0_LO, l); /* 5700 b2 errata */ if (sc->bge_chiprev == BGE_CHIPREV_5700_BX) bge_writembx(sc, BGE_MBX_TX_HOST_PROD0_LO, l); sc->bge_timer = 5; } if (do_lock) BGE_UNLOCK(sc); return 0; } /* * Reconcile kernel and user view of the receive ring. * In bge, the rx ring is initialized by setting the ring size * bge_writembx(sc, BGE_MBX_RX_STD_PROD_LO, BGE_STD_RX_RING_CNT - 1); * and the receiver always starts from 0. * sc->bge_rx_saved_considx starts from 0 and is the place from * which the driver reads incoming packets. * sc->bge_ldata.bge_status_block->bge_idx[0].bge_rx_prod_idx is the * next (free) receive buffer where the hardware will put incoming packets. * * sc->bge_rx_saved_considx is maintained in software and represents XXX * * After a successful rxeof we do * sc->bge_rx_saved_considx = rx_cons; * ^---- effectively becomes rx_prod_idx * * bge_writembx(sc, BGE_MBX_RX_CONS0_LO, sc->bge_rx_saved_considx); * ^--- we have freed some descriptors * * bge_writembx(sc, BGE_MBX_RX_STD_PROD_LO, (sc->bge_std + * BGE_STD_RX_RING_CNT - 1) % BGE_STD_RX_RING_CNT); * ^---- we have freed some buffers */ static int bge_netmap_rxsync(void *a, u_int ring_nr, int do_lock) { struct bge_softc *sc = a; struct netmap_adapter *na = NA(sc->bge_ifp); struct netmap_kring *kring = &na->rx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; int j, k, n, lim = kring->nkr_num_slots - 1; uint32_t end; k = ring->cur; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) BGE_LOCK(sc); /* XXX check sync modes */ bus_dmamap_sync(sc->bge_cdata.bge_rx_return_ring_tag, sc->bge_cdata.bge_rx_return_ring_map, BUS_DMASYNC_POSTREAD); bus_dmamap_sync(sc->bge_cdata.bge_rx_std_ring_tag, sc->bge_cdata.bge_rx_std_ring_map, BUS_DMASYNC_POSTWRITE); l = sc->bge_rx_saved_considx; j = kring->nkr_hwcur + kring->nkr_hwavail; l = j + kring->nkr_hwofs; if (j > lim) j -= lim + 1; /* bge_rx_prod_idx is the same as RDH on intel cards -- the next * (empty) buffer to be used for receptions. * To decide when to stop we rely on bge_rx_prod_idx * and not on the flags in the frame descriptors. */ end = sc->bge_ldata.bge_status_block->bge_idx[0].bge_rx_prod_idx; if (l != end) { for (n = 0; l != end; n++) { struct bge_rx_bd *cur_rx; uint32_t len; cur_rx = &sc->bge_ldata.bge_rx_return_ring[l]; len = cur_rx->bge_len - ETHER_CRC_LEN; kring->ring->slot[j].len = len; kring->ring->slot[j].flags = kring->nkr_slot_flags; /* sync was in bge_newbuf() */ bus_dmamap_sync(sc->bge_cdata.bge_rx_mtag, sc->bge_cdata.bge_rx_std_dmamap[l], BUS_DMASYNC_POSTREAD); j = j == lim ? 0 : j + 1; l = l == lim ? 0 : l + 1; } sc->bge_rx_saved_considx = end; bge_writembx(sc, BGE_MBX_RX_CONS0_LO, end); sc->bge_ifp->if_ipackets += n; kring->nr_hwavail += n; } /* skip past packets that userspace has already processed, * making them available for reception. * advance nr_hwcur and issue a bus_dmamap_sync on the * buffers so it is safe to write to them. * Also increase nr_hwavail */ j = kring->nr_hwcur; if (j != k) { /* userspace has read some packets. */ n = 0; l = kring->nr_hwcur - kring->nkr_hwofs; if (l < 0) l += lim + 1; while (j != k) { struct netmap_slot *slot = ring->slot + j; struct bge_rx_bd *r = sc->bge_ldata.bge_rx_std_ring + l; void *addr = NMB(slot); uint64_t paddr = vtophys(addr); if (addr == netmap_buffer_base) { /* bad buf */ if (do_lock) BGE_UNLOCK(sc); return netmap_ring_reinit(kring); } slot->flags &= ~NS_REPORT; r->bge_addr.bge_addr_lo = BGE_ADDR_LO(paddr); r->bge_addr.bge_addr_hi = BGE_ADDR_HI(paddr); if (slot->flags & NS_BUF_CHANGED) { netmap_reload_map(sc->bge_cdata.bge_rx_mtag, sc->bge_cdata.bge_rx_std_dmamap[l], addr, na->buff_size); slot->flags &= ~NS_BUF_CHANGED; } r->bge_flags = BGE_RXBDFLAG_END; r->bge_len = na->buff_size; r->bge_idx = l; bus_dmamap_sync(sc->bge_cdata.bge_rx_mtag, sc->bge_cdata.bge_rx_std_dmamap[l], BUS_DMASYNC_PREREAD); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; n++; } kring->nr_hwcur = k; /* the saved ring->cur */ kring->nr_hwavail -= n; /* Flush the RX DMA ring */ bus_dmamap_sync(sc->bge_cdata.bge_rx_return_ring_tag, sc->bge_cdata.bge_rx_return_ring_map, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE); } /* tell userspace that there are new packets */ ring->avail = kring->nr_hwavail ; if (do_lock) BGE_UNLOCK(sc); return 0; } static void bge_netmap_tx_init(struct bge_softc *sc) { struct bge_tx_bd *d = sc->bge_ldata.bge_tx_ring; int i; struct netmap_adapter *na = NA(sc->bge_ifp); struct netmap_slot *slot = netmap_reset(na, NR_TX, 0, 0); /* slot is NULL if we are not in netmap mode */ if (!slot) return; /* in netmap mode, overwrite addresses and maps */ for (i = 0; i < BGE_TX_RING_CNT; i++) { /* * the first time, ``slot`` points the first slot of * the ring; the reset might have introduced some kind * of offset between the kernel and userspace view of * the ring; for these reasons, we use l to point * to the slot linked to the i-th descriptor. */ void *addr; uint64_t paddr; struct netmap_kring *kring = &na->tx_rings[0]; int l = i + kring->nkr_hwofs; if (l >= sc->rl_ldata.rl_tx_desc_cnt) l -= sc->rl_ldata.rl_tx_desc_cnt; addr = NMB(slot + l); paddr = vtophys(addr); d[i].bge_addr.bge_addr_lo = BGE_ADDR_LO(paddr); d[i].bge_addr.bge_addr_hi = BGE_ADDR_HI(paddr); netmap_load_map(sc->bge_cdata.bge_tx_mtag, sc->bge_cdata.bge_tx_dmamap[i], addr, na->buff_size); } } static void bge_netmap_rx_init(struct bge_softc *sc) { /* slot is NULL if we are not in netmap mode */ struct netmap_adapter *na = NA(sc->bge_ifp); struct netmap_slot *slot = netmap_reset(na, NR_RX, 0, 0); struct bge_rx_bd *r = sc->bge_ldata.bge_rx_std_ring; int i; if (!slot) return; for (i = 0; i < BGE_STD_RX_RING_CNT; i++) { /* * the first time, ``slot`` points the first slot of * the ring; the reset might have introduced some kind * of offset between the kernel and userspace view of * the ring; for these reasons, we use l to point * to the slot linked to the i-th descriptor. */ void *addr; uint64_t paddr; struct netmap_kring *kring = &na->rx_rings[0]; int l = i + kring->nkr_hwofs; if (l >= sc->rl_ldata.rl_rx_desc_cnt) l -= sc->rl_ldata.rl_rx_desc_cnt; addr = NMB(slot + l); paddr = vtophys(addr); r[i].bge_addr.bge_addr_lo = BGE_ADDR_LO(paddr); r[i].bge_addr.bge_addr_hi = BGE_ADDR_HI(paddr); r[i].bge_flags = BGE_RXBDFLAG_END; r[i].bge_len = na->buff_size; r[i].bge_idx = i; /* * userspace knows that hwavail packets were ready before the * reset, so we need to tell the NIC that last hwavail * descriptors of the ring are still owned by the driver. */ D("incomplete driver: don't know how to reserve hwavail slots"); netmap_reload_map(sc->bge_cdata.bge_rx_mtag, sc->bge_cdata.bge_rx_std_dmamap[i], addr, na->buff_size); } } static void bge_netmap_attach(struct bge_softc *sc) { struct netmap_adapter na; bzero(&na, sizeof(na)); na.ifp = sc->bge_ifp; na.separate_locks = 0; na.num_tx_desc = BGE_TX_RING_CNT; na.num_rx_desc = BGE_STD_RX_RING_CNT; na.nm_txsync = bge_netmap_txsync; na.nm_rxsync = bge_netmap_rxsync; na.nm_lock = bge_netmap_lock_wrapper; na.nm_register = bge_netmap_reg; netmap_attach(&na, 1); } /* end of file */ netmap-release/sys/dev/netmap/if_lem_netmap.h000644 000423 000000 00000024037 12076103424 022053 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2011 Matteo Landi, Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $FreeBSD: head/sys/dev/netmap/if_lem_netmap.h 231881 2012-02-17 14:09:04Z luigi $ * $Id: if_lem_netmap.h 11998 2013-01-17 22:04:36Z luigi $ * * netmap support for "lem" * * For details on netmap support please see ixgbe_netmap.h */ #include #include #include #include /* vtophys ? */ #include static void lem_netmap_lock_wrapper(struct ifnet *ifp, int what, u_int ringid) { struct adapter *adapter = ifp->if_softc; /* only one ring here so ignore the ringid */ switch (what) { case NETMAP_CORE_LOCK: EM_CORE_LOCK(adapter); break; case NETMAP_CORE_UNLOCK: EM_CORE_UNLOCK(adapter); break; case NETMAP_TX_LOCK: EM_TX_LOCK(adapter); break; case NETMAP_TX_UNLOCK: EM_TX_UNLOCK(adapter); break; case NETMAP_RX_LOCK: EM_RX_LOCK(adapter); break; case NETMAP_RX_UNLOCK: EM_RX_UNLOCK(adapter); break; } } /* * Register/unregister */ static int lem_netmap_reg(struct ifnet *ifp, int onoff) { struct adapter *adapter = ifp->if_softc; struct netmap_adapter *na = NA(ifp); int error = 0; if (na == NULL) return EINVAL; lem_disable_intr(adapter); /* Tell the stack that the interface is no longer active */ ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); #ifndef EM_LEGACY_IRQ // XXX do we need this ? taskqueue_block(adapter->tq); taskqueue_drain(adapter->tq, &adapter->rxtx_task); taskqueue_drain(adapter->tq, &adapter->link_task); #endif /* !EM_LEGCY_IRQ */ if (onoff) { ifp->if_capenable |= IFCAP_NETMAP; na->if_transmit = ifp->if_transmit; ifp->if_transmit = netmap_start; lem_init_locked(adapter); if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) == 0) { error = ENOMEM; goto fail; } } else { fail: /* return to non-netmap mode */ ifp->if_transmit = na->if_transmit; ifp->if_capenable &= ~IFCAP_NETMAP; lem_init_locked(adapter); /* also enable intr */ } #ifndef EM_LEGACY_IRQ taskqueue_unblock(adapter->tq); // XXX do we need this ? #endif /* !EM_LEGCY_IRQ */ return (error); } /* * Reconcile kernel and user view of the transmit ring. */ static int lem_netmap_txsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct adapter *adapter = ifp->if_softc; struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->tx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, k, l, n = 0, lim = kring->nkr_num_slots - 1; /* generate an interrupt approximately every half ring */ int report_frequency = kring->nkr_num_slots >> 1; /* take a copy of ring->cur now, and never read it again */ k = ring->cur; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) EM_TX_LOCK(adapter); bus_dmamap_sync(adapter->txdma.dma_tag, adapter->txdma.dma_map, BUS_DMASYNC_POSTREAD); /* * Process new packets to send. j is the current index in the * netmap ring, l is the corresponding index in the NIC ring. */ j = kring->nr_hwcur; if (j != k) { /* we have new packets to send */ l = netmap_idx_k2n(kring, j); for (n = 0; j != k; n++) { /* slot is the current slot in the netmap ring */ struct netmap_slot *slot = &ring->slot[j]; /* curr is the current slot in the nic ring */ struct e1000_tx_desc *curr = &adapter->tx_desc_base[l]; struct em_buffer *txbuf = &adapter->tx_buffer_area[l]; int flags = ((slot->flags & NS_REPORT) || j == 0 || j == report_frequency) ? E1000_TXD_CMD_RS : 0; uint64_t paddr; void *addr = PNMB(slot, &paddr); u_int len = slot->len; if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) { if (do_lock) EM_TX_UNLOCK(adapter); return netmap_ring_reinit(kring); } slot->flags &= ~NS_REPORT; if (slot->flags & NS_BUF_CHANGED) { /* buffer has changed, reload map */ netmap_reload_map(adapter->txtag, txbuf->map, addr); curr->buffer_addr = htole64(paddr); slot->flags &= ~NS_BUF_CHANGED; } curr->upper.data = 0; curr->lower.data = htole32( adapter->txd_cmd | len | (E1000_TXD_CMD_EOP | flags) ); bus_dmamap_sync(adapter->txtag, txbuf->map, BUS_DMASYNC_PREWRITE); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwcur = k; /* the saved ring->cur */ kring->nr_hwavail -= n; bus_dmamap_sync(adapter->txdma.dma_tag, adapter->txdma.dma_map, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE); E1000_WRITE_REG(&adapter->hw, E1000_TDT(0), l); } if (n == 0 || kring->nr_hwavail < 1) { int delta; /* record completed transmissions using TDH */ l = E1000_READ_REG(&adapter->hw, E1000_TDH(0)); if (l >= kring->nkr_num_slots) { /* XXX can it happen ? */ D("bad TDH %d", l); l -= kring->nkr_num_slots; } delta = l - adapter->next_tx_to_clean; if (delta) { /* some tx completed, increment hwavail. */ if (delta < 0) delta += kring->nkr_num_slots; adapter->next_tx_to_clean = l; kring->nr_hwavail += delta; } } /* update avail to what the kernel knows */ ring->avail = kring->nr_hwavail; if (do_lock) EM_TX_UNLOCK(adapter); return 0; } /* * Reconcile kernel and user view of the receive ring. */ static int lem_netmap_rxsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct adapter *adapter = ifp->if_softc; struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->rx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; int j, l, n, lim = kring->nkr_num_slots - 1; int force_update = do_lock || kring->nr_kflags & NKR_PENDINTR; u_int k = ring->cur, resvd = ring->reserved; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) EM_RX_LOCK(adapter); /* XXX check sync modes */ bus_dmamap_sync(adapter->rxdma.dma_tag, adapter->rxdma.dma_map, BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE); /* * Import newly received packets into the netmap ring. * j is an index in the netmap ring, l in the NIC ring. */ l = adapter->next_rx_desc_to_check; j = netmap_idx_n2k(kring, l); if (netmap_no_pendintr || force_update) { uint16_t slot_flags = kring->nkr_slot_flags; for (n = 0; ; n++) { struct e1000_rx_desc *curr = &adapter->rx_desc_base[l]; uint32_t staterr = le32toh(curr->status); int len; if ((staterr & E1000_RXD_STAT_DD) == 0) break; len = le16toh(curr->length) - 4; // CRC if (len < 0) { D("bogus pkt size at %d", j); len = 0; } ring->slot[j].len = len; ring->slot[j].flags = slot_flags; bus_dmamap_sync(adapter->rxtag, adapter->rx_buffer_area[l].map, BUS_DMASYNC_POSTREAD); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } if (n) { /* update the state variables */ adapter->next_rx_desc_to_check = l; kring->nr_hwavail += n; } kring->nr_kflags &= ~NKR_PENDINTR; } /* skip past packets that userspace has released */ j = kring->nr_hwcur; /* netmap ring index */ if (resvd > 0) { if (resvd + ring->avail >= lim + 1) { D("XXX invalid reserve/avail %d %d", resvd, ring->avail); ring->reserved = resvd = 0; // XXX panic... } k = (k >= resvd) ? k - resvd : k + lim + 1 - resvd; } if (j != k) { /* userspace has released some packets. */ l = netmap_idx_k2n(kring, j); /* NIC ring index */ for (n = 0; j != k; n++) { struct netmap_slot *slot = &ring->slot[j]; struct e1000_rx_desc *curr = &adapter->rx_desc_base[l]; struct em_buffer *rxbuf = &adapter->rx_buffer_area[l]; uint64_t paddr; void *addr = PNMB(slot, &paddr); if (addr == netmap_buffer_base) { /* bad buf */ if (do_lock) EM_RX_UNLOCK(adapter); return netmap_ring_reinit(kring); } if (slot->flags & NS_BUF_CHANGED) { /* buffer has changed, reload map */ netmap_reload_map(adapter->rxtag, rxbuf->map, addr); curr->buffer_addr = htole64(paddr); slot->flags &= ~NS_BUF_CHANGED; } curr->status = 0; bus_dmamap_sync(adapter->rxtag, rxbuf->map, BUS_DMASYNC_PREREAD); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwavail -= n; kring->nr_hwcur = k; bus_dmamap_sync(adapter->rxdma.dma_tag, adapter->rxdma.dma_map, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE); /* * IMPORTANT: we must leave one free slot in the ring, * so move l back by one unit */ l = (l == 0) ? lim : l - 1; E1000_WRITE_REG(&adapter->hw, E1000_RDT(0), l); } /* tell userspace that there are new packets */ ring->avail = kring->nr_hwavail - resvd; if (do_lock) EM_RX_UNLOCK(adapter); return 0; } static void lem_netmap_attach(struct adapter *adapter) { struct netmap_adapter na; bzero(&na, sizeof(na)); na.ifp = adapter->ifp; na.separate_locks = 1; na.num_tx_desc = adapter->num_tx_desc; na.num_rx_desc = adapter->num_rx_desc; na.nm_txsync = lem_netmap_txsync; na.nm_rxsync = lem_netmap_rxsync; na.nm_lock = lem_netmap_lock_wrapper; na.nm_register = lem_netmap_reg; netmap_attach(&na, 1); } /* end of file */ netmap-release/sys/dev/netmap/netmap.c000644 000423 000000 00000211730 12077774155 020551 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2011-2012 Matteo Landi, Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #define NM_BRIDGE /* * This module supports memory mapped access to network devices, * see netmap(4). * * The module uses a large, memory pool allocated by the kernel * and accessible as mmapped memory by multiple userspace threads/processes. * The memory pool contains packet buffers and "netmap rings", * i.e. user-accessible copies of the interface's queues. * * Access to the network card works like this: * 1. a process/thread issues one or more open() on /dev/netmap, to create * select()able file descriptor on which events are reported. * 2. on each descriptor, the process issues an ioctl() to identify * the interface that should report events to the file descriptor. * 3. on each descriptor, the process issues an mmap() request to * map the shared memory region within the process' address space. * The list of interesting queues is indicated by a location in * the shared memory region. * 4. using the functions in the netmap(4) userspace API, a process * can look up the occupation state of a queue, access memory buffers, * and retrieve received packets or enqueue packets to transmit. * 5. using some ioctl()s the process can synchronize the userspace view * of the queue with the actual status in the kernel. This includes both * receiving the notification of new packets, and transmitting new * packets on the output interface. * 6. select() or poll() can be used to wait for events on individual * transmit or receive queues (or all queues for a given interface). */ #ifdef linux #include "bsd_glue.h" static netdev_tx_t linux_netmap_start(struct sk_buff *skb, struct net_device *dev); #endif /* linux */ #ifdef __APPLE__ #include "osx_glue.h" #endif /* __APPLE__ */ #ifdef __FreeBSD__ #include /* prerequisite */ __FBSDID("$FreeBSD: head/sys/dev/netmap/netmap.c 241723 2012-10-19 09:41:45Z glebius $"); #include #include #include #include /* defines used in kernel.h */ #include #include /* types used in module initialization */ #include /* cdevsw struct */ #include /* uio struct */ #include #include /* struct socket */ #include #include /* PROT_EXEC */ #include #include #include /* vtophys */ #include /* vtophys */ #include /* sockaddrs */ #include #include #include #include #include /* BIOCIMMEDIATE */ #include #include /* bus_dmamap_* */ MALLOC_DEFINE(M_NETMAP, "netmap", "Network memory map"); #endif /* __FreeBSD__ */ #include #include u_int netmap_total_buffers; u_int netmap_buf_size; char *netmap_buffer_base; /* address of an invalid buffer */ /* user-controlled variables */ int netmap_verbose; static int netmap_no_timestamp; /* don't timestamp on rxsync */ SYSCTL_NODE(_dev, OID_AUTO, netmap, CTLFLAG_RW, 0, "Netmap args"); SYSCTL_INT(_dev_netmap, OID_AUTO, verbose, CTLFLAG_RW, &netmap_verbose, 0, "Verbose mode"); SYSCTL_INT(_dev_netmap, OID_AUTO, no_timestamp, CTLFLAG_RW, &netmap_no_timestamp, 0, "no_timestamp"); int netmap_mitigate = 1; SYSCTL_INT(_dev_netmap, OID_AUTO, mitigate, CTLFLAG_RW, &netmap_mitigate, 0, ""); int netmap_no_pendintr = 1; SYSCTL_INT(_dev_netmap, OID_AUTO, no_pendintr, CTLFLAG_RW, &netmap_no_pendintr, 0, "Always look for new received packets."); int netmap_drop = 0; /* debugging */ int netmap_flags = 0; /* debug flags */ int netmap_fwd = 0; /* force transparent mode */ int netmap_copy = 0; /* debugging, copy content */ SYSCTL_INT(_dev_netmap, OID_AUTO, drop, CTLFLAG_RW, &netmap_drop, 0 , ""); SYSCTL_INT(_dev_netmap, OID_AUTO, flags, CTLFLAG_RW, &netmap_flags, 0 , ""); SYSCTL_INT(_dev_netmap, OID_AUTO, fwd, CTLFLAG_RW, &netmap_fwd, 0 , ""); SYSCTL_INT(_dev_netmap, OID_AUTO, copy, CTLFLAG_RW, &netmap_copy, 0 , ""); #ifdef NM_BRIDGE /* support for netmap bridge */ /* * system parameters. * * All switched ports have prefix NM_NAME. * The switch has a max of NM_BDG_MAXPORTS ports (often stored in a bitmap, * so a practical upper bound is 64). * Each tx ring is read-write, whereas rx rings are readonly (XXX not done yet). * The virtual interfaces use per-queue lock instead of core lock. * In the tx loop, we aggregate traffic in batches to make all operations * faster. The batch size is NM_BDG_BATCH */ #define NM_NAME "vale" /* prefix for the interface */ #define NM_BDG_MAXPORTS 16 /* up to 64 ? */ #define NM_BRIDGE_RINGSIZE 1024 /* in the device */ #define NM_BDG_HASH 1024 /* forwarding table entries */ #define NM_BDG_BATCH 1024 /* entries in the forwarding buffer */ #define NM_BRIDGES 4 /* number of bridges */ int netmap_bridge = NM_BDG_BATCH; /* bridge batch size */ SYSCTL_INT(_dev_netmap, OID_AUTO, bridge, CTLFLAG_RW, &netmap_bridge, 0 , ""); #ifdef linux #define ADD_BDG_REF(ifp) (NA(ifp)->if_refcount++) #define DROP_BDG_REF(ifp) (NA(ifp)->if_refcount-- <= 1) #else /* !linux */ #define ADD_BDG_REF(ifp) (ifp)->if_refcount++ #define DROP_BDG_REF(ifp) refcount_release(&(ifp)->if_refcount) #ifdef __FreeBSD__ #include #include #endif /* __FreeBSD__ */ #define prefetch(x) __builtin_prefetch(x) #endif /* !linux */ static void bdg_netmap_attach(struct ifnet *ifp); static int bdg_netmap_reg(struct ifnet *ifp, int onoff); /* per-tx-queue entry */ struct nm_bdg_fwd { /* forwarding entry for a bridge */ void *buf; uint64_t dst; /* dst mask */ uint32_t src; /* src index ? */ uint16_t len; /* src len */ }; struct nm_hash_ent { uint64_t mac; /* the top 2 bytes are the epoch */ uint64_t ports; }; /* * Interfaces for a bridge are all in ports[]. * The array has fixed size, an empty entry does not terminate * the search. */ struct nm_bridge { struct ifnet *bdg_ports[NM_BDG_MAXPORTS]; int n_ports; uint64_t act_ports; int freelist; /* first buffer index */ NM_SELINFO_T si; /* poll/select wait queue */ NM_LOCK_T bdg_lock; /* protect the selinfo ? */ /* the forwarding table, MAC+ports */ struct nm_hash_ent ht[NM_BDG_HASH]; int namelen; /* 0 means free */ char basename[IFNAMSIZ]; }; struct nm_bridge nm_bridges[NM_BRIDGES]; #define BDG_LOCK(b) mtx_lock(&(b)->bdg_lock) #define BDG_UNLOCK(b) mtx_unlock(&(b)->bdg_lock) /* * NA(ifp)->bdg_port port index */ // XXX only for multiples of 64 bytes, non overlapped. static inline void pkt_copy(void *_src, void *_dst, int l) { uint64_t *src = _src; uint64_t *dst = _dst; if (unlikely(l >= 1024)) { bcopy(src, dst, l); return; } for (; likely(l > 0); l-=64) { *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; } } /* * locate a bridge among the existing ones. * a ':' in the name terminates the bridge name. Otherwise, just NM_NAME. * We assume that this is called with a name of at least NM_NAME chars. */ static struct nm_bridge * nm_find_bridge(const char *name) { int i, l, namelen, e; struct nm_bridge *b = NULL; namelen = strlen(NM_NAME); /* base length */ l = strlen(name); /* actual length */ for (i = namelen + 1; i < l; i++) { if (name[i] == ':') { namelen = i; break; } } if (namelen >= IFNAMSIZ) namelen = IFNAMSIZ; ND("--- prefix is '%.*s' ---", namelen, name); /* use the first entry for locking */ BDG_LOCK(nm_bridges); // XXX do better for (e = -1, i = 1; i < NM_BRIDGES; i++) { b = nm_bridges + i; if (b->namelen == 0) e = i; /* record empty slot */ else if (strncmp(name, b->basename, namelen) == 0) { ND("found '%.*s' at %d", namelen, name, i); break; } } if (i == NM_BRIDGES) { /* all full */ if (e == -1) { /* no empty slot */ b = NULL; } else { b = nm_bridges + e; strncpy(b->basename, name, namelen); b->namelen = namelen; } } BDG_UNLOCK(nm_bridges); return b; } #endif /* NM_BRIDGE */ /* * Fetch configuration from the device, to cope with dynamic * reconfigurations after loading the module. */ static int netmap_update_config(struct netmap_adapter *na) { struct ifnet *ifp = na->ifp; u_int txr, txd, rxr, rxd; txr = txd = rxr = rxd = 0; if (na->nm_config) { na->nm_config(ifp, &txr, &txd, &rxr, &rxd); } else { /* take whatever we had at init time */ txr = na->num_tx_rings; txd = na->num_tx_desc; rxr = na->num_rx_rings; rxd = na->num_rx_desc; } if (na->num_tx_rings == txr && na->num_tx_desc == txd && na->num_rx_rings == rxr && na->num_rx_desc == rxd) return 0; /* nothing changed */ if (netmap_verbose || na->refcount > 0) { D("stored config %s: txring %d x %d, rxring %d x %d", ifp->if_xname, na->num_tx_rings, na->num_tx_desc, na->num_rx_rings, na->num_rx_desc); D("new config %s: txring %d x %d, rxring %d x %d", ifp->if_xname, txr, txd, rxr, rxd); } if (na->refcount == 0) { D("configuration changed (but fine)"); na->num_tx_rings = txr; na->num_tx_desc = txd; na->num_rx_rings = rxr; na->num_rx_desc = rxd; return 0; } D("configuration changed while active, this is bad..."); return 1; } /*------------- memory allocator -----------------*/ #ifdef NETMAP_MEM2 #include "netmap_mem2.c" #else /* !NETMAP_MEM2 */ #include "netmap_mem1.c" #endif /* !NETMAP_MEM2 */ /*------------ end of memory allocator ----------*/ /* Structure associated to each thread which registered an interface. * * The first 4 fields of this structure are written by NIOCREGIF and * read by poll() and NIOC?XSYNC. * There is low contention among writers (actually, a correct user program * should have no contention among writers) and among writers and readers, * so we use a single global lock to protect the structure initialization. * Since initialization involves the allocation of memory, we reuse the memory * allocator lock. * Read access to the structure is lock free. Readers must check that * np_nifp is not NULL before using the other fields. * If np_nifp is NULL initialization has not been performed, so they should * return an error to userlevel. * * The ref_done field is used to regulate access to the refcount in the * memory allocator. The refcount must be incremented at most once for * each open("/dev/netmap"). The increment is performed by the first * function that calls netmap_get_memory() (currently called by * mmap(), NIOCGINFO and NIOCREGIF). * If the refcount is incremented, it is then decremented when the * private structure is destroyed. */ struct netmap_priv_d { struct netmap_if * volatile np_nifp; /* netmap interface descriptor. */ struct ifnet *np_ifp; /* device for which we hold a reference */ int np_ringid; /* from the ioctl */ u_int np_qfirst, np_qlast; /* range of rings to scan */ uint16_t np_txpoll; unsigned long ref_done; /* use with NMA_LOCK held */ }; static int netmap_get_memory(struct netmap_priv_d* p) { int error = 0; NMA_LOCK(); if (!p->ref_done) { error = netmap_memory_finalize(); if (!error) p->ref_done = 1; } NMA_UNLOCK(); return error; } /* * File descriptor's private data destructor. * * Call nm_register(ifp,0) to stop netmap mode on the interface and * revert to normal operation. We expect that np_ifp has not gone. */ /* call with NMA_LOCK held */ static void netmap_dtor_locked(void *data) { struct netmap_priv_d *priv = data; struct ifnet *ifp = priv->np_ifp; struct netmap_adapter *na = NA(ifp); struct netmap_if *nifp = priv->np_nifp; na->refcount--; if (na->refcount <= 0) { /* last instance */ u_int i, j, lim; if (netmap_verbose) D("deleting last instance for %s", ifp->if_xname); /* * there is a race here with *_netmap_task() and * netmap_poll(), which don't run under NETMAP_REG_LOCK. * na->refcount == 0 && na->ifp->if_capenable & IFCAP_NETMAP * (aka NETMAP_DELETING(na)) are a unique marker that the * device is dying. * Before destroying stuff we sleep a bit, and then complete * the job. NIOCREG should realize the condition and * loop until they can continue; the other routines * should check the condition at entry and quit if * they cannot run. */ na->nm_lock(ifp, NETMAP_REG_UNLOCK, 0); tsleep(na, 0, "NIOCUNREG", 4); na->nm_lock(ifp, NETMAP_REG_LOCK, 0); na->nm_register(ifp, 0); /* off, clear IFCAP_NETMAP */ /* Wake up any sleeping threads. netmap_poll will * then return POLLERR */ for (i = 0; i < na->num_tx_rings + 1; i++) selwakeuppri(&na->tx_rings[i].si, PI_NET); for (i = 0; i < na->num_rx_rings + 1; i++) selwakeuppri(&na->rx_rings[i].si, PI_NET); selwakeuppri(&na->tx_si, PI_NET); selwakeuppri(&na->rx_si, PI_NET); /* release all buffers */ for (i = 0; i < na->num_tx_rings + 1; i++) { struct netmap_ring *ring = na->tx_rings[i].ring; lim = na->tx_rings[i].nkr_num_slots; for (j = 0; j < lim; j++) netmap_free_buf(nifp, ring->slot[j].buf_idx); /* knlist_destroy(&na->tx_rings[i].si.si_note); */ mtx_destroy(&na->tx_rings[i].q_lock); } for (i = 0; i < na->num_rx_rings + 1; i++) { struct netmap_ring *ring = na->rx_rings[i].ring; lim = na->rx_rings[i].nkr_num_slots; for (j = 0; j < lim; j++) netmap_free_buf(nifp, ring->slot[j].buf_idx); /* knlist_destroy(&na->rx_rings[i].si.si_note); */ mtx_destroy(&na->rx_rings[i].q_lock); } /* XXX kqueue(9) needed; these will mirror knlist_init. */ /* knlist_destroy(&na->tx_si.si_note); */ /* knlist_destroy(&na->rx_si.si_note); */ netmap_free_rings(na); wakeup(na); } netmap_if_free(nifp); } static void nm_if_rele(struct ifnet *ifp) { #ifndef NM_BRIDGE if_rele(ifp); #else /* NM_BRIDGE */ int i, full; struct nm_bridge *b; if (strncmp(ifp->if_xname, NM_NAME, sizeof(NM_NAME) - 1)) { if_rele(ifp); return; } if (!DROP_BDG_REF(ifp)) return; b = ifp->if_bridge; BDG_LOCK(nm_bridges); BDG_LOCK(b); ND("want to disconnect %s from the bridge", ifp->if_xname); full = 0; for (i = 0; i < NM_BDG_MAXPORTS; i++) { if (b->bdg_ports[i] == ifp) { b->bdg_ports[i] = NULL; bzero(ifp, sizeof(*ifp)); free(ifp, M_DEVBUF); break; } else if (b->bdg_ports[i] != NULL) full = 1; } BDG_UNLOCK(b); if (full == 0) { ND("freeing bridge %d", b - nm_bridges); b->namelen = 0; } BDG_UNLOCK(nm_bridges); if (i == NM_BDG_MAXPORTS) D("ouch, cannot find ifp to remove"); #endif /* NM_BRIDGE */ } static void netmap_dtor(void *data) { struct netmap_priv_d *priv = data; struct ifnet *ifp = priv->np_ifp; struct netmap_adapter *na; NMA_LOCK(); if (ifp) { na = NA(ifp); na->nm_lock(ifp, NETMAP_REG_LOCK, 0); netmap_dtor_locked(data); na->nm_lock(ifp, NETMAP_REG_UNLOCK, 0); nm_if_rele(ifp); } if (priv->ref_done) { netmap_memory_deref(); } NMA_UNLOCK(); bzero(priv, sizeof(*priv)); /* XXX for safety */ free(priv, M_DEVBUF); } #ifdef __FreeBSD__ #include #include #include #include #include #include static struct cdev_pager_ops saved_cdev_pager_ops; static int netmap_dev_pager_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot, vm_ooffset_t foff, struct ucred *cred, u_short *color) { if (netmap_verbose) D("first mmap for %p", handle); return saved_cdev_pager_ops.cdev_pg_ctor(handle, size, prot, foff, cred, color); } static void netmap_dev_pager_dtor(void *handle) { saved_cdev_pager_ops.cdev_pg_dtor(handle); ND("ready to release memory for %p", handle); } static struct cdev_pager_ops netmap_cdev_pager_ops = { .cdev_pg_ctor = netmap_dev_pager_ctor, .cdev_pg_dtor = netmap_dev_pager_dtor, .cdev_pg_fault = NULL, }; static int netmap_mmap_single(struct cdev *cdev, vm_ooffset_t *foff, vm_size_t objsize, vm_object_t *objp, int prot) { vm_object_t obj; ND("cdev %p foff %jd size %jd objp %p prot %d", cdev, (intmax_t )*foff, (intmax_t )objsize, objp, prot); obj = vm_pager_allocate(OBJT_DEVICE, cdev, objsize, prot, *foff, curthread->td_ucred); ND("returns obj %p", obj); if (obj == NULL) return EINVAL; if (saved_cdev_pager_ops.cdev_pg_fault == NULL) { ND("initialize cdev_pager_ops"); saved_cdev_pager_ops = *(obj->un_pager.devp.ops); netmap_cdev_pager_ops.cdev_pg_fault = saved_cdev_pager_ops.cdev_pg_fault; }; obj->un_pager.devp.ops = &netmap_cdev_pager_ops; *objp = obj; return 0; } #endif /* __FreeBSD__ */ /* * mmap(2) support for the "netmap" device. * * Expose all the memory previously allocated by our custom memory * allocator: this way the user has only to issue a single mmap(2), and * can work on all the data structures flawlessly. * * Return 0 on success, -1 otherwise. */ #ifdef __FreeBSD__ static int netmap_mmap(__unused struct cdev *dev, #if __FreeBSD_version < 900000 vm_offset_t offset, vm_paddr_t *paddr, int nprot #else vm_ooffset_t offset, vm_paddr_t *paddr, int nprot, __unused vm_memattr_t *memattr #endif ) { int error = 0; struct netmap_priv_d *priv; if (nprot & PROT_EXEC) return (-1); // XXX -1 or EINVAL ? error = devfs_get_cdevpriv((void **)&priv); if (error == EBADF) { /* called on fault, memory is initialized */ ND(5, "handling fault at ofs 0x%x", offset); error = 0; } else if (error == 0) /* make sure memory is set */ error = netmap_get_memory(priv); if (error) return (error); ND("request for offset 0x%x", (uint32_t)offset); *paddr = netmap_ofstophys(offset); return (*paddr ? 0 : ENOMEM); } static int netmap_close(struct cdev *dev, int fflag, int devtype, struct thread *td) { if (netmap_verbose) D("dev %p fflag 0x%x devtype %d td %p", dev, fflag, devtype, td); return 0; } static int netmap_open(struct cdev *dev, int oflags, int devtype, struct thread *td) { struct netmap_priv_d *priv; int error; priv = malloc(sizeof(struct netmap_priv_d), M_DEVBUF, M_NOWAIT | M_ZERO); if (priv == NULL) return ENOMEM; error = devfs_set_cdevpriv(priv, netmap_dtor); if (error) return error; return 0; } #endif /* __FreeBSD__ */ /* * Handlers for synchronization of the queues from/to the host. * Netmap has two operating modes: * - in the default mode, the rings connected to the host stack are * just another ring pair managed by userspace; * - in transparent mode (XXX to be defined) incoming packets * (from the host or the NIC) are marked as NS_FORWARD upon * arrival, and the user application has a chance to reset the * flag for packets that should be dropped. * On the RXSYNC or poll(), packets in RX rings between * kring->nr_kcur and ring->cur with NS_FORWARD still set are moved * to the other side. * The transfer NIC --> host is relatively easy, just encapsulate * into mbufs and we are done. The host --> NIC side is slightly * harder because there might not be room in the tx ring so it * might take a while before releasing the buffer. */ /* * pass a chain of buffers to the host stack as coming from 'dst' */ static void netmap_send_up(struct ifnet *dst, struct mbuf *head) { struct mbuf *m; /* send packets up, outside the lock */ while ((m = head) != NULL) { head = head->m_nextpkt; m->m_nextpkt = NULL; if (netmap_verbose & NM_VERB_HOST) D("sending up pkt %p size %d", m, MBUF_LEN(m)); NM_SEND_UP(dst, m); } } struct mbq { struct mbuf *head; struct mbuf *tail; int count; }; /* * put a copy of the buffers marked NS_FORWARD into an mbuf chain. * Run from hwcur to cur - reserved */ static void netmap_grab_packets(struct netmap_kring *kring, struct mbq *q, int force) { /* Take packets from hwcur to cur-reserved and pass them up. * In case of no buffers we give up. At the end of the loop, * the queue is drained in all cases. * XXX handle reserved */ int k = kring->ring->cur - kring->ring->reserved; u_int n, lim = kring->nkr_num_slots - 1; struct mbuf *m, *tail = q->tail; if (k < 0) k = k + kring->nkr_num_slots; for (n = kring->nr_hwcur; n != k;) { struct netmap_slot *slot = &kring->ring->slot[n]; n = (n == lim) ? 0 : n + 1; if ((slot->flags & NS_FORWARD) == 0 && !force) continue; if (slot->len < 14 || slot->len > NETMAP_BUF_SIZE) { D("bad pkt at %d len %d", n, slot->len); continue; } slot->flags &= ~NS_FORWARD; // XXX needed ? m = m_devget(NMB(slot), slot->len, 0, kring->na->ifp, NULL); if (m == NULL) break; if (tail) tail->m_nextpkt = m; else q->head = m; tail = m; q->count++; m->m_nextpkt = NULL; } q->tail = tail; } /* * called under main lock to send packets from the host to the NIC * The host ring has packets from nr_hwcur to (cur - reserved) * to be sent down. We scan the tx rings, which have just been * flushed so nr_hwcur == cur. Pushing packets down means * increment cur and decrement avail. * XXX to be verified */ static void netmap_sw_to_nic(struct netmap_adapter *na) { struct netmap_kring *kring = &na->rx_rings[na->num_rx_rings]; struct netmap_kring *k1 = &na->tx_rings[0]; int i, howmany, src_lim, dst_lim; howmany = kring->nr_hwavail; /* XXX otherwise cur - reserved - nr_hwcur */ src_lim = kring->nkr_num_slots; for (i = 0; howmany > 0 && i < na->num_tx_rings; i++, k1++) { ND("%d packets left to ring %d (space %d)", howmany, i, k1->nr_hwavail); dst_lim = k1->nkr_num_slots; while (howmany > 0 && k1->ring->avail > 0) { struct netmap_slot *src, *dst, tmp; src = &kring->ring->slot[kring->nr_hwcur]; dst = &k1->ring->slot[k1->ring->cur]; tmp = *src; src->buf_idx = dst->buf_idx; src->flags = NS_BUF_CHANGED; dst->buf_idx = tmp.buf_idx; dst->len = tmp.len; dst->flags = NS_BUF_CHANGED; ND("out len %d buf %d from %d to %d", dst->len, dst->buf_idx, kring->nr_hwcur, k1->ring->cur); if (++kring->nr_hwcur >= src_lim) kring->nr_hwcur = 0; howmany--; kring->nr_hwavail--; if (++k1->ring->cur >= dst_lim) k1->ring->cur = 0; k1->ring->avail--; } kring->ring->cur = kring->nr_hwcur; // XXX k1++; } } /* * netmap_sync_to_host() passes packets up. We are called from a * system call in user process context, and the only contention * can be among multiple user threads erroneously calling * this routine concurrently. */ static void netmap_sync_to_host(struct netmap_adapter *na) { struct netmap_kring *kring = &na->tx_rings[na->num_tx_rings]; struct netmap_ring *ring = kring->ring; u_int k, lim = kring->nkr_num_slots - 1; struct mbq q = { NULL, NULL }; k = ring->cur; if (k > lim) { netmap_ring_reinit(kring); return; } // na->nm_lock(na->ifp, NETMAP_CORE_LOCK, 0); /* Take packets from hwcur to cur and pass them up. * In case of no buffers we give up. At the end of the loop, * the queue is drained in all cases. */ netmap_grab_packets(kring, &q, 1); kring->nr_hwcur = k; kring->nr_hwavail = ring->avail = lim; // na->nm_lock(na->ifp, NETMAP_CORE_UNLOCK, 0); netmap_send_up(na->ifp, q.head); } /* * rxsync backend for packets coming from the host stack. * They have been put in the queue by netmap_start() so we * need to protect access to the kring using a lock. * * This routine also does the selrecord if called from the poll handler * (we know because td != NULL). * * NOTE: on linux, selrecord() is defined as a macro and uses pwait * as an additional hidden argument. */ static void netmap_sync_from_host(struct netmap_adapter *na, struct thread *td, void *pwait) { struct netmap_kring *kring = &na->rx_rings[na->num_rx_rings]; struct netmap_ring *ring = kring->ring; u_int j, n, lim = kring->nkr_num_slots; u_int k = ring->cur, resvd = ring->reserved; (void)pwait; /* disable unused warnings */ na->nm_lock(na->ifp, NETMAP_CORE_LOCK, 0); if (k >= lim) { netmap_ring_reinit(kring); return; } /* new packets are already set in nr_hwavail */ /* skip past packets that userspace has released */ j = kring->nr_hwcur; if (resvd > 0) { if (resvd + ring->avail >= lim + 1) { D("XXX invalid reserve/avail %d %d", resvd, ring->avail); ring->reserved = resvd = 0; // XXX panic... } k = (k >= resvd) ? k - resvd : k + lim - resvd; } if (j != k) { n = k >= j ? k - j : k + lim - j; kring->nr_hwavail -= n; kring->nr_hwcur = k; } k = ring->avail = kring->nr_hwavail - resvd; if (k == 0 && td) selrecord(td, &kring->si); if (k && (netmap_verbose & NM_VERB_HOST)) D("%d pkts from stack", k); na->nm_lock(na->ifp, NETMAP_CORE_UNLOCK, 0); } /* * get a refcounted reference to an interface. * Return ENXIO if the interface does not exist, EINVAL if netmap * is not supported by the interface. * If successful, hold a reference. */ static int get_ifp(const char *name, struct ifnet **ifp) { #ifdef NM_BRIDGE struct ifnet *iter = NULL; do { struct nm_bridge *b; int i, l, cand = -1; if (strncmp(name, NM_NAME, sizeof(NM_NAME) - 1)) break; b = nm_find_bridge(name); if (b == NULL) { D("no bridges available for '%s'", name); return (ENXIO); } /* XXX locking */ BDG_LOCK(b); /* lookup in the local list of ports */ for (i = 0; i < NM_BDG_MAXPORTS; i++) { iter = b->bdg_ports[i]; if (iter == NULL) { if (cand == -1) cand = i; /* potential insert point */ continue; } if (!strcmp(iter->if_xname, name)) { ADD_BDG_REF(iter); ND("found existing interface"); BDG_UNLOCK(b); break; } } if (i < NM_BDG_MAXPORTS) /* already unlocked */ break; if (cand == -1) { D("bridge full, cannot create new port"); no_port: BDG_UNLOCK(b); *ifp = NULL; return EINVAL; } ND("create new bridge port %s", name); /* space for forwarding list after the ifnet */ l = sizeof(*iter) + sizeof(struct nm_bdg_fwd)*NM_BDG_BATCH ; iter = malloc(l, M_DEVBUF, M_NOWAIT | M_ZERO); if (!iter) goto no_port; strcpy(iter->if_xname, name); bdg_netmap_attach(iter); b->bdg_ports[cand] = iter; iter->if_bridge = b; ADD_BDG_REF(iter); BDG_UNLOCK(b); ND("attaching virtual bridge %p", b); } while (0); *ifp = iter; if (! *ifp) #endif /* NM_BRIDGE */ *ifp = ifunit_ref(name); if (*ifp == NULL) return (ENXIO); /* can do this if the capability exists and if_pspare[0] * points to the netmap descriptor. */ if (NETMAP_CAPABLE(*ifp)) return 0; /* valid pointer, we hold the refcount */ nm_if_rele(*ifp); return EINVAL; // not NETMAP capable } /* * Error routine called when txsync/rxsync detects an error. * Can't do much more than resetting cur = hwcur, avail = hwavail. * Return 1 on reinit. * * This routine is only called by the upper half of the kernel. * It only reads hwcur (which is changed only by the upper half, too) * and hwavail (which may be changed by the lower half, but only on * a tx ring and only to increase it, so any error will be recovered * on the next call). For the above, we don't strictly need to call * it under lock. */ int netmap_ring_reinit(struct netmap_kring *kring) { struct netmap_ring *ring = kring->ring; u_int i, lim = kring->nkr_num_slots - 1; int errors = 0; RD(10, "called for %s", kring->na->ifp->if_xname); if (ring->cur > lim) errors++; for (i = 0; i <= lim; i++) { u_int idx = ring->slot[i].buf_idx; u_int len = ring->slot[i].len; if (idx < 2 || idx >= netmap_total_buffers) { if (!errors++) D("bad buffer at slot %d idx %d len %d ", i, idx, len); ring->slot[i].buf_idx = 0; ring->slot[i].len = 0; } else if (len > NETMAP_BUF_SIZE) { ring->slot[i].len = 0; if (!errors++) D("bad len %d at slot %d idx %d", len, i, idx); } } if (errors) { int pos = kring - kring->na->tx_rings; int n = kring->na->num_tx_rings + 1; RD(10, "total %d errors", errors); errors++; RD(10, "%s %s[%d] reinit, cur %d -> %d avail %d -> %d", kring->na->ifp->if_xname, pos < n ? "TX" : "RX", pos < n ? pos : pos - n, ring->cur, kring->nr_hwcur, ring->avail, kring->nr_hwavail); ring->cur = kring->nr_hwcur; ring->avail = kring->nr_hwavail; } return (errors ? 1 : 0); } /* * Set the ring ID. For devices with a single queue, a request * for all rings is the same as a single ring. */ static int netmap_set_ringid(struct netmap_priv_d *priv, u_int ringid) { struct ifnet *ifp = priv->np_ifp; struct netmap_adapter *na = NA(ifp); u_int i = ringid & NETMAP_RING_MASK; /* initially (np_qfirst == np_qlast) we don't want to lock */ int need_lock = (priv->np_qfirst != priv->np_qlast); int lim = na->num_rx_rings; if (na->num_tx_rings > lim) lim = na->num_tx_rings; if ( (ringid & NETMAP_HW_RING) && i >= lim) { D("invalid ring id %d", i); return (EINVAL); } if (need_lock) na->nm_lock(ifp, NETMAP_CORE_LOCK, 0); priv->np_ringid = ringid; if (ringid & NETMAP_SW_RING) { priv->np_qfirst = NETMAP_SW_RING; priv->np_qlast = 0; } else if (ringid & NETMAP_HW_RING) { priv->np_qfirst = i; priv->np_qlast = i + 1; } else { priv->np_qfirst = 0; priv->np_qlast = NETMAP_HW_RING ; } priv->np_txpoll = (ringid & NETMAP_NO_TX_POLL) ? 0 : 1; if (need_lock) na->nm_lock(ifp, NETMAP_CORE_UNLOCK, 0); if (netmap_verbose) { if (ringid & NETMAP_SW_RING) D("ringid %s set to SW RING", ifp->if_xname); else if (ringid & NETMAP_HW_RING) D("ringid %s set to HW RING %d", ifp->if_xname, priv->np_qfirst); else D("ringid %s set to all %d HW RINGS", ifp->if_xname, lim); } return 0; } /* * ioctl(2) support for the "netmap" device. * * Following a list of accepted commands: * - NIOCGINFO * - SIOCGIFADDR just for convenience * - NIOCREGIF * - NIOCUNREGIF * - NIOCTXSYNC * - NIOCRXSYNC * * Return 0 on success, errno otherwise. */ static int netmap_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, struct thread *td) { struct netmap_priv_d *priv = NULL; struct ifnet *ifp; struct nmreq *nmr = (struct nmreq *) data; struct netmap_adapter *na; int error; u_int i, lim; struct netmap_if *nifp; (void)dev; /* UNUSED */ (void)fflag; /* UNUSED */ #ifdef linux #define devfs_get_cdevpriv(pp) \ ({ *(struct netmap_priv_d **)pp = ((struct file *)td)->private_data; \ (*pp ? 0 : ENOENT); }) /* devfs_set_cdevpriv cannot fail on linux */ #define devfs_set_cdevpriv(p, fn) \ ({ ((struct file *)td)->private_data = p; (p ? 0 : EINVAL); }) #define devfs_clear_cdevpriv() do { \ netmap_dtor(priv); ((struct file *)td)->private_data = 0; \ } while (0) #endif /* linux */ CURVNET_SET(TD_TO_VNET(td)); error = devfs_get_cdevpriv((void **)&priv); if (error) { CURVNET_RESTORE(); /* XXX ENOENT should be impossible, since the priv * is now created in the open */ return (error == ENOENT ? ENXIO : error); } nmr->nr_name[sizeof(nmr->nr_name) - 1] = '\0'; /* truncate name */ switch (cmd) { case NIOCGINFO: /* return capabilities etc */ if (nmr->nr_version != NETMAP_API) { D("API mismatch got %d have %d", nmr->nr_version, NETMAP_API); nmr->nr_version = NETMAP_API; error = EINVAL; break; } /* update configuration */ error = netmap_get_memory(priv); ND("get_memory returned %d", error); if (error) break; /* memsize is always valid */ nmr->nr_memsize = nm_mem.nm_totalsize; nmr->nr_offset = 0; nmr->nr_rx_rings = nmr->nr_tx_rings = 0; nmr->nr_rx_slots = nmr->nr_tx_slots = 0; if (nmr->nr_name[0] == '\0') /* just get memory info */ break; error = get_ifp(nmr->nr_name, &ifp); /* get a refcount */ if (error) break; na = NA(ifp); /* retrieve netmap_adapter */ netmap_update_config(na); nmr->nr_rx_rings = na->num_rx_rings; nmr->nr_tx_rings = na->num_tx_rings; nmr->nr_rx_slots = na->num_rx_desc; nmr->nr_tx_slots = na->num_tx_desc; nm_if_rele(ifp); /* return the refcount */ break; case NIOCREGIF: if (nmr->nr_version != NETMAP_API) { nmr->nr_version = NETMAP_API; error = EINVAL; break; } /* ensure allocators are ready */ error = netmap_get_memory(priv); ND("get_memory returned %d", error); if (error) break; /* protect access to priv from concurrent NIOCREGIF */ NMA_LOCK(); if (priv->np_ifp != NULL) { /* thread already registered */ error = netmap_set_ringid(priv, nmr->nr_ringid); NMA_UNLOCK(); break; } /* find the interface and a reference */ error = get_ifp(nmr->nr_name, &ifp); /* keep reference */ if (error) { NMA_UNLOCK(); break; } na = NA(ifp); /* retrieve netmap adapter */ for (i = 10; i > 0; i--) { na->nm_lock(ifp, NETMAP_REG_LOCK, 0); if (!NETMAP_DELETING(na)) break; na->nm_lock(ifp, NETMAP_REG_UNLOCK, 0); tsleep(na, 0, "NIOCREGIF", hz/10); } if (i == 0) { D("too many NIOCREGIF attempts, give up"); error = EINVAL; nm_if_rele(ifp); /* return the refcount */ NMA_UNLOCK(); break; } /* ring configuration may have changed, fetch from the card */ netmap_update_config(na); priv->np_ifp = ifp; /* store the reference */ error = netmap_set_ringid(priv, nmr->nr_ringid); if (error) goto error; nifp = netmap_if_new(nmr->nr_name, na); if (nifp == NULL) { /* allocation failed */ error = ENOMEM; } else if (ifp->if_capenable & IFCAP_NETMAP) { /* was already set */ } else { /* Otherwise set the card in netmap mode * and make it use the shared buffers. */ for (i = 0 ; i < na->num_tx_rings + 1; i++) mtx_init(&na->tx_rings[i].q_lock, "nm_txq_lock", MTX_NETWORK_LOCK, MTX_DEF); for (i = 0 ; i < na->num_rx_rings + 1; i++) { mtx_init(&na->rx_rings[i].q_lock, "nm_rxq_lock", MTX_NETWORK_LOCK, MTX_DEF); } error = na->nm_register(ifp, 1); /* mode on */ if (error) { netmap_dtor_locked(priv); netmap_if_free(nifp); } } if (error) { /* reg. failed, release priv and ref */ error: na->nm_lock(ifp, NETMAP_REG_UNLOCK, 0); nm_if_rele(ifp); /* return the refcount */ priv->np_ifp = NULL; priv->np_nifp = NULL; NMA_UNLOCK(); break; } na->nm_lock(ifp, NETMAP_REG_UNLOCK, 0); /* the following assignment is a commitment. * Readers (i.e., poll and *SYNC) check for * np_nifp != NULL without locking */ wmb(); /* make sure previous writes are visible to all CPUs */ priv->np_nifp = nifp; NMA_UNLOCK(); /* return the offset of the netmap_if object */ nmr->nr_rx_rings = na->num_rx_rings; nmr->nr_tx_rings = na->num_tx_rings; nmr->nr_rx_slots = na->num_rx_desc; nmr->nr_tx_slots = na->num_tx_desc; nmr->nr_memsize = nm_mem.nm_totalsize; nmr->nr_offset = netmap_if_offset(nifp); break; case NIOCUNREGIF: // XXX we have no data here ? D("deprecated, data is %p", nmr); error = EINVAL; break; case NIOCTXSYNC: case NIOCRXSYNC: nifp = priv->np_nifp; if (nifp == NULL) { error = ENXIO; break; } rmb(); /* make sure following reads are not from cache */ ifp = priv->np_ifp; /* we have a reference */ if (ifp == NULL) { D("Internal error: nifp != NULL && ifp == NULL"); error = ENXIO; break; } na = NA(ifp); /* retrieve netmap adapter */ if (priv->np_qfirst == NETMAP_SW_RING) { /* host rings */ if (cmd == NIOCTXSYNC) netmap_sync_to_host(na); else netmap_sync_from_host(na, NULL, NULL); break; } /* find the last ring to scan */ lim = priv->np_qlast; if (lim == NETMAP_HW_RING) lim = (cmd == NIOCTXSYNC) ? na->num_tx_rings : na->num_rx_rings; for (i = priv->np_qfirst; i < lim; i++) { if (cmd == NIOCTXSYNC) { struct netmap_kring *kring = &na->tx_rings[i]; if (netmap_verbose & NM_VERB_TXSYNC) D("pre txsync ring %d cur %d hwcur %d", i, kring->ring->cur, kring->nr_hwcur); na->nm_txsync(ifp, i, 1 /* do lock */); if (netmap_verbose & NM_VERB_TXSYNC) D("post txsync ring %d cur %d hwcur %d", i, kring->ring->cur, kring->nr_hwcur); } else { na->nm_rxsync(ifp, i, 1 /* do lock */); microtime(&na->rx_rings[i].ring->ts); } } break; #ifdef __FreeBSD__ case BIOCIMMEDIATE: case BIOCGHDRCMPLT: case BIOCSHDRCMPLT: case BIOCSSEESENT: D("ignore BIOCIMMEDIATE/BIOCSHDRCMPLT/BIOCSHDRCMPLT/BIOCSSEESENT"); break; default: /* allow device-specific ioctls */ { struct socket so; bzero(&so, sizeof(so)); error = get_ifp(nmr->nr_name, &ifp); /* keep reference */ if (error) break; so.so_vnet = ifp->if_vnet; // so->so_proto not null. error = ifioctl(&so, cmd, data, td); nm_if_rele(ifp); break; } #else /* linux */ default: error = EOPNOTSUPP; #endif /* linux */ } CURVNET_RESTORE(); return (error); } /* * select(2) and poll(2) handlers for the "netmap" device. * * Can be called for one or more queues. * Return true the event mask corresponding to ready events. * If there are no ready events, do a selrecord on either individual * selfd or on the global one. * Device-dependent parts (locking and sync of tx/rx rings) * are done through callbacks. * * On linux, arguments are really pwait, the poll table, and 'td' is struct file * * The first one is remapped to pwait as selrecord() uses the name as an * hidden argument. */ static int netmap_poll(struct cdev *dev, int events, struct thread *td) { struct netmap_priv_d *priv = NULL; struct netmap_adapter *na; struct ifnet *ifp; struct netmap_kring *kring; u_int core_lock, i, check_all, want_tx, want_rx, revents = 0; u_int lim_tx, lim_rx, host_forwarded = 0; struct mbq q = { NULL, NULL, 0 }; enum {NO_CL, NEED_CL, LOCKED_CL }; /* see below */ void *pwait = dev; /* linux compatibility */ (void)pwait; if (devfs_get_cdevpriv((void **)&priv) != 0 || priv == NULL) return POLLERR; if (priv->np_nifp == NULL) { D("No if registered"); return POLLERR; } rmb(); /* make sure following reads are not from cache */ ifp = priv->np_ifp; // XXX check for deleting() ? if ( (ifp->if_capenable & IFCAP_NETMAP) == 0) return POLLERR; if (netmap_verbose & 0x8000) D("device %s events 0x%x", ifp->if_xname, events); want_tx = events & (POLLOUT | POLLWRNORM); want_rx = events & (POLLIN | POLLRDNORM); na = NA(ifp); /* retrieve netmap adapter */ lim_tx = na->num_tx_rings; lim_rx = na->num_rx_rings; /* how many queues we are scanning */ if (priv->np_qfirst == NETMAP_SW_RING) { if (priv->np_txpoll || want_tx) { /* push any packets up, then we are always ready */ kring = &na->tx_rings[lim_tx]; netmap_sync_to_host(na); revents |= want_tx; } if (want_rx) { kring = &na->rx_rings[lim_rx]; if (kring->ring->avail == 0) netmap_sync_from_host(na, td, dev); if (kring->ring->avail > 0) { revents |= want_rx; } } return (revents); } /* if we are in transparent mode, check also the host rx ring */ kring = &na->rx_rings[lim_rx]; if ( (priv->np_qlast == NETMAP_HW_RING) // XXX check_all && want_rx && (netmap_fwd || kring->ring->flags & NR_FORWARD) ) { if (kring->ring->avail == 0) netmap_sync_from_host(na, td, dev); if (kring->ring->avail > 0) revents |= want_rx; } /* * check_all is set if the card has more than one queue and * the client is polling all of them. If true, we sleep on * the "global" selfd, otherwise we sleep on individual selfd * (we can only sleep on one of them per direction). * The interrupt routine in the driver should always wake on * the individual selfd, and also on the global one if the card * has more than one ring. * * If the card has only one lock, we just use that. * If the card has separate ring locks, we just use those * unless we are doing check_all, in which case the whole * loop is wrapped by the global lock. * We acquire locks only when necessary: if poll is called * when buffers are available, we can just return without locks. * * rxsync() is only called if we run out of buffers on a POLLIN. * txsync() is called if we run out of buffers on POLLOUT, or * there are pending packets to send. The latter can be disabled * passing NETMAP_NO_TX_POLL in the NIOCREG call. */ check_all = (priv->np_qlast == NETMAP_HW_RING) && (lim_tx > 1 || lim_rx > 1); /* * core_lock indicates what to do with the core lock. * The core lock is used when either the card has no individual * locks, or it has individual locks but we are cheking all * rings so we need the core lock to avoid missing wakeup events. * * It has three possible states: * NO_CL we don't need to use the core lock, e.g. * because we are protected by individual locks. * NEED_CL we need the core lock. In this case, when we * call the lock routine, move to LOCKED_CL * to remember to release the lock once done. * LOCKED_CL core lock is set, so we need to release it. */ core_lock = (check_all || !na->separate_locks) ? NEED_CL : NO_CL; #ifdef NM_BRIDGE /* the bridge uses separate locks */ if (na->nm_register == bdg_netmap_reg) { ND("not using core lock for %s", ifp->if_xname); core_lock = NO_CL; } #endif /* NM_BRIDGE */ if (priv->np_qlast != NETMAP_HW_RING) { lim_tx = lim_rx = priv->np_qlast; } /* * We start with a lock free round which is good if we have * data available. If this fails, then lock and call the sync * routines. */ for (i = priv->np_qfirst; want_rx && i < lim_rx; i++) { kring = &na->rx_rings[i]; if (kring->ring->avail > 0) { revents |= want_rx; want_rx = 0; /* also breaks the loop */ } } for (i = priv->np_qfirst; want_tx && i < lim_tx; i++) { kring = &na->tx_rings[i]; if (kring->ring->avail > 0) { revents |= want_tx; want_tx = 0; /* also breaks the loop */ } } /* * If we to push packets out (priv->np_txpoll) or want_tx is * still set, we do need to run the txsync calls (on all rings, * to avoid that the tx rings stall). */ if (priv->np_txpoll || want_tx) { flush_tx: for (i = priv->np_qfirst; i < lim_tx; i++) { kring = &na->tx_rings[i]; /* * Skip the current ring if want_tx == 0 * (we have already done a successful sync on * a previous ring) AND kring->cur == kring->hwcur * (there are no pending transmissions for this ring). */ if (!want_tx && kring->ring->cur == kring->nr_hwcur) continue; if (core_lock == NEED_CL) { na->nm_lock(ifp, NETMAP_CORE_LOCK, 0); core_lock = LOCKED_CL; } if (na->separate_locks) na->nm_lock(ifp, NETMAP_TX_LOCK, i); if (netmap_verbose & NM_VERB_TXSYNC) D("send %d on %s %d", kring->ring->cur, ifp->if_xname, i); if (na->nm_txsync(ifp, i, 0 /* no lock */)) revents |= POLLERR; /* Check avail/call selrecord only if called with POLLOUT */ if (want_tx) { if (kring->ring->avail > 0) { /* stop at the first ring. We don't risk * starvation. */ revents |= want_tx; want_tx = 0; } else if (!check_all) selrecord(td, &kring->si); } if (na->separate_locks) na->nm_lock(ifp, NETMAP_TX_UNLOCK, i); } } /* * now if want_rx is still set we need to lock and rxsync. * Do it on all rings because otherwise we starve. */ if (want_rx) { for (i = priv->np_qfirst; i < lim_rx; i++) { kring = &na->rx_rings[i]; if (core_lock == NEED_CL) { na->nm_lock(ifp, NETMAP_CORE_LOCK, 0); core_lock = LOCKED_CL; } if (na->separate_locks) na->nm_lock(ifp, NETMAP_RX_LOCK, i); if (netmap_fwd ||kring->ring->flags & NR_FORWARD) { ND(10, "forwarding some buffers up %d to %d", kring->nr_hwcur, kring->ring->cur); netmap_grab_packets(kring, &q, netmap_fwd); } if (na->nm_rxsync(ifp, i, 0 /* no lock */)) revents |= POLLERR; if (netmap_no_timestamp == 0 || kring->ring->flags & NR_TIMESTAMP) { microtime(&kring->ring->ts); } if (kring->ring->avail > 0) revents |= want_rx; else if (!check_all) selrecord(td, &kring->si); if (na->separate_locks) na->nm_lock(ifp, NETMAP_RX_UNLOCK, i); } } if (check_all && revents == 0) { /* signal on the global queue */ if (want_tx) selrecord(td, &na->tx_si); if (want_rx) selrecord(td, &na->rx_si); } /* forward host to the netmap ring */ kring = &na->rx_rings[lim_rx]; if (kring->nr_hwavail > 0) ND("host rx %d has %d packets", lim_rx, kring->nr_hwavail); if ( (priv->np_qlast == NETMAP_HW_RING) // XXX check_all && (netmap_fwd || kring->ring->flags & NR_FORWARD) && kring->nr_hwavail > 0 && !host_forwarded) { if (core_lock == NEED_CL) { na->nm_lock(ifp, NETMAP_CORE_LOCK, 0); core_lock = LOCKED_CL; } netmap_sw_to_nic(na); host_forwarded = 1; /* prevent another pass */ want_rx = 0; goto flush_tx; } if (core_lock == LOCKED_CL) na->nm_lock(ifp, NETMAP_CORE_UNLOCK, 0); if (q.head) netmap_send_up(na->ifp, q.head); return (revents); } /*------- driver support routines ------*/ /* * default lock wrapper. */ static void netmap_lock_wrapper(struct ifnet *dev, int what, u_int queueid) { struct netmap_adapter *na = NA(dev); switch (what) { #ifdef linux /* some system do not need lock on register */ case NETMAP_REG_LOCK: case NETMAP_REG_UNLOCK: break; #endif /* linux */ case NETMAP_CORE_LOCK: mtx_lock(&na->core_lock); break; case NETMAP_CORE_UNLOCK: mtx_unlock(&na->core_lock); break; case NETMAP_TX_LOCK: mtx_lock(&na->tx_rings[queueid].q_lock); break; case NETMAP_TX_UNLOCK: mtx_unlock(&na->tx_rings[queueid].q_lock); break; case NETMAP_RX_LOCK: mtx_lock(&na->rx_rings[queueid].q_lock); break; case NETMAP_RX_UNLOCK: mtx_unlock(&na->rx_rings[queueid].q_lock); break; } } /* * Initialize a ``netmap_adapter`` object created by driver on attach. * We allocate a block of memory with room for a struct netmap_adapter * plus two sets of N+2 struct netmap_kring (where N is the number * of hardware rings): * krings 0..N-1 are for the hardware queues. * kring N is for the host stack queue * kring N+1 is only used for the selinfo for all queues. * Return 0 on success, ENOMEM otherwise. * * By default the receive and transmit adapter ring counts are both initialized * to num_queues. na->num_tx_rings can be set for cards with different tx/rx * setups. */ int netmap_attach(struct netmap_adapter *arg, int num_queues) { struct netmap_adapter *na = NULL; struct ifnet *ifp = arg ? arg->ifp : NULL; if (arg == NULL || ifp == NULL) goto fail; na = malloc(sizeof(*na), M_DEVBUF, M_NOWAIT | M_ZERO); if (na == NULL) goto fail; WNA(ifp) = na; *na = *arg; /* copy everything, trust the driver to not pass junk */ NETMAP_SET_CAPABLE(ifp); if (na->num_tx_rings == 0) na->num_tx_rings = num_queues; na->num_rx_rings = num_queues; na->refcount = na->na_single = na->na_multi = 0; /* Core lock initialized here, others after netmap_if_new. */ mtx_init(&na->core_lock, "netmap core lock", MTX_NETWORK_LOCK, MTX_DEF); if (na->nm_lock == NULL) { ND("using default locks for %s", ifp->if_xname); na->nm_lock = netmap_lock_wrapper; } #ifdef linux if (ifp->netdev_ops) { ND("netdev_ops %p", ifp->netdev_ops); /* prepare a clone of the netdev ops */ na->nm_ndo = *ifp->netdev_ops; } na->nm_ndo.ndo_start_xmit = linux_netmap_start; #endif D("success for %s", ifp->if_xname); return 0; fail: D("fail, arg %p ifp %p na %p", arg, ifp, na); return (na ? EINVAL : ENOMEM); } /* * Free the allocated memory linked to the given ``netmap_adapter`` * object. */ void netmap_detach(struct ifnet *ifp) { struct netmap_adapter *na = NA(ifp); if (!na) return; mtx_destroy(&na->core_lock); if (na->tx_rings) { /* XXX should not happen */ D("freeing leftover tx_rings"); free(na->tx_rings, M_DEVBUF); } bzero(na, sizeof(*na)); WNA(ifp) = NULL; free(na, M_DEVBUF); } /* * Intercept packets from the network stack and pass them * to netmap as incoming packets on the 'software' ring. * We are not locked when called. */ int netmap_start(struct ifnet *ifp, struct mbuf *m) { struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->rx_rings[na->num_rx_rings]; u_int i, len = MBUF_LEN(m); u_int error = EBUSY, lim = kring->nkr_num_slots - 1; struct netmap_slot *slot; if (netmap_verbose & NM_VERB_HOST) D("%s packet %d len %d from the stack", ifp->if_xname, kring->nr_hwcur + kring->nr_hwavail, len); na->nm_lock(ifp, NETMAP_CORE_LOCK, 0); if (kring->nr_hwavail >= lim) { if (netmap_verbose) D("stack ring %s full\n", ifp->if_xname); goto done; /* no space */ } if (len > NETMAP_BUF_SIZE) { D("%s from_host, drop packet size %d > %d", ifp->if_xname, len, NETMAP_BUF_SIZE); goto done; /* too long for us */ } /* compute the insert position */ i = kring->nr_hwcur + kring->nr_hwavail; if (i > lim) i -= lim + 1; slot = &kring->ring->slot[i]; m_copydata(m, 0, len, NMB(slot)); slot->len = len; slot->flags = kring->nkr_slot_flags; kring->nr_hwavail++; if (netmap_verbose & NM_VERB_HOST) D("wake up host ring %s %d", na->ifp->if_xname, na->num_rx_rings); selwakeuppri(&kring->si, PI_NET); error = 0; done: na->nm_lock(ifp, NETMAP_CORE_UNLOCK, 0); /* release the mbuf in either cases of success or failure. As an * alternative, put the mbuf in a free list and free the list * only when really necessary. */ m_freem(m); return (error); } /* * netmap_reset() is called by the driver routines when reinitializing * a ring. The driver is in charge of locking to protect the kring. * If netmap mode is not set just return NULL. */ struct netmap_slot * netmap_reset(struct netmap_adapter *na, enum txrx tx, int n, u_int new_cur) { struct netmap_kring *kring; int new_hwofs, lim; if (na == NULL) return NULL; /* no netmap support here */ if (!(na->ifp->if_capenable & IFCAP_NETMAP)) return NULL; /* nothing to reinitialize */ if (tx == NR_TX) { if (n >= na->num_tx_rings) return NULL; kring = na->tx_rings + n; new_hwofs = kring->nr_hwcur - new_cur; } else { if (n >= na->num_rx_rings) return NULL; kring = na->rx_rings + n; new_hwofs = kring->nr_hwcur + kring->nr_hwavail - new_cur; } lim = kring->nkr_num_slots - 1; if (new_hwofs > lim) new_hwofs -= lim + 1; /* Alwayws set the new offset value and realign the ring. */ kring->nkr_hwofs = new_hwofs; if (tx == NR_TX) kring->nr_hwavail = kring->nkr_num_slots - 1; ND(10, "new hwofs %d on %s %s[%d]", kring->nkr_hwofs, na->ifp->if_xname, tx == NR_TX ? "TX" : "RX", n); #if 0 // def linux /* XXX check that the mappings are correct */ /* need ring_nr, adapter->pdev, direction */ buffer_info->dma = dma_map_single(&pdev->dev, addr, adapter->rx_buffer_len, DMA_FROM_DEVICE); if (dma_mapping_error(&adapter->pdev->dev, buffer_info->dma)) { D("error mapping rx netmap buffer %d", i); // XXX fix error handling } #endif /* linux */ /* * Wakeup on the individual and global lock * We do the wakeup here, but the ring is not yet reconfigured. * However, we are under lock so there are no races. */ selwakeuppri(&kring->si, PI_NET); selwakeuppri(tx == NR_TX ? &na->tx_si : &na->rx_si, PI_NET); return kring->ring->slot; } /* * Default functions to handle rx/tx interrupts * we have 4 cases: * 1 ring, single lock: * lock(core); wake(i=0); unlock(core) * N rings, single lock: * lock(core); wake(i); wake(N+1) unlock(core) * 1 ring, separate locks: (i=0) * lock(i); wake(i); unlock(i) * N rings, separate locks: * lock(i); wake(i); unlock(i); lock(core) wake(N+1) unlock(core) * work_done is non-null on the RX path. */ int netmap_rx_irq(struct ifnet *ifp, int q, int *work_done) { struct netmap_adapter *na; struct netmap_kring *r; NM_SELINFO_T *main_wq; if (!(ifp->if_capenable & IFCAP_NETMAP)) return 0; ND(5, "received %s queue %d", work_done ? "RX" : "TX" , q); na = NA(ifp); if (na->na_flags & NAF_SKIP_INTR) { ND("use regular interrupt"); return 0; } if (work_done) { /* RX path */ if (q >= na->num_rx_rings) return 0; // regular queue r = na->rx_rings + q; r->nr_kflags |= NKR_PENDINTR; main_wq = (na->num_rx_rings > 1) ? &na->rx_si : NULL; } else { /* tx path */ if (q >= na->num_tx_rings) return 0; // regular queue r = na->tx_rings + q; main_wq = (na->num_tx_rings > 1) ? &na->tx_si : NULL; work_done = &q; /* dummy */ } if (na->separate_locks) { mtx_lock(&r->q_lock); selwakeuppri(&r->si, PI_NET); mtx_unlock(&r->q_lock); if (main_wq) { mtx_lock(&na->core_lock); selwakeuppri(main_wq, PI_NET); mtx_unlock(&na->core_lock); } } else { mtx_lock(&na->core_lock); selwakeuppri(&r->si, PI_NET); if (main_wq) selwakeuppri(main_wq, PI_NET); mtx_unlock(&na->core_lock); } *work_done = 1; /* do not fire napi again */ return 1; } #ifdef linux /* linux-specific routines */ /* * Remap linux arguments into the FreeBSD call. * - pwait is the poll table, passed as 'dev'; * If pwait == NULL someone else already woke up before. We can report * events but they are filtered upstream. * If pwait != NULL, then pwait->key contains the list of events. * - events is computed from pwait as above. * - file is passed as 'td'; */ static u_int linux_netmap_poll(struct file * file, struct poll_table_struct *pwait) { #if LINUX_VERSION_CODE < KERNEL_VERSION(3,4,0) int events = pwait ? pwait->key : POLLIN | POLLOUT; #else /* in 3.4.0 field 'key' was renamed to '_key' */ int events = pwait ? pwait->_key : POLLIN | POLLOUT; #endif return netmap_poll((void *)pwait, events, (void *)file); } static int linux_netmap_mmap(struct file *f, struct vm_area_struct *vma) { int lut_skip, i, j; int user_skip = 0; struct lut_entry *l_entry; int error = 0; unsigned long off, tomap; /* * vma->vm_start: start of mapping user address space * vma->vm_end: end of the mapping user address space * vma->vm_pfoff: offset of first page in the device */ // XXX security checks error = netmap_get_memory(f->private_data); ND("get_memory returned %d", error); if (error) return -error; off = vma->vm_pgoff << PAGE_SHIFT; /* offset in bytes */ tomap = vma->vm_end - vma->vm_start; for (i = 0; i < NETMAP_POOLS_NR; i++) { /* loop through obj_pools */ const struct netmap_obj_pool *p = &nm_mem.pools[i]; /* * In each pool memory is allocated in clusters * of size _clustsize, each containing clustentries * entries. For each object k we already store the * vtophys mapping in lut[k] so we use that, scanning * the lut[] array in steps of clustentries, * and we map each cluster (not individual pages, * it would be overkill). */ /* * We interpret vm_pgoff as an offset into the whole * netmap memory, as if all clusters where contiguous. */ for (lut_skip = 0, j = 0; j < p->_numclusters; j++, lut_skip += p->clustentries) { unsigned long paddr, mapsize; if (p->_clustsize <= off) { off -= p->_clustsize; continue; } l_entry = &p->lut[lut_skip]; /* first obj in the cluster */ paddr = l_entry->paddr + off; mapsize = p->_clustsize - off; off = 0; if (mapsize > tomap) mapsize = tomap; ND("remap_pfn_range(%lx, %lx, %lx)", vma->vm_start + user_skip, paddr >> PAGE_SHIFT, mapsize); if (remap_pfn_range(vma, vma->vm_start + user_skip, paddr >> PAGE_SHIFT, mapsize, vma->vm_page_prot)) return -EAGAIN; // XXX check return value user_skip += mapsize; tomap -= mapsize; if (tomap == 0) goto done; } } done: return 0; } static netdev_tx_t linux_netmap_start(struct sk_buff *skb, struct net_device *dev) { netmap_start(dev, skb); return (NETDEV_TX_OK); } #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,37) // XXX was 38 #define LIN_IOCTL_NAME .ioctl int linux_netmap_ioctl(struct inode *inode, struct file *file, u_int cmd, u_long data /* arg */) #else #define LIN_IOCTL_NAME .unlocked_ioctl long linux_netmap_ioctl(struct file *file, u_int cmd, u_long data /* arg */) #endif { int ret; struct nmreq nmr; bzero(&nmr, sizeof(nmr)); if (data && copy_from_user(&nmr, (void *)data, sizeof(nmr) ) != 0) return -EFAULT; ret = netmap_ioctl(NULL, cmd, (caddr_t)&nmr, 0, (void *)file); if (data && copy_to_user((void*)data, &nmr, sizeof(nmr) ) != 0) return -EFAULT; return -ret; } static int netmap_release(struct inode *inode, struct file *file) { (void)inode; /* UNUSED */ if (file->private_data) netmap_dtor(file->private_data); return (0); } static int linux_netmap_open(struct inode *inode, struct file *file) { struct netmap_priv_d *priv; (void)inode; /* UNUSED */ priv = malloc(sizeof(struct netmap_priv_d), M_DEVBUF, M_NOWAIT | M_ZERO); if (priv == NULL) return -ENOMEM; file->private_data = priv; return (0); } static struct file_operations netmap_fops = { .open = linux_netmap_open, .mmap = linux_netmap_mmap, LIN_IOCTL_NAME = linux_netmap_ioctl, .poll = linux_netmap_poll, .release = netmap_release, }; static struct miscdevice netmap_cdevsw = { /* same name as FreeBSD */ MISC_DYNAMIC_MINOR, "netmap", &netmap_fops, }; static int netmap_init(void); static void netmap_fini(void); /* Errors have negative values on linux */ static int linux_netmap_init(void) { return -netmap_init(); } module_init(linux_netmap_init); module_exit(netmap_fini); /* export certain symbols to other modules */ EXPORT_SYMBOL(netmap_attach); // driver attach routines EXPORT_SYMBOL(netmap_detach); // driver detach routines EXPORT_SYMBOL(netmap_ring_reinit); // ring init on error EXPORT_SYMBOL(netmap_buffer_lut); EXPORT_SYMBOL(netmap_total_buffers); // index check EXPORT_SYMBOL(netmap_buffer_base); EXPORT_SYMBOL(netmap_reset); // ring init routines EXPORT_SYMBOL(netmap_buf_size); EXPORT_SYMBOL(netmap_rx_irq); // default irq handler EXPORT_SYMBOL(netmap_no_pendintr); // XXX mitigation - should go away MODULE_AUTHOR("http://info.iet.unipi.it/~luigi/netmap/"); MODULE_DESCRIPTION("The netmap packet I/O framework"); MODULE_LICENSE("Dual BSD/GPL"); /* the code here is all BSD. */ #else /* __FreeBSD__ */ static struct cdevsw netmap_cdevsw = { .d_version = D_VERSION, .d_name = "netmap", .d_open = netmap_open, .d_mmap = netmap_mmap, .d_mmap_single = netmap_mmap_single, .d_ioctl = netmap_ioctl, .d_poll = netmap_poll, .d_close = netmap_close, }; #endif /* __FreeBSD__ */ #ifdef NM_BRIDGE /* *---- support for virtual bridge ----- */ /* ----- FreeBSD if_bridge hash function ------- */ /* * The following hash function is adapted from "Hash Functions" by Bob Jenkins * ("Algorithm Alley", Dr. Dobbs Journal, September 1997). * * http://www.burtleburtle.net/bob/hash/spooky.html */ #define mix(a, b, c) \ do { \ a -= b; a -= c; a ^= (c >> 13); \ b -= c; b -= a; b ^= (a << 8); \ c -= a; c -= b; c ^= (b >> 13); \ a -= b; a -= c; a ^= (c >> 12); \ b -= c; b -= a; b ^= (a << 16); \ c -= a; c -= b; c ^= (b >> 5); \ a -= b; a -= c; a ^= (c >> 3); \ b -= c; b -= a; b ^= (a << 10); \ c -= a; c -= b; c ^= (b >> 15); \ } while (/*CONSTCOND*/0) static __inline uint32_t nm_bridge_rthash(const uint8_t *addr) { uint32_t a = 0x9e3779b9, b = 0x9e3779b9, c = 0; // hask key b += addr[5] << 8; b += addr[4]; a += addr[3] << 24; a += addr[2] << 16; a += addr[1] << 8; a += addr[0]; mix(a, b, c); #define BRIDGE_RTHASH_MASK (NM_BDG_HASH-1) return (c & BRIDGE_RTHASH_MASK); } #undef mix static int bdg_netmap_reg(struct ifnet *ifp, int onoff) { int i, err = 0; struct nm_bridge *b = ifp->if_bridge; BDG_LOCK(b); if (onoff) { /* the interface must be already in the list. * only need to mark the port as active */ ND("should attach %s to the bridge", ifp->if_xname); for (i=0; i < NM_BDG_MAXPORTS; i++) if (b->bdg_ports[i] == ifp) break; if (i == NM_BDG_MAXPORTS) { D("no more ports available"); err = EINVAL; goto done; } ND("setting %s in netmap mode", ifp->if_xname); ifp->if_capenable |= IFCAP_NETMAP; NA(ifp)->bdg_port = i; b->act_ports |= (1<bdg_ports[i] = ifp; } else { /* should be in the list, too -- remove from the mask */ ND("removing %s from netmap mode", ifp->if_xname); ifp->if_capenable &= ~IFCAP_NETMAP; i = NA(ifp)->bdg_port; b->act_ports &= ~(1<bdg_port; uint64_t smac, dmac; struct netmap_slot *slot; struct nm_bridge *b = ifp->if_bridge; ND("prepare to send %d packets, act_ports 0x%x", n, b->act_ports); /* only consider valid destinations */ all_dst = (b->act_ports & ~mysrc); /* first pass: hash and find destinations */ for (i = 0; likely(i < n); i++) { uint8_t *buf = ft[i].buf; dmac = le64toh(*(uint64_t *)(buf)) & 0xffffffffffff; smac = le64toh(*(uint64_t *)(buf + 4)); smac >>= 16; if (unlikely(netmap_verbose)) { uint8_t *s = buf+6, *d = buf; D("%d len %4d %02x:%02x:%02x:%02x:%02x:%02x -> %02x:%02x:%02x:%02x:%02x:%02x", i, ft[i].len, s[0], s[1], s[2], s[3], s[4], s[5], d[0], d[1], d[2], d[3], d[4], d[5]); } /* * The hash is somewhat expensive, there might be some * worthwhile optimizations here. */ if ((buf[6] & 1) == 0) { /* valid src */ uint8_t *s = buf+6; sh = nm_bridge_rthash(buf+6); // XXX hash of source /* update source port forwarding entry */ b->ht[sh].mac = smac; /* XXX expire ? */ b->ht[sh].ports = mysrc; if (netmap_verbose) D("src %02x:%02x:%02x:%02x:%02x:%02x on port %d", s[0], s[1], s[2], s[3], s[4], s[5], NA(ifp)->bdg_port); } dst = 0; if ( (buf[0] & 1) == 0) { /* unicast */ uint8_t *d = buf; dh = nm_bridge_rthash(buf); // XXX hash of dst if (b->ht[dh].mac == dmac) { /* found dst */ dst = b->ht[dh].ports; if (netmap_verbose) D("dst %02x:%02x:%02x:%02x:%02x:%02x to port %x", d[0], d[1], d[2], d[3], d[4], d[5], (uint32_t)(dst >> 16)); } } if (dst == 0) dst = all_dst; dst &= all_dst; /* only consider valid ports */ if (unlikely(netmap_verbose)) D("pkt goes to ports 0x%x", (uint32_t)dst); ft[i].dst = dst; } /* second pass, scan interfaces and forward */ all_dst = (b->act_ports & ~mysrc); for (ifn = 0; all_dst; ifn++) { struct ifnet *dst_ifp = b->bdg_ports[ifn]; struct netmap_adapter *na; struct netmap_kring *kring; struct netmap_ring *ring; int j, lim, sent, locked; if (!dst_ifp) continue; ND("scan port %d %s", ifn, dst_ifp->if_xname); dst = 1 << ifn; if ((dst & all_dst) == 0) /* skip if not set */ continue; all_dst &= ~dst; /* clear current node */ na = NA(dst_ifp); ring = NULL; kring = NULL; lim = sent = locked = 0; /* inside, scan slots */ for (i = 0; likely(i < n); i++) { if ((ft[i].dst & dst) == 0) continue; /* not here */ if (!locked) { kring = &na->rx_rings[0]; ring = kring->ring; lim = kring->nkr_num_slots - 1; na->nm_lock(dst_ifp, NETMAP_RX_LOCK, 0); locked = 1; } if (unlikely(kring->nr_hwavail >= lim)) { if (netmap_verbose) D("rx ring full on %s", ifp->if_xname); break; } j = kring->nr_hwcur + kring->nr_hwavail; if (j > lim) j -= kring->nkr_num_slots; slot = &ring->slot[j]; ND("send %d %d bytes at %s:%d", i, ft[i].len, dst_ifp->if_xname, j); pkt_copy(ft[i].buf, NMB(slot), ft[i].len); slot->len = ft[i].len; kring->nr_hwavail++; sent++; } if (locked) { ND("sent %d on %s", sent, dst_ifp->if_xname); if (sent) selwakeuppri(&kring->si, PI_NET); na->nm_lock(dst_ifp, NETMAP_RX_UNLOCK, 0); } } return 0; } /* * main dispatch routine */ static int bdg_netmap_txsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->tx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; int i, j, k, lim = kring->nkr_num_slots - 1; struct nm_bdg_fwd *ft = (struct nm_bdg_fwd *)(ifp + 1); int ft_i; /* position in the forwarding table */ k = ring->cur; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) na->nm_lock(ifp, NETMAP_TX_LOCK, ring_nr); if (netmap_bridge <= 0) { /* testing only */ j = k; // used all goto done; } if (netmap_bridge > NM_BDG_BATCH) netmap_bridge = NM_BDG_BATCH; ft_i = 0; /* start from 0 */ for (j = kring->nr_hwcur; likely(j != k); j = unlikely(j == lim) ? 0 : j+1) { struct netmap_slot *slot = &ring->slot[j]; int len = ft[ft_i].len = slot->len; char *buf = ft[ft_i].buf = NMB(slot); prefetch(buf); if (unlikely(len < 14)) continue; if (unlikely(++ft_i == netmap_bridge)) ft_i = nm_bdg_flush(ft, ft_i, ifp); } if (ft_i) ft_i = nm_bdg_flush(ft, ft_i, ifp); /* count how many packets we sent */ i = k - j; if (i < 0) i += kring->nkr_num_slots; kring->nr_hwavail = kring->nkr_num_slots - 1 - i; if (j != k) D("early break at %d/ %d, avail %d", j, k, kring->nr_hwavail); done: kring->nr_hwcur = j; ring->avail = kring->nr_hwavail; if (do_lock) na->nm_lock(ifp, NETMAP_TX_UNLOCK, ring_nr); if (netmap_verbose) D("%s ring %d lock %d", ifp->if_xname, ring_nr, do_lock); return 0; } static int bdg_netmap_rxsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->rx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, n, lim = kring->nkr_num_slots - 1; u_int k = ring->cur, resvd = ring->reserved; ND("%s ring %d lock %d avail %d", ifp->if_xname, ring_nr, do_lock, kring->nr_hwavail); if (k > lim) return netmap_ring_reinit(kring); if (do_lock) na->nm_lock(ifp, NETMAP_RX_LOCK, ring_nr); /* skip past packets that userspace has released */ j = kring->nr_hwcur; /* netmap ring index */ if (resvd > 0) { if (resvd + ring->avail >= lim + 1) { D("XXX invalid reserve/avail %d %d", resvd, ring->avail); ring->reserved = resvd = 0; // XXX panic... } k = (k >= resvd) ? k - resvd : k + lim + 1 - resvd; } if (j != k) { /* userspace has released some packets. */ n = k - j; if (n < 0) n += kring->nkr_num_slots; ND("userspace releases %d packets", n); for (n = 0; likely(j != k); n++) { struct netmap_slot *slot = &ring->slot[j]; void *addr = NMB(slot); if (addr == netmap_buffer_base) { /* bad buf */ if (do_lock) na->nm_lock(ifp, NETMAP_RX_UNLOCK, ring_nr); return netmap_ring_reinit(kring); } /* decrease refcount for buffer */ slot->flags &= ~NS_BUF_CHANGED; j = unlikely(j == lim) ? 0 : j + 1; } kring->nr_hwavail -= n; kring->nr_hwcur = k; } /* tell userspace that there are new packets */ ring->avail = kring->nr_hwavail - resvd; if (do_lock) na->nm_lock(ifp, NETMAP_RX_UNLOCK, ring_nr); return 0; } static void bdg_netmap_attach(struct ifnet *ifp) { struct netmap_adapter na; ND("attaching virtual bridge"); bzero(&na, sizeof(na)); na.ifp = ifp; na.separate_locks = 1; na.num_tx_desc = NM_BRIDGE_RINGSIZE; na.num_rx_desc = NM_BRIDGE_RINGSIZE; na.nm_txsync = bdg_netmap_txsync; na.nm_rxsync = bdg_netmap_rxsync; na.nm_register = bdg_netmap_reg; netmap_attach(&na, 1); } #endif /* NM_BRIDGE */ static struct cdev *netmap_dev; /* /dev/netmap character device. */ /* * Module loader. * * Create the /dev/netmap device and initialize all global * variables. * * Return 0 on success, errno on failure. */ static int netmap_init(void) { int error; error = netmap_memory_init(); if (error != 0) { printf("netmap: unable to initialize the memory allocator.\n"); return (error); } printf("netmap: loaded module\n"); netmap_dev = make_dev(&netmap_cdevsw, 0, UID_ROOT, GID_WHEEL, 0660, "netmap"); #ifdef NM_BRIDGE { int i; for (i = 0; i < NM_BRIDGES; i++) mtx_init(&nm_bridges[i].bdg_lock, "bdg lock", "bdg_lock", MTX_DEF); } #endif return (error); } /* * Module unloader. * * Free all the memory, and destroy the ``/dev/netmap`` device. */ static void netmap_fini(void) { destroy_dev(netmap_dev); netmap_memory_fini(); printf("netmap: unloaded module.\n"); } #ifdef __FreeBSD__ /* * Kernel entry point. * * Initialize/finalize the module and return. * * Return 0 on success, errno on failure. */ static int netmap_loader(__unused struct module *module, int event, __unused void *arg) { int error = 0; switch (event) { case MOD_LOAD: error = netmap_init(); break; case MOD_UNLOAD: netmap_fini(); break; default: error = EOPNOTSUPP; break; } return (error); } DEV_MODULE(netmap, netmap_loader, NULL); #endif /* __FreeBSD__ */ netmap-release/sys/dev/netmap/netmap.4000644 000423 000000 00000024762 12006436627 020470 0ustar00luigiwheel000000 000000 .\" Copyright (c) 2011 Matteo Landi, Luigi Rizzo, Universita` di Pisa .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" This document is derived in part from the enet man page (enet.4) .\" distributed with 4.3BSD Unix. .\" .\" $FreeBSD: head/share/man/man4/netmap.4 228017 2011-11-27 06:55:57Z gjb $ .\" $Id: netmap.4 11563 2012-08-02 08:59:12Z luigi $: stable/8/share/man/man4/bpf.4 181694 2008-08-13 17:45:06Z ed $ .\" .Dd February 27, 2012 .Dt NETMAP 4 .Os .Sh NAME .Nm netmap .Nd a framework for fast packet I/O .Sh SYNOPSIS .Cd device netmap .Sh DESCRIPTION .Nm is a framework for fast and safe access to network devices (reaching 14.88 Mpps at less than 1 GHz). .Nm uses memory mapped buffers and metadata (buffer indexes and lengths) to communicate with the kernel, which is in charge of validating information through .Pa ioctl() and .Pa select()/poll(). .Nm can exploit the parallelism in multiqueue devices and multicore systems. .Pp .Pp .Nm requires explicit support in device drivers. For a list of supported devices, see the end of this manual page. .Sh OPERATION .Nm clients must first open the .Pa open("/dev/netmap") , and then issue an .Pa ioctl(...,NIOCREGIF,...) to bind the file descriptor to a network device. .Pp When a device is put in .Nm mode, its data path is disconnected from the host stack. The processes owning the file descriptor can exchange packets with the device, or with the host stack, through an mmapped memory region that contains pre-allocated buffers and metadata. .Pp Non blocking I/O is done with special .Pa ioctl()'s , whereas the file descriptor can be passed to .Pa select()/poll() to be notified about incoming packet or available transmit buffers. .Ss Data structures All data structures for all devices in .Nm mode are in a memory region shared by the kernel and all processes who open .Pa /dev/netmap (NOTE: visibility may be restricted in future implementations). All references between the shared data structure are relative (offsets or indexes). Some macros help converting them into actual pointers. .Pp The data structures in shared memory are the following: .Pp .Bl -tag -width XXX .It Dv struct netmap_if (one per interface) indicates the number of rings supported by an interface, their sizes, and the offsets of the .Pa netmap_rings associated to the interface. The offset of a .Pa struct netmap_if in the shared memory region is indicated by the .Pa nr_offset field in the structure returned by the .Pa NIOCREGIF (see below). .Bd -literal struct netmap_if { char ni_name[IFNAMSIZ]; /* name of the interface. */ const u_int ni_num_queues; /* number of hw ring pairs */ const ssize_t ring_ofs[]; /* offset of tx and rx rings */ }; .Ed .It Dv struct netmap_ring (one per ring) contains the index of the current read or write slot (cur), the number of slots available for reception or transmission (avail), and an array of .Pa slots describing the buffers. There is one ring pair for each of the N hardware ring pairs supported by the card (numbered 0..N-1), plus one ring pair (numbered N) for packets from/to the host stack. .Bd -literal struct netmap_ring { const ssize_t buf_ofs; const uint32_t num_slots; /* number of slots in the ring. */ uint32_t avail; /* number of usable slots */ uint32_t cur; /* 'current' index for the user side */ uint32_t reserved; /* not refilled before current */ const uint16_t nr_buf_size; uint16_t flags; struct netmap_slot slot[0]; /* array of slots. */ } .Ed .It Dv struct netmap_slot (one per packet) contains the metadata for a packet: a buffer index (buf_idx), a buffer length (len), and some flags. .Bd -literal struct netmap_slot { uint32_t buf_idx; /* buffer index */ uint16_t len; /* packet length */ uint16_t flags; /* buf changed, etc. */ #define NS_BUF_CHANGED 0x0001 /* must resync, buffer changed */ #define NS_REPORT 0x0002 /* tell hw to report results * e.g. by generating an interrupt */ }; .Ed .It Dv packet buffers are fixed size (approximately 2k) buffers allocated by the kernel that contain packet data. Buffers addresses are computed through macros. .El .Pp Some macros support the access to objects in the shared memory region. In particular: .Bd -literal struct netmap_if *nifp; struct netmap_ring *txring = NETMAP_TXRING(nifp, i); struct netmap_ring *rxring = NETMAP_RXRING(nifp, i); int i = txring->slot[txring->cur].buf_idx; char *buf = NETMAP_BUF(txring, i); .Ed .Sh IOCTLS .Pp .Nm supports some ioctl() to synchronize the state of the rings between the kernel and the user processes, plus some to query and configure the interface. The former do not require any argument, whereas the latter use a .Pa struct netmap_req defined as follows: .Bd -literal struct nmreq { char nr_name[IFNAMSIZ]; uint32_t nr_version; /* API version */ #define NETMAP_API 3 /* current version */ uint32_t nr_offset; /* nifp offset in the shared region */ uint32_t nr_memsize; /* size of the shared region */ uint32_t nr_tx_slots; /* slots in tx rings */ uint32_t nr_rx_slots; /* slots in rx rings */ uint16_t nr_tx_rings; /* number of tx rings */ uint16_t nr_rx_rings; /* number of tx rings */ uint16_t nr_ringid; /* ring(s) we care about */ #define NETMAP_HW_RING 0x4000 /* low bits indicate one hw ring */ #define NETMAP_SW_RING 0x2000 /* we process the sw ring */ #define NETMAP_NO_TX_POLL 0x1000 /* no gratuitous txsync on poll */ #define NETMAP_RING_MASK 0xfff /* the actual ring number */ uint16_t spare1; uint32_t spare2[4]; }; .Ed A device descriptor obtained through .Pa /dev/netmap also supports the ioctl supported by network devices. .Pp The netmap-specific .Xr ioctl 2 command codes below are defined in .In net/netmap.h and are: .Bl -tag -width XXXX .It Dv NIOCGINFO returns information about the interface named in nr_name. On return, nr_memsize indicates the size of the shared netmap memory region (this is device-independent), nr_tx_slots and nr_rx_slots indicates how many buffers are in a transmit and receive ring, nr_tx_rings and nr_rx_rings indicates the number of transmit and receive rings supported by the hardware. .Pp If the device does not support netmap, the ioctl returns EINVAL. .It Dv NIOCREGIF puts the interface named in nr_name into netmap mode, disconnecting it from the host stack, and/or defines which rings are controlled through this file descriptor. On return, it gives the same info as NIOCGINFO, and nr_ringid indicates the identity of the rings controlled through the file descriptor. .Pp Possible values for nr_ringid are .Bl -tag -width XXXXX .It 0 default, all hardware rings .It NETMAP_SW_RING the ``host rings'' connecting to the host stack .It NETMAP_HW_RING + i the i-th hardware ring .El By default, a .Nm poll or .Nm select call pushes out any pending packets on the transmit ring, even if no write events are specified. The feature can be disabled by or-ing .Nm NETMAP_NO_TX_SYNC to nr_ringid. But normally you should keep this feature unless you are using separate file descriptors for the send and receive rings, because otherwise packets are pushed out only if NETMAP_TXSYNC is called, or the send queue is full. .Pp .Pa NIOCREGIF can be used multiple times to change the association of a file descriptor to a ring pair, always within the same device. .It Dv NIOCUNREGIF brings an interface back to normal mode. .It Dv NIOCTXSYNC tells the hardware of new packets to transmit, and updates the number of slots available for transmission. .It Dv NIOCRXSYNC tells the hardware of consumed packets, and asks for newly available packets. .El .Sh SYSTEM CALLS .Nm uses .Nm select and .Nm poll to wake up processes when significant events occur. .Sh EXAMPLES The following code implements a traffic generator .Pp .Bd -literal -compact #include #include struct netmap_if *nifp; struct netmap_ring *ring; struct netmap_request nmr; fd = open("/dev/netmap", O_RDWR); bzero(&nmr, sizeof(nmr)); strcpy(nmr.nm_name, "ix0"); nmr.nm_version = NETMAP_API; ioctl(fd, NIOCREG, &nmr); p = mmap(0, nmr.memsize, fd); nifp = NETMAP_IF(p, nmr.offset); ring = NETMAP_TXRING(nifp, 0); fds.fd = fd; fds.events = POLLOUT; for (;;) { poll(list, 1, -1); for ( ; ring->avail > 0 ; ring->avail--) { i = ring->cur; buf = NETMAP_BUF(ring, ring->slot[i].buf_index); ... prepare packet in buf ... ring->slot[i].len = ... packet length ... ring->cur = NETMAP_RING_NEXT(ring, i); } } .Ed .Sh SUPPORTED INTERFACES .Nm supports the following interfaces: .Xr em 4 , .Xr igb 4 , .Xr ixgbe 4 , .Xr lem 4 , .Xr re 4 .Sh SEE ALSO .Xr vale 4 .Pp http://info.iet.unipi.it/~luigi/netmap/ .Pp Luigi Rizzo, Revisiting network I/O APIs: the netmap framework, Communications of the ACM, 55 (3), pp.45-51, March 2012 .Pp Luigi Rizzo, netmap: a novel framework for fast packet I/O, Usenix ATC'12, June 2012, Boston .Sh AUTHORS .An -nosplit The .Nm framework has been designed and implemented at the Universita` di Pisa in 2011 by .An Luigi Rizzo , with help from .An Matteo Landi , .An Gaetano Catalli , .An Giuseppe Lettieri . .Pp .Nm has been funded by the European Commission within FP7 Project CHANGE (257422). netmap-release/sys/dev/netmap/ixgbe_netmap.h000644 000423 000000 00000047324 12076103424 021722 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2011 Matteo Landi, Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $FreeBSD: head/sys/dev/netmap/ixgbe_netmap.h 244514 2012-12-20 22:26:03Z luigi $ * $Id: ixgbe_netmap.h 11998 2013-01-17 22:04:36Z luigi $ * * netmap modifications for ixgbe * * This file is meant to be a reference on how to implement * netmap support for a network driver. * This file contains code but only static or inline functions * that are used by a single driver. To avoid replication of * code we just #include it near the beginning of the * standard driver. */ #include #include /* * Some drivers may need the following headers. Others * already include them by default #include #include */ #include /* * ix_crcstrip: 0: keep CRC in rx frames (default), 1: strip it. * During regular operations the CRC is stripped, but on some * hardware reception of frames not multiple of 64 is slower, * so using crcstrip=0 helps in benchmarks. * * ix_rx_miss, ix_rx_miss_bufs: * count packets that might be missed due to lost interrupts. * * ix_use_dd * use the dd bit for completed tx transmissions. * This is tricky, much better to use TDH for now. */ SYSCTL_DECL(_dev_netmap); static int ix_rx_miss, ix_rx_miss_bufs, ix_use_dd, ix_crcstrip; SYSCTL_INT(_dev_netmap, OID_AUTO, ix_crcstrip, CTLFLAG_RW, &ix_crcstrip, 0, "strip CRC on rx frames"); SYSCTL_INT(_dev_netmap, OID_AUTO, ix_use_dd, CTLFLAG_RW, &ix_use_dd, 0, "use dd instead of tdh to detect tx frames"); SYSCTL_INT(_dev_netmap, OID_AUTO, ix_rx_miss, CTLFLAG_RW, &ix_rx_miss, 0, "potentially missed rx intr"); SYSCTL_INT(_dev_netmap, OID_AUTO, ix_rx_miss_bufs, CTLFLAG_RW, &ix_rx_miss_bufs, 0, "potentially missed rx intr bufs"); /* * wrapper to export locks to the generic netmap code. */ static void ixgbe_netmap_lock_wrapper(struct ifnet *_a, int what, u_int queueid) { struct adapter *adapter = _a->if_softc; ASSERT(queueid < adapter->num_queues); switch (what) { case NETMAP_CORE_LOCK: IXGBE_CORE_LOCK(adapter); break; case NETMAP_CORE_UNLOCK: IXGBE_CORE_UNLOCK(adapter); break; case NETMAP_TX_LOCK: IXGBE_TX_LOCK(&adapter->tx_rings[queueid]); break; case NETMAP_TX_UNLOCK: IXGBE_TX_UNLOCK(&adapter->tx_rings[queueid]); break; case NETMAP_RX_LOCK: IXGBE_RX_LOCK(&adapter->rx_rings[queueid]); break; case NETMAP_RX_UNLOCK: IXGBE_RX_UNLOCK(&adapter->rx_rings[queueid]); break; } } static void set_crcstrip(struct ixgbe_hw *hw, int onoff) { /* crc stripping is set in two places: * IXGBE_HLREG0 (modified on init_locked and hw reset) * IXGBE_RDRXCTL (set by the original driver in * ixgbe_setup_hw_rsc() called in init_locked. * We disable the setting when netmap is compiled in). * We update the values here, but also in ixgbe.c because * init_locked sometimes is called outside our control. */ uint32_t hl, rxc; hl = IXGBE_READ_REG(hw, IXGBE_HLREG0); rxc = IXGBE_READ_REG(hw, IXGBE_RDRXCTL); if (netmap_verbose) D("%s read HLREG 0x%x rxc 0x%x", onoff ? "enter" : "exit", hl, rxc); /* hw requirements ... */ rxc &= ~IXGBE_RDRXCTL_RSCFRSTSIZE; rxc |= IXGBE_RDRXCTL_RSCACKC; if (onoff && !ix_crcstrip) { /* keep the crc. Fast rx */ hl &= ~IXGBE_HLREG0_RXCRCSTRP; rxc &= ~IXGBE_RDRXCTL_CRCSTRIP; } else { /* reset default mode */ hl |= IXGBE_HLREG0_RXCRCSTRP; rxc |= IXGBE_RDRXCTL_CRCSTRIP; } if (netmap_verbose) D("%s write HLREG 0x%x rxc 0x%x", onoff ? "enter" : "exit", hl, rxc); IXGBE_WRITE_REG(hw, IXGBE_HLREG0, hl); IXGBE_WRITE_REG(hw, IXGBE_RDRXCTL, rxc); } /* * Register/unregister. We are already under core lock. * Only called on the first register or the last unregister. */ static int ixgbe_netmap_reg(struct ifnet *ifp, int onoff) { struct adapter *adapter = ifp->if_softc; struct netmap_adapter *na = NA(ifp); int error = 0; if (na == NULL) return EINVAL; /* no netmap support here */ ixgbe_disable_intr(adapter); /* Tell the stack that the interface is no longer active */ ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); set_crcstrip(&adapter->hw, onoff); if (onoff) { /* enable netmap mode */ ifp->if_capenable |= IFCAP_NETMAP; /* save if_transmit and replace with our routine */ na->if_transmit = ifp->if_transmit; ifp->if_transmit = netmap_start; /* * reinitialize the adapter, now with netmap flag set, * so the rings will be set accordingly. */ ixgbe_init_locked(adapter); if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) == 0) { error = ENOMEM; goto fail; } } else { /* reset normal mode (explicit request or netmap failed) */ fail: /* restore if_transmit */ ifp->if_transmit = na->if_transmit; ifp->if_capenable &= ~IFCAP_NETMAP; /* initialize the card, this time in standard mode */ ixgbe_init_locked(adapter); /* also enables intr */ } set_crcstrip(&adapter->hw, onoff); return (error); } /* * Reconcile kernel and user view of the transmit ring. * This routine might be called frequently so it must be efficient. * * ring->cur holds the userspace view of the current ring index. Userspace * has filled the tx slots from the previous call's ring->cur up to but not * including ring->cur for this call. In this function the kernel updates * kring->nr_hwcur to ring->cur, thus slots [kring->nr_hwcur, ring->cur) are * now ready to transmit. At the last interrupt kring->nr_hwavail slots were * available. * * This function runs under lock (acquired from the caller or internally). * It must first update ring->avail to what the kernel knows, * subtract the newly used slots (ring->cur - kring->nr_hwcur) * from both avail and nr_hwavail, and set ring->nr_hwcur = ring->cur * issuing a dmamap_sync on all slots. * * Since ring comes from userspace, its content must be read only once, * and validated before being used to update the kernel's structures. * (this is also true for every use of ring in the kernel). * * ring->avail is never used, only checked for bogus values. * * do_lock is set iff the function is called from the ioctl handler. * In this case, grab a lock around the body, and also reclaim transmitted * buffers irrespective of interrupt mitigation. */ static int ixgbe_netmap_txsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct adapter *adapter = ifp->if_softc; struct tx_ring *txr = &adapter->tx_rings[ring_nr]; struct netmap_adapter *na = NA(adapter->ifp); struct netmap_kring *kring = &na->tx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, k = ring->cur, l, n = 0, lim = kring->nkr_num_slots - 1; /* * ixgbe can generate an interrupt on every tx packet, but it * seems very expensive, so we interrupt once every half ring, * or when requested with NS_REPORT */ u_int report_frequency = kring->nkr_num_slots >> 1; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) IXGBE_TX_LOCK(txr); bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map, BUS_DMASYNC_POSTREAD); /* * Process new packets to send. j is the current index in the * netmap ring, l is the corresponding index in the NIC ring. * The two numbers differ because upon a *_init() we reset * the NIC ring but leave the netmap ring unchanged. * For the transmit ring, we have * * j = kring->nr_hwcur * l = IXGBE_TDT (not tracked in the driver) * and * j == (l + kring->nkr_hwofs) % ring_size * * In this driver kring->nkr_hwofs >= 0, but for other * drivers it might be negative as well. */ j = kring->nr_hwcur; if (j != k) { /* we have new packets to send */ prefetch(&ring->slot[j]); l = netmap_idx_k2n(kring, j); /* NIC index */ prefetch(&txr->tx_buffers[l]); for (n = 0; j != k; n++) { /* * Collect per-slot info. * Note that txbuf and curr are indexed by l. * * In this driver we collect the buffer address * (using the PNMB() macro) because we always * need to rewrite it into the NIC ring. * Many other drivers preserve the address, so * we only need to access it if NS_BUF_CHANGED * is set. * XXX note, on this device the dmamap* calls are * not necessary because tag is 0, however just accessing * the per-packet tag kills 1Mpps at 900 MHz. */ struct netmap_slot *slot = &ring->slot[j]; union ixgbe_adv_tx_desc *curr = &txr->tx_base[l]; struct ixgbe_tx_buf *txbuf = &txr->tx_buffers[l]; uint64_t paddr; // XXX type for flags and len ? int flags = ((slot->flags & NS_REPORT) || j == 0 || j == report_frequency) ? IXGBE_TXD_CMD_RS : 0; u_int len = slot->len; void *addr = PNMB(slot, &paddr); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; prefetch(&ring->slot[j]); prefetch(&txr->tx_buffers[l]); /* * Quick check for valid addr and len. * NMB() returns netmap_buffer_base for invalid * buffer indexes (but the address is still a * valid one to be used in a ring). slot->len is * unsigned so no need to check for negative values. */ if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) { ring_reset: if (do_lock) IXGBE_TX_UNLOCK(txr); return netmap_ring_reinit(kring); } if (slot->flags & NS_BUF_CHANGED) { /* buffer has changed, unload and reload map */ netmap_reload_map(txr->txtag, txbuf->map, addr); slot->flags &= ~NS_BUF_CHANGED; } slot->flags &= ~NS_REPORT; /* * Fill the slot in the NIC ring. * In this driver we need to rewrite the buffer * address in the NIC ring. Other drivers do not * need this. * Use legacy descriptor, it is faster. */ curr->read.buffer_addr = htole64(paddr); curr->read.olinfo_status = 0; curr->read.cmd_type_len = htole32(len | flags | IXGBE_ADVTXD_DCMD_IFCS | IXGBE_TXD_CMD_EOP); /* make sure changes to the buffer are synced */ bus_dmamap_sync(txr->txtag, txbuf->map, BUS_DMASYNC_PREWRITE); } kring->nr_hwcur = k; /* the saved ring->cur */ /* decrease avail by number of packets sent */ kring->nr_hwavail -= n; /* synchronize the NIC ring */ bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE); /* (re)start the transmitter up to slot l (excluded) */ IXGBE_WRITE_REG(&adapter->hw, IXGBE_TDT(txr->me), l); } /* * Reclaim buffers for completed transmissions. * Because this is expensive (we read a NIC register etc.) * we only do it in specific cases (see below). * In all cases kring->nr_kflags indicates which slot will be * checked upon a tx interrupt (nkr_num_slots means none). */ if (do_lock) { j = 1; /* forced reclaim, ignore interrupts */ kring->nr_kflags = kring->nkr_num_slots; } else if (kring->nr_hwavail > 0) { j = 0; /* buffers still available: no reclaim, ignore intr. */ kring->nr_kflags = kring->nkr_num_slots; } else { /* * no buffers available, locate a slot for which we request * ReportStatus (approximately half ring after next_to_clean) * and record it in kring->nr_kflags. * If the slot has DD set, do the reclaim looking at TDH, * otherwise we go to sleep (in netmap_poll()) and will be * woken up when slot nr_kflags will be ready. */ struct ixgbe_legacy_tx_desc *txd = (struct ixgbe_legacy_tx_desc *)txr->tx_base; j = txr->next_to_clean + kring->nkr_num_slots/2; if (j >= kring->nkr_num_slots) j -= kring->nkr_num_slots; // round to the closest with dd set j= (j < kring->nkr_num_slots / 4 || j >= kring->nkr_num_slots*3/4) ? 0 : report_frequency; kring->nr_kflags = j; /* the slot to check */ j = txd[j].upper.fields.status & IXGBE_TXD_STAT_DD; // XXX cpu_to_le32 ? } if (j) { int delta; /* * Record completed transmissions. * We (re)use the driver's txr->next_to_clean to keep * track of the most recently completed transmission. * * The datasheet discourages the use of TDH to find out the * number of sent packets. We should rather check the DD * status bit in a packet descriptor. However, we only set * the "report status" bit for some descriptors (a kind of * interrupt mitigation), so we can only check on those. * For the time being we use TDH, as we do it infrequently * enough not to pose performance problems. */ if (ix_use_dd) { struct ixgbe_legacy_tx_desc *txd = (struct ixgbe_legacy_tx_desc *)txr->tx_base; l = txr->next_to_clean; k = netmap_idx_k2n(kring, kring->nr_hwcur); delta = 0; while (l != k && txd[l].upper.fields.status & IXGBE_TXD_STAT_DD) { delta++; l = (l == lim) ? 0 : l + 1; } } else { l = IXGBE_READ_REG(&adapter->hw, IXGBE_TDH(ring_nr)); if (l >= kring->nkr_num_slots) { /* XXX can happen */ D("TDH wrap %d", l); l -= kring->nkr_num_slots; } delta = l - txr->next_to_clean; } if (delta) { /* some tx completed, increment avail */ if (delta < 0) delta += kring->nkr_num_slots; txr->next_to_clean = l; kring->nr_hwavail += delta; if (kring->nr_hwavail > lim) goto ring_reset; } } /* update avail to what the kernel knows */ ring->avail = kring->nr_hwavail; if (do_lock) IXGBE_TX_UNLOCK(txr); return 0; } /* * Reconcile kernel and user view of the receive ring. * Same as for the txsync, this routine must be efficient and * avoid races in accessing the shared regions. * * When called, userspace has read data from slots kring->nr_hwcur * up to ring->cur (excluded). * * The last interrupt reported kring->nr_hwavail slots available * after kring->nr_hwcur. * We must subtract the newly consumed slots (cur - nr_hwcur) * from nr_hwavail, make the descriptors available for the next reads, * and set kring->nr_hwcur = ring->cur and ring->avail = kring->nr_hwavail. * * do_lock has a special meaning: please refer to txsync. */ static int ixgbe_netmap_rxsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct adapter *adapter = ifp->if_softc; struct rx_ring *rxr = &adapter->rx_rings[ring_nr]; struct netmap_adapter *na = NA(adapter->ifp); struct netmap_kring *kring = &na->rx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, l, n, lim = kring->nkr_num_slots - 1; int force_update = do_lock || kring->nr_kflags & NKR_PENDINTR; u_int k = ring->cur, resvd = ring->reserved; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) IXGBE_RX_LOCK(rxr); /* XXX check sync modes */ bus_dmamap_sync(rxr->rxdma.dma_tag, rxr->rxdma.dma_map, BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE); /* * First part, import newly received packets into the netmap ring. * * j is the index of the next free slot in the netmap ring, * and l is the index of the next received packet in the NIC ring, * and they may differ in case if_init() has been called while * in netmap mode. For the receive ring we have * * j = (kring->nr_hwcur + kring->nr_hwavail) % ring_size * l = rxr->next_to_check; * and * j == (l + kring->nkr_hwofs) % ring_size * * rxr->next_to_check is set to 0 on a ring reinit */ if (netmap_no_pendintr || force_update) { int crclen = ix_crcstrip ? 0 : 4; uint16_t slot_flags = kring->nkr_slot_flags; l = rxr->next_to_check; j = netmap_idx_n2k(kring, l); for (n = 0; ; n++) { union ixgbe_adv_rx_desc *curr = &rxr->rx_base[l]; uint32_t staterr = le32toh(curr->wb.upper.status_error); if ((staterr & IXGBE_RXD_STAT_DD) == 0) break; ring->slot[j].len = le16toh(curr->wb.upper.length) - crclen; ring->slot[j].flags = slot_flags; bus_dmamap_sync(rxr->ptag, rxr->rx_buffers[l].pmap, BUS_DMASYNC_POSTREAD); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } if (n) { /* update the state variables */ if (netmap_no_pendintr && !force_update) { /* diagnostics */ ix_rx_miss ++; ix_rx_miss_bufs += n; } rxr->next_to_check = l; kring->nr_hwavail += n; } kring->nr_kflags &= ~NKR_PENDINTR; } /* * Skip past packets that userspace has released * (from kring->nr_hwcur to ring->cur - ring->reserved excluded), * and make the buffers available for reception. * As usual j is the index in the netmap ring, l is the index * in the NIC ring, and j == (l + kring->nkr_hwofs) % ring_size */ j = kring->nr_hwcur; if (resvd > 0) { if (resvd + ring->avail >= lim + 1) { D("XXX invalid reserve/avail %d %d", resvd, ring->avail); ring->reserved = resvd = 0; // XXX panic... } k = (k >= resvd) ? k - resvd : k + lim + 1 - resvd; } if (j != k) { /* userspace has released some packets. */ l = netmap_idx_k2n(kring, j); for (n = 0; j != k; n++) { /* collect per-slot info, with similar validations * and flag handling as in the txsync code. * * NOTE curr and rxbuf are indexed by l. * Also, this driver needs to update the physical * address in the NIC ring, but other drivers * may not have this requirement. */ struct netmap_slot *slot = &ring->slot[j]; union ixgbe_adv_rx_desc *curr = &rxr->rx_base[l]; struct ixgbe_rx_buf *rxbuf = &rxr->rx_buffers[l]; uint64_t paddr; void *addr = PNMB(slot, &paddr); if (addr == netmap_buffer_base) /* bad buf */ goto ring_reset; if (slot->flags & NS_BUF_CHANGED) { netmap_reload_map(rxr->ptag, rxbuf->pmap, addr); slot->flags &= ~NS_BUF_CHANGED; } curr->wb.upper.status_error = 0; curr->read.pkt_addr = htole64(paddr); bus_dmamap_sync(rxr->ptag, rxbuf->pmap, BUS_DMASYNC_PREREAD); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwavail -= n; kring->nr_hwcur = k; bus_dmamap_sync(rxr->rxdma.dma_tag, rxr->rxdma.dma_map, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE); /* IMPORTANT: we must leave one free slot in the ring, * so move l back by one unit */ l = (l == 0) ? lim : l - 1; IXGBE_WRITE_REG(&adapter->hw, IXGBE_RDT(rxr->me), l); } /* tell userspace that there are new packets */ ring->avail = kring->nr_hwavail - resvd; if (do_lock) IXGBE_RX_UNLOCK(rxr); return 0; ring_reset: if (do_lock) IXGBE_RX_UNLOCK(rxr); return netmap_ring_reinit(kring); } /* * The attach routine, called near the end of ixgbe_attach(), * fills the parameters for netmap_attach() and calls it. * It cannot fail, in the worst case (such as no memory) * netmap mode will be disabled and the driver will only * operate in standard mode. */ static void ixgbe_netmap_attach(struct adapter *adapter) { struct netmap_adapter na; bzero(&na, sizeof(na)); na.ifp = adapter->ifp; na.separate_locks = 1; /* this card has separate rx/tx locks */ na.num_tx_desc = adapter->num_tx_desc; na.num_rx_desc = adapter->num_rx_desc; na.nm_txsync = ixgbe_netmap_txsync; na.nm_rxsync = ixgbe_netmap_rxsync; na.nm_lock = ixgbe_netmap_lock_wrapper; na.nm_register = ixgbe_netmap_reg; netmap_attach(&na, adapter->num_queues); } /* end of file */ netmap-release/sys/dev/netmap/if_em_netmap.h000644 000423 000000 00000025554 12076103424 021704 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2011 Matteo Landi, Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $FreeBSD: head/sys/dev/netmap/if_em_netmap.h 238985 2012-08-02 11:59:43Z luigi $ * $Id: if_em_netmap.h 11998 2013-01-17 22:04:36Z luigi $ * * netmap support for em. * * For more details on netmap support please see ixgbe_netmap.h */ #include #include #include #include /* vtophys ? */ #include static void em_netmap_block_tasks(struct adapter *); static void em_netmap_unblock_tasks(struct adapter *); static void em_netmap_lock_wrapper(struct ifnet *ifp, int what, u_int queueid) { struct adapter *adapter = ifp->if_softc; ASSERT(queueid < adapter->num_queues); switch (what) { case NETMAP_CORE_LOCK: EM_CORE_LOCK(adapter); break; case NETMAP_CORE_UNLOCK: EM_CORE_UNLOCK(adapter); break; case NETMAP_TX_LOCK: EM_TX_LOCK(&adapter->tx_rings[queueid]); break; case NETMAP_TX_UNLOCK: EM_TX_UNLOCK(&adapter->tx_rings[queueid]); break; case NETMAP_RX_LOCK: EM_RX_LOCK(&adapter->rx_rings[queueid]); break; case NETMAP_RX_UNLOCK: EM_RX_UNLOCK(&adapter->rx_rings[queueid]); break; } } // XXX do we need to block/unblock the tasks ? static void em_netmap_block_tasks(struct adapter *adapter) { if (adapter->msix > 1) { /* MSIX */ int i; struct tx_ring *txr = adapter->tx_rings; struct rx_ring *rxr = adapter->rx_rings; for (i = 0; i < adapter->num_queues; i++, txr++, rxr++) { taskqueue_block(txr->tq); taskqueue_drain(txr->tq, &txr->tx_task); taskqueue_block(rxr->tq); taskqueue_drain(rxr->tq, &rxr->rx_task); } } else { /* legacy */ taskqueue_block(adapter->tq); taskqueue_drain(adapter->tq, &adapter->link_task); taskqueue_drain(adapter->tq, &adapter->que_task); } } static void em_netmap_unblock_tasks(struct adapter *adapter) { if (adapter->msix > 1) { struct tx_ring *txr = adapter->tx_rings; struct rx_ring *rxr = adapter->rx_rings; int i; for (i = 0; i < adapter->num_queues; i++) { taskqueue_unblock(txr->tq); taskqueue_unblock(rxr->tq); } } else { /* legacy */ taskqueue_unblock(adapter->tq); } } /* * Register/unregister routine */ static int em_netmap_reg(struct ifnet *ifp, int onoff) { struct adapter *adapter = ifp->if_softc; struct netmap_adapter *na = NA(ifp); int error = 0; if (na == NULL) return EINVAL; /* no netmap support here */ em_disable_intr(adapter); /* Tell the stack that the interface is no longer active */ ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); em_netmap_block_tasks(adapter); if (onoff) { ifp->if_capenable |= IFCAP_NETMAP; na->if_transmit = ifp->if_transmit; ifp->if_transmit = netmap_start; em_init_locked(adapter); if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) == 0) { error = ENOMEM; goto fail; } } else { fail: /* return to non-netmap mode */ ifp->if_transmit = na->if_transmit; ifp->if_capenable &= ~IFCAP_NETMAP; em_init_locked(adapter); /* also enable intr */ } em_netmap_unblock_tasks(adapter); return (error); } /* * Reconcile kernel and user view of the transmit ring. */ static int em_netmap_txsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct adapter *adapter = ifp->if_softc; struct tx_ring *txr = &adapter->tx_rings[ring_nr]; struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->tx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, k, l, n = 0, lim = kring->nkr_num_slots - 1; /* generate an interrupt approximately every half ring */ u_int report_frequency = kring->nkr_num_slots >> 1; k = ring->cur; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) EM_TX_LOCK(txr); bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map, BUS_DMASYNC_POSTREAD); /* * Process new packets to send. j is the current index in the * netmap ring, l is the corresponding index in the NIC ring. */ j = kring->nr_hwcur; if (j != k) { /* we have new packets to send */ l = netmap_idx_k2n(kring, j); for (n = 0; j != k; n++) { /* slot is the current slot in the netmap ring */ struct netmap_slot *slot = &ring->slot[j]; /* curr is the current slot in the nic ring */ struct e1000_tx_desc *curr = &txr->tx_base[l]; struct em_buffer *txbuf = &txr->tx_buffers[l]; int flags = ((slot->flags & NS_REPORT) || j == 0 || j == report_frequency) ? E1000_TXD_CMD_RS : 0; uint64_t paddr; void *addr = PNMB(slot, &paddr); u_int len = slot->len; if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) { if (do_lock) EM_TX_UNLOCK(txr); return netmap_ring_reinit(kring); } slot->flags &= ~NS_REPORT; if (slot->flags & NS_BUF_CHANGED) { curr->buffer_addr = htole64(paddr); /* buffer has changed, reload map */ netmap_reload_map(txr->txtag, txbuf->map, addr); slot->flags &= ~NS_BUF_CHANGED; } curr->upper.data = 0; curr->lower.data = htole32(adapter->txd_cmd | len | (E1000_TXD_CMD_EOP | flags) ); bus_dmamap_sync(txr->txtag, txbuf->map, BUS_DMASYNC_PREWRITE); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwcur = k; /* the saved ring->cur */ kring->nr_hwavail -= n; bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE); E1000_WRITE_REG(&adapter->hw, E1000_TDT(txr->me), l); } if (n == 0 || kring->nr_hwavail < 1) { int delta; /* record completed transmissions using TDH */ l = E1000_READ_REG(&adapter->hw, E1000_TDH(ring_nr)); if (l >= kring->nkr_num_slots) { /* XXX can it happen ? */ D("TDH wrap %d", l); l -= kring->nkr_num_slots; } delta = l - txr->next_to_clean; if (delta) { /* some completed, increment hwavail. */ if (delta < 0) delta += kring->nkr_num_slots; txr->next_to_clean = l; kring->nr_hwavail += delta; } } /* update avail to what the kernel knows */ ring->avail = kring->nr_hwavail; if (do_lock) EM_TX_UNLOCK(txr); return 0; } /* * Reconcile kernel and user view of the receive ring. */ static int em_netmap_rxsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct adapter *adapter = ifp->if_softc; struct rx_ring *rxr = &adapter->rx_rings[ring_nr]; struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->rx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, l, n, lim = kring->nkr_num_slots - 1; int force_update = do_lock || kring->nr_kflags & NKR_PENDINTR; u_int k = ring->cur, resvd = ring->reserved; k = ring->cur; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) EM_RX_LOCK(rxr); /* XXX check sync modes */ bus_dmamap_sync(rxr->rxdma.dma_tag, rxr->rxdma.dma_map, BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE); /* * Import newly received packets into the netmap ring. * j is an index in the netmap ring, l in the NIC ring. */ l = rxr->next_to_check; j = netmap_idx_n2k(kring, l); if (netmap_no_pendintr || force_update) { uint16_t slot_flags = kring->nkr_slot_flags; for (n = 0; ; n++) { struct e1000_rx_desc *curr = &rxr->rx_base[l]; uint32_t staterr = le32toh(curr->status); if ((staterr & E1000_RXD_STAT_DD) == 0) break; ring->slot[j].len = le16toh(curr->length); ring->slot[j].flags = slot_flags; bus_dmamap_sync(rxr->rxtag, rxr->rx_buffers[l].map, BUS_DMASYNC_POSTREAD); j = (j == lim) ? 0 : j + 1; /* make sure next_to_refresh follows next_to_check */ rxr->next_to_refresh = l; // XXX l = (l == lim) ? 0 : l + 1; } if (n) { /* update the state variables */ rxr->next_to_check = l; kring->nr_hwavail += n; } kring->nr_kflags &= ~NKR_PENDINTR; } /* skip past packets that userspace has released */ j = kring->nr_hwcur; /* netmap ring index */ if (resvd > 0) { if (resvd + ring->avail >= lim + 1) { D("XXX invalid reserve/avail %d %d", resvd, ring->avail); ring->reserved = resvd = 0; // XXX panic... } k = (k >= resvd) ? k - resvd : k + lim + 1 - resvd; } if (j != k) { /* userspace has released some packets. */ l = netmap_idx_k2n(kring, j); /* NIC ring index */ for (n = 0; j != k; n++) { struct netmap_slot *slot = &ring->slot[j]; struct e1000_rx_desc *curr = &rxr->rx_base[l]; struct em_buffer *rxbuf = &rxr->rx_buffers[l]; uint64_t paddr; void *addr = PNMB(slot, &paddr); if (addr == netmap_buffer_base) { /* bad buf */ if (do_lock) EM_RX_UNLOCK(rxr); return netmap_ring_reinit(kring); } if (slot->flags & NS_BUF_CHANGED) { curr->buffer_addr = htole64(paddr); /* buffer has changed, reload map */ netmap_reload_map(rxr->rxtag, rxbuf->map, addr); slot->flags &= ~NS_BUF_CHANGED; } curr->status = 0; bus_dmamap_sync(rxr->rxtag, rxbuf->map, BUS_DMASYNC_PREREAD); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwavail -= n; kring->nr_hwcur = k; bus_dmamap_sync(rxr->rxdma.dma_tag, rxr->rxdma.dma_map, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE); /* * IMPORTANT: we must leave one free slot in the ring, * so move l back by one unit */ l = (l == 0) ? lim : l - 1; E1000_WRITE_REG(&adapter->hw, E1000_RDT(rxr->me), l); } /* tell userspace that there are new packets */ ring->avail = kring->nr_hwavail - resvd; if (do_lock) EM_RX_UNLOCK(rxr); return 0; } static void em_netmap_attach(struct adapter *adapter) { struct netmap_adapter na; bzero(&na, sizeof(na)); na.ifp = adapter->ifp; na.separate_locks = 1; na.num_tx_desc = adapter->num_tx_desc; na.num_rx_desc = adapter->num_rx_desc; na.nm_txsync = em_netmap_txsync; na.nm_rxsync = em_netmap_rxsync; na.nm_lock = em_netmap_lock_wrapper; na.nm_register = em_netmap_reg; netmap_attach(&na, adapter->num_queues); } /* end of file */ netmap-release/sys/dev/netmap/if_igb_netmap.h000644 000423 000000 00000024414 12076103424 022036 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2011 Universita` di Pisa. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $FreeBSD: head/sys/dev/netmap/if_igb_netmap.h 238985 2012-08-02 11:59:43Z luigi $ * $Id: if_igb_netmap.h 11998 2013-01-17 22:04:36Z luigi $ * * Netmap support for igb, partly contributed by Ahmed Kooli * For details on netmap support please see ixgbe_netmap.h */ #include #include #include #include /* vtophys ? */ #include /* * wrapper to export locks to the generic code */ static void igb_netmap_lock_wrapper(struct ifnet *ifp, int what, u_int queueid) { struct adapter *adapter = ifp->if_softc; ASSERT(queueid < adapter->num_queues); switch (what) { case NETMAP_CORE_LOCK: IGB_CORE_LOCK(adapter); break; case NETMAP_CORE_UNLOCK: IGB_CORE_UNLOCK(adapter); break; case NETMAP_TX_LOCK: IGB_TX_LOCK(&adapter->tx_rings[queueid]); break; case NETMAP_TX_UNLOCK: IGB_TX_UNLOCK(&adapter->tx_rings[queueid]); break; case NETMAP_RX_LOCK: IGB_RX_LOCK(&adapter->rx_rings[queueid]); break; case NETMAP_RX_UNLOCK: IGB_RX_UNLOCK(&adapter->rx_rings[queueid]); break; } } /* * register-unregister routine */ static int igb_netmap_reg(struct ifnet *ifp, int onoff) { struct adapter *adapter = ifp->if_softc; struct netmap_adapter *na = NA(ifp); int error = 0; if (na == NULL) return EINVAL; /* no netmap support here */ igb_disable_intr(adapter); /* Tell the stack that the interface is no longer active */ ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); if (onoff) { ifp->if_capenable |= IFCAP_NETMAP; na->if_transmit = ifp->if_transmit; ifp->if_transmit = netmap_start; igb_init_locked(adapter); if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) == 0) { error = ENOMEM; goto fail; } } else { fail: /* restore if_transmit */ ifp->if_transmit = na->if_transmit; ifp->if_capenable &= ~IFCAP_NETMAP; igb_init_locked(adapter); /* also enable intr */ } return (error); } /* * Reconcile kernel and user view of the transmit ring. */ static int igb_netmap_txsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct adapter *adapter = ifp->if_softc; struct tx_ring *txr = &adapter->tx_rings[ring_nr]; struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->tx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, k, l, n = 0, lim = kring->nkr_num_slots - 1; /* generate an interrupt approximately every half ring */ u_int report_frequency = kring->nkr_num_slots >> 1; k = ring->cur; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) IGB_TX_LOCK(txr); bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map, BUS_DMASYNC_POSTREAD); /* check for new packets to send. * j indexes the netmap ring, l indexes the nic ring, and * j = kring->nr_hwcur, l = E1000_TDT (not tracked), * j == (l + kring->nkr_hwofs) % ring_size */ j = kring->nr_hwcur; if (j != k) { /* we have new packets to send */ /* 82575 needs the queue index added */ u32 olinfo_status = (adapter->hw.mac.type == e1000_82575) ? (txr->me << 4) : 0; l = netmap_idx_k2n(kring, j); for (n = 0; j != k; n++) { /* slot is the current slot in the netmap ring */ struct netmap_slot *slot = &ring->slot[j]; /* curr is the current slot in the nic ring */ union e1000_adv_tx_desc *curr = (union e1000_adv_tx_desc *)&txr->tx_base[l]; struct igb_tx_buffer *txbuf = &txr->tx_buffers[l]; int flags = ((slot->flags & NS_REPORT) || j == 0 || j == report_frequency) ? E1000_ADVTXD_DCMD_RS : 0; uint64_t paddr; void *addr = PNMB(slot, &paddr); u_int len = slot->len; if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) { if (do_lock) IGB_TX_UNLOCK(txr); return netmap_ring_reinit(kring); } slot->flags &= ~NS_REPORT; if (slot->flags & NS_BUF_CHANGED) { /* buffer has changed, reload map */ netmap_reload_map(txr->txtag, txbuf->map, addr); slot->flags &= ~NS_BUF_CHANGED; } curr->read.buffer_addr = htole64(paddr); // XXX check olinfo and cmd_type_len curr->read.olinfo_status = htole32(olinfo_status | (len<< E1000_ADVTXD_PAYLEN_SHIFT)); curr->read.cmd_type_len = htole32(len | E1000_ADVTXD_DTYP_DATA | E1000_ADVTXD_DCMD_IFCS | E1000_ADVTXD_DCMD_DEXT | E1000_ADVTXD_DCMD_EOP | flags); bus_dmamap_sync(txr->txtag, txbuf->map, BUS_DMASYNC_PREWRITE); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwcur = k; /* the saved ring->cur */ kring->nr_hwavail -= n; /* Set the watchdog XXX ? */ txr->queue_status = IGB_QUEUE_WORKING; txr->watchdog_time = ticks; bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE); E1000_WRITE_REG(&adapter->hw, E1000_TDT(txr->me), l); } if (n == 0 || kring->nr_hwavail < 1) { int delta; /* record completed transmissions using TDH */ l = E1000_READ_REG(&adapter->hw, E1000_TDH(ring_nr)); if (l >= kring->nkr_num_slots) { /* XXX can it happen ? */ D("TDH wrap %d", l); l -= kring->nkr_num_slots; } delta = l - txr->next_to_clean; if (delta) { /* some completed, increment hwavail. */ if (delta < 0) delta += kring->nkr_num_slots; txr->next_to_clean = l; kring->nr_hwavail += delta; } } /* update avail to what the kernel knows */ ring->avail = kring->nr_hwavail; if (do_lock) IGB_TX_UNLOCK(txr); return 0; } /* * Reconcile kernel and user view of the receive ring. */ static int igb_netmap_rxsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct adapter *adapter = ifp->if_softc; struct rx_ring *rxr = &adapter->rx_rings[ring_nr]; struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->rx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, l, n, lim = kring->nkr_num_slots - 1; int force_update = do_lock || kring->nr_kflags & NKR_PENDINTR; u_int k = ring->cur, resvd = ring->reserved; k = ring->cur; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) IGB_RX_LOCK(rxr); /* XXX check sync modes */ bus_dmamap_sync(rxr->rxdma.dma_tag, rxr->rxdma.dma_map, BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE); /* * import newly received packets into the netmap ring. * j is an index in the netmap ring, l in the NIC ring. */ l = rxr->next_to_check; j = netmap_idx_n2k(kring, l); if (netmap_no_pendintr || force_update) { uint16_t slot_flags = kring->nkr_slot_flags; for (n = 0; ; n++) { union e1000_adv_rx_desc *curr = &rxr->rx_base[l]; uint32_t staterr = le32toh(curr->wb.upper.status_error); if ((staterr & E1000_RXD_STAT_DD) == 0) break; ring->slot[j].len = le16toh(curr->wb.upper.length); ring->slot[j].flags = slot_flags; bus_dmamap_sync(rxr->ptag, rxr->rx_buffers[l].pmap, BUS_DMASYNC_POSTREAD); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } if (n) { /* update the state variables */ rxr->next_to_check = l; kring->nr_hwavail += n; } kring->nr_kflags &= ~NKR_PENDINTR; } /* skip past packets that userspace has released */ j = kring->nr_hwcur; /* netmap ring index */ if (resvd > 0) { if (resvd + ring->avail >= lim + 1) { D("XXX invalid reserve/avail %d %d", resvd, ring->avail); ring->reserved = resvd = 0; // XXX panic... } k = (k >= resvd) ? k - resvd : k + lim + 1 - resvd; } if (j != k) { /* userspace has released some packets. */ l = netmap_idx_k2n(kring, j); for (n = 0; j != k; n++) { struct netmap_slot *slot = ring->slot + j; union e1000_adv_rx_desc *curr = &rxr->rx_base[l]; struct igb_rx_buf *rxbuf = rxr->rx_buffers + l; uint64_t paddr; void *addr = PNMB(slot, &paddr); if (addr == netmap_buffer_base) { /* bad buf */ if (do_lock) IGB_RX_UNLOCK(rxr); return netmap_ring_reinit(kring); } if (slot->flags & NS_BUF_CHANGED) { netmap_reload_map(rxr->ptag, rxbuf->pmap, addr); slot->flags &= ~NS_BUF_CHANGED; } curr->read.pkt_addr = htole64(paddr); curr->wb.upper.status_error = 0; bus_dmamap_sync(rxr->ptag, rxbuf->pmap, BUS_DMASYNC_PREREAD); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwavail -= n; kring->nr_hwcur = k; bus_dmamap_sync(rxr->rxdma.dma_tag, rxr->rxdma.dma_map, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE); /* * IMPORTANT: we must leave one free slot in the ring, * so move l back by one unit */ l = (l == 0) ? lim : l - 1; E1000_WRITE_REG(&adapter->hw, E1000_RDT(rxr->me), l); } /* tell userspace that there are new packets */ ring->avail = kring->nr_hwavail - resvd; if (do_lock) IGB_RX_UNLOCK(rxr); return 0; } static void igb_netmap_attach(struct adapter *adapter) { struct netmap_adapter na; bzero(&na, sizeof(na)); na.ifp = adapter->ifp; na.separate_locks = 1; na.num_tx_desc = adapter->num_tx_desc; na.num_rx_desc = adapter->num_rx_desc; na.nm_txsync = igb_netmap_txsync; na.nm_rxsync = igb_netmap_rxsync; na.nm_lock = igb_netmap_lock_wrapper; na.nm_register = igb_netmap_reg; netmap_attach(&na, adapter->num_queues); } /* end of file */ netmap-release/sys/dev/netmap/netmap_kern.h000644 000423 000000 00000035104 12110024375 021550 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2011-2012 Matteo Landi, Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $FreeBSD: head/sys/dev/netmap/netmap_kern.h 238985 2012-08-02 11:59:43Z luigi $ * $Id: netmap_kern.h 12089 2013-02-15 01:20:25Z luigi $ * * The header contains the definitions of constants and function * prototypes used only in kernelspace. */ #ifndef _NET_NETMAP_KERN_H_ #define _NET_NETMAP_KERN_H_ #define NETMAP_MEM2 // use the new memory allocator #if defined(__FreeBSD__) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #define NM_LOCK_T struct mtx #define NM_SELINFO_T struct selinfo #define MBUF_LEN(m) ((m)->m_pkthdr.len) #define NM_SEND_UP(ifp, m) ((ifp)->if_input)(ifp, m) #elif defined (linux) #define NM_LOCK_T safe_spinlock_t // see bsd_glue.h #define NM_SELINFO_T wait_queue_head_t #define MBUF_LEN(m) ((m)->len) #define NM_SEND_UP(ifp, m) netif_rx(m) #ifndef DEV_NETMAP #define DEV_NETMAP #endif /* * IFCAP_NETMAP goes into net_device's priv_flags (if_capenable). * This was 16 bits up to linux 2.6.36, so we need a 16 bit value on older * platforms and tolerate the clash with IFF_DYNAMIC and IFF_BRIDGE_PORT. * For the 32-bit value, 0x100000 has no clashes until at least 3.5.1 */ #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,37) #define IFCAP_NETMAP 0x8000 #else #define IFCAP_NETMAP 0x100000 #endif #elif defined (__APPLE__) #warning apple support is incomplete. #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #define NM_LOCK_T IOLock * #define NM_SELINFO_T struct selinfo #define MBUF_LEN(m) ((m)->m_pkthdr.len) #define NM_SEND_UP(ifp, m) ((ifp)->if_input)(ifp, m) #else #error unsupported platform #endif #define ND(format, ...) #define D(format, ...) \ do { \ struct timeval __xxts; \ microtime(&__xxts); \ printf("%03d.%06d %s [%d] " format "\n", \ (int)__xxts.tv_sec % 1000, (int)__xxts.tv_usec, \ __FUNCTION__, __LINE__, ##__VA_ARGS__); \ } while (0) /* rate limited, lps indicates how many per second */ #define RD(lps, format, ...) \ do { \ static int t0, __cnt; \ if (t0 != time_second) { \ t0 = time_second; \ __cnt = 0; \ } \ if (__cnt++ < lps) \ D(format, ##__VA_ARGS__); \ } while (0) struct netmap_adapter; /* * private, kernel view of a ring. Keeps track of the status of * a ring across system calls. * * nr_hwcur index of the next buffer to refill. * It corresponds to ring->cur - ring->reserved * * nr_hwavail the number of slots "owned" by userspace. * nr_hwavail =:= ring->avail + ring->reserved * * The indexes in the NIC and netmap rings are offset by nkr_hwofs slots. * This is so that, on a reset, buffers owned by userspace are not * modified by the kernel. In particular: * RX rings: the next empty buffer (hwcur + hwavail + hwofs) coincides with * the next empty buffer as known by the hardware (next_to_check or so). * TX rings: hwcur + hwofs coincides with next_to_send * * For received packets, slot->flags is set to nkr_slot_flags * so we can provide a proper initial value (e.g. set NS_FORWARD * when operating in 'transparent' mode). */ struct netmap_kring { struct netmap_ring *ring; u_int nr_hwcur; int nr_hwavail; u_int nr_kflags; /* private driver flags */ #define NKR_PENDINTR 0x1 // Pending interrupt. u_int nkr_num_slots; uint16_t nkr_slot_flags; /* initial value for flags */ int nkr_hwofs; /* offset between NIC and netmap ring */ struct netmap_adapter *na; NM_SELINFO_T si; /* poll/select wait queue */ NM_LOCK_T q_lock; /* used if no device lock available */ } __attribute__((__aligned__(64))); /* * This struct extends the 'struct adapter' (or * equivalent) device descriptor. It contains all fields needed to * support netmap operation. */ struct netmap_adapter { /* * On linux we do not have a good way to tell if an interface * is netmap-capable. So we use the following trick: * NA(ifp) points here, and the first entry (which hopefully * always exists and is at least 32 bits) contains a magic * value which we can use to detect that the interface is good. */ uint32_t magic; uint32_t na_flags; /* future place for IFCAP_NETMAP */ #define NAF_SKIP_INTR 1 /* use the regular interrupt handler. * useful during initialization */ int refcount; /* number of user-space descriptors using this interface, which is equal to the number of struct netmap_if objs in the mapped region. */ /* * The selwakeup in the interrupt thread can use per-ring * and/or global wait queues. We track how many clients * of each type we have so we can optimize the drivers, * and especially avoid huge contention on the locks. */ int na_single; /* threads attached to a single hw queue */ int na_multi; /* threads attached to multiple hw queues */ int separate_locks; /* set if the interface suports different locks for rx, tx and core. */ u_int num_rx_rings; /* number of adapter receive rings */ u_int num_tx_rings; /* number of adapter transmit rings */ u_int num_tx_desc; /* number of descriptor in each queue */ u_int num_rx_desc; /* tx_rings and rx_rings are private but allocated * as a contiguous chunk of memory. Each array has * N+1 entries, for the adapter queues and for the host queue. */ struct netmap_kring *tx_rings; /* array of TX rings. */ struct netmap_kring *rx_rings; /* array of RX rings. */ NM_SELINFO_T tx_si, rx_si; /* global wait queues */ /* copy of if_qflush and if_transmit pointers, to intercept * packets from the network stack when netmap is active. */ int (*if_transmit)(struct ifnet *, struct mbuf *); /* references to the ifnet and device routines, used by * the generic netmap functions. */ struct ifnet *ifp; /* adapter is ifp->if_softc */ NM_LOCK_T core_lock; /* used if no device lock available */ int (*nm_register)(struct ifnet *, int onoff); void (*nm_lock)(struct ifnet *, int what, u_int ringid); int (*nm_txsync)(struct ifnet *, u_int ring, int lock); int (*nm_rxsync)(struct ifnet *, u_int ring, int lock); /* return configuration information */ int (*nm_config)(struct ifnet *, u_int *txr, u_int *txd, u_int *rxr, u_int *rxd); int bdg_port; #ifdef linux struct net_device_ops nm_ndo; int if_refcount; // XXX additions for bridge #endif /* linux */ }; /* * The combination of "enable" (ifp->if_capenable & IFCAP_NETMAP) * and refcount gives the status of the interface, namely: * * enable refcount Status * * FALSE 0 normal operation * FALSE != 0 -- (impossible) * TRUE 1 netmap mode * TRUE 0 being deleted. */ #define NETMAP_DELETING(_na) ( ((_na)->refcount == 0) && \ ( (_na)->ifp->if_capenable & IFCAP_NETMAP) ) /* * parameters for (*nm_lock)(adapter, what, index) */ enum { NETMAP_NO_LOCK = 0, NETMAP_CORE_LOCK, NETMAP_CORE_UNLOCK, NETMAP_TX_LOCK, NETMAP_TX_UNLOCK, NETMAP_RX_LOCK, NETMAP_RX_UNLOCK, #ifdef __FreeBSD__ #define NETMAP_REG_LOCK NETMAP_CORE_LOCK #define NETMAP_REG_UNLOCK NETMAP_CORE_UNLOCK #else NETMAP_REG_LOCK, NETMAP_REG_UNLOCK #endif }; /* * The following are support routines used by individual drivers to * support netmap operation. * * netmap_attach() initializes a struct netmap_adapter, allocating the * struct netmap_ring's and the struct selinfo. * * netmap_detach() frees the memory allocated by netmap_attach(). * * netmap_start() replaces the if_transmit routine of the interface, * and is used to intercept packets coming from the stack. * * netmap_load_map/netmap_reload_map are helper routines to set/reset * the dmamap for a packet buffer * * netmap_reset() is a helper routine to be called in the driver * when reinitializing a ring. */ int netmap_attach(struct netmap_adapter *, int); void netmap_detach(struct ifnet *); int netmap_start(struct ifnet *, struct mbuf *); enum txrx { NR_RX = 0, NR_TX = 1 }; struct netmap_slot *netmap_reset(struct netmap_adapter *na, enum txrx tx, int n, u_int new_cur); int netmap_ring_reinit(struct netmap_kring *); extern u_int netmap_buf_size; #define NETMAP_BUF_SIZE netmap_buf_size extern int netmap_mitigate; extern int netmap_no_pendintr; extern u_int netmap_total_buffers; extern char *netmap_buffer_base; extern int netmap_verbose; // XXX debugging enum { /* verbose flags */ NM_VERB_ON = 1, /* generic verbose */ NM_VERB_HOST = 0x2, /* verbose host stack */ NM_VERB_RXSYNC = 0x10, /* verbose on rxsync/txsync */ NM_VERB_TXSYNC = 0x20, NM_VERB_RXINTR = 0x100, /* verbose on rx/tx intr (driver) */ NM_VERB_TXINTR = 0x200, NM_VERB_NIC_RXSYNC = 0x1000, /* verbose on rx/tx intr (driver) */ NM_VERB_NIC_TXSYNC = 0x2000, }; /* * NA returns a pointer to the struct netmap adapter from the ifp, * WNA is used to write it. */ #ifndef WNA #define WNA(_ifp) (_ifp)->if_pspare[0] #endif #define NA(_ifp) ((struct netmap_adapter *)WNA(_ifp)) /* * Macros to determine if an interface is netmap capable or netmap enabled. * See the magic field in struct netmap_adapter. */ #ifdef __FreeBSD__ /* * on FreeBSD just use if_capabilities and if_capenable. */ #define NETMAP_CAPABLE(ifp) (NA(ifp) && \ (ifp)->if_capabilities & IFCAP_NETMAP ) #define NETMAP_SET_CAPABLE(ifp) \ (ifp)->if_capabilities |= IFCAP_NETMAP #else /* linux */ /* * on linux: * we check if NA(ifp) is set and its first element has a related * magic value. The capenable is within the struct netmap_adapter. */ #define NETMAP_MAGIC 0x52697a7a #define NETMAP_CAPABLE(ifp) (NA(ifp) && \ ((uint32_t)(uintptr_t)NA(ifp) ^ NA(ifp)->magic) == NETMAP_MAGIC ) #define NETMAP_SET_CAPABLE(ifp) \ NA(ifp)->magic = ((uint32_t)(uintptr_t)NA(ifp)) ^ NETMAP_MAGIC #endif /* linux */ #ifdef __FreeBSD__ /* Callback invoked by the dma machinery after a successfull dmamap_load */ static void netmap_dmamap_cb(__unused void *arg, __unused bus_dma_segment_t * segs, __unused int nseg, __unused int error) { } /* bus_dmamap_load wrapper: call aforementioned function if map != NULL. * XXX can we do it without a callback ? */ static inline void netmap_load_map(bus_dma_tag_t tag, bus_dmamap_t map, void *buf) { if (map) bus_dmamap_load(tag, map, buf, NETMAP_BUF_SIZE, netmap_dmamap_cb, NULL, BUS_DMA_NOWAIT); } /* update the map when a buffer changes. */ static inline void netmap_reload_map(bus_dma_tag_t tag, bus_dmamap_t map, void *buf) { if (map) { bus_dmamap_unload(tag, map); bus_dmamap_load(tag, map, buf, NETMAP_BUF_SIZE, netmap_dmamap_cb, NULL, BUS_DMA_NOWAIT); } } #else /* linux */ /* * XXX How do we redefine these functions: * * on linux we need * dma_map_single(&pdev->dev, virt_addr, len, direction) * dma_unmap_single(&adapter->pdev->dev, phys_addr, len, direction * The len can be implicit (on netmap it is NETMAP_BUF_SIZE) * unfortunately the direction is not, so we need to change * something to have a cross API */ #define netmap_load_map(_t, _m, _b) #define netmap_reload_map(_t, _m, _b) #if 0 struct e1000_buffer *buffer_info = &tx_ring->buffer_info[l]; /* set time_stamp *before* dma to help avoid a possible race */ buffer_info->time_stamp = jiffies; buffer_info->mapped_as_page = false; buffer_info->length = len; //buffer_info->next_to_watch = l; /* reload dma map */ dma_unmap_single(&adapter->pdev->dev, buffer_info->dma, NETMAP_BUF_SIZE, DMA_TO_DEVICE); buffer_info->dma = dma_map_single(&adapter->pdev->dev, addr, NETMAP_BUF_SIZE, DMA_TO_DEVICE); if (dma_mapping_error(&adapter->pdev->dev, buffer_info->dma)) { D("dma mapping error"); /* goto dma_error; See e1000_put_txbuf() */ /* XXX reset */ } tx_desc->buffer_addr = htole64(buffer_info->dma); //XXX #endif /* * The bus_dmamap_sync() can be one of wmb() or rmb() depending on direction. */ #define bus_dmamap_sync(_a, _b, _c) #endif /* linux */ /* * functions to map NIC to KRING indexes (n2k) and vice versa (k2n) */ static inline int netmap_idx_n2k(struct netmap_kring *kr, int idx) { int n = kr->nkr_num_slots; idx += kr->nkr_hwofs; if (idx < 0) return idx + n; else if (idx < n) return idx; else return idx - n; } static inline int netmap_idx_k2n(struct netmap_kring *kr, int idx) { int n = kr->nkr_num_slots; idx -= kr->nkr_hwofs; if (idx < 0) return idx + n; else if (idx < n) return idx; else return idx - n; } #ifdef NETMAP_MEM2 /* Entries of the look-up table. */ struct lut_entry { void *vaddr; /* virtual address. */ vm_paddr_t paddr; /* phisical address. */ }; struct netmap_obj_pool; extern struct lut_entry *netmap_buffer_lut; #define NMB_VA(i) (netmap_buffer_lut[i].vaddr) #define NMB_PA(i) (netmap_buffer_lut[i].paddr) #else /* NETMAP_MEM1 */ #define NMB_VA(i) (netmap_buffer_base + (i * NETMAP_BUF_SIZE) ) #endif /* NETMAP_MEM2 */ /* * NMB return the virtual address of a buffer (buffer 0 on bad index) * PNMB also fills the physical address */ static inline void * NMB(struct netmap_slot *slot) { uint32_t i = slot->buf_idx; return (unlikely(i >= netmap_total_buffers)) ? NMB_VA(0) : NMB_VA(i); } static inline void * PNMB(struct netmap_slot *slot, uint64_t *pp) { uint32_t i = slot->buf_idx; void *ret = (i >= netmap_total_buffers) ? NMB_VA(0) : NMB_VA(i); #ifdef NETMAP_MEM2 *pp = (i >= netmap_total_buffers) ? NMB_PA(0) : NMB_PA(i); #else *pp = vtophys(ret); #endif return ret; } /* default functions to handle rx/tx interrupts */ int netmap_rx_irq(struct ifnet *, int, int *); #define netmap_tx_irq(_n, _q) netmap_rx_irq(_n, _q, NULL) extern int netmap_copy; #endif /* _NET_NETMAP_KERN_H_ */ netmap-release/sys/dev/netmap/if_re_netmap.h000644 000423 000000 00000030233 12076103424 021677 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2011 Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $FreeBSD: head/sys/dev/netmap/if_re_netmap.h 234225 2012-04-13 15:33:12Z luigi $ * $Id: if_re_netmap.h 11998 2013-01-17 22:04:36Z luigi $ * * netmap support for "re" * For details on netmap support please see ixgbe_netmap.h */ #include #include #include #include /* vtophys ? */ #include /* * wrapper to export locks to the generic code * We should not use the tx/rx locks */ static void re_netmap_lock_wrapper(struct ifnet *ifp, int what, u_int queueid) { struct rl_softc *adapter = ifp->if_softc; switch (what) { case NETMAP_CORE_LOCK: RL_LOCK(adapter); break; case NETMAP_CORE_UNLOCK: RL_UNLOCK(adapter); break; case NETMAP_TX_LOCK: case NETMAP_RX_LOCK: case NETMAP_TX_UNLOCK: case NETMAP_RX_UNLOCK: D("invalid lock call %d, no tx/rx locks here", what); break; } } /* * support for netmap register/unregisted. We are already under core lock. * only called on the first register or the last unregister. */ static int re_netmap_reg(struct ifnet *ifp, int onoff) { struct rl_softc *adapter = ifp->if_softc; struct netmap_adapter *na = NA(ifp); int error = 0; if (na == NULL) return EINVAL; /* Tell the stack that the interface is no longer active */ ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); re_stop(adapter); if (onoff) { ifp->if_capenable |= IFCAP_NETMAP; /* save if_transmit to restore it later */ na->if_transmit = ifp->if_transmit; ifp->if_transmit = netmap_start; re_init_locked(adapter); if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) == 0) { error = ENOMEM; goto fail; } } else { fail: /* restore if_transmit */ ifp->if_transmit = na->if_transmit; ifp->if_capenable &= ~IFCAP_NETMAP; re_init_locked(adapter); /* also enables intr */ } return (error); } /* * Reconcile kernel and user view of the transmit ring. */ static int re_netmap_txsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct rl_softc *sc = ifp->if_softc; struct rl_txdesc *txd = sc->rl_ldata.rl_tx_desc; struct netmap_adapter *na = NA(sc->rl_ifp); struct netmap_kring *kring = &na->tx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; int j, k, l, n, lim = kring->nkr_num_slots - 1; k = ring->cur; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) RL_LOCK(sc); /* Sync the TX descriptor list */ bus_dmamap_sync(sc->rl_ldata.rl_tx_list_tag, sc->rl_ldata.rl_tx_list_map, BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE); /* XXX move after the transmissions */ /* record completed transmissions */ for (n = 0, l = sc->rl_ldata.rl_tx_considx; l != sc->rl_ldata.rl_tx_prodidx; n++, l = RL_TX_DESC_NXT(sc, l)) { uint32_t cmdstat = le32toh(sc->rl_ldata.rl_tx_list[l].rl_cmdstat); if (cmdstat & RL_TDESC_STAT_OWN) break; } if (n > 0) { sc->rl_ldata.rl_tx_considx = l; sc->rl_ldata.rl_tx_free += n; kring->nr_hwavail += n; } /* update avail to what the kernel knows */ ring->avail = kring->nr_hwavail; j = kring->nr_hwcur; if (j != k) { /* we have new packets to send */ l = sc->rl_ldata.rl_tx_prodidx; for (n = 0; j != k; n++) { struct netmap_slot *slot = &ring->slot[j]; struct rl_desc *desc = &sc->rl_ldata.rl_tx_list[l]; int cmd = slot->len | RL_TDESC_CMD_EOF | RL_TDESC_CMD_OWN | RL_TDESC_CMD_SOF ; uint64_t paddr; void *addr = PNMB(slot, &paddr); int len = slot->len; if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) { if (do_lock) RL_UNLOCK(sc); // XXX what about prodidx ? return netmap_ring_reinit(kring); } if (l == lim) /* mark end of ring */ cmd |= RL_TDESC_CMD_EOR; if (slot->flags & NS_BUF_CHANGED) { desc->rl_bufaddr_lo = htole32(RL_ADDR_LO(paddr)); desc->rl_bufaddr_hi = htole32(RL_ADDR_HI(paddr)); /* buffer has changed, unload and reload map */ netmap_reload_map(sc->rl_ldata.rl_tx_mtag, txd[l].tx_dmamap, addr); slot->flags &= ~NS_BUF_CHANGED; } slot->flags &= ~NS_REPORT; desc->rl_cmdstat = htole32(cmd); bus_dmamap_sync(sc->rl_ldata.rl_tx_mtag, txd[l].tx_dmamap, BUS_DMASYNC_PREWRITE); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } sc->rl_ldata.rl_tx_prodidx = l; kring->nr_hwcur = k; /* the saved ring->cur */ ring->avail -= n; // XXX see others kring->nr_hwavail = ring->avail; bus_dmamap_sync(sc->rl_ldata.rl_tx_list_tag, sc->rl_ldata.rl_tx_list_map, BUS_DMASYNC_PREWRITE|BUS_DMASYNC_PREREAD); /* start ? */ CSR_WRITE_1(sc, sc->rl_txstart, RL_TXSTART_START); } if (do_lock) RL_UNLOCK(sc); return 0; } /* * Reconcile kernel and user view of the receive ring. */ static int re_netmap_rxsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct rl_softc *sc = ifp->if_softc; struct rl_rxdesc *rxd = sc->rl_ldata.rl_rx_desc; struct netmap_adapter *na = NA(sc->rl_ifp); struct netmap_kring *kring = &na->rx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; int j, l, n, lim = kring->nkr_num_slots - 1; int force_update = do_lock || kring->nr_kflags & NKR_PENDINTR; u_int k = ring->cur, resvd = ring->reserved; k = ring->cur; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) RL_LOCK(sc); /* XXX check sync modes */ bus_dmamap_sync(sc->rl_ldata.rl_rx_list_tag, sc->rl_ldata.rl_rx_list_map, BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE); /* * Import newly received packets into the netmap ring. * j is an index in the netmap ring, l in the NIC ring. * * The device uses all the buffers in the ring, so we need * another termination condition in addition to RL_RDESC_STAT_OWN * cleared (all buffers could have it cleared. The easiest one * is to limit the amount of data reported up to 'lim' */ l = sc->rl_ldata.rl_rx_prodidx; /* next pkt to check */ j = netmap_idx_n2k(kring, l); /* the kring index */ if (netmap_no_pendintr || force_update) { uint16_t slot_flags = kring->nkr_slot_flags; for (n = kring->nr_hwavail; n < lim ; n++) { struct rl_desc *cur_rx = &sc->rl_ldata.rl_rx_list[l]; uint32_t rxstat = le32toh(cur_rx->rl_cmdstat); uint32_t total_len; if ((rxstat & RL_RDESC_STAT_OWN) != 0) break; total_len = rxstat & sc->rl_rxlenmask; /* XXX subtract crc */ total_len = (total_len < 4) ? 0 : total_len - 4; kring->ring->slot[j].len = total_len; kring->ring->slot[j].flags = slot_flags; /* sync was in re_newbuf() */ bus_dmamap_sync(sc->rl_ldata.rl_rx_mtag, rxd[l].rx_dmamap, BUS_DMASYNC_POSTREAD); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } if (n != kring->nr_hwavail) { sc->rl_ldata.rl_rx_prodidx = l; sc->rl_ifp->if_ipackets += n - kring->nr_hwavail; kring->nr_hwavail = n; } kring->nr_kflags &= ~NKR_PENDINTR; } /* skip past packets that userspace has released */ j = kring->nr_hwcur; if (resvd > 0) { if (resvd + ring->avail >= lim + 1) { D("XXX invalid reserve/avail %d %d", resvd, ring->avail); ring->reserved = resvd = 0; // XXX panic... } k = (k >= resvd) ? k - resvd : k + lim + 1 - resvd; } if (j != k) { /* userspace has released some packets. */ l = netmap_idx_k2n(kring, j); /* the NIC index */ for (n = 0; j != k; n++) { struct netmap_slot *slot = ring->slot + j; struct rl_desc *desc = &sc->rl_ldata.rl_rx_list[l]; int cmd = NETMAP_BUF_SIZE | RL_RDESC_CMD_OWN; uint64_t paddr; void *addr = PNMB(slot, &paddr); if (addr == netmap_buffer_base) { /* bad buf */ if (do_lock) RL_UNLOCK(sc); return netmap_ring_reinit(kring); } if (l == lim) /* mark end of ring */ cmd |= RL_RDESC_CMD_EOR; slot->flags &= ~NS_REPORT; if (slot->flags & NS_BUF_CHANGED) { netmap_reload_map(sc->rl_ldata.rl_rx_mtag, rxd[l].rx_dmamap, addr); desc->rl_bufaddr_lo = htole32(RL_ADDR_LO(paddr)); desc->rl_bufaddr_hi = htole32(RL_ADDR_HI(paddr)); slot->flags &= ~NS_BUF_CHANGED; } desc->rl_cmdstat = htole32(cmd); bus_dmamap_sync(sc->rl_ldata.rl_rx_mtag, rxd[l].rx_dmamap, BUS_DMASYNC_PREREAD); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwavail -= n; kring->nr_hwcur = k; /* Flush the RX DMA ring */ bus_dmamap_sync(sc->rl_ldata.rl_rx_list_tag, sc->rl_ldata.rl_rx_list_map, BUS_DMASYNC_PREWRITE|BUS_DMASYNC_PREREAD); } /* tell userspace that there are new packets */ ring->avail = kring->nr_hwavail - resvd; if (do_lock) RL_UNLOCK(sc); return 0; } /* * Additional routines to init the tx and rx rings. * In other drivers we do that inline in the main code. */ static void re_netmap_tx_init(struct rl_softc *sc) { struct rl_txdesc *txd; struct rl_desc *desc; int i, n; struct netmap_adapter *na = NA(sc->rl_ifp); struct netmap_slot *slot = netmap_reset(na, NR_TX, 0, 0); /* slot is NULL if we are not in netmap mode */ if (!slot) return; /* in netmap mode, overwrite addresses and maps */ txd = sc->rl_ldata.rl_tx_desc; desc = sc->rl_ldata.rl_tx_list; n = sc->rl_ldata.rl_tx_desc_cnt; /* l points in the netmap ring, i points in the NIC ring */ for (i = 0; i < n; i++) { uint64_t paddr; int l = netmap_idx_n2k(&na->tx_rings[0], i); void *addr = PNMB(slot + l, &paddr); desc[i].rl_bufaddr_lo = htole32(RL_ADDR_LO(paddr)); desc[i].rl_bufaddr_hi = htole32(RL_ADDR_HI(paddr)); netmap_load_map(sc->rl_ldata.rl_tx_mtag, txd[i].tx_dmamap, addr); } } static void re_netmap_rx_init(struct rl_softc *sc) { struct netmap_adapter *na = NA(sc->rl_ifp); struct netmap_slot *slot = netmap_reset(na, NR_RX, 0, 0); struct rl_desc *desc = sc->rl_ldata.rl_rx_list; uint32_t cmdstat; int i, n, max_avail; if (!slot) return; n = sc->rl_ldata.rl_rx_desc_cnt; /* * Userspace owned hwavail packets before the reset, * so the NIC that last hwavail descriptors of the ring * are still owned by the driver (and keep one empty). */ max_avail = n - 1 - na->rx_rings[0].nr_hwavail; for (i = 0; i < n; i++) { void *addr; uint64_t paddr; int l = netmap_idx_n2k(&na->rx_rings[0], i); addr = PNMB(slot + l, &paddr); netmap_reload_map(sc->rl_ldata.rl_rx_mtag, sc->rl_ldata.rl_rx_desc[i].rx_dmamap, addr); bus_dmamap_sync(sc->rl_ldata.rl_rx_mtag, sc->rl_ldata.rl_rx_desc[i].rx_dmamap, BUS_DMASYNC_PREREAD); desc[i].rl_bufaddr_lo = htole32(RL_ADDR_LO(paddr)); desc[i].rl_bufaddr_hi = htole32(RL_ADDR_HI(paddr)); cmdstat = NETMAP_BUF_SIZE; if (i == n - 1) /* mark the end of ring */ cmdstat |= RL_RDESC_CMD_EOR; if (i < max_avail) cmdstat |= RL_RDESC_CMD_OWN; desc[i].rl_cmdstat = htole32(cmdstat); } } static void re_netmap_attach(struct rl_softc *sc) { struct netmap_adapter na; bzero(&na, sizeof(na)); na.ifp = sc->rl_ifp; na.separate_locks = 0; na.num_tx_desc = sc->rl_ldata.rl_tx_desc_cnt; na.num_rx_desc = sc->rl_ldata.rl_rx_desc_cnt; na.nm_txsync = re_netmap_txsync; na.nm_rxsync = re_netmap_rxsync; na.nm_lock = re_netmap_lock_wrapper; na.nm_register = re_netmap_reg; netmap_attach(&na, 1); } /* end of file */ netmap-release/sys/dev/netmap/if_sfxge_netmap.h000644 000423 000000 00000033706 12076103424 022415 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2012 Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $FreeBSD: head/sys/dev/netmap/ixgbe_netmap.h 232238 2012-02-27 19:05:01Z luigi $ * $Id: ixgbe_netmap.h 10627 2012-02-23 19:37:15Z luigi $ * * netmap modifications for sfxge init: interrupt: sfxge_ev: sfxge_ev_qpoll() in turn calls common/efx_ev.c efx_ev_qpoll() the queue contains handlers which are interleaved, The specific drivers are efx_ev_rx 0 then call eec_rx() or sfxge_ev_rx efx_ev_tx 2 then call eec_tx() or sfxge_ev_tx plus some generic events. efx_ev_driver 5 efx_ev_global 6 efx_ev_drv_gen 7 efx_ev_mcdi 0xc The receive ring seems to be circular, SFXGE_NDESCS in both rx and tx. struct sfxge_rxq *rxq; struct sfxge_rx_sw_desc *rx_desc; id = rxq->pending modulo SFXGE_NDESCS the descriptor is rxq->queue[id] each slot has size efx_qword_t (8 bytes with all overlays) The card is reset through sfxge_schedule_reset() Global lock: sx_xlock(&sc->softc_lock); */ #include #include /* * Some drivers may need the following headers. Others * already include them by default #include #include */ #include static void sfxge_stop(struct sfxge_softc *sc); static int sfxge_start(struct sfxge_softc *sc); void sfxge_tx_qlist_post(struct sfxge_txq *txq); static int sfxge_netmap_init_buffers(struct sfxge_softc *sc) { struct netmap_adapter *na = NA(sc->ifnet); struct netmap_slot *slot = netmap_reset(na, NR_TX, 0, 0); int i, l, n, max_avail; void *addr; uint64_t paddr; // tx rings, see // sfxge_tx_qinit() return 0; } /* * wrapper to export locks to the generic netmap code. */ static void sfxge_netmap_lock_wrapper(struct ifnet *ifp, int what, u_int queueid) { struct sfxge_softc *sc = ifp->if_softc; switch (what) { case NETMAP_CORE_LOCK: sx_xlock(&sc->softc_lock); break; case NETMAP_CORE_UNLOCK: sx_xunlock(&sc->softc_lock); break; case NETMAP_TX_LOCK: mtx_lock(SFXGE_TXQ_LOCK(sc->txq[queueid])); break; case NETMAP_TX_UNLOCK: mtx_unlock(SFXGE_TXQ_LOCK(sc->txq[queueid])); break; case NETMAP_RX_LOCK: mtx_lock(&sc->evq[queueid]->lock); break; case NETMAP_RX_UNLOCK: mtx_unlock(&sc->evq[queueid]->lock); break; } } /* * Register/unregister. We are already under core lock. * Only called on the first register or the last unregister. */ static int sfxge_netmap_reg(struct ifnet *ifp, int onoff) { struct sfxge_softc *sc = ifp->if_softc; struct netmap_adapter *na = NA(ifp); int error = 0; if (na == NULL) return EINVAL; /* no netmap support here */ sfxge_stop(sc); /* Tell the stack that the interface is no longer active */ ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); if (onoff) { /* enable netmap mode */ ifp->if_capenable |= IFCAP_NETMAP; /* save if_transmit and replace with our routine */ na->if_transmit = ifp->if_transmit; ifp->if_transmit = netmap_start; /* * reinitialize the adapter, now with netmap flag set, * so the rings will be set accordingly. */ sfxge_start(sc); if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) == 0) { error = ENOMEM; goto fail; } } else { /* reset normal mode (explicit request or netmap failed) */ fail: /* restore if_transmit */ ifp->if_transmit = na->if_transmit; ifp->if_capenable &= ~IFCAP_NETMAP; /* initialize the card, this time in standard mode */ sfxge_start(sc); /* also enables intr */ } return (error); } /* * Reconcile kernel and user view of the transmit ring. */ static int sfxge_netmap_txsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct sfxge_softc *sc = ifp->if_softc; struct sfxge_txq *txr = sc->txq[ring_nr]; struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->tx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, k = ring->cur, l, n = 0, lim = kring->nkr_num_slots - 1; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) mtx_lock(SFXGE_TXQ_LOCK(txr)); // bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map, // BUS_DMASYNC_POSTREAD); /* * Process new packets to send. j is the current index in the * netmap ring, l is the corresponding index in the NIC ring. * The two numbers differ because upon a *_init() we reset * the NIC ring but leave the netmap ring unchanged. * For the transmit ring, we have * * j = kring->nr_hwcur * l = IXGBE_TDT (not tracked in the driver) * and * j == (l + kring->nkr_hwofs) % ring_size * * In this driver kring->nkr_hwofs >= 0, but for other * drivers it might be negative as well. */ j = kring->nr_hwcur; if (j != k) { /* we have new packets to send */ l = netmap_idx_k2n(kring, j); /* NIC index */ for (n = 0; j != k; n++) { /* * Collect per-slot info. * Note that txbuf and curr are indexed by l. * * In this driver we collect the buffer address * (using the PNMB() macro) because we always * need to rewrite it into the NIC ring. * Many other drivers preserve the address, so * we only need to access it if NS_BUF_CHANGED * is set. * XXX note, on this device the dmamap* calls are * not necessary because tag is 0, however just accessing * the per-packet tag kills 1Mpps at 900 MHz. */ struct netmap_slot *slot = &ring->slot[j]; uint64_t paddr; u_int len = slot->len; efx_buffer_t *desc; void *addr = PNMB(slot, &paddr); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) { ring_reset: if (do_lock) mtx_unlock(SFXGE_TXQ_LOCK(txr)); return netmap_ring_reinit(kring); } if (slot->flags & NS_BUF_CHANGED) { /* buffer has changed, unload and reload map */ netmap_reload_map(txr->packet_dma_tag, txr->stmp[l].map, addr); slot->flags &= ~NS_BUF_CHANGED; } slot->flags &= ~NS_REPORT; /* * Fill the slot in the NIC ring. * In this driver we need to rewrite the buffer * address in the NIC ring. Other drivers do not * need this. * Use legacy descriptor, it is faster. */ desc->eb_addr = paddr; desc->eb_size = len; desc->eb_eop = 1; txr->n_pend_desc = 1; sfxge_tx_qlist_post(txr); /* make sure changes to the buffer are synced */ bus_dmamap_sync(txr->packet_dma_tag, txr->stmp[l].map, BUS_DMASYNC_PREWRITE); } kring->nr_hwcur = k; /* the saved ring->cur */ /* decrease avail by number of packets sent */ kring->nr_hwavail -= n; /* synchronize the NIC ring */ // bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map, // BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE); /* (re)start the transmitter up to slot l (excluded) */ // IXGBE_WRITE_REG(&adapter->hw, IXGBE_TDT(txr->me), l); } /* * Reclaim buffers for completed transmissions. */ if (do_lock) { j = 1; /* forced reclaim, ignore interrupts */ } else if (kring->nr_hwavail > 0) { j = 0; /* buffers still available: no reclaim, ignore intr. */ } else { j = 1; } if (j) { // txeof body to reclaim buffers if (txr->pending != txr->completed) { n = (txr->pending > txr->completed) ? txr->pending - txr->completed : txr->pending - txr->completed + SFXGE_NDESCS; txr->completed = txr->pending; kring->nr_hwavail += n; } } /* update avail to what the kernel knows */ ring->avail = kring->nr_hwavail; if (do_lock) mtx_unlock(SFXGE_TXQ_LOCK(txr)); if (kring->nr_hwavail > lim) return netmap_ring_reinit(kring); return 0; } /* * Reconcile kernel and user view of the receive ring. * Same as for the txsync, this routine must be efficient and * avoid races in accessing the shared regions. * * When called, userspace has read data from slots kring->nr_hwcur * up to ring->cur (excluded). * * The last interrupt reported kring->nr_hwavail slots available * after kring->nr_hwcur. * We must subtract the newly consumed slots (cur - nr_hwcur) * from nr_hwavail, make the descriptors available for the next reads, * and set kring->nr_hwcur = ring->cur and ring->avail = kring->nr_hwavail. * * do_lock has a special meaning: please refer to txsync. */ static int sfxge_netmap_rxsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct sfxge_softc *sc = ifp->if_softc; struct sfxge_rxq *rxq = sc->rxq[ring_nr]; struct sfxge_evq *evq = sc->evq[ring_nr]; struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->rx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, l, n, lim = kring->nkr_num_slots - 1; int force_update = do_lock || kring->nr_kflags & NKR_PENDINTR; u_int k = ring->cur, resvd = ring->reserved; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) mtx_lock(&evq->lock); /* XXX check sync modes */ // bus_dmamap_sync(rxq->rxdma.dma_tag, rxq->rxdma.dma_map, // BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE); /* * First part, import newly received packets into the netmap ring. * * j is the index of the next free slot in the netmap ring, * and l is the index of the next received packet in the NIC ring, * and they may differ in case if_init() has been called while * in netmap mode. For the receive ring we have * * j = (kring->nr_hwcur + kring->nr_hwavail) % ring_size * l = rxr->next_to_check; * and * j == (l + kring->nkr_hwofs) % ring_size * * rxr->next_to_check is set to 0 on a ring reinit */ l = rxq->completed; j = netmap_idx_n2k(kring, l); if (netmap_no_pendintr || force_update) { uint16_t slot_flags = kring->nkr_slot_flags; // see sfxge_rx_qcomplete() for (n = 0; l != rxq->pending ; n++) { struct sfxge_rx_sw_desc *rx_desc = &rxq->queue[l]; ring->slot[j].len = rx_desc->size - sc->rx_prefix_size; ring->slot[j].flags = slot_flags; // bus_dmamap_sync(rxq->ptag, // rxq->rx_buffers[l].pmap, BUS_DMASYNC_POSTREAD); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } if (n) { /* update the state variables */ // rxq->next_to_check = l; kring->nr_hwavail += n; } kring->nr_kflags &= ~NKR_PENDINTR; } /* * Skip past packets that userspace has released * (from kring->nr_hwcur to ring->cur - ring->reserved excluded), * and make the buffers available for reception. * As usual j is the index in the netmap ring, l is the index * in the NIC ring, and j == (l + kring->nkr_hwofs) % ring_size */ j = kring->nr_hwcur; if (resvd > 0) { if (resvd + ring->avail >= lim + 1) { D("XXX invalid reserve/avail %d %d", resvd, ring->avail); ring->reserved = resvd = 0; // XXX panic... } k = (k >= resvd) ? k - resvd : k + lim + 1 - resvd; } if (j != k) { /* userspace has released some packets. */ l = netmap_idx_k2n(kring, j); for (n = 0; j != k; n++) { /* collect per-slot info, with similar validations * and flag handling as in the txsync code. * * NOTE curr and rxbuf are indexed by l. * Also, this driver needs to update the physical * address in the NIC ring, but other drivers * may not have this requirement. */ struct netmap_slot *slot = &ring->slot[j]; uint64_t paddr; void *addr = PNMB(slot, &paddr); if (addr == netmap_buffer_base) /* bad buf */ goto ring_reset; if (slot->flags & NS_BUF_CHANGED) { //netmap_reload_map(rxq->ptag, rxbuf->pmap, addr); slot->flags &= ~NS_BUF_CHANGED; } // curr->wb.upper.status_error = 0; // curr->read.pkt_addr = htole64(paddr); // bus_dmamap_sync(rxq->ptag, rxbuf->pmap, // BUS_DMASYNC_PREREAD); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwavail -= n; kring->nr_hwcur = k; // bus_dmamap_sync(rxq->rxdma.dma_tag, rxq->rxdma.dma_map, // BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE); /* IMPORTANT: we must leave one free slot in the ring, * so move l back by one unit */ l = (l == 0) ? lim : l - 1; //IXGBE_WRITE_REG(&adapter->hw, IXGBE_RDT(rxr->me), l); } /* tell userspace that there are new packets */ ring->avail = kring->nr_hwavail - resvd; if (do_lock) mtx_unlock(&evq->lock); return 0; ring_reset: if (do_lock) mtx_unlock(&evq->lock); return netmap_ring_reinit(kring); } /* * The attach routine, called near the end of ixgbe_attach(), * fills the parameters for netmap_attach() and calls it. * It cannot fail, in the worst case (such as no memory) * netmap mode will be disabled and the driver will only * operate in standard mode. */ static void sfxge_netmap_attach(struct sfxge_softc *sc) { struct netmap_adapter na; bzero(&na, sizeof(na)); na.ifp = sc->ifnet; na.separate_locks = 1; /* this card has separate rx/tx locks */ na.num_tx_desc = SFXGE_NDESCS; na.num_rx_desc = SFXGE_NDESCS; na.nm_txsync = sfxge_netmap_txsync; na.nm_rxsync = sfxge_netmap_rxsync; na.nm_lock = sfxge_netmap_lock_wrapper; na.nm_register = sfxge_netmap_reg; na.num_tx_rings = SFXGE_TXQ_NTYPES + SFXGE_RX_SCALE_MAX; netmap_attach(&na, SFXGE_RX_SCALE_MAX); } /* end of file */ netmap-release/sys/dev/netmap/if_nfe_netmap.h000644 000423 000000 00000030463 12076103424 022046 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2011 Matteo Landi, Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $FreeBSD: head/sys/dev/netmap/if_em_netmap.h 231881 2012-02-17 14:09:04Z luigi $ * $Id: if_nfe_netmap.h 10669 2012-02-27 18:55:05Z luigi $ * * netmap support for nfe. XXX not yet tested. * * For more details on netmap support please see ixgbe_netmap.h */ #include #include #include #include /* vtophys ? */ #include static int nfe_netmap_init_buffers(struct nfe_softc *sc) { struct netmap_adapter *na = NA(sc->nfe_ifp); struct netmap_slot *slot = netmap_reset(na, NR_TX, 0, 0); int i, l, n, max_avail; struct nfe_desc32 *desc32 = NULL; struct nfe_desc64 *desc64 = NULL; void *addr; uint64_t paddr; if (!slot) return 0; // XXX init the tx ring n = NFE_TX_RING_COUNT; for (i = 0; i < n; i++) { l = netmap_idx_n2k(&na->tx_rings[0], i); addr = PNMB(slot + l, &paddr); netmap_reload_map(sc->txq.tx_data_tag, sc->txq.data[l].tx_data_map, addr); slot[l].flags = 0; if (sc->nfe_flags & NFE_40BIT_ADDR) { desc64 = &sc->txq.desc64[l]; desc64->physaddr[0] = htole32(NFE_ADDR_HI(paddr)); desc64->physaddr[1] = htole32(NFE_ADDR_LO(paddr)); desc64->vtag = 0; desc64->length = htole16(0); desc64->flags = htole16(0); } else { desc32 = &sc->txq.desc32[l]; desc32->physaddr = htole32(NFE_ADDR_LO(paddr)); desc32->length = htole16(0); desc32->flags = htole16(0); } } slot = netmap_reset(na, NR_RX, 0, 0); // XXX init the rx ring /* * Userspace owned hwavail packets before the reset, * so the NIC that last hwavail descriptors of the ring * are still owned by the driver (and keep one empty). */ n = NFE_RX_RING_COUNT; max_avail = n - 1 - na->rx_rings[0].nr_hwavail; for (i = 0; i < n; i++) { uint16_t flags; l = netmap_idx_n2k(&na->rx_rings[0], i); addr = PNMB(slot + l, &paddr); flags = (i < max_avail) ? NFE_RX_READY : 0; if (sc->nfe_flags & NFE_40BIT_ADDR) { desc64 = &sc->rxq.desc64[l]; desc64->physaddr[0] = htole32(NFE_ADDR_HI(paddr)); desc64->physaddr[1] = htole32(NFE_ADDR_LO(paddr)); desc64->vtag = 0; desc64->length = htole16(NETMAP_BUF_SIZE); desc64->flags = htole16(NFE_RX_READY); } else { desc32 = &sc->rxq.desc32[l]; desc32->physaddr = htole32(NFE_ADDR_LO(paddr)); desc32->length = htole16(NETMAP_BUF_SIZE); desc32->flags = htole16(NFE_RX_READY); } netmap_reload_map(sc->rxq.rx_data_tag, sc->rxq.data[l].rx_data_map, addr); bus_dmamap_sync(sc->rxq.rx_data_tag, sc->rxq.data[l].rx_data_map, BUS_DMASYNC_PREREAD); } return 1; } static void nfe_netmap_lock_wrapper(struct ifnet *ifp, int what, u_int queueid) { struct nfe_softc *sc = ifp->if_softc; switch (what) { case NETMAP_CORE_LOCK: NFE_LOCK(sc); break; case NETMAP_CORE_UNLOCK: NFE_UNLOCK(sc); break; } } /* * Register/unregister routine */ static int nfe_netmap_reg(struct ifnet *ifp, int onoff) { struct nfe_softc *sc = ifp->if_softc; struct netmap_adapter *na = NA(ifp); if (na == NULL) return EINVAL; /* no netmap support here */ /* Tell the stack that the interface is no longer active */ ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); if (onoff) { ifp->if_capenable |= IFCAP_NETMAP; na->if_transmit = ifp->if_transmit; ifp->if_transmit = netmap_start; nfe_init_locked(sc); } else { /* return to non-netmap mode */ ifp->if_transmit = na->if_transmit; ifp->if_capenable &= ~IFCAP_NETMAP; nfe_init_locked(sc); /* also enable intr */ } return (0); } /* * Reconcile kernel and user view of the transmit ring. */ static int nfe_netmap_txsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct nfe_softc *sc = ifp->if_softc; struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->tx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, k, l, n = 0, lim = kring->nkr_num_slots - 1; struct nfe_desc32 *desc32 = NULL; struct nfe_desc64 *desc64 = NULL; /* generate an interrupt approximately every half ring */ int report_frequency = kring->nkr_num_slots >> 1; k = ring->cur; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) NFE_LOCK(sc); bus_dmamap_sync(sc->txq.tx_desc_tag, sc->txq.tx_desc_map, BUS_DMASYNC_POSTREAD); /* * Process new packets to send. j is the current index in the * netmap ring, l is the corresponding index in the NIC ring. */ j = kring->nr_hwcur; ND("hwcur %d cur %d", j, k); na->tx_rings[0].nr_kflags &= ~NKR_PENDINTR; if (j != k) { /* we have new packets to send */ l = netmap_idx_k2n(kring, j); for (n = 0; j != k; n++) { /* slot is the current slot in the netmap ring */ struct netmap_slot *slot = &ring->slot[j]; uint64_t paddr; void *addr = PNMB(slot, &paddr); u_int len = slot->len; if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) { if (do_lock) NFE_UNLOCK(sc); return netmap_ring_reinit(kring); } slot->flags &= ~NS_REPORT; if (slot->flags & NS_BUF_CHANGED) { /* buffer has changed, reload map */ netmap_reload_map(sc->txq.tx_data_tag, sc->txq.data[l].tx_data_map, addr); slot->flags &= ~NS_BUF_CHANGED; } if (sc->nfe_flags & NFE_40BIT_ADDR) { desc64 = &sc->txq.desc64[l]; desc64->physaddr[0] = htole32(NFE_ADDR_HI(paddr)); desc64->physaddr[1] = htole32(NFE_ADDR_LO(paddr)); desc64->vtag = 0; desc64->length = htole16(len - 1); desc64->flags = htole16(NFE_TX_VALID | NFE_TX_LASTFRAG_V2); } else { desc32 = &sc->txq.desc32[l]; desc32->physaddr = htole32(NFE_ADDR_LO(paddr)); desc32->length = htole16(len - 1); desc32->flags = htole16(NFE_TX_VALID | NFE_TX_LASTFRAG_V1); } bus_dmamap_sync(sc->txq.tx_data_tag, sc->txq.data[l].tx_data_map, BUS_DMASYNC_PREWRITE); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwcur = k; /* the saved ring->cur */ kring->nr_hwavail -= n; sc->txq.cur = l; bus_dmamap_sync(sc->txq.tx_desc_tag, sc->txq.tx_desc_map, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE); NFE_WRITE(sc, NFE_RXTX_CTL, NFE_RXTX_KICKTX | sc->rxtxctl); } ND("send %d avail %d reclaim next %d cur %d", n, kring->nr_hwavail, sc->txq.next, sc->txq.cur); if (n == 0 || kring->nr_hwavail < 1) { l = sc->txq.next; k = sc->txq.cur; for (n = 0; l != k; n++, NFE_INC(l, NFE_TX_RING_COUNT)) { uint16_t flags; if (sc->nfe_flags & NFE_40BIT_ADDR) { desc64 = &sc->txq.desc64[l]; flags = le16toh(desc64->flags); } else { desc32 = &sc->txq.desc32[l]; flags = le16toh(desc32->flags); } if (flags & NFE_TX_VALID) break; } ND("reclaimed %d next %d cur %d", n, sc->txq.next, sc->txq.cur); if (n > 0) { sc->txq.next = l; kring->nr_hwavail += n; } ND("reclaimed %d next %d cur %d", n, sc->txq.next, sc->txq.cur); } /* update avail to what the kernel knows */ ring->avail = kring->nr_hwavail; if (do_lock) NFE_UNLOCK(sc); return 0; } /* * Reconcile kernel and user view of the receive ring. */ static int nfe_netmap_rxsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct nfe_softc *sc = ifp->if_softc; struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->rx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, l, n, lim = kring->nkr_num_slots - 1; int force_update = do_lock || kring->nr_kflags & NKR_PENDINTR; u_int k = ring->cur, resvd = ring->reserved; struct nfe_desc32 *desc32; struct nfe_desc64 *desc64; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) NFE_LOCK(sc); /* XXX check sync modes */ bus_dmamap_sync(sc->rxq.rx_desc_tag, sc->rxq.rx_desc_map, BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE); /* * Import newly received packets into the netmap ring. * j is an index in the netmap ring, l in the NIC ring. */ l = sc->rxq.cur; j = netmap_idx_n2k(kring, l); if (netmap_no_pendintr || force_update) { uint16_t flags, len; uint16_t slot_flags = kring->nkr_slot_flags; for (n = 0; ; n++) { if (sc->nfe_flags & NFE_40BIT_ADDR) { desc64 = &sc->rxq.desc64[sc->rxq.cur]; flags = le16toh(desc64->flags); len = le16toh(desc64->length) & NFE_RX_LEN_MASK; } else { desc32 = &sc->rxq.desc32[sc->rxq.cur]; flags = le16toh(desc32->flags); len = le16toh(desc32->length) & NFE_RX_LEN_MASK; } if (flags & NFE_RX_READY) break; ring->slot[j].len = len; ring->slot[j].flags = slot_flags; bus_dmamap_sync(sc->rxq.rx_data_tag, sc->rxq.data[l].rx_data_map, BUS_DMASYNC_POSTREAD); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } if (n) { /* update the state variables */ sc->rxq.cur = l; kring->nr_hwavail += n; } kring->nr_kflags &= ~NKR_PENDINTR; } /* skip past packets that userspace has released */ j = kring->nr_hwcur; /* netmap ring index */ if (resvd > 0) { if (resvd + ring->avail >= lim + 1) { D("XXX invalid reserve/avail %d %d", resvd, ring->avail); ring->reserved = resvd = 0; // XXX panic... } k = (k >= resvd) ? k - resvd : k + lim + 1 - resvd; } if (j != k) { /* userspace has released some packets. */ l = netmap_idx_k2n(kring, j); /* NIC ring index */ for (n = 0; j != k; n++) { struct netmap_slot *slot = &ring->slot[j]; uint64_t paddr; void *addr = PNMB(slot, &paddr); if (addr == netmap_buffer_base) { /* bad buf */ if (do_lock) NFE_UNLOCK(sc); return netmap_ring_reinit(kring); } if (slot->flags & NS_BUF_CHANGED) { /* buffer has changed, reload map */ netmap_reload_map(sc->rxq.rx_data_tag, sc->rxq.data[l].rx_data_map, addr); slot->flags &= ~NS_BUF_CHANGED; } if (sc->nfe_flags & NFE_40BIT_ADDR) { desc64 = &sc->rxq.desc64[l]; desc64->physaddr[0] = htole32(NFE_ADDR_HI(paddr)); desc64->physaddr[1] = htole32(NFE_ADDR_LO(paddr)); desc64->length = htole16(NETMAP_BUF_SIZE); desc64->flags = htole16(NFE_RX_READY); } else { desc32 = &sc->rxq.desc32[l]; desc32->physaddr = htole32(NFE_ADDR_LO(paddr)); desc32->length = htole16(NETMAP_BUF_SIZE); desc32->flags = htole16(NFE_RX_READY); } bus_dmamap_sync(sc->rxq.rx_data_tag, sc->rxq.data[l].rx_data_map, BUS_DMASYNC_PREREAD); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwavail -= n; kring->nr_hwcur = k; bus_dmamap_sync(sc->rxq.rx_desc_tag, sc->rxq.rx_desc_map, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE); } /* tell userspace that there are new packets */ ring->avail = kring->nr_hwavail - resvd; if (do_lock) NFE_UNLOCK(sc); return 0; } static void nfe_netmap_attach(struct nfe_softc *sc) { struct netmap_adapter na; bzero(&na, sizeof(na)); na.ifp = sc->nfe_ifp; na.separate_locks = 0; na.num_tx_desc = NFE_TX_RING_COUNT; na.num_rx_desc = NFE_RX_RING_COUNT; na.nm_txsync = nfe_netmap_txsync; na.nm_rxsync = nfe_netmap_rxsync; na.nm_lock = nfe_netmap_lock_wrapper; na.nm_register = nfe_netmap_reg; netmap_attach(&na, 1); } /* end of file */ netmap-release/sys/dev/netmap/netmap_mem2.c000644 000423 000000 00000066704 12077774155 021502 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2012 Matteo Landi, Luigi Rizzo, Giuseppe Lettieri. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $FreeBSD: head/sys/dev/netmap/netmap_mem2.c 234290 2012-04-14 16:44:18Z luigi $ * $Id: netmap_mem2.c 12010 2013-01-23 03:57:30Z luigi $ * * (New) memory allocator for netmap */ /* * This allocator creates three memory regions: * nm_if_pool for the struct netmap_if * nm_ring_pool for the struct netmap_ring * nm_buf_pool for the packet buffers. * * All regions need to be multiple of a page size as we export them to * userspace through mmap. Only the latter needs to be dma-able, * but for convenience use the same type of allocator for all. * * Once mapped, the three regions are exported to userspace * as a contiguous block, starting from nm_if_pool. Each * cluster (and pool) is an integral number of pages. * [ . . . ][ . . . . . .][ . . . . . . . . . .] * nm_if nm_ring nm_buf * * The userspace areas contain offsets of the objects in userspace. * When (at init time) we write these offsets, we find out the index * of the object, and from there locate the offset from the beginning * of the region. * * The invididual allocators manage a pool of memory for objects of * the same size. * The pool is split into smaller clusters, whose size is a * multiple of the page size. The cluster size is chosen * to minimize the waste for a given max cluster size * (we do it by brute force, as we have relatively few object * per cluster). * * Objects are aligned to the cache line (64 bytes) rounding up object * sizes when needed. A bitmap contains the state of each object. * Allocation scans the bitmap; this is done only on attach, so we are not * too worried about performance * * For each allocator we can define (thorugh sysctl) the size and * number of each object. Memory is allocated at the first use of a * netmap file descriptor, and can be freed when all such descriptors * have been released (including unmapping the memory). * If memory is scarce, the system tries to get as much as possible * and the sysctl values reflect the actual allocation. * Together with desired values, the sysctl export also absolute * min and maximum values that cannot be overridden. * * struct netmap_if: * variable size, max 16 bytes per ring pair plus some fixed amount. * 1024 bytes should be large enough in practice. * * In the worst case we have one netmap_if per ring in the system. * * struct netmap_ring * variable too, 8 byte per slot plus some fixed amount. * Rings can be large (e.g. 4k slots, or >32Kbytes). * We default to 36 KB (9 pages), and a few hundred rings. * * struct netmap_buffer * The more the better, both because fast interfaces tend to have * many slots, and because we may want to use buffers to store * packets in userspace avoiding copies. * Must contain a full frame (eg 1518, or more for vlans, jumbo * frames etc.) plus be nicely aligned, plus some NICs restrict * the size to multiple of 1K or so. Default to 2K */ #ifndef CONSERVATIVE #define NETMAP_BUF_MAX_NUM 20*4096*2 /* large machine */ #else /* CONSERVATIVE */ #define NETMAP_BUF_MAX_NUM 20000 /* 40MB */ #endif #ifdef linux #define NMA_LOCK_T struct semaphore #define NMA_LOCK_INIT() sema_init(&nm_mem.nm_mtx, 1) #define NMA_LOCK_DESTROY() #define NMA_LOCK() down(&nm_mem.nm_mtx) #define NMA_UNLOCK() up(&nm_mem.nm_mtx) #else /* !linux */ #define NMA_LOCK_T struct mtx #define NMA_LOCK_INIT() mtx_init(&nm_mem.nm_mtx, "netmap memory allocator lock", NULL, MTX_DEF) #define NMA_LOCK_DESTROY() mtx_destroy(&nm_mem.nm_mtx) #define NMA_LOCK() mtx_lock(&nm_mem.nm_mtx) #define NMA_UNLOCK() mtx_unlock(&nm_mem.nm_mtx) #endif /* linux */ enum { NETMAP_IF_POOL = 0, NETMAP_RING_POOL, NETMAP_BUF_POOL, NETMAP_POOLS_NR }; struct netmap_obj_params { u_int size; u_int num; }; struct netmap_obj_params netmap_params[NETMAP_POOLS_NR] = { [NETMAP_IF_POOL] = { .size = 1024, .num = 100, }, [NETMAP_RING_POOL] = { .size = 9*PAGE_SIZE, .num = 200, }, [NETMAP_BUF_POOL] = { .size = 2048, .num = NETMAP_BUF_MAX_NUM, }, }; struct netmap_obj_pool { char name[16]; /* name of the allocator */ u_int objtotal; /* actual total number of objects. */ u_int objfree; /* number of free objects. */ u_int clustentries; /* actual objects per cluster */ /* limits */ u_int objminsize; /* minimum object size */ u_int objmaxsize; /* maximum object size */ u_int nummin; /* minimum number of objects */ u_int nummax; /* maximum number of objects */ /* the total memory space is _numclusters*_clustsize */ u_int _numclusters; /* how many clusters */ u_int _clustsize; /* cluster size */ u_int _objsize; /* actual object size */ u_int _memtotal; /* _numclusters*_clustsize */ struct lut_entry *lut; /* virt,phys addresses, objtotal entries */ uint32_t *bitmap; /* one bit per buffer, 1 means free */ uint32_t bitmap_slots; /* number of uint32 entries in bitmap */ }; struct netmap_mem_d { NMA_LOCK_T nm_mtx; /* protect the allocator */ u_int nm_totalsize; /* shorthand */ int finalized; /* !=0 iff preallocation done */ int lasterr; /* last error for curr config */ int refcount; /* existing priv structures */ /* the three allocators */ struct netmap_obj_pool pools[NETMAP_POOLS_NR]; }; static struct netmap_mem_d nm_mem = { /* Our memory allocator. */ .pools = { [NETMAP_IF_POOL] = { .name = "netmap_if", .objminsize = sizeof(struct netmap_if), .objmaxsize = 4096, .nummin = 10, /* don't be stingy */ .nummax = 10000, /* XXX very large */ }, [NETMAP_RING_POOL] = { .name = "netmap_ring", .objminsize = sizeof(struct netmap_ring), .objmaxsize = 32*PAGE_SIZE, .nummin = 2, .nummax = 1024, }, [NETMAP_BUF_POOL] = { .name = "netmap_buf", .objminsize = 64, .objmaxsize = 65536, .nummin = 4, .nummax = 1000000, /* one million! */ }, }, }; struct lut_entry *netmap_buffer_lut; /* exported */ /* memory allocator related sysctls */ #define STRINGIFY(x) #x #define DECLARE_SYSCTLS(id, name) \ /* TUNABLE_INT("hw.netmap." STRINGIFY(name) "_size", &netmap_params[id].size); */ \ SYSCTL_INT(_dev_netmap, OID_AUTO, name##_size, \ CTLFLAG_RW, &netmap_params[id].size, 0, "Requested size of netmap " STRINGIFY(name) "s"); \ SYSCTL_INT(_dev_netmap, OID_AUTO, name##_curr_size, \ CTLFLAG_RD, &nm_mem.pools[id]._objsize, 0, "Current size of netmap " STRINGIFY(name) "s"); \ /* TUNABLE_INT("hw.netmap." STRINGIFY(name) "_num", &netmap_params[id].num); */ \ SYSCTL_INT(_dev_netmap, OID_AUTO, name##_num, \ CTLFLAG_RW, &netmap_params[id].num, 0, "Requested number of netmap " STRINGIFY(name) "s"); \ SYSCTL_INT(_dev_netmap, OID_AUTO, name##_curr_num, \ CTLFLAG_RD, &nm_mem.pools[id].objtotal, 0, "Current number of netmap " STRINGIFY(name) "s") DECLARE_SYSCTLS(NETMAP_IF_POOL, if); DECLARE_SYSCTLS(NETMAP_RING_POOL, ring); DECLARE_SYSCTLS(NETMAP_BUF_POOL, buf); /* * Convert a userspace offset to a phisical address. * XXX re-do in a simpler way. * * The idea here is to hide userspace applications the fact that pre-allocated * memory is not contiguous, but fragmented across different clusters and * smaller memory allocators. Consequently, first of all we need to find which * allocator is owning provided offset, then we need to find out the physical * address associated to target page (this is done using the look-up table. */ static inline vm_paddr_t netmap_ofstophys(vm_offset_t offset) { int i; vm_offset_t o = offset; struct netmap_obj_pool *p = nm_mem.pools; for (i = 0; i < NETMAP_POOLS_NR; offset -= p[i]._memtotal, i++) { if (offset >= p[i]._memtotal) continue; // XXX now scan the clusters return p[i].lut[offset / p[i]._objsize].paddr + offset % p[i]._objsize; } /* this is only in case of errors */ D("invalid ofs 0x%x out of 0x%x 0x%x 0x%x", (u_int)o, p[NETMAP_IF_POOL]._memtotal, p[NETMAP_IF_POOL]._memtotal + p[NETMAP_RING_POOL]._memtotal, p[NETMAP_IF_POOL]._memtotal + p[NETMAP_RING_POOL]._memtotal + p[NETMAP_BUF_POOL]._memtotal); return 0; // XXX bad address } /* * we store objects by kernel address, need to find the offset * within the pool to export the value to userspace. * Algorithm: scan until we find the cluster, then add the * actual offset in the cluster */ static ssize_t netmap_obj_offset(struct netmap_obj_pool *p, const void *vaddr) { int i, k = p->clustentries, n = p->objtotal; ssize_t ofs = 0; for (i = 0; i < n; i += k, ofs += p->_clustsize) { const char *base = p->lut[i].vaddr; ssize_t relofs = (const char *) vaddr - base; if (relofs < 0 || relofs > p->_clustsize) continue; ofs = ofs + relofs; ND("%s: return offset %d (cluster %d) for pointer %p", p->name, ofs, i, vaddr); return ofs; } D("address %p is not contained inside any cluster (%s)", vaddr, p->name); return 0; /* An error occurred */ } /* Helper functions which convert virtual addresses to offsets */ #define netmap_if_offset(v) \ netmap_obj_offset(&nm_mem.pools[NETMAP_IF_POOL], (v)) #define netmap_ring_offset(v) \ (nm_mem.pools[NETMAP_IF_POOL]._memtotal + \ netmap_obj_offset(&nm_mem.pools[NETMAP_RING_POOL], (v))) #define netmap_buf_offset(v) \ (nm_mem.pools[NETMAP_IF_POOL]._memtotal + \ nm_mem.pools[NETMAP_RING_POOL]._memtotal + \ netmap_obj_offset(&nm_mem.pools[NETMAP_BUF_POOL], (v))) /* * report the index, and use start position as a hint, * otherwise buffer allocation becomes terribly expensive. */ static void * netmap_obj_malloc(struct netmap_obj_pool *p, int len, uint32_t *start, uint32_t *index) { uint32_t i = 0; /* index in the bitmap */ uint32_t mask, j; /* slot counter */ void *vaddr = NULL; if (len > p->_objsize) { D("%s request size %d too large", p->name, len); // XXX cannot reduce the size return NULL; } if (p->objfree == 0) { D("%s allocator: run out of memory", p->name); return NULL; } if (start) i = *start; /* termination is guaranteed by p->free, but better check bounds on i */ while (vaddr == NULL && i < p->bitmap_slots) { uint32_t cur = p->bitmap[i]; if (cur == 0) { /* bitmask is fully used */ i++; continue; } /* locate a slot */ for (j = 0, mask = 1; (cur & mask) == 0; j++, mask <<= 1) ; p->bitmap[i] &= ~mask; /* mark object as in use */ p->objfree--; vaddr = p->lut[i * 32 + j].vaddr; if (index) *index = i * 32 + j; } ND("%s allocator: allocated object @ [%d][%d]: vaddr %p", i, j, vaddr); if (start) *start = i; return vaddr; } /* * free by index, not by address */ static void netmap_obj_free(struct netmap_obj_pool *p, uint32_t j) { if (j >= p->objtotal) { D("invalid index %u, max %u", j, p->objtotal); return; } p->bitmap[j / 32] |= (1 << (j % 32)); p->objfree++; return; } static void netmap_obj_free_va(struct netmap_obj_pool *p, void *vaddr) { int i, j, n = p->_memtotal / p->_clustsize; for (i = 0, j = 0; i < n; i++, j += p->clustentries) { void *base = p->lut[i * p->clustentries].vaddr; ssize_t relofs = (ssize_t) vaddr - (ssize_t) base; /* Given address, is out of the scope of the current cluster.*/ if (vaddr < base || relofs > p->_clustsize) continue; j = j + relofs / p->_objsize; KASSERT(j != 0, ("Cannot free object 0")); netmap_obj_free(p, j); return; } D("address %p is not contained inside any cluster (%s)", vaddr, p->name); } #define netmap_if_malloc(len) netmap_obj_malloc(&nm_mem.pools[NETMAP_IF_POOL], len, NULL, NULL) #define netmap_if_free(v) netmap_obj_free_va(&nm_mem.pools[NETMAP_IF_POOL], (v)) #define netmap_ring_malloc(len) netmap_obj_malloc(&nm_mem.pools[NETMAP_RING_POOL], len, NULL, NULL) #define netmap_ring_free(v) netmap_obj_free_va(&nm_mem.pools[NETMAP_RING_POOL], (v)) #define netmap_buf_malloc(_pos, _index) \ netmap_obj_malloc(&nm_mem.pools[NETMAP_BUF_POOL], NETMAP_BUF_SIZE, _pos, _index) /* Return the index associated to the given packet buffer */ #define netmap_buf_index(v) \ (netmap_obj_offset(&nm_mem.pools[NETMAP_BUF_POOL], (v)) / nm_mem.pools[NETMAP_BUF_POOL]._objsize) /* Return nonzero on error */ static int netmap_new_bufs(struct netmap_if *nifp, struct netmap_slot *slot, u_int n) { struct netmap_obj_pool *p = &nm_mem.pools[NETMAP_BUF_POOL]; int i = 0; /* slot counter */ uint32_t pos = 0; /* slot in p->bitmap */ uint32_t index = 0; /* buffer index */ (void)nifp; /* UNUSED */ for (i = 0; i < n; i++) { void *vaddr = netmap_buf_malloc(&pos, &index); if (vaddr == NULL) { D("unable to locate empty packet buffer"); goto cleanup; } slot[i].buf_idx = index; slot[i].len = p->_objsize; /* XXX setting flags=NS_BUF_CHANGED forces a pointer reload * in the NIC ring. This is a hack that hides missing * initializations in the drivers, and should go away. */ slot[i].flags = NS_BUF_CHANGED; } ND("allocated %d buffers, %d available, first at %d", n, p->objfree, pos); return (0); cleanup: while (i > 0) { i--; netmap_obj_free(p, slot[i].buf_idx); } bzero(slot, n * sizeof(slot[0])); return (ENOMEM); } static void netmap_free_buf(struct netmap_if *nifp, uint32_t i) { struct netmap_obj_pool *p = &nm_mem.pools[NETMAP_BUF_POOL]; if (i < 2 || i >= p->objtotal) { D("Cannot free buf#%d: should be in [2, %d[", i, p->objtotal); return; } netmap_obj_free(p, i); } static void netmap_reset_obj_allocator(struct netmap_obj_pool *p) { if (p == NULL) return; if (p->bitmap) free(p->bitmap, M_NETMAP); p->bitmap = NULL; if (p->lut) { int i; for (i = 0; i < p->objtotal; i += p->clustentries) { if (p->lut[i].vaddr) contigfree(p->lut[i].vaddr, p->_clustsize, M_NETMAP); } bzero(p->lut, sizeof(struct lut_entry) * p->objtotal); #ifdef linux vfree(p->lut); #else free(p->lut, M_NETMAP); #endif } p->lut = NULL; } /* * Free all resources related to an allocator. */ static void netmap_destroy_obj_allocator(struct netmap_obj_pool *p) { if (p == NULL) return; netmap_reset_obj_allocator(p); } /* * We receive a request for objtotal objects, of size objsize each. * Internally we may round up both numbers, as we allocate objects * in small clusters multiple of the page size. * In the allocator we don't need to store the objsize, * but we do need to keep track of objtotal' and clustentries, * as they are needed when freeing memory. * * XXX note -- userspace needs the buffers to be contiguous, * so we cannot afford gaps at the end of a cluster. */ /* call with NMA_LOCK held */ static int netmap_config_obj_allocator(struct netmap_obj_pool *p, u_int objtotal, u_int objsize) { int i, n; u_int clustsize; /* the cluster size, multiple of page size */ u_int clustentries; /* how many objects per entry */ #define MAX_CLUSTSIZE (1<<17) #define LINE_ROUND 64 if (objsize >= MAX_CLUSTSIZE) { /* we could do it but there is no point */ D("unsupported allocation for %d bytes", objsize); goto error; } /* make sure objsize is a multiple of LINE_ROUND */ i = (objsize & (LINE_ROUND - 1)); if (i) { D("XXX aligning object by %d bytes", LINE_ROUND - i); objsize += LINE_ROUND - i; } if (objsize < p->objminsize || objsize > p->objmaxsize) { D("requested objsize %d out of range [%d, %d]", objsize, p->objminsize, p->objmaxsize); goto error; } if (objtotal < p->nummin || objtotal > p->nummax) { D("requested objtotal %d out of range [%d, %d]", objtotal, p->nummin, p->nummax); goto error; } /* * Compute number of objects using a brute-force approach: * given a max cluster size, * we try to fill it with objects keeping track of the * wasted space to the next page boundary. */ for (clustentries = 0, i = 1;; i++) { u_int delta, used = i * objsize; if (used > MAX_CLUSTSIZE) break; delta = used % PAGE_SIZE; if (delta == 0) { // exact solution clustentries = i; break; } if (delta > ( (clustentries*objsize) % PAGE_SIZE) ) clustentries = i; } // D("XXX --- ouch, delta %d (bad for buffers)", delta); /* compute clustsize and round to the next page */ clustsize = clustentries * objsize; i = (clustsize & (PAGE_SIZE - 1)); if (i) clustsize += PAGE_SIZE - i; if (netmap_verbose) D("objsize %d clustsize %d objects %d", objsize, clustsize, clustentries); /* * The number of clusters is n = ceil(objtotal/clustentries) * objtotal' = n * clustentries */ p->clustentries = clustentries; p->_clustsize = clustsize; n = (objtotal + clustentries - 1) / clustentries; p->_numclusters = n; p->objtotal = n * clustentries; p->objfree = p->objtotal - 2; /* obj 0 and 1 are reserved */ p->_memtotal = p->_numclusters * p->_clustsize; p->_objsize = objsize; return 0; error: p->_objsize = objsize; p->objtotal = objtotal; return EINVAL; } /* call with NMA_LOCK held */ static int netmap_finalize_obj_allocator(struct netmap_obj_pool *p) { int i, n; n = sizeof(struct lut_entry) * p->objtotal; #ifdef linux p->lut = vmalloc(n); #else p->lut = malloc(n, M_NETMAP, M_NOWAIT | M_ZERO); #endif if (p->lut == NULL) { D("Unable to create lookup table (%d bytes) for '%s'", n, p->name); goto clean; } /* Allocate the bitmap */ n = (p->objtotal + 31) / 32; p->bitmap = malloc(sizeof(uint32_t) * n, M_NETMAP, M_NOWAIT | M_ZERO); if (p->bitmap == NULL) { D("Unable to create bitmap (%d entries) for allocator '%s'", n, p->name); goto clean; } p->bitmap_slots = n; /* * Allocate clusters, init pointers and bitmap */ for (i = 0; i < p->objtotal;) { int lim = i + p->clustentries; char *clust; clust = contigmalloc(p->_clustsize, M_NETMAP, M_NOWAIT | M_ZERO, 0, -1UL, PAGE_SIZE, 0); if (clust == NULL) { /* * If we get here, there is a severe memory shortage, * so halve the allocated memory to reclaim some. * XXX check boundaries */ D("Unable to create cluster at %d for '%s' allocator", i, p->name); lim = i / 2; for (i--; i >= lim; i--) { p->bitmap[ (i>>5) ] &= ~( 1 << (i & 31) ); if (i % p->clustentries == 0 && p->lut[i].vaddr) contigfree(p->lut[i].vaddr, p->_clustsize, M_NETMAP); } p->objtotal = i; p->objfree = p->objtotal - 2; p->_numclusters = i / p->clustentries; p->_memtotal = p->_numclusters * p->_clustsize; break; } for (; i < lim; i++, clust += p->_objsize) { p->bitmap[ (i>>5) ] |= ( 1 << (i & 31) ); p->lut[i].vaddr = clust; p->lut[i].paddr = vtophys(clust); } } p->bitmap[0] = ~3; /* objs 0 and 1 is always busy */ if (netmap_verbose) D("Pre-allocated %d clusters (%d/%dKB) for '%s'", p->_numclusters, p->_clustsize >> 10, p->_memtotal >> 10, p->name); return 0; clean: netmap_reset_obj_allocator(p); return ENOMEM; } /* call with lock held */ static int netmap_memory_config_changed(void) { int i; for (i = 0; i < NETMAP_POOLS_NR; i++) { if (nm_mem.pools[i]._objsize != netmap_params[i].size || nm_mem.pools[i].objtotal != netmap_params[i].num) return 1; } return 0; } /* call with lock held */ static int netmap_memory_config(void) { int i; if (!netmap_memory_config_changed()) goto out; D("reconfiguring"); if (nm_mem.finalized) { /* reset previous allocation */ for (i = 0; i < NETMAP_POOLS_NR; i++) { netmap_reset_obj_allocator(&nm_mem.pools[i]); } nm_mem.finalized = 0; } for (i = 0; i < NETMAP_POOLS_NR; i++) { nm_mem.lasterr = netmap_config_obj_allocator(&nm_mem.pools[i], netmap_params[i].num, netmap_params[i].size); if (nm_mem.lasterr) goto out; } D("Have %d KB for interfaces, %d KB for rings and %d MB for buffers", nm_mem.pools[NETMAP_IF_POOL]._memtotal >> 10, nm_mem.pools[NETMAP_RING_POOL]._memtotal >> 10, nm_mem.pools[NETMAP_BUF_POOL]._memtotal >> 20); out: return nm_mem.lasterr; } /* call with lock held */ static int netmap_memory_finalize(void) { int i; u_int totalsize = 0; nm_mem.refcount++; if (nm_mem.refcount > 1) { ND("busy (refcount %d)", nm_mem.refcount); goto out; } /* update configuration if changed */ if (netmap_memory_config()) goto out; if (nm_mem.finalized) { /* may happen if config is not changed */ ND("nothing to do"); goto out; } for (i = 0; i < NETMAP_POOLS_NR; i++) { nm_mem.lasterr = netmap_finalize_obj_allocator(&nm_mem.pools[i]); if (nm_mem.lasterr) goto cleanup; totalsize += nm_mem.pools[i]._memtotal; } nm_mem.nm_totalsize = totalsize; /* backward compatibility */ netmap_buf_size = nm_mem.pools[NETMAP_BUF_POOL]._objsize; netmap_total_buffers = nm_mem.pools[NETMAP_BUF_POOL].objtotal; netmap_buffer_lut = nm_mem.pools[NETMAP_BUF_POOL].lut; netmap_buffer_base = nm_mem.pools[NETMAP_BUF_POOL].lut[0].vaddr; nm_mem.finalized = 1; nm_mem.lasterr = 0; /* make sysctl values match actual values in the pools */ for (i = 0; i < NETMAP_POOLS_NR; i++) { netmap_params[i].size = nm_mem.pools[i]._objsize; netmap_params[i].num = nm_mem.pools[i].objtotal; } out: if (nm_mem.lasterr) nm_mem.refcount--; return nm_mem.lasterr; cleanup: for (i = 0; i < NETMAP_POOLS_NR; i++) { netmap_reset_obj_allocator(&nm_mem.pools[i]); } nm_mem.refcount--; return nm_mem.lasterr; } static int netmap_memory_init(void) { NMA_LOCK_INIT(); return (0); } static void netmap_memory_fini(void) { int i; for (i = 0; i < NETMAP_POOLS_NR; i++) { netmap_destroy_obj_allocator(&nm_mem.pools[i]); } NMA_LOCK_DESTROY(); } static void netmap_free_rings(struct netmap_adapter *na) { int i; if (!na->tx_rings) return; for (i = 0; i < na->num_tx_rings + 1; i++) { netmap_ring_free(na->tx_rings[i].ring); na->tx_rings[i].ring = NULL; } for (i = 0; i < na->num_rx_rings + 1; i++) { netmap_ring_free(na->rx_rings[i].ring); na->rx_rings[i].ring = NULL; } free(na->tx_rings, M_DEVBUF); na->tx_rings = na->rx_rings = NULL; } /* call with NMA_LOCK held */ /* * Allocate the per-fd structure netmap_if. * If this is the first instance, also allocate the krings, rings etc. */ static void * netmap_if_new(const char *ifname, struct netmap_adapter *na) { struct netmap_if *nifp; struct netmap_ring *ring; ssize_t base; /* handy for relative offsets between rings and nifp */ u_int i, len, ndesc, ntx, nrx; struct netmap_kring *kring; if (netmap_update_config(na)) { /* configuration mismatch, report and fail */ return NULL; } ntx = na->num_tx_rings + 1; /* shorthand, include stack ring */ nrx = na->num_rx_rings + 1; /* shorthand, include stack ring */ /* * the descriptor is followed inline by an array of offsets * to the tx and rx rings in the shared memory region. */ len = sizeof(struct netmap_if) + (nrx + ntx) * sizeof(ssize_t); nifp = netmap_if_malloc(len); if (nifp == NULL) { return NULL; } /* initialize base fields -- override const */ *(int *)(uintptr_t)&nifp->ni_tx_rings = na->num_tx_rings; *(int *)(uintptr_t)&nifp->ni_rx_rings = na->num_rx_rings; strncpy(nifp->ni_name, ifname, IFNAMSIZ); (na->refcount)++; /* XXX atomic ? we are under lock */ if (na->refcount > 1) { /* already setup, we are done */ goto final; } len = (ntx + nrx) * sizeof(struct netmap_kring); na->tx_rings = malloc(len, M_DEVBUF, M_NOWAIT | M_ZERO); if (na->tx_rings == NULL) { D("Cannot allocate krings for %s", ifname); goto cleanup; } na->rx_rings = na->tx_rings + ntx; /* * First instance, allocate netmap rings and buffers for this card * The rings are contiguous, but have variable size. */ for (i = 0; i < ntx; i++) { /* Transmit rings */ kring = &na->tx_rings[i]; ndesc = na->num_tx_desc; bzero(kring, sizeof(*kring)); len = sizeof(struct netmap_ring) + ndesc * sizeof(struct netmap_slot); ring = netmap_ring_malloc(len); if (ring == NULL) { D("Cannot allocate tx_ring[%d] for %s", i, ifname); goto cleanup; } ND("txring[%d] at %p ofs %d", i, ring); kring->na = na; kring->ring = ring; *(int *)(uintptr_t)&ring->num_slots = kring->nkr_num_slots = ndesc; *(ssize_t *)(uintptr_t)&ring->buf_ofs = (nm_mem.pools[NETMAP_IF_POOL]._memtotal + nm_mem.pools[NETMAP_RING_POOL]._memtotal) - netmap_ring_offset(ring); /* * IMPORTANT: * Always keep one slot empty, so we can detect new * transmissions comparing cur and nr_hwcur (they are * the same only if there are no new transmissions). */ ring->avail = kring->nr_hwavail = ndesc - 1; ring->cur = kring->nr_hwcur = 0; *(int *)(uintptr_t)&ring->nr_buf_size = NETMAP_BUF_SIZE; ND("initializing slots for txring[%d]", i); if (netmap_new_bufs(nifp, ring->slot, ndesc)) { D("Cannot allocate buffers for tx_ring[%d] for %s", i, ifname); goto cleanup; } } for (i = 0; i < nrx; i++) { /* Receive rings */ kring = &na->rx_rings[i]; ndesc = na->num_rx_desc; bzero(kring, sizeof(*kring)); len = sizeof(struct netmap_ring) + ndesc * sizeof(struct netmap_slot); ring = netmap_ring_malloc(len); if (ring == NULL) { D("Cannot allocate rx_ring[%d] for %s", i, ifname); goto cleanup; } ND("rxring[%d] at %p ofs %d", i, ring); kring->na = na; kring->ring = ring; *(int *)(uintptr_t)&ring->num_slots = kring->nkr_num_slots = ndesc; *(ssize_t *)(uintptr_t)&ring->buf_ofs = (nm_mem.pools[NETMAP_IF_POOL]._memtotal + nm_mem.pools[NETMAP_RING_POOL]._memtotal) - netmap_ring_offset(ring); ring->cur = kring->nr_hwcur = 0; ring->avail = kring->nr_hwavail = 0; /* empty */ *(int *)(uintptr_t)&ring->nr_buf_size = NETMAP_BUF_SIZE; ND("initializing slots for rxring[%d]", i); if (netmap_new_bufs(nifp, ring->slot, ndesc)) { D("Cannot allocate buffers for rx_ring[%d] for %s", i, ifname); goto cleanup; } } #ifdef linux // XXX initialize the selrecord structs. for (i = 0; i < ntx; i++) init_waitqueue_head(&na->tx_rings[i].si); for (i = 0; i < nrx; i++) init_waitqueue_head(&na->rx_rings[i].si); init_waitqueue_head(&na->tx_si); init_waitqueue_head(&na->rx_si); #endif final: /* * fill the slots for the rx and tx rings. They contain the offset * between the ring and nifp, so the information is usable in * userspace to reach the ring from the nifp. */ base = netmap_if_offset(nifp); for (i = 0; i < ntx; i++) { *(ssize_t *)(uintptr_t)&nifp->ring_ofs[i] = netmap_ring_offset(na->tx_rings[i].ring) - base; } for (i = 0; i < nrx; i++) { *(ssize_t *)(uintptr_t)&nifp->ring_ofs[i+ntx] = netmap_ring_offset(na->rx_rings[i].ring) - base; } return (nifp); cleanup: netmap_free_rings(na); netmap_if_free(nifp); (na->refcount)--; return NULL; } /* call with NMA_LOCK held */ static void netmap_memory_deref(void) { nm_mem.refcount--; if (netmap_verbose) D("refcount = %d", nm_mem.refcount); } netmap-release/sys/dev/netmap/netmap_mem1.c000644 000423 000000 00000037104 11741654023 021455 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2011 Matteo Landi, Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $FreeBSD: head/sys/dev/netmap/netmap_mem1.c 234174 2012-04-12 11:27:09Z luigi $ * * The original netmap memory allocator, using a single large * chunk of memory allocated with contigmalloc. */ /* * Default amount of memory pre-allocated by the module. * We start with a large size and then shrink our demand * according to what is avalable when the module is loaded. */ #define NETMAP_MEMORY_SIZE (64 * 1024 * PAGE_SIZE) static void * netmap_malloc(size_t size, const char *msg); static void netmap_free(void *addr, const char *msg); #define netmap_if_malloc(len) netmap_malloc(len, "nifp") #define netmap_if_free(v) netmap_free((v), "nifp") #define netmap_ring_malloc(len) netmap_malloc(len, "ring") #define netmap_free_rings(na) \ netmap_free((na)->tx_rings[0].ring, "shadow rings"); /* * Allocator for a pool of packet buffers. For each buffer we have * one entry in the bitmap to signal the state. Allocation scans * the bitmap, but since this is done only on attach, we are not * too worried about performance * XXX if we need to allocate small blocks, a translation * table is used both for kernel virtual address and physical * addresses. */ struct netmap_buf_pool { u_int total_buffers; /* total buffers. */ u_int free; u_int bufsize; char *base; /* buffer base address */ uint32_t *bitmap; /* one bit per buffer, 1 means free */ }; struct netmap_buf_pool nm_buf_pool; SYSCTL_INT(_dev_netmap, OID_AUTO, total_buffers, CTLFLAG_RD, &nm_buf_pool.total_buffers, 0, "total_buffers"); SYSCTL_INT(_dev_netmap, OID_AUTO, free_buffers, CTLFLAG_RD, &nm_buf_pool.free, 0, "free_buffers"); /* * Allocate n buffers from the ring, and fill the slot. * Buffer 0 is the 'junk' buffer. */ static void netmap_new_bufs(struct netmap_if *nifp __unused, struct netmap_slot *slot, u_int n) { struct netmap_buf_pool *p = &nm_buf_pool; uint32_t bi = 0; /* index in the bitmap */ uint32_t mask, j, i = 0; /* slot counter */ if (n > p->free) { D("only %d out of %d buffers available", i, n); return; } /* termination is guaranteed by p->free */ while (i < n && p->free > 0) { uint32_t cur = p->bitmap[bi]; if (cur == 0) { /* bitmask is fully used */ bi++; continue; } /* locate a slot */ for (j = 0, mask = 1; (cur & mask) == 0; j++, mask <<= 1) ; p->bitmap[bi] &= ~mask; /* slot in use */ p->free--; slot[i].buf_idx = bi*32+j; slot[i].len = p->bufsize; slot[i].flags = NS_BUF_CHANGED; i++; } ND("allocated %d buffers, %d available", n, p->free); } static void netmap_free_buf(struct netmap_if *nifp __unused, uint32_t i) { struct netmap_buf_pool *p = &nm_buf_pool; uint32_t pos, mask; if (i >= p->total_buffers) { D("invalid free index %d", i); return; } pos = i / 32; mask = 1 << (i % 32); if (p->bitmap[pos] & mask) { D("slot %d already free", i); return; } p->bitmap[pos] |= mask; p->free++; } /* Descriptor of the memory objects handled by our memory allocator. */ struct netmap_mem_obj { TAILQ_ENTRY(netmap_mem_obj) nmo_next; /* next object in the chain. */ int nmo_used; /* flag set on used memory objects. */ size_t nmo_size; /* size of the memory area reserved for the object. */ void *nmo_data; /* pointer to the memory area. */ }; /* Wrap our memory objects to make them ``chainable``. */ TAILQ_HEAD(netmap_mem_obj_h, netmap_mem_obj); /* Descriptor of our custom memory allocator. */ struct netmap_mem_d { struct mtx nm_mtx; /* lock used to handle the chain of memory objects. */ struct netmap_mem_obj_h nm_molist; /* list of memory objects */ size_t nm_size; /* total amount of memory used for rings etc. */ size_t nm_totalsize; /* total amount of allocated memory (the difference is used for buffers) */ size_t nm_buf_start; /* offset of packet buffers. This is page-aligned. */ size_t nm_buf_len; /* total memory for buffers */ void *nm_buffer; /* pointer to the whole pre-allocated memory area. */ }; /* Shorthand to compute a netmap interface offset. */ #define netmap_if_offset(v) \ ((char *) (v) - (char *) nm_mem->nm_buffer) /* .. and get a physical address given a memory offset */ #define netmap_ofstophys(o) \ (vtophys(nm_mem->nm_buffer) + (o)) /*------ netmap memory allocator -------*/ /* * Request for a chunk of memory. * * Memory objects are arranged into a list, hence we need to walk this * list until we find an object with the needed amount of data free. * This sounds like a completely inefficient implementation, but given * the fact that data allocation is done once, we can handle it * flawlessly. * * Return NULL on failure. */ static void * netmap_malloc(size_t size, __unused const char *msg) { struct netmap_mem_obj *mem_obj, *new_mem_obj; void *ret = NULL; NMA_LOCK(); TAILQ_FOREACH(mem_obj, &nm_mem->nm_molist, nmo_next) { if (mem_obj->nmo_used != 0 || mem_obj->nmo_size < size) continue; new_mem_obj = malloc(sizeof(struct netmap_mem_obj), M_NETMAP, M_WAITOK | M_ZERO); TAILQ_INSERT_BEFORE(mem_obj, new_mem_obj, nmo_next); new_mem_obj->nmo_used = 1; new_mem_obj->nmo_size = size; new_mem_obj->nmo_data = mem_obj->nmo_data; memset(new_mem_obj->nmo_data, 0, new_mem_obj->nmo_size); mem_obj->nmo_size -= size; mem_obj->nmo_data = (char *) mem_obj->nmo_data + size; if (mem_obj->nmo_size == 0) { TAILQ_REMOVE(&nm_mem->nm_molist, mem_obj, nmo_next); free(mem_obj, M_NETMAP); } ret = new_mem_obj->nmo_data; break; } NMA_UNLOCK(); ND("%s: %d bytes at %p", msg, size, ret); return (ret); } /* * Return the memory to the allocator. * * While freeing a memory object, we try to merge adjacent chunks in * order to reduce memory fragmentation. */ static void netmap_free(void *addr, const char *msg) { size_t size; struct netmap_mem_obj *cur, *prev, *next; if (addr == NULL) { D("NULL addr for %s", msg); return; } NMA_LOCK(); TAILQ_FOREACH(cur, &nm_mem->nm_molist, nmo_next) { if (cur->nmo_data == addr && cur->nmo_used) break; } if (cur == NULL) { NMA_UNLOCK(); D("invalid addr %s %p", msg, addr); return; } size = cur->nmo_size; cur->nmo_used = 0; /* merge current chunk of memory with the previous one, if present. */ prev = TAILQ_PREV(cur, netmap_mem_obj_h, nmo_next); if (prev && prev->nmo_used == 0) { TAILQ_REMOVE(&nm_mem->nm_molist, cur, nmo_next); prev->nmo_size += cur->nmo_size; free(cur, M_NETMAP); cur = prev; } /* merge with the next one */ next = TAILQ_NEXT(cur, nmo_next); if (next && next->nmo_used == 0) { TAILQ_REMOVE(&nm_mem->nm_molist, next, nmo_next); cur->nmo_size += next->nmo_size; free(next, M_NETMAP); } NMA_UNLOCK(); ND("freed %s %d bytes at %p", msg, size, addr); } /* * Create and return a new ``netmap_if`` object, and possibly also * rings and packet buffors. * * Return NULL on failure. */ static void * netmap_if_new(const char *ifname, struct netmap_adapter *na) { struct netmap_if *nifp; struct netmap_ring *ring; struct netmap_kring *kring; char *buff; u_int i, len, ofs, numdesc; u_int nrx = na->num_rx_rings + 1; /* shorthand, include stack queue */ u_int ntx = na->num_tx_rings + 1; /* shorthand, include stack queue */ /* * the descriptor is followed inline by an array of offsets * to the tx and rx rings in the shared memory region. */ len = sizeof(struct netmap_if) + (nrx + ntx) * sizeof(ssize_t); nifp = netmap_if_malloc(len); if (nifp == NULL) return (NULL); /* initialize base fields */ *(int *)(uintptr_t)&nifp->ni_rx_rings = na->num_rx_rings; *(int *)(uintptr_t)&nifp->ni_tx_rings = na->num_tx_rings; strncpy(nifp->ni_name, ifname, IFNAMSIZ); (na->refcount)++; /* XXX atomic ? we are under lock */ if (na->refcount > 1) goto final; /* * First instance. Allocate the netmap rings * (one for each hw queue, one pair for the host). * The rings are contiguous, but have variable size. * The entire block is reachable at * na->tx_rings[0] */ len = (ntx + nrx) * sizeof(struct netmap_ring) + (ntx * na->num_tx_desc + nrx * na->num_rx_desc) * sizeof(struct netmap_slot); buff = netmap_ring_malloc(len); if (buff == NULL) { D("failed to allocate %d bytes for %s shadow ring", len, ifname); error: (na->refcount)--; netmap_if_free(nifp); return (NULL); } /* Check whether we have enough buffers */ len = ntx * na->num_tx_desc + nrx * na->num_rx_desc; NMA_LOCK(); if (nm_buf_pool.free < len) { NMA_UNLOCK(); netmap_free(buff, "not enough bufs"); goto error; } /* * in the kring, store the pointers to the shared rings * and initialize the rings. We are under NMA_LOCK(). */ ofs = 0; for (i = 0; i < ntx; i++) { /* Transmit rings */ kring = &na->tx_rings[i]; numdesc = na->num_tx_desc; bzero(kring, sizeof(*kring)); kring->na = na; ring = kring->ring = (struct netmap_ring *)(buff + ofs); *(ssize_t *)(uintptr_t)&ring->buf_ofs = nm_buf_pool.base - (char *)ring; ND("txring[%d] at %p ofs %d", i, ring, ring->buf_ofs); *(uint32_t *)(uintptr_t)&ring->num_slots = kring->nkr_num_slots = numdesc; /* * IMPORTANT: * Always keep one slot empty, so we can detect new * transmissions comparing cur and nr_hwcur (they are * the same only if there are no new transmissions). */ ring->avail = kring->nr_hwavail = numdesc - 1; ring->cur = kring->nr_hwcur = 0; *(uint16_t *)(uintptr_t)&ring->nr_buf_size = NETMAP_BUF_SIZE; netmap_new_bufs(nifp, ring->slot, numdesc); ofs += sizeof(struct netmap_ring) + numdesc * sizeof(struct netmap_slot); } for (i = 0; i < nrx; i++) { /* Receive rings */ kring = &na->rx_rings[i]; numdesc = na->num_rx_desc; bzero(kring, sizeof(*kring)); kring->na = na; ring = kring->ring = (struct netmap_ring *)(buff + ofs); *(ssize_t *)(uintptr_t)&ring->buf_ofs = nm_buf_pool.base - (char *)ring; ND("rxring[%d] at %p offset %d", i, ring, ring->buf_ofs); *(uint32_t *)(uintptr_t)&ring->num_slots = kring->nkr_num_slots = numdesc; ring->cur = kring->nr_hwcur = 0; ring->avail = kring->nr_hwavail = 0; /* empty */ *(uint16_t *)(uintptr_t)&ring->nr_buf_size = NETMAP_BUF_SIZE; netmap_new_bufs(nifp, ring->slot, numdesc); ofs += sizeof(struct netmap_ring) + numdesc * sizeof(struct netmap_slot); } NMA_UNLOCK(); // XXX initialize the selrecord structs. final: /* * fill the slots for the rx and tx queues. They contain the offset * between the ring and nifp, so the information is usable in * userspace to reach the ring from the nifp. */ for (i = 0; i < ntx; i++) { *(ssize_t *)(uintptr_t)&nifp->ring_ofs[i] = (char *)na->tx_rings[i].ring - (char *)nifp; } for (i = 0; i < nrx; i++) { *(ssize_t *)(uintptr_t)&nifp->ring_ofs[i+ntx] = (char *)na->rx_rings[i].ring - (char *)nifp; } return (nifp); } /* * Initialize the memory allocator. * * Create the descriptor for the memory , allocate the pool of memory * and initialize the list of memory objects with a single chunk * containing the whole pre-allocated memory marked as free. * * Start with a large size, then halve as needed if we fail to * allocate the block. While halving, always add one extra page * because buffers 0 and 1 are used for special purposes. * Return 0 on success, errno otherwise. */ static int netmap_memory_init(void) { struct netmap_mem_obj *mem_obj; void *buf = NULL; int i, n, sz = NETMAP_MEMORY_SIZE; int extra_sz = 0; // space for rings and two spare buffers for (; sz >= 1<<20; sz >>=1) { extra_sz = sz/200; extra_sz = (extra_sz + 2*PAGE_SIZE - 1) & ~(PAGE_SIZE-1); buf = contigmalloc(sz + extra_sz, M_NETMAP, M_WAITOK | M_ZERO, 0, /* low address */ -1UL, /* high address */ PAGE_SIZE, /* alignment */ 0 /* boundary */ ); if (buf) break; } if (buf == NULL) return (ENOMEM); sz += extra_sz; nm_mem = malloc(sizeof(struct netmap_mem_d), M_NETMAP, M_WAITOK | M_ZERO); mtx_init(&nm_mem->nm_mtx, "netmap memory allocator lock", NULL, MTX_DEF); TAILQ_INIT(&nm_mem->nm_molist); nm_mem->nm_buffer = buf; nm_mem->nm_totalsize = sz; /* * A buffer takes 2k, a slot takes 8 bytes + ring overhead, * so the ratio is 200:1. In other words, we can use 1/200 of * the memory for the rings, and the rest for the buffers, * and be sure we never run out. */ nm_mem->nm_size = sz/200; nm_mem->nm_buf_start = (nm_mem->nm_size + PAGE_SIZE - 1) & ~(PAGE_SIZE-1); nm_mem->nm_buf_len = sz - nm_mem->nm_buf_start; nm_buf_pool.base = nm_mem->nm_buffer; nm_buf_pool.base += nm_mem->nm_buf_start; netmap_buffer_base = nm_buf_pool.base; D("netmap_buffer_base %p (offset %d)", netmap_buffer_base, (int)nm_mem->nm_buf_start); /* number of buffers, they all start as free */ netmap_total_buffers = nm_buf_pool.total_buffers = nm_mem->nm_buf_len / NETMAP_BUF_SIZE; nm_buf_pool.bufsize = NETMAP_BUF_SIZE; D("Have %d MB, use %dKB for rings, %d buffers at %p", (sz >> 20), (int)(nm_mem->nm_size >> 10), nm_buf_pool.total_buffers, nm_buf_pool.base); /* allocate and initialize the bitmap. Entry 0 is considered * always busy (used as default when there are no buffers left). */ n = (nm_buf_pool.total_buffers + 31) / 32; nm_buf_pool.bitmap = malloc(sizeof(uint32_t) * n, M_NETMAP, M_WAITOK | M_ZERO); nm_buf_pool.bitmap[0] = ~3; /* slot 0 and 1 always busy */ for (i = 1; i < n; i++) nm_buf_pool.bitmap[i] = ~0; nm_buf_pool.free = nm_buf_pool.total_buffers - 2; mem_obj = malloc(sizeof(struct netmap_mem_obj), M_NETMAP, M_WAITOK | M_ZERO); TAILQ_INSERT_HEAD(&nm_mem->nm_molist, mem_obj, nmo_next); mem_obj->nmo_used = 0; mem_obj->nmo_size = nm_mem->nm_size; mem_obj->nmo_data = nm_mem->nm_buffer; return (0); } /* * Finalize the memory allocator. * * Free all the memory objects contained inside the list, and deallocate * the pool of memory; finally free the memory allocator descriptor. */ static void netmap_memory_fini(void) { struct netmap_mem_obj *mem_obj; while (!TAILQ_EMPTY(&nm_mem->nm_molist)) { mem_obj = TAILQ_FIRST(&nm_mem->nm_molist); TAILQ_REMOVE(&nm_mem->nm_molist, mem_obj, nmo_next); if (mem_obj->nmo_used == 1) { printf("netmap: leaked %d bytes at %p\n", (int)mem_obj->nmo_size, mem_obj->nmo_data); } free(mem_obj, M_NETMAP); } contigfree(nm_mem->nm_buffer, nm_mem->nm_totalsize, M_NETMAP); // XXX mutex_destroy(nm_mtx); free(nm_mem, M_NETMAP); } /*------------- end of memory allocator -----------------*/ netmap-release/sys/dev/netmap/README000644 000423 000000 00000004147 12004266676 017775 0ustar00luigiwheel000000 000000 NOTES on debugging netmap performance /* * debugging support to analyse syscall behaviour * netmap_drop is the point where to drop Path is: ./libthr/thread/thr_syscalls.c lib/libc/i386/SYS.h lib/libc/i386/sys/syscall.S head/sys/kern/syscall.master ; Processed to created init_sysent.c, syscalls.c and syscall.h. sys/kern/uipc_syscalls.c::sys_sendto() sendit() kern_sendit() sosend() sys/kern/uipc_socket.c::sosend() so->so_proto->pr_usrreqs->pru_sosend(...) sys/netinet/udp_usrreq.c::udp_usrreqs { } .pru_sosend = sosend_dgram, .pru_send = udp_send, .pru_soreceive = soreceive_dgram, sys/kern/uipc_socket.c::sosend_dgram() m_uiotombuf() (*so->so_proto->pr_usrreqs->pru_send) sys/netinet/udp_usrreq.c::udp_send() sotoinpcb(so); udp_output() INP_RLOCK(inp); INP_HASH_RLOCK(&V_udbinfo); fill udp and ip headers ip_output() 30 udp_send() before udp_output 31 udp_output before ip_output 32 udp_output beginning 33 before in_pcbbind_setup 34 after in_pcbbind_setup 35 before prison_remote_ip4 36 after prison_remote_ip4 37 before computing udp 20 beginning of sys_sendto 21 beginning of sendit 22 sendit after getsockaddr 23 before kern_sendit 24 kern_sendit before getsock_cap() 25 kern_sendit before sosend() 40 sosend_dgram beginning 41 sosend_dgram after sbspace 42 sosend_dgram after m_uiotombuf 43 sosend_dgram after SO_DONTROUTE 44 sosend_dgram after pru_send (useless) 50 ip_output beginning 51 ip_output after flowtable 52 ip_output at sendit 53 ip_output after pfil_hooked 54 ip_output at passout 55 ip_output before if_output 56 ip_output after rtalloc etc. 60 uiomove print 70 pfil.c:: pfil_run_hooks beginning 71 print number of pfil entries 80 ether_output start 81 ether_output after first switch 82 ether_output after M_PREPEND 83 ether_output after simloop 84 ether_output after carp and netgraph 85 ether_output_frame before if_transmit() 90 ixgbe_mq_start (if_transmit) beginning 91 ixgbe_mq_start_locked before ixgbe_xmit FLAGS: 1 disable ETHER_BPF_MTAP 2 disable drbr stats update 4 8 16 32 64 128 */ netmap-release/sys/dev/netmap/vale.4000644 000423 000000 00000010213 12006437206 020107 0ustar00luigiwheel000000 000000 .\" Copyright (c) 2012 Luigi Rizzo, Universita` di Pisa .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" This document is derived in part from the enet man page (enet.4) .\" distributed with 4.3BSD Unix. .\" .\" $FreeBSD: head/share/man/man4/vale.4 228017 2011-11-27 06:55:57Z gjb $ .\" $Id: $ .\" .Dd July 27, 2012 .Dt VALE 4 .Os .Sh NAME .Nm vale .Nd a very fast Virtual Local Ethernet using the netmap API .Sh SYNOPSIS .Cd device netmap .Sh DESCRIPTION .Nm is a feature of the .Nm netmap module that implements multiple Virtual switches that can be used to interconnect netmap clients, including traffic sources and sinks, packet forwarders, userspace firewalls, and so on. .Pp .Nm is implemented completely in software, and is extremely fast. On a modern machine it can move almost 20 Million packets per second (Mpps) per core with small frames, and about 70 Gbit/s with 1500 byte frames. .Pp .Sh OPERATION .Nm dynamically creates switches and ports as client connect to it using the .Xr netmap 4 API. .Pp .Nm ports are named .Pa vale[bdg:][port] where .Pa vale is the prefix indicating a VALE switch rather than a standard interface, .Pa bdg indicates a specific switch (the colon is a separator), and .Pa port indicates a port within the switch. Bridge and ports names are arbitrary strings, the only constraint being that the full name must fit within 16 characters. .Pp See .Xr netmap 4 for details on the API. .Ss LIMITS .Nm currently supports up to 4 switches, 16 ports per switch, 1024 buffers per port. These hard limits will be changed to sysctl variables in future releases. .Pp .Sh SYSCTL VARIABLES .Nm uses the following sysctl variables to control operation: .Bl -tag -width 12 .It dev.netmap.bridge The maximum number of packets processed internally in each iteration. Defaults to 1024, use lower values to trade latency with throughput. .Pp .It dev.netmap.verbose Set to non-zero values to enable in-kernel diagnostics. .El .Pp .Sh EXAMPLES Create one switch, with a traffic generator connected to one port, and a netmap-enabled tcpdump instance on another port: .Bd -literal -offset indent tcpdump -ni vale-a:1 & pkt-gen -i vale-a:0 -f tx & .Ed .Pp Create two switches, each connected to two qemu machines on different ports. .Bd -literal -offset indent qemu -net nic -net netmap,ifname=vale-1:a ... & qemu -net nic -net netmap,ifname=vale-1:b ... & qemu -net nic -net netmap,ifname=vale-2:c ... & qemu -net nic -net netmap,ifname=vale-2:d ... & .Ed .Sh SEE ALSO .Xr netmap 4 .Pp .Xr http://info.iet.unipi.it/~luigi/vale/ .Pp Luigi Rizzo, Giuseppe Lettieri: VALE, a switched ethernet for virtual machines, June 2012, http://info.iet.unipi.it/~luigi/vale/ .Sh AUTHORS .An -nosplit The .Nm switch has been designed and implemented in 2012 by .An Luigi Rizzo and .An Giuseppe Lettieri at the Universita` di Pisa. .Pp .Nm has been funded by the European Commission within FP7 Projects CHANGE (257422) and OPENLAB (287581). netmap-release/sys/modules/000755 000423 000000 00000000000 11703265240 016504 5ustar00luigiwheel000000 000000 netmap-release/sys/modules/netmap/000755 000423 000000 00000000000 11703265240 017770 5ustar00luigiwheel000000 000000 netmap-release/sys/modules/netmap/Makefile000644 000423 000000 00000000521 11703265240 021426 0ustar00luigiwheel000000 000000 # $FreeBSD$ # # Compile netmap as a module, though it is not useful now # because drivers do depend on it. .PATH: ${.CURDIR}/../../dev/netmap .PATH.h: ${.CURDIR}/../../net KMOD = netmap SRCS = device_if.h bus_if.h opt_netmap.h SRCS += netmap.c netmap.h netmap_kern.h # CFLAGS += -I${.CURDIR}/../.. -DDEV_NETMAP .include netmap-release/examples/000755 000423 000000 00000000000 12110024427 016025 5ustar00luigiwheel000000 000000 netmap-release/examples/click-test.cfg000644 000423 000000 00000000644 11703265240 020563 0ustar00luigiwheel000000 000000 // // $FreeBSD: head/tools/tools/netmap/click-test.cfg 227614 2011-11-17 12:17:39Z luigi $ // // A sample test configuration for click // // // create a switch myswitch :: EtherSwitch; // two input devices c0 :: FromDevice(ix0, PROMISC true); c1 :: FromDevice(ix1, PROMISC true); // and now pass packets around c0[0] -> [0]sw[0] -> Queue(10000) -> ToDevice(ix0); c1[0] -> [1]sw[1] -> Queue(10000) -> ToDevice(ix1); netmap-release/examples/pingd.c000644 000423 000000 00000032022 11765361434 017312 0ustar00luigiwheel000000 000000 /* * (C) 2011 Luigi Rizzo, Matteo Landi, Davide Barelli * * BSD license * * A simple program to bridge two network interfaces */ #include #include /* signal */ #include #include #include /* strcmp */ #include /* open */ #include /* close */ #include /* le64toh */ #include /* PROT_* */ #include /* ioctl */ #include #include #include /* sockaddr.. */ #include /* ntohs */ #include /* ifreq */ #include #include #include #include /* sockaddr_in */ #include #include #define MIN(a, b) ((a) < (b) ? (a) : (b)) int verbose = 0; int report = 0; /* debug support */ #define ND(format, ...) {} #define D(format, ...) do { \ if (!verbose) break; \ struct timeval _xxts; \ gettimeofday(&_xxts, NULL); \ fprintf(stderr, "%03d.%06d %s [%d] " format "\n", \ (int)_xxts.tv_sec %1000, (int)_xxts.tv_usec, \ __FUNCTION__, __LINE__, ##__VA_ARGS__); \ } while (0) char *version = "$Id: pingd.c 11283 2012-06-11 12:37:17Z luigi $"; static int ABORT = 0; /* * info on a ring we handle */ struct my_ring { const char *ifname; int fd; char *mem; /* userspace mmap address */ u_int memsize; u_int queueid; u_int begin, end; /* first..last+1 rings to check */ struct netmap_if *nifp; struct netmap_ring *tx, *rx; /* shortcuts */ uint32_t if_flags; uint32_t if_reqcap; uint32_t if_curcap; }; static void sigint_h(__unused int sig) { ABORT = 1; signal(SIGINT, SIG_DFL); } static int do_ioctl(struct my_ring *me, int what) { struct ifreq ifr; int error; bzero(&ifr, sizeof(ifr)); strncpy(ifr.ifr_name, me->ifname, sizeof(ifr.ifr_name)); switch (what) { case SIOCSIFFLAGS: ifr.ifr_flagshigh = me->if_flags >> 16; ifr.ifr_flags = me->if_flags & 0xffff; break; case SIOCSIFCAP: ifr.ifr_reqcap = me->if_reqcap; ifr.ifr_curcap = me->if_curcap; break; } error = ioctl(me->fd, what, &ifr); if (error) { D("ioctl error %d", what); return error; } switch (what) { case SIOCGIFFLAGS: me->if_flags = (ifr.ifr_flagshigh << 16) | (0xffff & ifr.ifr_flags); if (verbose) D("flags are 0x%x", me->if_flags); break; case SIOCGIFCAP: me->if_reqcap = ifr.ifr_reqcap; me->if_curcap = ifr.ifr_curcap; if (verbose) D("curcap are 0x%x", me->if_curcap); break; } return 0; } /* * open a device. if me->mem is null then do an mmap. */ static int netmap_open(struct my_ring *me, int ringid) { int fd, err, l; struct nmreq req; me->fd = fd = open("/dev/netmap", O_RDWR); if (fd < 0) { D("Unable to open /dev/netmap"); return (-1); } bzero(&req, sizeof(req)); strncpy(req.nr_name, me->ifname, sizeof(req.nr_name)); req.nr_ringid = ringid; err = ioctl(fd, NIOCGINFO, &req); if (err) { D("cannot get info on %s", me->ifname); goto error; } me->memsize = l = req.nr_memsize; if (verbose) D("memsize is %d MB", l>>20); err = ioctl(fd, NIOCREGIF, &req); if (err) { D("Unable to register %s", me->ifname); goto error; } if (me->mem == NULL) { me->mem = mmap(0, l, PROT_WRITE | PROT_READ, MAP_SHARED, fd, 0); if (me->mem == MAP_FAILED) { D("Unable to mmap"); me->mem = NULL; goto error; } } me->nifp = NETMAP_IF(me->mem, req.nr_offset); me->queueid = ringid; if (ringid & NETMAP_SW_RING) { me->begin = req.nr_numrings; me->end = me->begin + 1; } else if (ringid & NETMAP_HW_RING) { me->begin = ringid & NETMAP_RING_MASK; me->end = me->begin + 1; } else { me->begin = 0; me->end = req.nr_numrings; } me->tx = NETMAP_TXRING(me->nifp, me->begin); me->rx = NETMAP_RXRING(me->nifp, me->begin); return (0); error: close(me->fd); return -1; } static int netmap_close(struct my_ring *me) { D(""); if (me->mem) munmap(me->mem, me->memsize); ioctl(me->fd, NIOCUNREGIF, NULL); close(me->fd); return (0); } /* Compute the checksum of the given ip header. */ /* len = number of byte. */ static uint16_t checksum(const void *data, uint16_t len) { const uint8_t *addr = data; uint32_t sum = 0; while (len > 1) { sum += addr[0] * 256 + addr[1]; addr += 2; len -= 2; } if (len == 1) sum += *addr * 256; sum = (sum >> 16) + (sum & 0xffff); sum += (sum >> 16); sum = htons(sum); return ~sum; } /* * Checksum routine for Internet Protocol family headers (C Version) */ u_short icmp_cksum(u_short *addr, int len) { int nleft, sum; u_short *w; union { u_short us; u_char uc[2]; } last; u_short answer; nleft = len; sum = 0; w = addr; /* * Our algorithm is simple, using a 32 bit accumulator (sum), we add * sequential 16 bit words to it, and at the end, fold back all the * carry bits from the top 16 bits into the lower 16 bits. */ while (nleft > 1) { sum += *w++; nleft -= 2; } /* mop up an odd byte, if necessary */ if (nleft == 1) { last.uc[0] = *(u_char *)w; last.uc[1] = 0; sum += last.us; } /* add back carry outs from top 16 bits to low 16 bits */ sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ sum += (sum >> 16); /* add carry */ answer = ~sum; /* truncate to 16 bits */ return(answer); } /* * - Switch addresses (both MAC and IP) * - Change echo request into echo reply * - Recompute checksums (IP and ICMP) */ void icmp_packet_process(char *pkt, uint16_t slot_len) { struct ether_header *eh; struct ip *ip; struct icmp *icmp; int len; u_char MAC_src[6]; struct in_addr IP_src; bzero(MAC_src, sizeof(MAC_src)); bzero(&IP_src, sizeof(IP_src)); eh = (struct ether_header *) pkt; ip = (struct ip *) &eh[1]; icmp = (struct icmp *) &ip[1]; // Copy MAC address memcpy(MAC_src, &eh->ether_shost, ETHER_ADDR_LEN); // Switch them memcpy(&eh->ether_shost, &eh->ether_dhost, ETHER_ADDR_LEN); memcpy(&eh->ether_dhost, MAC_src, ETHER_ADDR_LEN); // Copy IP adress memcpy(&IP_src, &ip->ip_src, sizeof(ip->ip_src)); // Switch them memcpy(&ip->ip_src, &ip->ip_dst, sizeof(ip->ip_src)); memcpy(&ip->ip_dst, &IP_src , sizeof(ip->ip_src)); // Setting ICMP Type and Code to 0 (ICMP echo reply) icmp->icmp_type = 0; icmp->icmp_code = 0; // Update IP checksum ip->ip_sum = 0; ip->ip_sum = checksum(ip, sizeof(*ip)); // Update ICMP checksum len = slot_len - 14 - 20; icmp->icmp_cksum = 0; icmp->icmp_cksum = icmp_cksum((u_short *) icmp, len); } int is_icmp(char *pkt) { struct ether_header *eh; struct ip *ip; struct icmp *icmp; eh = (struct ether_header *) pkt; ip = (struct ip *) &eh[1]; icmp = (struct icmp *) &ip[1]; if (ntohs(eh->ether_type) != ETHERTYPE_IP || ip->ip_p != 1 || icmp->icmp_type != ICMP_ECHO) return 0; return 1; } /* * move up to 'limit' pkts from rxring to txring swapping buffers. * * If txring2 is NULL the function acts like a bridge between the stack and the * NIC card; otherwise ICMP packets will be routed back to the NIC card. */ static int process_rings(struct netmap_ring *rxring, struct netmap_ring *txring, u_int limit, const char *msg, int modify_icmp) { u_int j, k, m = 0; /* print a warning if any of the ring flags is set (e.g. NM_REINIT) */ if (rxring->flags || txring->flags) D("%s rxflags %x stack txflags %x", msg, rxring->flags, txring->flags); j = rxring->cur; /* RX */ k = txring->cur; /* TX */ if (rxring->avail < limit) limit = rxring->avail; if (txring->avail < limit) limit = txring->avail; while (m < limit) { struct netmap_slot *rs = &rxring->slot[j]; struct netmap_slot *ts = &txring->slot[k]; char *buf = NETMAP_BUF(rxring, rxring->slot[j].buf_idx); uint32_t pkt; if (modify_icmp) { if (!is_icmp(buf)) { D("rx[%d] is not ICMP", j); break; /* best effort! */ } /*Swap addresses*/ icmp_packet_process(buf, rxring->slot[j].len); } else if (is_icmp(buf)) { D("rx[%d] is ICMP", j); break; /* best effort! */ } if (ts->buf_idx < 2 || rs->buf_idx < 2) { D("wrong index rx[%d] = %d -> tx[%d] = %d", j, rs->buf_idx, k, ts->buf_idx); sleep(2); } pkt = ts->buf_idx; ts->buf_idx = rs->buf_idx; rs->buf_idx = pkt; /* copy the packet lenght. */ if (rs->len < 14 || rs->len > 2048) D("wrong len %d rx[%d] -> tx[%d]", rs->len, j, k); else if (verbose > 1) D("send len %d rx[%d] -> tx[%d]", rs->len, j, k); ts->len = rs->len; /* report the buffer change. */ ts->flags |= NS_BUF_CHANGED; rs->flags |= NS_BUF_CHANGED; /* report status */ if (report) ts->flags |= NS_REPORT; j = NETMAP_RING_NEXT(rxring, j); k = NETMAP_RING_NEXT(txring, k); m++; } rxring->avail -= m; txring->avail -= m; rxring->cur = j; txring->cur = k; if (verbose && m > 0) D("sent %d packets to %p", m, txring); return (m); } /* move packts from src to destination */ static int move(struct my_ring *src, struct my_ring *dst, u_int limit, int modify_icmp) { struct netmap_ring *txring, *rxring; u_int m = 0, si = src->begin, di = dst->begin; const char *msg = (src->queueid & NETMAP_SW_RING) ? "host->net" : "net->host"; while (si < src->end && di < dst->end) { rxring = NETMAP_RXRING(src->nifp, si); txring = NETMAP_TXRING(dst->nifp, di); ND("txring %p rxring %p", txring, rxring); if (rxring->avail == 0) { si++; continue; } if (txring->avail == 0) { di++; continue; } m += process_rings(rxring, txring, limit, msg, modify_icmp); if (rxring->avail != 0 && txring->avail != 0) si++; } return (m); } /* * how many packets on this set of queues ? */ static int howmany(struct my_ring *me, int tx) { u_int i, tot = 0; ND("me %p begin %d end %d", me, me->begin, me->end); for (i = me->begin; i < me->end; i++) { struct netmap_ring *ring = tx ? NETMAP_TXRING(me->nifp, i) : NETMAP_RXRING(me->nifp, i); tot += ring->avail; } if (0 && verbose && tot && !tx) D("ring %s %s %s has %d avail at %d", me->ifname, tx ? "tx": "rx", me->end > me->nifp->ni_num_queues ? "host":"net", tot, NETMAP_TXRING(me->nifp, me->begin)->cur); return tot; } /* * bridge [-v] if1 if2 * * If only one name, or the two interfaces are the same, * bridges userland and the adapter. */ int main(int argc, char **argv) { struct pollfd pollfd[2]; int i, single_fd = 0; u_int burst = 1024; struct my_ring me[2]; fprintf(stderr, "%s %s built %s %s\n", argv[0], version, __DATE__, __TIME__); bzero(me, sizeof(me)); while (argc > 1) { if (!strcmp(argv[1], "-v")) { verbose++; } else if (!strcmp(argv[1], "-r")) { report++; } else if (!strcmp(argv[1], "-1")) { single_fd = 1; } else break; argv++; argc--; } if (argc < 2 || argc > 3) { D("Usage: %s [-vr1] IFNAME1 [BURST]", argv[0]); return (1); } me[0].ifname = me[1].ifname = argv[1]; if (!single_fd && netmap_open(me, NETMAP_SW_RING)) return (1); me[1].mem = me[0].mem; if (netmap_open(me+1, 0)) return (1); do_ioctl(me+1, SIOCGIFFLAGS); if ((me[1].if_flags & IFF_UP) == 0) { D("%s is down, bringing up...", me[1].ifname); me[1].if_flags |= IFF_UP; } do_ioctl(me+1, SIOCSIFFLAGS); do_ioctl(me+1, SIOCGIFCAP); me[1].if_reqcap = me[1].if_curcap; me[1].if_reqcap &= ~(IFCAP_HWCSUM | IFCAP_TSO | IFCAP_TOE); do_ioctl(me+1, SIOCSIFCAP); if (argc > 2) burst = atoi(argv[3]); /* packets burst size. */ /* setup poll(2) variables. */ memset(pollfd, 0, sizeof(pollfd)); for (i = 0; i < 2; i++) pollfd[i].fd = me[i].fd; D("Wait 2 secs for link to come up..."); sleep(2); D("Ready to go, %s 0x%x/%d <-> %s 0x%x/%d.", me[0].ifname, me[0].queueid, me[0].nifp->ni_num_queues, me[1].ifname, me[1].queueid, me[1].nifp->ni_num_queues); /* main loop */ signal(SIGINT, sigint_h); while (!ABORT) { int n0 = 0, n1 = 0, ret; if (!single_fd) { pollfd[0].events = pollfd[0].revents = 0; n0 = howmany(me, 0); if (n0) pollfd[1].events |= POLLOUT; else pollfd[0].events |= POLLIN; } pollfd[1].events = pollfd[1].revents = 0; n1 = howmany(me + 1, 0); if (n1) { pollfd[0].events |= POLLOUT; pollfd[1].events |= POLLOUT; } else pollfd[1].events |= POLLIN; ret = poll(pollfd + single_fd, 2 - single_fd, 2500); if (ret <= 0 || verbose) D("poll %s [0] ev %x %x rx %d@%d tx %d," " [1] ev %x %x rx %d@%d tx %d", ret <= 0 ? "timeout" : "ok", pollfd[0].events, pollfd[0].revents, howmany(me, 0), me[0].rx->cur, howmany(me, 1), pollfd[1].events, pollfd[1].revents, howmany(me+1, 0), me[1].rx->cur, howmany(me+1, 1) ); if (ret < 0) continue; if (!single_fd && pollfd[0].revents & POLLERR) { D("error on fd0, rxcur %d@%d", me[0].rx->avail, me[0].rx->cur); } if (pollfd[1].revents & POLLERR) { D("error on fd1, rxcur %d@%d", me[1].rx->avail, me[1].rx->cur); } if (pollfd[1].revents & POLLOUT) { if (n1) move(me + 1, me + 1, burst, 1 /* change ICMP content */); if (!single_fd && n0) move(me, me + 1, burst, 0 /* swap packets */); } if (!single_fd && pollfd[0].revents & POLLOUT) { move(me + 1, me, burst, 0 /* swap packets */); } } D("exiting"); netmap_close(me + 1); netmap_close(me + 0); return (0); } netmap-release/examples/pcap.c000644 000423 000000 00000032500 12005541713 017121 0ustar00luigiwheel000000 000000 /* * (C) 2011-2012 Luigi Rizzo * * BSD license * * A simple library that maps some pcap functions onto netmap * This is not 100% complete but enough to let tcpdump, trafshow * and other apps work. * * $FreeBSD: head/tools/tools/netmap/pcap.c 227614 2011-11-17 12:17:39Z luigi $ */ #define MY_PCAP #include "nm_util.h" char *version = "$Id: pcap.c 11463 2012-07-30 15:26:02Z luigi $"; int verbose = 0; /* * We redefine here a number of structures that are in pcap.h * so we can compile this file without the system header. */ #ifndef PCAP_ERRBUF_SIZE #define PCAP_ERRBUF_SIZE 128 /* * Each packet is accompanied by a header including the timestamp, * captured size and actual size. */ struct pcap_pkthdr { struct timeval ts; /* time stamp */ uint32_t caplen; /* length of portion present */ uint32_t len; /* length this packet (off wire) */ }; typedef struct pcap_if pcap_if_t; /* * Representation of an interface address. */ struct pcap_addr { struct pcap_addr *next; struct sockaddr *addr; /* address */ struct sockaddr *netmask; /* netmask for the above */ struct sockaddr *broadaddr; /* broadcast addr for the above */ struct sockaddr *dstaddr; /* P2P dest. address for the above */ }; struct pcap_if { struct pcap_if *next; char *name; /* name to hand to "pcap_open_live()" */ char *description; /* textual description of interface, or NULL */ struct pcap_addr *addresses; uint32_t flags; /* PCAP_IF_ interface flags */ }; /* * We do not support stats (yet) */ struct pcap_stat { u_int ps_recv; /* number of packets received */ u_int ps_drop; /* number of packets dropped */ u_int ps_ifdrop; /* drops by interface XXX not yet supported */ #ifdef WIN32 u_int bs_capt; /* number of packets that reach the app. */ #endif /* WIN32 */ }; typedef void pcap_t; typedef enum { PCAP_D_INOUT = 0, PCAP_D_IN, PCAP_D_OUT } pcap_direction_t; typedef void (*pcap_handler)(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes); char errbuf[PCAP_ERRBUF_SIZE]; pcap_t *pcap_open_live(const char *device, int snaplen, int promisc, int to_ms, char *errbuf); int pcap_findalldevs(pcap_if_t **alldevsp, char *errbuf); void pcap_close(pcap_t *p); int pcap_get_selectable_fd(pcap_t *p); int pcap_dispatch(pcap_t *p, int cnt, pcap_handler callback, u_char *user); int pcap_setnonblock(pcap_t *p, int nonblock, char *errbuf); int pcap_setdirection(pcap_t *p, pcap_direction_t d); char *pcap_lookupdev(char *errbuf); int pcap_inject(pcap_t *p, const void *buf, size_t size); int pcap_fileno(pcap_t *p); const char *pcap_lib_version(void); struct eproto { const char *s; u_short p; }; #endif /* !PCAP_ERRBUF_SIZE */ #ifndef TEST /* * build as a shared library */ char pcap_version[] = "libnetmap version 0.3"; /* * Our equivalent of pcap_t */ struct pcap_ring { struct my_ring me; #if 0 const char *ifname; //struct nmreq nmr; int fd; char *mem; /* userspace mmap address */ u_int memsize; u_int queueid; u_int begin, end; /* first..last+1 rings to check */ struct netmap_if *nifp; uint32_t if_flags; uint32_t if_reqcap; uint32_t if_curcap; #endif int snaplen; char *errbuf; int promisc; int to_ms; struct pcap_pkthdr hdr; struct pcap_stat st; char msg[PCAP_ERRBUF_SIZE]; }; /* * There is a set of functions that tcpdump expects even if probably * not used */ struct eproto eproto_db[] = { { "ip", ETHERTYPE_IP }, { "arp", ETHERTYPE_ARP }, { (char *)0, 0 } }; const char *pcap_lib_version(void) { return pcap_version; } int pcap_findalldevs(pcap_if_t **alldevsp, char *errbuf) { pcap_if_t *top = NULL; #ifndef linux struct ifaddrs *i_head, *i; pcap_if_t *cur; struct pcap_addr *tail = NULL; int l; D("listing all devs"); *alldevsp = NULL; i_head = NULL; if (getifaddrs(&i_head)) { D("cannot get if addresses"); return -1; } for (i = i_head; i; i = i->ifa_next) { //struct ifaddrs *ifa; struct pcap_addr *pca; //struct sockaddr *sa; D("got interface %s", i->ifa_name); if (!top || strcmp(top->name, i->ifa_name)) { /* new interface */ l = sizeof(*top) + strlen(i->ifa_name) + 1; cur = calloc(1, l); if (cur == NULL) { D("no space for if descriptor"); continue; } cur->name = (char *)(cur + 1); //cur->flags = i->ifa_flags; strcpy(cur->name, i->ifa_name); cur->description = NULL; cur->next = top; top = cur; tail = NULL; } /* now deal with addresses */ D("%s addr family %d len %d %s %s", top->name, i->ifa_addr->sa_family, i->ifa_addr->sa_len, i->ifa_netmask ? "Netmask" : "", i->ifa_broadaddr ? "Broadcast" : ""); l = sizeof(struct pcap_addr) + (i->ifa_addr ? i->ifa_addr->sa_len:0) + (i->ifa_netmask ? i->ifa_netmask->sa_len:0) + (i->ifa_broadaddr? i->ifa_broadaddr->sa_len:0); pca = calloc(1, l); if (pca == NULL) { D("no space for if addr"); continue; } #define SA_NEXT(x) ((struct sockaddr *)((char *)(x) + (x)->sa_len)) pca->addr = (struct sockaddr *)(pca + 1); pkt_copy(i->ifa_addr, pca->addr, i->ifa_addr->sa_len); if (i->ifa_netmask) { pca->netmask = SA_NEXT(pca->addr); bcopy(i->ifa_netmask, pca->netmask, i->ifa_netmask->sa_len); if (i->ifa_broadaddr) { pca->broadaddr = SA_NEXT(pca->netmask); bcopy(i->ifa_broadaddr, pca->broadaddr, i->ifa_broadaddr->sa_len); } } if (tail == NULL) { top->addresses = pca; } else { tail->next = pca; } tail = pca; } freeifaddrs(i_head); #endif /* !linux */ (void)errbuf; /* UNUSED */ *alldevsp = top; return 0; } void pcap_freealldevs(pcap_if_t *alldevs) { (void)alldevs; /* UNUSED */ D("unimplemented"); } char * pcap_lookupdev(char *buf) { D("%s", buf); strcpy(buf, "/dev/netmap"); return buf; } pcap_t * pcap_create(const char *source, char *errbuf) { D("src %s (call open liveted)", source); return pcap_open_live(source, 0, 1, 100, errbuf); } int pcap_activate(pcap_t *p) { D("pcap %p running", p); return 0; } int pcap_can_set_rfmon(pcap_t *p) { (void)p; /* UNUSED */ D(""); return 0; /* no we can't */ } int pcap_set_snaplen(pcap_t *p, int snaplen) { struct pcap_ring *me = p; D("len %d", snaplen); me->snaplen = snaplen; return 0; } int pcap_snapshot(pcap_t *p) { struct pcap_ring *me = p; D("len %d", me->snaplen); return me->snaplen; } int pcap_lookupnet(const char *device, uint32_t *netp, uint32_t *maskp, char *errbuf) { (void)errbuf; /* UNUSED */ D("device %s", device); inet_aton("10.0.0.255", (struct in_addr *)netp); inet_aton("255.255.255.0",(struct in_addr *) maskp); return 0; } int pcap_set_promisc(pcap_t *p, int promisc) { struct pcap_ring *me = p; D("promisc %d", promisc); if (nm_do_ioctl(&me->me, SIOCGIFFLAGS, 0)) D("SIOCGIFFLAGS failed"); if (promisc) { me->me.if_flags |= IFF_PPROMISC; } else { me->me.if_flags &= ~IFF_PPROMISC; } if (nm_do_ioctl(&me->me, SIOCSIFFLAGS, 0)) D("SIOCSIFFLAGS failed"); return 0; } int pcap_set_timeout(pcap_t *p, int to_ms) { struct pcap_ring *me = p; D("%d ms", to_ms); me->to_ms = to_ms; return 0; } struct bpf_program; int pcap_compile(pcap_t *p, struct bpf_program *fp, const char *str, int optimize, uint32_t netmask) { (void)p; /* UNUSED */ (void)fp; /* UNUSED */ (void)optimize; /* UNUSED */ (void)netmask; /* UNUSED */ D("%s", str); return 0; } int pcap_setfilter(pcap_t *p, struct bpf_program *fp) { (void)p; /* UNUSED */ (void)fp; /* UNUSED */ D(""); return 0; } int pcap_datalink(pcap_t *p) { (void)p; /* UNUSED */ D("returns 1"); return 1; // ethernet } const char * pcap_datalink_val_to_name(int dlt) { D("%d returns DLT_EN10MB", dlt); return "DLT_EN10MB"; } const char * pcap_datalink_val_to_description(int dlt) { D("%d returns Ethernet link", dlt); return "Ethernet link"; } struct pcap_stat; int pcap_stats(pcap_t *p, struct pcap_stat *ps) { struct pcap_ring *me = p; ND(""); *ps = me->st; return 0; /* accumulate from pcap_dispatch() */ }; char * pcap_geterr(pcap_t *p) { struct pcap_ring *me = p; D(""); return me->msg; } pcap_t * pcap_open_live(const char *device, int snaplen, int promisc, int to_ms, char *errbuf) { struct pcap_ring *me; int l; (void)snaplen; /* UNUSED */ (void)errbuf; /* UNUSED */ if (!device) { D("missing device name"); return NULL; } l = strlen(device) + 1; D("request to open %s snaplen %d promisc %d timeout %dms", device, snaplen, promisc, to_ms); me = calloc(1, sizeof(*me) + l); if (me == NULL) { D("failed to allocate struct for %s", device); return NULL; } me->me.ifname = (char *)(me + 1); strcpy((char *)me->me.ifname, device); if (netmap_open(&me->me, 0, promisc)) { D("error opening %s", device); free(me); return NULL; } me->to_ms = to_ms; return (pcap_t *)me; } void pcap_close(pcap_t *p) { struct my_ring *me = p; D(""); if (!me) return; if (me->mem) munmap(me->mem, me->memsize); /* restore original flags ? */ ioctl(me->fd, NIOCUNREGIF, NULL); close(me->fd); bzero(me, sizeof(*me)); free(me); } int pcap_fileno(pcap_t *p) { struct my_ring *me = p; D("returns %d", me->fd); return me->fd; } int pcap_get_selectable_fd(pcap_t *p) { struct my_ring *me = p; ND(""); return me->fd; } int pcap_setnonblock(pcap_t *p, int nonblock, char *errbuf) { (void)p; /* UNUSED */ (void)errbuf; /* UNUSED */ D("mode is %d", nonblock); return 0; /* ignore */ } int pcap_setdirection(pcap_t *p, pcap_direction_t d) { (void)p; /* UNUSED */ (void)d; /* UNUSED */ D(""); return 0; /* ignore */ }; int pcap_dispatch(pcap_t *p, int cnt, pcap_handler callback, u_char *user) { struct pcap_ring *pme = p; struct my_ring *me = &pme->me; int got = 0; u_int si; ND("cnt %d", cnt); if (cnt == 0) cnt = -1; /* scan all rings */ for (si = me->begin; si < me->end; si++) { struct netmap_ring *ring = NETMAP_RXRING(me->nifp, si); ND("ring has %d pkts", ring->avail); if (ring->avail == 0) continue; pme->hdr.ts = ring->ts; /* * XXX a proper prefetch should be done as * prefetch(i); callback(i-1); ... */ while ((cnt == -1 || cnt != got) && ring->avail > 0) { u_int i = ring->cur; u_int idx = ring->slot[i].buf_idx; if (idx < 2) { D("%s bogus RX index %d at offset %d", me->nifp->ni_name, idx, i); sleep(2); } u_char *buf = (u_char *)NETMAP_BUF(ring, idx); prefetch(buf); pme->hdr.len = pme->hdr.caplen = ring->slot[i].len; // D("call %p len %d", p, me->hdr.len); callback(user, &pme->hdr, buf); ring->cur = NETMAP_RING_NEXT(ring, i); ring->avail--; got++; } } pme->st.ps_recv += got; return got; } int pcap_inject(pcap_t *p, const void *buf, size_t size) { struct my_ring *me = p; u_int si; ND("cnt %d", cnt); /* scan all rings */ for (si = me->begin; si < me->end; si++) { struct netmap_ring *ring = NETMAP_TXRING(me->nifp, si); ND("ring has %d pkts", ring->avail); if (ring->avail == 0) continue; u_int i = ring->cur; u_int idx = ring->slot[i].buf_idx; if (idx < 2) { D("%s bogus TX index %d at offset %d", me->nifp->ni_name, idx, i); sleep(2); } u_char *dst = (u_char *)NETMAP_BUF(ring, idx); ring->slot[i].len = size; pkt_copy(buf, dst, size); ring->cur = NETMAP_RING_NEXT(ring, i); ring->avail--; // if (ring->avail == 0) ioctl(me->fd, NIOCTXSYNC, NULL); return size; } errno = ENOBUFS; return -1; } int pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user) { struct pcap_ring *me = p; struct pollfd fds[1]; int i; ND("cnt %d", cnt); memset(fds, 0, sizeof(fds)); fds[0].fd = me->me.fd; fds[0].events = (POLLIN); while (cnt == -1 || cnt > 0) { if (poll(fds, 1, me->to_ms) <= 0) { D("poll error/timeout"); continue; } i = pcap_dispatch(p, cnt, callback, user); if (cnt > 0) cnt -= i; } return 0; } #endif /* !TEST */ #ifdef TEST /* build test code */ void do_send(u_char *user, const struct pcap_pkthdr *h, const u_char *buf) { pcap_inject((pcap_t *)user, buf, h->caplen); } /* * a simple pcap test program, bridge between two interfaces. */ int main(int argc, char **argv) { pcap_t *p0, *p1; int burst = 1024; struct pollfd pollfd[2]; fprintf(stderr, "%s %s built %s %s\n", argv[0], version, __DATE__, __TIME__); while (argc > 1 && !strcmp(argv[1], "-v")) { verbose++; argv++; argc--; } if (argc < 3 || argc > 4 || !strcmp(argv[1], argv[2])) { D("Usage: %s IFNAME1 IFNAME2 [BURST]", argv[0]); return (1); } if (argc > 3) burst = atoi(argv[3]); p0 = pcap_open_live(argv[1], 0, 1, 100, NULL); p1 = pcap_open_live(argv[2], 0, 1, 100, NULL); D("%s", version); D("open returns %p %p", p0, p1); if (!p0 || !p1) return(1); bzero(pollfd, sizeof(pollfd)); pollfd[0].fd = pcap_fileno(p0); pollfd[1].fd = pcap_fileno(p1); pollfd[0].events = pollfd[1].events = POLLIN; for (;;) { /* do i need to reset ? */ pollfd[0].revents = pollfd[1].revents = 0; int ret = poll(pollfd, 2, 1000); if (ret <= 0 || verbose) D("poll %s [0] ev %x %x [1] ev %x %x", ret <= 0 ? "timeout" : "ok", pollfd[0].events, pollfd[0].revents, pollfd[1].events, pollfd[1].revents); if (ret < 0) continue; if (pollfd[0].revents & POLLIN) pcap_dispatch(p0, burst, do_send, p1); if (pollfd[1].revents & POLLIN) pcap_dispatch(p1, burst, do_send, p0); } return (0); } #endif /* TEST */ netmap-release/examples/pkt-gen.c000644 000423 000000 00000106430 12103733570 017552 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2011-2012 Matteo Landi, Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $FreeBSD: head/tools/tools/netmap/pkt-gen.c 231198 2012-02-08 11:43:29Z luigi $ * $Id: pkt-gen.c 12024 2013-01-25 05:41:51Z luigi $ * * Example program to show how to build a multithreaded packet * source/sink using the netmap device. * * In this example we create a programmable number of threads * to take care of all the queues of the interface used to * send or receive traffic. * */ #include "nm_util.h" const char *default_payload="netmap pkt-gen payload\n" "http://info.iet.unipi.it/~luigi/netmap/ "; int time_second; // support for RD() debugging macro int verbose = 0; #define SKIP_PAYLOAD 1 /* do not check payload. */ struct pkt { struct ether_header eh; struct ip ip; struct udphdr udp; uint8_t body[2048]; // XXX hardwired } __attribute__((__packed__)); struct ip_range { char *name; struct in_addr start, end, cur; uint16_t port0, port1, cur_p; }; struct mac_range { char *name; struct ether_addr start, end; }; /* * global arguments for all threads */ struct glob_arg { struct ip_range src_ip; struct ip_range dst_ip; struct mac_range dst_mac; struct mac_range src_mac; int pkt_size; int burst; int forever; int npackets; /* total packets to send */ int nthreads; int cpus; int options; /* testing */ #define OPT_PREFETCH 1 #define OPT_ACCESS 2 #define OPT_COPY 4 #define OPT_MEMCPY 8 #define OPT_TS 16 /* add a timestamp */ int dev_type; pcap_t *p; int affinity; int main_fd; int report_interval; void *(*td_body)(void *); void *mmap_addr; int mmap_size; char *ifname; }; enum dev_type { DEV_NONE, DEV_NETMAP, DEV_PCAP, DEV_TAP }; /* * Arguments for a new thread. The same structure is used by * the source and the sink */ struct targ { struct glob_arg *g; int used; int completed; int cancel; int fd; struct nmreq nmr; struct netmap_if *nifp; uint16_t qfirst, qlast; /* range of queues to scan */ volatile uint64_t count; struct timeval tic, toc; int me; pthread_t thread; int affinity; struct pkt pkt; }; /* * extract the extremes from a range of ipv4 addresses. * addr_lo[-addr_hi][:port_lo[-port_hi]] */ static void extract_ip_range(struct ip_range *r) { char *p_lo, *p_hi; char buf1[16]; // one ip address D("extract IP range from %s", r->name); p_lo = index(r->name, ':'); /* do we have ports ? */ if (p_lo) { D(" found ports at %s", p_lo); *p_lo++ = '\0'; p_hi = index(p_lo, '-'); if (p_hi) *p_hi++ = '\0'; else p_hi = p_lo; r->port0 = strtol(p_lo, NULL, 0); r->port1 = strtol(p_hi, NULL, 0); if (r->port1 < r->port0) { r->cur_p = r->port0; r->port0 = r->port1; r->port1 = r->cur_p; } r->cur_p = r->port0; D("ports are %d to %d", r->port0, r->port1); } p_hi = index(r->name, '-'); /* do we have upper ip ? */ if (p_hi) { *p_hi++ = '\0'; } else p_hi = r->name; inet_aton(r->name, &r->start); inet_aton(p_hi, &r->end); if (r->start.s_addr > r->end.s_addr) { r->cur = r->start; r->start = r->end; r->end = r->cur; } r->cur = r->start; strncpy(buf1, inet_ntoa(r->end), sizeof(buf1)); D("range is %s %d to %s %d", inet_ntoa(r->start), r->port0, buf1, r->port1); } static void extract_mac_range(struct mac_range *r) { D("extract MAC range from %s", r->name); bcopy(ether_aton(r->name), &r->start, 6); bcopy(ether_aton(r->name), &r->end, 6); #if 0 bcopy(targ->src_mac, eh->ether_shost, 6); p = index(targ->g->src_mac, '-'); if (p) targ->src_mac_range = atoi(p+1); bcopy(ether_aton(targ->g->dst_mac), targ->dst_mac, 6); bcopy(targ->dst_mac, eh->ether_dhost, 6); p = index(targ->g->dst_mac, '-'); if (p) targ->dst_mac_range = atoi(p+1); #endif D("%s starts at %s", r->name, ether_ntoa(&r->start)); } static struct targ *targs; static int global_nthreads; /* control-C handler */ static void sigint_h(int sig) { int i; (void)sig; /* UNUSED */ for (i = 0; i < global_nthreads; i++) { targs[i].cancel = 1; } signal(SIGINT, SIG_DFL); } /* sysctl wrapper to return the number of active CPUs */ static int system_ncpus(void) { #ifdef __FreeBSD__ int mib[2], ncpus; size_t len; mib[0] = CTL_HW; mib[1] = HW_NCPU; len = sizeof(mib); sysctl(mib, 2, &ncpus, &len, NULL, 0); return (ncpus); #else return 1; #endif /* !__FreeBSD__ */ } #ifdef __linux__ #define sockaddr_dl sockaddr_ll #define sdl_family sll_family #define AF_LINK AF_PACKET #define LLADDR(s) s->sll_addr; #include #define TAP_CLONEDEV "/dev/net/tun" #endif /* __linux__ */ #ifdef __FreeBSD__ #include #define TAP_CLONEDEV "/dev/tap" #endif /* __FreeBSD */ #ifdef __APPLE__ // #warning TAP not supported on apple ? #include #define TAP_CLONEDEV "/dev/tap" #endif /* __APPLE__ */ /* * locate the src mac address for our interface, put it * into the user-supplied buffer. return 0 if ok, -1 on error. */ static int source_hwaddr(const char *ifname, char *buf) { struct ifaddrs *ifaphead, *ifap; int l = sizeof(ifap->ifa_name); if (getifaddrs(&ifaphead) != 0) { D("getifaddrs %s failed", ifname); return (-1); } for (ifap = ifaphead; ifap; ifap = ifap->ifa_next) { struct sockaddr_dl *sdl = (struct sockaddr_dl *)ifap->ifa_addr; uint8_t *mac; if (!sdl || sdl->sdl_family != AF_LINK) continue; if (strncmp(ifap->ifa_name, ifname, l) != 0) continue; mac = (uint8_t *)LLADDR(sdl); sprintf(buf, "%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); if (verbose) D("source hwaddr %s", buf); break; } freeifaddrs(ifaphead); return ifap ? 0 : 1; } /* set the thread affinity. */ static int setaffinity(pthread_t me, int i) { #ifdef __FreeBSD__ cpuset_t cpumask; if (i == -1) return 0; /* Set thread affinity affinity.*/ CPU_ZERO(&cpumask); CPU_SET(i, &cpumask); if (pthread_setaffinity_np(me, sizeof(cpuset_t), &cpumask) != 0) { D("Unable to set affinity"); return 1; } #else (void)me; /* suppress 'unused' warnings */ (void)i; #endif /* __FreeBSD__ */ return 0; } /* Compute the checksum of the given ip header. */ static uint16_t checksum(const void *data, uint16_t len, uint32_t sum) { const uint8_t *addr = data; uint32_t i; /* Checksum all the pairs of bytes first... */ for (i = 0; i < (len & ~1U); i += 2) { sum += (u_int16_t)ntohs(*((u_int16_t *)(addr + i))); if (sum > 0xFFFF) sum -= 0xFFFF; } /* * If there's a single byte left over, checksum it, too. * Network byte order is big-endian, so the remaining byte is * the high byte. */ if (i < len) { sum += addr[i] << 8; if (sum > 0xFFFF) sum -= 0xFFFF; } return sum; } static u_int16_t wrapsum(u_int32_t sum) { sum = ~sum & 0xFFFF; return (htons(sum)); } /* * Fill a packet with some payload. * We create a UDP packet so the payload starts at * 14+20+8 = 42 bytes. */ #ifdef __linux__ #define uh_sport source #define uh_dport dest #define uh_ulen len #define uh_sum check #endif /* linux */ static void initialize_packet(struct targ *targ) { struct pkt *pkt = &targ->pkt; struct ether_header *eh; struct ip *ip; struct udphdr *udp; uint16_t paylen = targ->g->pkt_size - sizeof(*eh) - sizeof(struct ip); int i, l, l0 = strlen(default_payload); for (i = 0; i < paylen;) { l = min(l0, paylen - i); bcopy(default_payload, pkt->body + i, l); i += l; } pkt->body[i-1] = '\0'; ip = &pkt->ip; ip->ip_v = IPVERSION; ip->ip_hl = 5; ip->ip_id = 0; ip->ip_tos = IPTOS_LOWDELAY; ip->ip_len = ntohs(targ->g->pkt_size - sizeof(*eh)); ip->ip_id = 0; ip->ip_off = htons(IP_DF); /* Don't fragment */ ip->ip_ttl = IPDEFTTL; ip->ip_p = IPPROTO_UDP; ip->ip_dst.s_addr = targ->g->dst_ip.cur.s_addr; if (++targ->g->dst_ip.cur.s_addr > targ->g->dst_ip.end.s_addr) targ->g->dst_ip.cur.s_addr = targ->g->dst_ip.start.s_addr; ip->ip_src.s_addr = targ->g->src_ip.cur.s_addr; if (++targ->g->src_ip.cur.s_addr > targ->g->src_ip.end.s_addr) targ->g->src_ip.cur.s_addr = targ->g->src_ip.start.s_addr; ip->ip_sum = wrapsum(checksum(ip, sizeof(*ip), 0)); udp = &pkt->udp; udp->uh_sport = htons(targ->g->src_ip.cur_p); if (++targ->g->src_ip.cur_p > targ->g->src_ip.port1) targ->g->src_ip.cur_p = targ->g->src_ip.port0; udp->uh_dport = htons(targ->g->dst_ip.cur_p); if (++targ->g->dst_ip.cur_p > targ->g->dst_ip.port1) targ->g->dst_ip.cur_p = targ->g->dst_ip.port0; udp->uh_ulen = htons(paylen); /* Magic: taken from sbin/dhclient/packet.c */ udp->uh_sum = wrapsum(checksum(udp, sizeof(*udp), checksum(pkt->body, paylen - sizeof(*udp), checksum(&ip->ip_src, 2 * sizeof(ip->ip_src), IPPROTO_UDP + (u_int32_t)ntohs(udp->uh_ulen) ) ) )); eh = &pkt->eh; bcopy(&targ->g->src_mac.start, eh->ether_shost, 6); bcopy(&targ->g->dst_mac.start, eh->ether_dhost, 6); eh->ether_type = htons(ETHERTYPE_IP); } /* Check the payload of the packet for errors (use it for debug). * Look for consecutive ascii representations of the size of the packet. */ static void check_payload(char *p, int psize) { char temp[64]; int n_read, size, sizelen; /* get the length in ASCII of the length of the packet. */ sizelen = sprintf(temp, "%d", psize) + 1; // include a whitespace /* dummy payload. */ p += 14; /* skip packet header. */ n_read = 14; while (psize - n_read >= sizelen) { sscanf(p, "%d", &size); if (size != psize) { D("Read %d instead of %d", size, psize); break; } p += sizelen; n_read += sizelen; } } /* * create and enqueue a batch of packets on a ring. * On the last one set NS_REPORT to tell the driver to generate * an interrupt when done. */ static int send_packets(struct netmap_ring *ring, struct pkt *pkt, int size, u_int count, int options) { u_int sent, cur = ring->cur; if (ring->avail < count) count = ring->avail; #if 0 if (options & (OPT_COPY | OPT_PREFETCH) ) { for (sent = 0; sent < count; sent++) { struct netmap_slot *slot = &ring->slot[cur]; char *p = NETMAP_BUF(ring, slot->buf_idx); prefetch(p); cur = NETMAP_RING_NEXT(ring, cur); } cur = ring->cur; } #endif for (sent = 0; sent < count; sent++) { struct netmap_slot *slot = &ring->slot[cur]; char *p = NETMAP_BUF(ring, slot->buf_idx); if (options & OPT_COPY) pkt_copy(pkt, p, size); else if (options & OPT_MEMCPY) memcpy(p, pkt, size); else if (options & OPT_PREFETCH) prefetch(p); slot->len = size; if (sent == count - 1) slot->flags |= NS_REPORT; cur = NETMAP_RING_NEXT(ring, cur); } ring->avail -= sent; ring->cur = cur; return (sent); } /* * Send a packet, and wait for a response. * The payload (after UDP header, ofs 42) has a 4-byte sequence * followed by a struct timeval (or bintime?) */ #define PAY_OFS 42 /* where in the pkt... */ static void * pinger_body(void *data) { struct targ *targ = (struct targ *) data; struct pollfd fds[1]; struct netmap_if *nifp = targ->nifp; int i, rx = 0, n = targ->g->npackets; fds[0].fd = targ->fd; fds[0].events = (POLLIN); static uint32_t sent; struct timespec ts, now, last_print; uint32_t count = 0, min = 1000000000, av = 0; if (targ->g->nthreads > 1) { D("can only ping with 1 thread"); return NULL; } clock_gettime(CLOCK_REALTIME_PRECISE, &last_print); while (n == 0 || (int)sent < n) { struct netmap_ring *ring = NETMAP_TXRING(nifp, 0); struct netmap_slot *slot; char *p; for (i = 0; i < 1; i++) { slot = &ring->slot[ring->cur]; slot->len = targ->g->pkt_size; p = NETMAP_BUF(ring, slot->buf_idx); if (ring->avail == 0) { D("-- ouch, cannot send"); } else { pkt_copy(&targ->pkt, p, targ->g->pkt_size); clock_gettime(CLOCK_REALTIME_PRECISE, &ts); bcopy(&sent, p+42, sizeof(sent)); bcopy(&ts, p+46, sizeof(ts)); sent++; ring->cur = NETMAP_RING_NEXT(ring, ring->cur); ring->avail--; } } /* should use a parameter to decide how often to send */ if (poll(fds, 1, 3000) <= 0) { D("poll error/timeout on queue %d", targ->me); continue; } /* see what we got back */ for (i = targ->qfirst; i < targ->qlast; i++) { ring = NETMAP_RXRING(nifp, i); while (ring->avail > 0) { uint32_t seq; slot = &ring->slot[ring->cur]; p = NETMAP_BUF(ring, slot->buf_idx); clock_gettime(CLOCK_REALTIME_PRECISE, &now); bcopy(p+42, &seq, sizeof(seq)); bcopy(p+46, &ts, sizeof(ts)); ts.tv_sec = now.tv_sec - ts.tv_sec; ts.tv_nsec = now.tv_nsec - ts.tv_nsec; if (ts.tv_nsec < 0) { ts.tv_nsec += 1000000000; ts.tv_sec--; } if (1) D("seq %d/%d delta %d.%09d", seq, sent, (int)ts.tv_sec, (int)ts.tv_nsec); if (ts.tv_nsec < (int)min) min = ts.tv_nsec; count ++; av += ts.tv_nsec; ring->avail--; ring->cur = NETMAP_RING_NEXT(ring, ring->cur); rx++; } } //D("tx %d rx %d", sent, rx); //usleep(100000); ts.tv_sec = now.tv_sec - last_print.tv_sec; ts.tv_nsec = now.tv_nsec - last_print.tv_nsec; if (ts.tv_nsec < 0) { ts.tv_nsec += 1000000000; ts.tv_sec--; } if (ts.tv_sec >= 1) { D("count %d min %d av %d", count, min, av/count); count = 0; av = 0; min = 100000000; last_print = now; } } return NULL; } /* * reply to ping requests */ static void * ponger_body(void *data) { struct targ *targ = (struct targ *) data; struct pollfd fds[1]; struct netmap_if *nifp = targ->nifp; struct netmap_ring *txring, *rxring; int i, rx = 0, sent = 0, n = targ->g->npackets; fds[0].fd = targ->fd; fds[0].events = (POLLIN); if (targ->g->nthreads > 1) { D("can only reply ping with 1 thread"); return NULL; } D("understood ponger %d but don't know how to do it", n); while (n == 0 || sent < n) { uint32_t txcur, txavail; //#define BUSYWAIT #ifdef BUSYWAIT ioctl(fds[0].fd, NIOCRXSYNC, NULL); #else if (poll(fds, 1, 1000) <= 0) { D("poll error/timeout on queue %d", targ->me); continue; } #endif txring = NETMAP_TXRING(nifp, 0); txcur = txring->cur; txavail = txring->avail; /* see what we got back */ for (i = targ->qfirst; i < targ->qlast; i++) { rxring = NETMAP_RXRING(nifp, i); while (rxring->avail > 0) { uint16_t *spkt, *dpkt; uint32_t cur = rxring->cur; struct netmap_slot *slot = &rxring->slot[cur]; char *src, *dst; src = NETMAP_BUF(rxring, slot->buf_idx); //D("got pkt %p of size %d", src, slot->len); rxring->avail--; rxring->cur = NETMAP_RING_NEXT(rxring, cur); rx++; if (txavail == 0) continue; dst = NETMAP_BUF(txring, txring->slot[txcur].buf_idx); /* copy... */ dpkt = (uint16_t *)dst; spkt = (uint16_t *)src; pkt_copy(src, dst, slot->len); dpkt[0] = spkt[3]; dpkt[1] = spkt[4]; dpkt[2] = spkt[5]; dpkt[3] = spkt[0]; dpkt[4] = spkt[1]; dpkt[5] = spkt[2]; txring->slot[txcur].len = slot->len; /* XXX swap src dst mac */ txcur = NETMAP_RING_NEXT(txring, txcur); txavail--; sent++; } } txring->cur = txcur; txring->avail = txavail; targ->count = sent; #ifdef BUSYWAIT ioctl(fds[0].fd, NIOCTXSYNC, NULL); #endif //D("tx %d rx %d", sent, rx); } return NULL; } static void * sender_body(void *data) { struct targ *targ = (struct targ *) data; struct pollfd fds[1]; struct netmap_if *nifp = targ->nifp; struct netmap_ring *txring; int i, n = targ->g->npackets / targ->g->nthreads, sent = 0; int options = targ->g->options | OPT_COPY; D("start"); if (setaffinity(targ->thread, targ->affinity)) goto quit; /* setup poll(2) mechanism. */ memset(fds, 0, sizeof(fds)); fds[0].fd = targ->fd; fds[0].events = (POLLOUT); /* main loop.*/ gettimeofday(&targ->tic, NULL); if (targ->g->dev_type == DEV_PCAP) { int size = targ->g->pkt_size; void *pkt = &targ->pkt; pcap_t *p = targ->g->p; for (i = 0; !targ->cancel && (n == 0 || sent < n); i++) { if (pcap_inject(p, pkt, size) != -1) sent++; if (i > 10000) { targ->count = sent; i = 0; } } } else if (targ->g->dev_type == DEV_TAP) { /* tap */ int size = targ->g->pkt_size; void *pkt = &targ->pkt; D("writing to file desc %d", targ->g->main_fd); for (i = 0; !targ->cancel && (n == 0 || sent < n); i++) { if (write(targ->g->main_fd, pkt, size) != -1) sent++; if (i > 10000) { targ->count = sent; i = 0; } } } else { while (!targ->cancel && (n == 0 || sent < n)) { /* * wait for available room in the send queue(s) */ if (poll(fds, 1, 2000) <= 0) { if (targ->cancel) break; D("poll error/timeout on queue %d", targ->me); goto quit; } /* * scan our queues and send on those with room */ if (options & OPT_COPY && sent > 100000 && !(targ->g->options & OPT_COPY) ) { D("drop copy"); options &= ~OPT_COPY; } for (i = targ->qfirst; i < targ->qlast; i++) { int m, limit = targ->g->burst; if (n > 0 && n - sent < limit) limit = n - sent; txring = NETMAP_TXRING(nifp, i); if (txring->avail == 0) continue; m = send_packets(txring, &targ->pkt, targ->g->pkt_size, limit, options); sent += m; targ->count = sent; } } /* flush any remaining packets */ ioctl(fds[0].fd, NIOCTXSYNC, NULL); /* final part: wait all the TX queues to be empty. */ for (i = targ->qfirst; i < targ->qlast; i++) { txring = NETMAP_TXRING(nifp, i); while (!NETMAP_TX_RING_EMPTY(txring)) { ioctl(fds[0].fd, NIOCTXSYNC, NULL); usleep(1); /* wait 1 tick */ } } } gettimeofday(&targ->toc, NULL); targ->completed = 1; targ->count = sent; quit: /* reset the ``used`` flag. */ targ->used = 0; return (NULL); } static void receive_pcap(u_char *user, const struct pcap_pkthdr * h, const u_char * bytes) { int *count = (int *)user; (void)h; /* UNUSED */ (void)bytes; /* UNUSED */ (*count)++; } static int receive_packets(struct netmap_ring *ring, u_int limit, int skip_payload) { u_int cur, rx; cur = ring->cur; if (ring->avail < limit) limit = ring->avail; for (rx = 0; rx < limit; rx++) { struct netmap_slot *slot = &ring->slot[cur]; char *p = NETMAP_BUF(ring, slot->buf_idx); if (!skip_payload) check_payload(p, slot->len); cur = NETMAP_RING_NEXT(ring, cur); } ring->avail -= rx; ring->cur = cur; return (rx); } static void * receiver_body(void *data) { struct targ *targ = (struct targ *) data; struct pollfd fds[1]; struct netmap_if *nifp = targ->nifp; struct netmap_ring *rxring; int i; uint64_t received = 0; if (setaffinity(targ->thread, targ->affinity)) goto quit; /* setup poll(2) mechanism. */ memset(fds, 0, sizeof(fds)); fds[0].fd = targ->fd; fds[0].events = (POLLIN); /* unbounded wait for the first packet. */ for (;;) { i = poll(fds, 1, 1000); if (i > 0 && !(fds[0].revents & POLLERR)) break; D("waiting for initial packets, poll returns %d %d", i, fds[0].revents); } /* main loop, exit after 1s silence */ gettimeofday(&targ->tic, NULL); if (targ->g->dev_type == DEV_PCAP) { while (!targ->cancel) { /* XXX should we poll ? */ pcap_dispatch(targ->g->p, targ->g->burst, receive_pcap, NULL); } } else if (targ->g->dev_type == DEV_TAP) { D("reading from %s fd %d", targ->g->ifname, targ->g->main_fd); while (!targ->cancel) { char buf[2048]; /* XXX should we poll ? */ if (read(targ->g->main_fd, buf, sizeof(buf)) > 0) targ->count++; } } else { while (!targ->cancel) { /* Once we started to receive packets, wait at most 1 seconds before quitting. */ if (poll(fds, 1, 1 * 1000) <= 0 && targ->g->forever == 0) { gettimeofday(&targ->toc, NULL); targ->toc.tv_sec -= 1; /* Subtract timeout time. */ break; } for (i = targ->qfirst; i < targ->qlast; i++) { int m; rxring = NETMAP_RXRING(nifp, i); if (rxring->avail == 0) continue; m = receive_packets(rxring, targ->g->burst, SKIP_PAYLOAD); received += m; } targ->count = received; // tell the card we have read the data //ioctl(fds[0].fd, NIOCRXSYNC, NULL); } } targ->completed = 1; targ->count = received; quit: /* reset the ``used`` flag. */ targ->used = 0; return (NULL); } /* very crude code to print a number in normalized form. * Caller has to make sure that the buffer is large enough. */ static const char * norm(char *buf, double val) { char *units[] = { "", "K", "M", "G" }; u_int i; for (i = 0; val >=1000 && i < sizeof(units)/sizeof(char *); i++) val /= 1000; sprintf(buf, "%.2f %s", val, units[i]); return buf; } static void tx_output(uint64_t sent, int size, double delta) { double bw, raw_bw, pps; char b1[40], b2[80], b3[80]; printf("Sent %" PRIu64 " packets, %d bytes each, in %.2f seconds.\n", sent, size, delta); if (delta == 0) delta = 1e-6; if (size < 60) /* correct for min packet size */ size = 60; pps = sent / delta; bw = (8.0 * size * sent) / delta; /* raw packets have4 bytes crc + 20 bytes framing */ raw_bw = (8.0 * (size + 24) * sent) / delta; printf("Speed: %spps Bandwidth: %sbps (raw %sbps)\n", norm(b1, pps), norm(b2, bw), norm(b3, raw_bw) ); } static void rx_output(uint64_t received, double delta) { double pps; char b1[40]; printf("Received %" PRIu64 " packets, in %.2f seconds.\n", received, delta); if (delta == 0) delta = 1e-6; pps = received / delta; printf("Speed: %spps\n", norm(b1, pps)); } static void usage(void) { const char *cmd = "pkt-gen"; fprintf(stderr, "Usage:\n" "%s arguments\n" "\t-i interface interface name\n" "\t-f function tx rx ping pong\n" "\t-n count number of iterations (can be 0)\n" "\t-t pkts_to_send also forces tx mode\n" "\t-r pkts_to_receive also forces rx mode\n" "\t-l pkts_size in bytes excluding CRC\n" "\t-d dst-ip end with %%n to sweep n addresses\n" "\t-s src-ip end with %%n to sweep n addresses\n" "\t-D dst-mac end with %%n to sweep n addresses\n" "\t-S src-mac end with %%n to sweep n addresses\n" "\t-a cpu_id use setaffinity\n" "\t-b burst size testing, mostly\n" "\t-c cores cores to use\n" "\t-p threads processes/threads to use\n" "\t-T report_ms milliseconds between reports\n" "\t-P use libpcap instead of netmap\n" "\t-w wait_for_link_time in seconds\n" "", cmd); exit(0); } static void start_threads(struct glob_arg *g) { int i; targs = calloc(g->nthreads, sizeof(*targs)); /* * Now create the desired number of threads, each one * using a single descriptor. */ for (i = 0; i < g->nthreads; i++) { bzero(&targs[i], sizeof(targs[i])); targs[i].fd = -1; /* default, with pcap */ targs[i].g = g; if (g->dev_type == DEV_NETMAP) { struct nmreq tifreq; int tfd; /* register interface. */ tfd = open("/dev/netmap", O_RDWR); if (tfd == -1) { D("Unable to open /dev/netmap"); continue; } targs[i].fd = tfd; bzero(&tifreq, sizeof(tifreq)); strncpy(tifreq.nr_name, g->ifname, sizeof(tifreq.nr_name)); tifreq.nr_version = NETMAP_API; tifreq.nr_ringid = (g->nthreads > 1) ? (i | NETMAP_HW_RING) : 0; /* * if we are acting as a receiver only, do not touch the transmit ring. * This is not the default because many apps may use the interface * in both directions, but a pure receiver does not. */ if (g->td_body == receiver_body) { tifreq.nr_ringid |= NETMAP_NO_TX_POLL; } if ((ioctl(tfd, NIOCREGIF, &tifreq)) == -1) { D("Unable to register %s", g->ifname); continue; } targs[i].nmr = tifreq; targs[i].nifp = NETMAP_IF(g->mmap_addr, tifreq.nr_offset); /* start threads. */ targs[i].qfirst = (g->nthreads > 1) ? i : 0; targs[i].qlast = (g->nthreads > 1) ? i+1 : (g->td_body == receiver_body ? tifreq.nr_rx_rings : tifreq.nr_tx_rings); } else { targs[i].fd = g->main_fd; } targs[i].used = 1; targs[i].me = i; if (g->affinity >= 0) { if (g->affinity < g->cpus) targs[i].affinity = g->affinity; else targs[i].affinity = i % g->cpus; } else targs[i].affinity = -1; /* default, init packets */ initialize_packet(&targs[i]); if (pthread_create(&targs[i].thread, NULL, g->td_body, &targs[i]) == -1) { D("Unable to create thread %d", i); targs[i].used = 0; } } } static void main_thread(struct glob_arg *g) { int i; uint64_t prev = 0; uint64_t count = 0; double delta_t; struct timeval tic, toc; gettimeofday(&toc, NULL); for (;;) { struct timeval now, delta; uint64_t pps, usec, my_count, npkts; int done = 0; delta.tv_sec = g->report_interval/1000; delta.tv_usec = (g->report_interval%1000)*1000; select(0, NULL, NULL, NULL, &delta); gettimeofday(&now, NULL); time_second = now.tv_sec; timersub(&now, &toc, &toc); my_count = 0; for (i = 0; i < g->nthreads; i++) { my_count += targs[i].count; if (targs[i].used == 0) done++; } usec = toc.tv_sec* 1000000 + toc.tv_usec; if (usec < 10000) continue; npkts = my_count - prev; pps = (npkts*1000000 + usec/2) / usec; D("%" PRIu64 " pps (%" PRIu64 " pkts in %" PRIu64 " usec)", pps, npkts, usec); prev = my_count; toc = now; if (done == g->nthreads) break; } timerclear(&tic); timerclear(&toc); for (i = 0; i < g->nthreads; i++) { /* * Join active threads, unregister interfaces and close * file descriptors. */ pthread_join(targs[i].thread, NULL); close(targs[i].fd); if (targs[i].completed == 0) D("ouch, thread %d exited with error", i); /* * Collect threads output and extract information about * how long it took to send all the packets. */ count += targs[i].count; if (!timerisset(&tic) || timercmp(&targs[i].tic, &tic, <)) tic = targs[i].tic; if (!timerisset(&toc) || timercmp(&targs[i].toc, &toc, >)) toc = targs[i].toc; } /* print output. */ timersub(&toc, &tic, &toc); delta_t = toc.tv_sec + 1e-6* toc.tv_usec; if (g->td_body == sender_body) tx_output(count, g->pkt_size, delta_t); else rx_output(count, delta_t); if (g->dev_type == DEV_NETMAP) { ioctl(g->main_fd, NIOCUNREGIF, NULL); // XXX deprecated munmap(g->mmap_addr, g->mmap_size); close(g->main_fd); } } struct sf { char *key; void *f; }; static struct sf func[] = { { "tx", sender_body }, { "rx", receiver_body }, { "ping", pinger_body }, { "pong", ponger_body }, { NULL, NULL } }; static int tap_alloc(char *dev) { struct ifreq ifr; int fd, err; char *clonedev = TAP_CLONEDEV; (void)err; (void)dev; /* Arguments taken by the function: * * char *dev: the name of an interface (or '\0'). MUST have enough * space to hold the interface name if '\0' is passed * int flags: interface flags (eg, IFF_TUN etc.) */ #ifdef __FreeBSD__ if (dev[3]) { /* tapSomething */ static char buf[128]; snprintf(buf, sizeof(buf), "/dev/%s", dev); clonedev = buf; } #endif /* open the device */ if( (fd = open(clonedev, O_RDWR)) < 0 ) { return fd; } D("%s open successful", clonedev); /* preparation of the struct ifr, of type "struct ifreq" */ memset(&ifr, 0, sizeof(ifr)); #ifdef linux ifr.ifr_flags = IFF_TAP | IFF_NO_PI; if (*dev) { /* if a device name was specified, put it in the structure; otherwise, * the kernel will try to allocate the "next" device of the * specified type */ strncpy(ifr.ifr_name, dev, IFNAMSIZ); } /* try to create the device */ if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ) { D("failed to to a TUNSETIFF"); close(fd); return err; } /* if the operation was successful, write back the name of the * interface to the variable "dev", so the caller can know * it. Note that the caller MUST reserve space in *dev (see calling * code below) */ strcpy(dev, ifr.ifr_name); D("new name is %s", dev); #endif /* linux */ /* this is the special file descriptor that the caller will use to talk * with the virtual interface */ return fd; } int main(int arc, char **argv) { int i; struct glob_arg g; struct nmreq nmr; int ch; int wait_link = 2; int devqueues = 1; /* how many device queues */ bzero(&g, sizeof(g)); g.main_fd = -1; g.td_body = receiver_body; g.report_interval = 1000; /* report interval */ g.affinity = -1; /* ip addresses can also be a range x.x.x.x-x.x.x.y */ g.src_ip.name = "10.0.0.1"; g.dst_ip.name = "10.1.0.1"; g.dst_mac.name = "ff:ff:ff:ff:ff:ff"; g.src_mac.name = NULL; g.pkt_size = 60; g.burst = 512; // default g.nthreads = 1; g.cpus = 1; while ( (ch = getopt(arc, argv, "a:f:n:i:t:r:l:d:s:D:S:b:c:o:p:PT:w:Wv")) != -1) { struct sf *fn; switch(ch) { default: D("bad option %c %s", ch, optarg); usage(); break; case 'n': g.npackets = atoi(optarg); break; case 'f': for (fn = func; fn->key; fn++) { if (!strcmp(fn->key, optarg)) break; } if (fn->key) g.td_body = fn->f; else D("unrecognised function %s", optarg); break; case 'o': /* data generation options */ g.options = atoi(optarg); break; case 'a': /* force affinity */ g.affinity = atoi(optarg); break; case 'i': /* interface */ g.ifname = optarg; if (!strncmp(optarg, "tap", 3)) g.dev_type = DEV_TAP; else g.dev_type = DEV_NETMAP; break; case 't': /* send, deprecated */ D("-t deprecated, please use -f tx -n %s", optarg); g.td_body = sender_body; g.npackets = atoi(optarg); break; case 'r': /* receive */ D("-r deprecated, please use -f rx -n %s", optarg); g.td_body = receiver_body; g.npackets = atoi(optarg); break; case 'l': /* pkt_size */ g.pkt_size = atoi(optarg); break; case 'd': g.dst_ip.name = optarg; break; case 's': g.src_ip.name = optarg; break; case 'T': /* report interval */ g.report_interval = atoi(optarg); break; case 'w': wait_link = atoi(optarg); break; case 'W': g.forever = 1; /* do not exit rx even with no traffic */ break; case 'b': /* burst */ g.burst = atoi(optarg); break; case 'c': g.cpus = atoi(optarg); break; case 'p': g.nthreads = atoi(optarg); break; case 'P': g.dev_type = DEV_PCAP; break; case 'D': /* destination mac */ g.dst_mac.name = optarg; break; case 'S': /* source mac */ g.src_mac.name = optarg; break; case 'v': verbose++; } } if (g.ifname == NULL) { D("missing ifname"); usage(); } i = system_ncpus(); if (g.cpus < 0 || g.cpus > i) { D("%d cpus is too high, have only %d cpus", g.cpus, i); usage(); } if (g.cpus == 0) g.cpus = i; if (g.pkt_size < 16 || g.pkt_size > 1536) { D("bad pktsize %d\n", g.pkt_size); usage(); } if (g.src_mac.name == NULL) { static char mybuf[20] = "00:00:00:00:00:00"; /* retrieve source mac address. */ if (source_hwaddr(g.ifname, mybuf) == -1) { D("Unable to retrieve source mac"); // continue, fail later } g.src_mac.name = mybuf; } /* extract address ranges */ extract_ip_range(&g.src_ip); extract_ip_range(&g.dst_ip); extract_mac_range(&g.src_mac); extract_mac_range(&g.dst_mac); if (g.dev_type == DEV_TAP) { D("want to use tap %s", g.ifname); g.main_fd = tap_alloc(g.ifname); if (g.main_fd < 0) { D("cannot open tap %s", g.ifname); usage(); } } else if (g.dev_type > DEV_NETMAP) { char pcap_errbuf[PCAP_ERRBUF_SIZE]; D("using pcap on %s", g.ifname); pcap_errbuf[0] = '\0'; // init the buffer g.p = pcap_open_live(g.ifname, 0, 1, 100, pcap_errbuf); if (g.p == NULL) { D("cannot open pcap on %s", g.ifname); usage(); } } else { bzero(&nmr, sizeof(nmr)); nmr.nr_version = NETMAP_API; /* * Open the netmap device to fetch the number of queues of our * interface. * * The first NIOCREGIF also detaches the card from the * protocol stack and may cause a reset of the card, * which in turn may take some time for the PHY to * reconfigure. */ g.main_fd = open("/dev/netmap", O_RDWR); if (g.main_fd == -1) { D("Unable to open /dev/netmap"); // fail later } else { if ((ioctl(g.main_fd, NIOCGINFO, &nmr)) == -1) { D("Unable to get if info without name"); } else { D("map size is %d Kb", nmr.nr_memsize >> 10); } bzero(&nmr, sizeof(nmr)); nmr.nr_version = NETMAP_API; strncpy(nmr.nr_name, g.ifname, sizeof(nmr.nr_name)); if ((ioctl(g.main_fd, NIOCGINFO, &nmr)) == -1) { D("Unable to get if info for %s", g.ifname); } devqueues = nmr.nr_rx_rings; } /* validate provided nthreads. */ if (g.nthreads < 1 || g.nthreads > devqueues) { D("bad nthreads %d, have %d queues", g.nthreads, devqueues); // continue, fail later } /* * Map the netmap shared memory: instead of issuing mmap() * inside the body of the threads, we prefer to keep this * operation here to simplify the thread logic. */ D("mapping %d Kbytes", nmr.nr_memsize>>10); g.mmap_size = nmr.nr_memsize; g.mmap_addr = (struct netmap_d *) mmap(0, nmr.nr_memsize, PROT_WRITE | PROT_READ, MAP_SHARED, g.main_fd, 0); if (g.mmap_addr == MAP_FAILED) { D("Unable to mmap %d KB", nmr.nr_memsize >> 10); // continue, fail later } /* * Register the interface on the netmap device: from now on, * we can operate on the network interface without any * interference from the legacy network stack. * * We decide to put the first interface registration here to * give time to cards that take a long time to reset the PHY. */ nmr.nr_version = NETMAP_API; if (ioctl(g.main_fd, NIOCREGIF, &nmr) == -1) { D("Unable to register interface %s", g.ifname); //continue, fail later } /* Print some debug information. */ fprintf(stdout, "%s %s: %d queues, %d threads and %d cpus.\n", (g.td_body == sender_body) ? "Sending on" : "Receiving from", g.ifname, devqueues, g.nthreads, g.cpus); if (g.td_body == sender_body) { fprintf(stdout, "%s -> %s (%s -> %s)\n", g.src_ip.name, g.dst_ip.name, g.src_mac.name, g.dst_mac.name); } /* Exit if something went wrong. */ if (g.main_fd < 0) { D("aborting"); usage(); } } if (g.options) { D("special options:%s%s%s%s\n", g.options & OPT_PREFETCH ? " prefetch" : "", g.options & OPT_ACCESS ? " access" : "", g.options & OPT_MEMCPY ? " memcpy" : "", g.options & OPT_COPY ? " copy" : ""); } /* Wait for PHY reset. */ D("Wait %d secs for phy reset", wait_link); sleep(wait_link); D("Ready..."); /* Install ^C handler. */ global_nthreads = g.nthreads; signal(SIGINT, sigint_h); #if 0 // XXX this is not needed, i believe if (g.dev_type > DEV_NETMAP) { g.p = pcap_open_live(g.ifname, 0, 1, 100, NULL); if (g.p == NULL) { D("cannot open pcap on %s", g.ifname); usage(); } else D("using pcap %p on %s", g.p, g.ifname); } #endif // XXX start_threads(&g); main_thread(&g); return 0; } /* end of file */ netmap-release/examples/Makefile000644 000423 000000 00000002133 12103733570 017474 0ustar00luigiwheel000000 000000 # For multiple programs using a single source file each, # we can just define 'progs' and create custom targets. PROGS = pkt-gen bridge testpcap libnetmap.so #PROGS += pingd PROGS += testlock testcsum test_select kern_test testmmap CLEANFILES = $(PROGS) pcap.o nm_util.o *.o NO_MAN= CFLAGS = -O2 -pipe CFLAGS += -Werror -Wall CFLAGS += -I ../sys # -I/home/luigi/FreeBSD/head/sys -I../sys CFLAGS += -Wextra CFLAGS += -DNO_PCAP LDFLAGS += -lpthread #LDFLAGS += -lpcap #LDFLAGS += -lrt # on linux #SRCS = pkt-gen.c all: $(PROGS) testpcap: pcap.c libnetmap.so nm_util.o $(CC) $(CFLAGS) -DTEST -o testpcap pcap.c nm_util.o $(LDFLAGS) -lpcap kern_test: testmod/kern_test.c nm_util.o pkt-gen.o bridge.o libnetmap.so pcap.o: nm_util.h pkt-gen: pkt-gen.o nm_util.o $(CC) $(CFLAGS) -o pkt-gen pkt-gen.o nm_util.o $(LDFLAGS) bridge: bridge.o nm_util.o libnetmap.so: pcap.c nm_util.c $(CC) $(CFLAGS) -fpic -c pcap.c $(CC) $(CFLAGS) -fpic -c nm_util.c $(CC) -shared -o libnetmap.so pcap.o nm_util.o clean: -@rm -rf $(CLEANFILES) testlock: testlock.c $(CC) $(CFLAGS) -o testlock testlock.c -lpthread $(LDFLAGS) netmap-release/examples/README000644 000423 000000 00000000507 11703265240 016716 0ustar00luigiwheel000000 000000 $FreeBSD: head/tools/tools/netmap/README 227614 2011-11-17 12:17:39Z luigi $ This directory contains examples that use netmap pkt-gen a packet sink/source using the netmap API bridge a two-port jumper wire, also using the native API testpcap a jumper wire using libnetmap (or libpcap) click* various click examples netmap-release/examples/bridge.c000644 000423 000000 00000015364 12100017020 017424 0ustar00luigiwheel000000 000000 /* * (C) 2011 Luigi Rizzo, Matteo Landi * * BSD license * * A netmap client to bridge two network interfaces * (or one interface and the host stack). * * $FreeBSD: head/tools/tools/netmap/bridge.c 228975 2011-12-30 00:04:11Z uqs $ */ #include "nm_util.h" int verbose = 0; char *version = "$Id: bridge.c 12016 2013-01-23 17:24:22Z luigi $"; static int do_abort = 0; static void sigint_h(int sig) { (void)sig; /* UNUSED */ do_abort = 1; signal(SIGINT, SIG_DFL); } /* * move up to 'limit' pkts from rxring to txring swapping buffers. */ static int process_rings(struct netmap_ring *rxring, struct netmap_ring *txring, u_int limit, const char *msg) { u_int j, k, m = 0; /* print a warning if any of the ring flags is set (e.g. NM_REINIT) */ if (rxring->flags || txring->flags) D("%s rxflags %x txflags %x", msg, rxring->flags, txring->flags); j = rxring->cur; /* RX */ k = txring->cur; /* TX */ if (rxring->avail < limit) limit = rxring->avail; if (txring->avail < limit) limit = txring->avail; m = limit; while (limit-- > 0) { struct netmap_slot *rs = &rxring->slot[j]; struct netmap_slot *ts = &txring->slot[k]; uint32_t pkt; /* swap packets */ if (ts->buf_idx < 2 || rs->buf_idx < 2) { D("wrong index rx[%d] = %d -> tx[%d] = %d", j, rs->buf_idx, k, ts->buf_idx); sleep(2); } pkt = ts->buf_idx; ts->buf_idx = rs->buf_idx; rs->buf_idx = pkt; /* copy the packet length. */ if (rs->len < 14 || rs->len > 2048) D("wrong len %d rx[%d] -> tx[%d]", rs->len, j, k); else if (verbose > 1) D("%s send len %d rx[%d] -> tx[%d]", msg, rs->len, j, k); ts->len = rs->len; /* report the buffer change. */ ts->flags |= NS_BUF_CHANGED; rs->flags |= NS_BUF_CHANGED; j = NETMAP_RING_NEXT(rxring, j); k = NETMAP_RING_NEXT(txring, k); } rxring->avail -= m; txring->avail -= m; rxring->cur = j; txring->cur = k; if (verbose && m > 0) D("%s sent %d packets to %p", msg, m, txring); return (m); } /* move packts from src to destination */ static int move(struct my_ring *src, struct my_ring *dst, u_int limit) { struct netmap_ring *txring, *rxring; u_int m = 0, si = src->begin, di = dst->begin; const char *msg = (src->queueid & NETMAP_SW_RING) ? "host->net" : "net->host"; while (si < src->end && di < dst->end) { rxring = NETMAP_RXRING(src->nifp, si); txring = NETMAP_TXRING(dst->nifp, di); ND("txring %p rxring %p", txring, rxring); if (rxring->avail == 0) { si++; continue; } if (txring->avail == 0) { di++; continue; } m += process_rings(rxring, txring, limit, msg); } return (m); } /* * how many packets on this set of queues ? */ static int pkt_queued(struct my_ring *me, int tx) { u_int i, tot = 0; ND("me %p begin %d end %d", me, me->begin, me->end); for (i = me->begin; i < me->end; i++) { struct netmap_ring *ring = tx ? NETMAP_TXRING(me->nifp, i) : NETMAP_RXRING(me->nifp, i); tot += ring->avail; } if (0 && verbose && tot && !tx) D("ring %s %s %s has %d avail at %d", me->ifname, tx ? "tx": "rx", me->end >= me->nifp->ni_tx_rings ? // XXX who comes first ? "host":"net", tot, NETMAP_TXRING(me->nifp, me->begin)->cur); return tot; } static void usage(void) { fprintf(stderr, "usage: bridge [-v] [-i ifa] [-i ifb] [-b burst] [-w wait_time] [iface]\n"); exit(1); } /* * bridge [-v] if1 [if2] * * If only one name, or the two interfaces are the same, * bridges userland and the adapter. Otherwise bridge * two intefaces. */ int main(int argc, char **argv) { struct pollfd pollfd[2]; int i, ch; u_int burst = 1024, wait_link = 4; struct my_ring me[2]; char *ifa = NULL, *ifb = NULL; fprintf(stderr, "%s %s built %s %s\n", argv[0], version, __DATE__, __TIME__); bzero(me, sizeof(me)); while ( (ch = getopt(argc, argv, "b:i:vw:")) != -1) { switch (ch) { default: D("bad option %c %s", ch, optarg); usage(); break; case 'b': /* burst */ burst = atoi(optarg); break; case 'i': /* interface */ if (ifa == NULL) ifa = optarg; else if (ifb == NULL) ifb = optarg; else D("%s ignored, already have 2 interfaces", optarg); break; case 'v': verbose++; break; case 'w': wait_link = atoi(optarg); break; } } argc -= optind; argv += optind; if (argc > 1) ifa = argv[1]; if (argc > 2) ifb = argv[2]; if (argc > 3) burst = atoi(argv[3]); if (!ifb) ifb = ifa; if (!ifa) { D("missing interface"); usage(); } if (burst < 1 || burst > 8192) { D("invalid burst %d, set to 1024", burst); burst = 1024; } if (wait_link > 100) { D("invalid wait_link %d, set to 4", wait_link); wait_link = 4; } /* setup netmap interface #1. */ me[0].ifname = ifa; me[1].ifname = ifb; if (!strcmp(ifa, ifb)) { D("same interface, endpoint 0 goes to host"); i = NETMAP_SW_RING; } else { /* two different interfaces. Take all rings on if1 */ i = 0; // all hw rings } if (netmap_open(me, i, 1)) return (1); me[1].mem = me[0].mem; /* copy the pointer, so only one mmap */ if (netmap_open(me+1, 0, 1)) return (1); /* setup poll(2) variables. */ memset(pollfd, 0, sizeof(pollfd)); for (i = 0; i < 2; i++) { pollfd[i].fd = me[i].fd; pollfd[i].events = (POLLIN); } D("Wait %d secs for link to come up...", wait_link); sleep(wait_link); D("Ready to go, %s 0x%x/%d <-> %s 0x%x/%d.", me[0].ifname, me[0].queueid, me[0].nifp->ni_rx_rings, me[1].ifname, me[1].queueid, me[1].nifp->ni_rx_rings); /* main loop */ signal(SIGINT, sigint_h); while (!do_abort) { int n0, n1, ret; pollfd[0].events = pollfd[1].events = 0; pollfd[0].revents = pollfd[1].revents = 0; n0 = pkt_queued(me, 0); n1 = pkt_queued(me + 1, 0); if (n0) pollfd[1].events |= POLLOUT; else pollfd[0].events |= POLLIN; if (n1) pollfd[0].events |= POLLOUT; else pollfd[1].events |= POLLIN; ret = poll(pollfd, 2, 2500); if (ret <= 0 || verbose) D("poll %s [0] ev %x %x rx %d@%d tx %d," " [1] ev %x %x rx %d@%d tx %d", ret <= 0 ? "timeout" : "ok", pollfd[0].events, pollfd[0].revents, pkt_queued(me, 0), me[0].rx->cur, pkt_queued(me, 1), pollfd[1].events, pollfd[1].revents, pkt_queued(me+1, 0), me[1].rx->cur, pkt_queued(me+1, 1) ); if (ret < 0) continue; if (pollfd[0].revents & POLLERR) { D("error on fd0, rxcur %d@%d", me[0].rx->avail, me[0].rx->cur); } if (pollfd[1].revents & POLLERR) { D("error on fd1, rxcur %d@%d", me[1].rx->avail, me[1].rx->cur); } if (pollfd[0].revents & POLLOUT) { move(me + 1, me, burst); // XXX we don't need the ioctl */ // ioctl(me[0].fd, NIOCTXSYNC, NULL); } if (pollfd[1].revents & POLLOUT) { move(me, me + 1, burst); // XXX we don't need the ioctl */ // ioctl(me[1].fd, NIOCTXSYNC, NULL); } } D("exiting"); netmap_close(me + 1); netmap_close(me + 0); return (0); } netmap-release/examples/testlock.c000644 000423 000000 00000041572 12100115752 020033 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2012 Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $Id: testlock.c 12022 2013-01-24 02:20:24Z luigi $ * * Test program to study various ops and concurrency issues. * Create multiple threads, possibly bind to cpus, and run a workload. * * cc -O2 -Werror -Wall testlock.c -o testlock -lpthread * you might need -lrt */ #include #include #include /* pthread_* */ #if defined(__APPLE__) #include #define atomic_add_int(p, n) OSAtomicAdd32(n, (int *)p) #define atomic_cmpset_32(p, o, n) OSAtomicCompareAndSwap32(o, n, (int *)p) #elif defined(linux) int atomic_cmpset_32(volatile uint32_t *p, uint32_t old, uint32_t new) { int ret = *p == old; *p = new; return ret; } #if defined(HAVE_GCC_ATOMICS) int atomic_add_int(volatile int *p, int v) { return __sync_fetch_and_add(p, v); } #else inline uint32_t atomic_add_int(uint32_t *p, int v) { __asm __volatile ( " lock xaddl %0, %1 ; " : "+r" (v), /* 0 (result) */ "=m" (*p) /* 1 */ : "m" (*p)); /* 2 */ return (v); } #endif #else /* FreeBSD */ #include #include #include /* pthread w/ affinity */ #if __FreeBSD_version > 500000 #include /* cpu_set */ #if __FreeBSD_version > 800000 #define HAVE_AFFINITY #endif inline void prefetch (const void *x) { __asm volatile("prefetcht0 %0" :: "m" (*(const unsigned long *)x)); } #else /* FreeBSD 4.x */ int atomic_cmpset_32(volatile uint32_t *p, uint32_t old, uint32_t new) { int ret = *p == old; *p = new; return ret; } #define PRIu64 "llu" #endif /* FreeBSD 4.x */ #endif /* FreeBSD */ #include /* signal */ #include #include #include #include /* PRI* macros */ #include /* strcmp */ #include /* open */ #include /* getopt */ #include /* sysctl */ #include /* timersub */ static inline int min(int a, int b) { return a < b ? a : b; } #define ONE_MILLION 1000000 /* debug support */ #define ND(format, ...) #define D(format, ...) \ fprintf(stderr, "%s [%d] " format "\n", \ __FUNCTION__, __LINE__, ##__VA_ARGS__) int verbose = 0; #if 1//def MY_RDTSC /* Wrapper around `rdtsc' to take reliable timestamps flushing the pipeline */ #define my_rdtsc(t) \ do { \ u_int __regs[4]; \ \ do_cpuid(0, __regs); \ (t) = rdtsc(); \ } while (0) static __inline void do_cpuid(u_int ax, u_int *p) { __asm __volatile("cpuid" : "=a" (p[0]), "=b" (p[1]), "=c" (p[2]), "=d" (p[3]) : "0" (ax) ); } static __inline uint64_t rdtsc(void) { uint64_t rv; // XXX does not work on linux-64 bit __asm __volatile("rdtscp" : "=A" (rv) : : "%rax"); return (rv); } #endif /* 1 */ struct targ; /*** global arguments for all threads ***/ struct glob_arg { struct { uint32_t ctr[1024]; } v __attribute__ ((aligned(256) )); int64_t m_cycles; /* total cycles */ int nthreads; int cpus; int privs; // 1 if has IO privileges int arg; // microseconds in usleep char *test_name; void (*fn)(struct targ *); uint64_t scale; // scaling factor char *scale_name; // scaling factor }; /* * Arguments for a new thread. */ struct targ { struct glob_arg *g; int completed; u_int *glob_ctr; uint64_t volatile count; struct timeval tic, toc; int me; pthread_t thread; int affinity; }; static struct targ *ta; static int global_nthreads; /* control-C handler */ static void sigint_h(int sig) { int i; (void)sig; /* UNUSED */ for (i = 0; i < global_nthreads; i++) { /* cancel active threads. */ if (ta[i].completed) continue; D("Cancelling thread #%d\n", i); pthread_cancel(ta[i].thread); ta[i].completed = 0; } signal(SIGINT, SIG_DFL); } /* sysctl wrapper to return the number of active CPUs */ static int system_ncpus(void) { #ifdef linux return 1; #else int mib[2] = { CTL_HW, HW_NCPU}, ncpus; size_t len = sizeof(mib); sysctl(mib, len / sizeof(mib[0]), &ncpus, &len, NULL, 0); D("system had %d cpus", ncpus); return (ncpus); #endif } /* * try to get I/O privileges so we can execute cli/sti etc. */ int getprivs(void) { int fd = open("/dev/io", O_RDWR); if (fd < 0) { D("cannot open /dev/io, fd %d", fd); return 0; } return 1; } /* set the thread affinity. */ /* ARGSUSED */ #ifdef HAVE_AFFINITY static int setaffinity(pthread_t me, int i) { cpuset_t cpumask; if (i == -1) return 0; /* Set thread affinity affinity.*/ CPU_ZERO(&cpumask); CPU_SET(i, &cpumask); if (pthread_setaffinity_np(me, sizeof(cpuset_t), &cpumask) != 0) { D("Unable to set affinity"); return 1; } return 0; } #endif static void * td_body(void *data) { struct targ *t = (struct targ *) data; #ifdef HAVE_AFFINITY if (0 == setaffinity(t->thread, t->affinity)) #endif { /* main loop.*/ D("testing %ld cycles", t->g->m_cycles); gettimeofday(&t->tic, NULL); t->g->fn(t); gettimeofday(&t->toc, NULL); } t->completed = 1; return (NULL); } void test_sel(struct targ *t) { int64_t m; for (m = 0; m < t->g->m_cycles; m++) { fd_set r; struct timeval to = { 0, t->g->arg}; FD_ZERO(&r); FD_SET(0,&r); // FD_SET(1,&r); select(1, &r, NULL, NULL, &to); t->count++; } } void test_poll(struct targ *t) { int64_t m, ms = t->g->arg/1000; for (m = 0; m < t->g->m_cycles; m++) { struct pollfd x; x.fd = 0; x.events = POLLIN; poll(&x, 1, ms); t->count++; } } void test_usleep(struct targ *t) { int64_t m; for (m = 0; m < t->g->m_cycles; m++) { usleep(t->g->arg); t->count++; } } void test_cli(struct targ *t) { int64_t m, i; if (!t->g->privs) { D("%s", "privileged instructions not available"); return; } for (m = 0; m < t->g->m_cycles; m++) { for (i = 0; i < ONE_MILLION; i++) { __asm __volatile("cli;"); __asm __volatile("and %eax, %eax;"); __asm __volatile("sti;"); t->count++; } } } void test_nop(struct targ *t) { int64_t m, i; for (m = 0; m < t->g->m_cycles; m++) { for (i = 0; i < ONE_MILLION; i++) { __asm __volatile("nop;"); __asm __volatile("nop; nop; nop; nop; nop;"); //__asm __volatile("nop; nop; nop; nop; nop;"); t->count++; } } } void test_rdtsc1(struct targ *t) { int64_t m, i; uint64_t v; (void)v; for (m = 0; m < t->g->m_cycles; m++) { for (i = 0; i < ONE_MILLION; i++) { my_rdtsc(v); t->count++; } } } void test_rdtsc(struct targ *t) { int64_t m, i; volatile uint64_t v; (void)v; for (m = 0; m < t->g->m_cycles; m++) { for (i = 0; i < ONE_MILLION; i++) { v = rdtsc(); t->count++; } } } void test_add(struct targ *t) { int64_t m, i; for (m = 0; m < t->g->m_cycles; m++) { for (i = 0; i < ONE_MILLION; i++) { t->glob_ctr[0] ++; t->count++; } } } void test_atomic_add(struct targ *t) { int64_t m, i; for (m = 0; m < t->g->m_cycles; m++) { for (i = 0; i < ONE_MILLION; i++) { atomic_add_int(t->glob_ctr, 1); t->count++; } } } void test_atomic_cmpset(struct targ *t) { int64_t m, i; for (m = 0; m < t->g->m_cycles; m++) { for (i = 0; i < ONE_MILLION; i++) { atomic_cmpset_32(t->glob_ctr, m, i); t->count++; } } } void test_time(struct targ *t) { int64_t m; for (m = 0; m < t->g->m_cycles; m++) { #ifndef __APPLE__ struct timespec ts; clock_gettime(t->g->arg, &ts); #endif t->count++; } } void test_gettimeofday(struct targ *t) { int64_t m; struct timeval ts; for (m = 0; m < t->g->m_cycles; m++) { gettimeofday(&ts, NULL); t->count++; } } /* * getppid is the simplest system call (getpid is cached by glibc * so it would not be a good test) */ void test_getpid(struct targ *t) { int64_t m; for (m = 0; m < t->g->m_cycles; m++) { getppid(); t->count++; } } #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) static void fast_bcopy(void *_src, void *_dst, int l) { uint64_t *src = _src; uint64_t *dst = _dst; if (unlikely(l >= 1024)) { bcopy(src, dst, l); return; } for (; likely(l > 0); l-=64) { *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; } } // XXX if you want to make sure there is no inlining... // static void (*fp)(void *_src, void *_dst, int l) = fast_bcopy; #define HU 0x3ffff static struct glob_arg huge[HU+1]; void test_fastcopy(struct targ *t) { int64_t m; int len = t->g->arg; if (len > (int)sizeof(struct glob_arg)) len = sizeof(struct glob_arg); D("fast copying %d bytes", len); for (m = 0; m < t->g->m_cycles; m++) { fast_bcopy(t->g, (void *)&huge[m & HU], len); t->count+=1; } } void test_bcopy(struct targ *t) { int64_t m; int len = t->g->arg; if (len > (int)sizeof(struct glob_arg)) len = sizeof(struct glob_arg); D("bcopying %d bytes", len); for (m = 0; m < t->g->m_cycles; m++) { bcopy(t->g, (void *)&huge[m & HU], len); t->count+=1; } } void test_builtin_memcpy(struct targ *t) { int64_t m; int len = t->g->arg; if (len > (int)sizeof(struct glob_arg)) len = sizeof(struct glob_arg); D("bcopying %d bytes", len); for (m = 0; m < t->g->m_cycles; m++) { __builtin_memcpy((void *)&huge[m & HU], t->g, len); t->count+=1; } } void test_memcpy(struct targ *t) { int64_t m; int len = t->g->arg; if (len > (int)sizeof(struct glob_arg)) len = sizeof(struct glob_arg); D("memcopying %d bytes", len); for (m = 0; m < t->g->m_cycles; m++) { memcpy((void *)&huge[m & HU], t->g, len); t->count+=1; } } struct entry { void (*fn)(struct targ *); char *name; uint64_t scale; uint64_t m_cycles; }; struct entry tests[] = { { test_sel, "select", 1, 1000 }, { test_poll, "poll", 1, 1000 }, { test_usleep, "usleep", 1, 1000 }, { test_time, "time", 1, 1000 }, { test_gettimeofday, "gettimeofday", 1, 1000000 }, { test_getpid, "getpid", 1, 1000000 }, { test_bcopy, "bcopy", 1000, 100000000 }, { test_builtin_memcpy, "__builtin_memcpy", 1000, 100000000 }, { test_memcpy, "memcpy", 1000, 100000000 }, { test_fastcopy, "fastcopy", 1000, 100000000 }, { test_add, "add", ONE_MILLION, 100000000 }, { test_nop, "nop", ONE_MILLION, 100000000 }, { test_atomic_add, "atomic-add", ONE_MILLION, 100000000 }, { test_cli, "cli", ONE_MILLION, 100000000 }, { test_rdtsc, "rdtsc", ONE_MILLION, 100000000 }, // unserialized { test_rdtsc1, "rdtsc1", ONE_MILLION, 100000000 }, // serialized { test_atomic_cmpset, "cmpset", ONE_MILLION, 100000000 }, { NULL, NULL, 0, 0 } }; static void usage(void) { const char *cmd = "test"; int i; fprintf(stderr, "Usage:\n" "%s arguments\n" "\t-m name test name\n" "\t-n cycles (millions) of cycles\n" "\t-l arg bytes, usec, ... \n" "\t-t threads total threads\n" "\t-c cores cores to use\n" "\t-a n force affinity every n cores\n" "\t-A n cache contention every n bytes\n" "\t-w report_ms milliseconds between reports\n" "", cmd); fprintf(stderr, "Available tests:\n"); for (i = 0; tests[i].name; i++) { fprintf(stderr, "%12s\n", tests[i].name); } exit(0); } static int64_t getnum(const char *s) { int64_t n; char *e; n = strtol(s, &e, 0); switch (e ? *e : '\0') { case 'k': case 'K': return n*1000; case 'm': case 'M': return n*1000*1000; case 'g': case 'G': return n*1000*1000*1000; case 't': case 'T': return n*1000*1000*1000*1000; default: return n; } } struct glob_arg g; int main(int argc, char **argv) { int i, ch, report_interval, affinity, align; ND("g has size %d", (int)sizeof(g)); report_interval = 250; /* ms */ affinity = 0; /* no affinity */ align = 0; /* global variable */ bzero(&g, sizeof(g)); g.privs = getprivs(); g.nthreads = 1; g.cpus = 1; g.m_cycles = 0; while ( (ch = getopt(argc, argv, "A:a:m:n:w:c:t:vl:")) != -1) { switch(ch) { default: D("bad option %c %s", ch, optarg); usage(); break; case 'A': /* align */ align = atoi(optarg); break; case 'a': /* force affinity */ affinity = atoi(optarg); break; case 'n': /* cycles */ g.m_cycles = getnum(optarg); break; case 'w': /* report interval */ report_interval = atoi(optarg); break; case 'c': g.cpus = atoi(optarg); break; case 't': g.nthreads = atoi(optarg); break; case 'm': g.test_name = optarg; break; case 'l': g.arg = getnum(optarg); break; case 'v': verbose++; break; } } argc -= optind; argv += optind; if (!g.test_name && argc > 0) g.test_name = argv[0]; if (g.test_name) { for (i = 0; tests[i].name; i++) { if (!strcmp(g.test_name, tests[i].name)) { g.fn = tests[i].fn; g.scale = tests[i].scale; if (g.m_cycles == 0) g.m_cycles = tests[i].m_cycles; if (g.scale == ONE_MILLION) g.scale_name = "M"; else if (g.scale == 1000) g.scale_name = "K"; else { g.scale = 1; g.scale_name = ""; } break; } } } if (!g.fn) { D("%s", "missing/unknown test name"); usage(); } i = system_ncpus(); if (g.cpus < 0 || g.cpus > i) { D("%d cpus is too high, have only %d cpus", g.cpus, i); usage(); } if (g.cpus == 0) g.cpus = i; if (g.nthreads < 1) { D("bad nthreads %d, using 1", g.nthreads); g.nthreads = 1; } i = sizeof(g.v.ctr) / g.nthreads*sizeof(g.v.ctr[0]); if (align < 0 || align > i) { D("bad align %d, max is %d", align, i); align = i; } /* Install ^C handler. */ global_nthreads = g.nthreads; signal(SIGINT, sigint_h); ta = calloc(g.nthreads, sizeof(*ta)); /* * Now create the desired number of threads, each one * using a single descriptor. */ D("start %d threads on %d cores", g.nthreads, g.cpus); for (i = 0; i < g.nthreads; i++) { struct targ *t = &ta[i]; bzero(t, sizeof(*t)); t->g = &g; t->me = i; t->glob_ctr = &g.v.ctr[(i*align)/sizeof(g.v.ctr[0])]; D("thread %d ptr %p", i, t->glob_ctr); t->affinity = affinity ? (affinity*i) % g.cpus : -1; if (pthread_create(&t->thread, NULL, td_body, t) == -1) { D("Unable to create thread %d", i); t->completed = 1; } } /* the main loop */ { uint64_t my_count = 0, prev = 0; uint64_t count = 0; double delta_t; struct timeval tic, toc; gettimeofday(&toc, NULL); for (;;) { struct timeval now, delta; uint64_t pps; int done = 0; delta.tv_sec = report_interval/1000; delta.tv_usec = (report_interval%1000)*1000; select(0, NULL, NULL, NULL, &delta); gettimeofday(&now, NULL); timersub(&now, &toc, &toc); my_count = 0; for (i = 0; i < g.nthreads; i++) { my_count += ta[i].count; if (ta[i].completed) done++; } pps = toc.tv_sec* ONE_MILLION + toc.tv_usec; if (pps < 10000) continue; pps = (my_count - prev)*ONE_MILLION / pps; D("%" PRIu64 " %scycles/s scale %" PRIu64 " in %dus", pps/g.scale, g.scale_name, g.scale, (int)(toc.tv_sec* ONE_MILLION + toc.tv_usec)); prev = my_count; toc = now; if (done == g.nthreads) break; } D("total %" PRIu64 " cycles", prev); timerclear(&tic); timerclear(&toc); for (i = 0; i < g.nthreads; i++) { pthread_join(ta[i].thread, NULL); if (ta[i].completed == 0) continue; /* * Collect threads o1utput and extract information about * how log it took to send all the packets. */ count += ta[i].count; if (!timerisset(&tic) || timercmp(&ta[i].tic, &tic, <)) tic = ta[i].tic; if (!timerisset(&toc) || timercmp(&ta[i].toc, &toc, >)) toc = ta[i].toc; } /* print output. */ timersub(&toc, &tic, &toc); delta_t = toc.tv_sec + 1e-6* toc.tv_usec; D("total %8.6f seconds", delta_t); } return (0); } /* end of file */ netmap-release/examples/testcsum.c000644 000423 000000 00000012337 12005466751 020063 0ustar00luigiwheel000000 000000 /* * test checksum * * General * - on new cpus (AMD X2, i5, i7) alignment is not very important. * - on old P4, the unrolling is not very useful * - the assembly version is uniformly slower * * In summary the 32-bit version with unrolling is quite fast. Data on i7-2600 checksums for 1518 bytes on i7-2600 at 3400 bufs ns/cycle 1 80 128 85 1024 90 2048 91 3000 90 3500 92 3800 95 3900 100 4096 119 8192 141 freq bufs ns/cy 200 1 1658 200 2048 1923 200 8192 2331 3400 1 78 3400 8192 141 For short packets bufs size ns/cy 1 64 7 3900 64 16 8192 64 33 */ #include #include #include #include #include inline void prefetch (const void *x) { __asm volatile("prefetcht0 %0" :: "m" (*(const unsigned long *)x)); } volatile uint16_t res; #define REDUCE16(_x) ({ uint32_t x = _x; \ x = (x & 0xffff) + (x >> 16); \ x = (x & 0xffff) + (x >> 16); \ x; } ) #define REDUCE32(_x) ({ uint64_t x = _x; \ x = (x & 0xffffffff) + (x >> 32); \ x = (x & 0xffffffff) + (x >> 32); \ x; } ) uint32_t dummy(const unsigned char *addr, int count) { (void)addr; (void)count; return 0; } /* * Base mechanism, 16 bit at a time, not unrolled */ uint32_t sum16(const unsigned char *addr, int count) { uint32_t sum = 0; uint16_t *d = (uint16_t *)addr; for (;count >= 2; count -= 2) sum += *d++; /* Add left-over byte, if any */ if (count & 1) sum += *(uint8_t *)d; return REDUCE16(sum); } /* * Better mechanism, 32 bit at a time, not unrolled */ uint32_t sum32(const unsigned char *addr, int count) { uint64_t sum = 0; const uint32_t *d = (const uint32_t *)addr; for (; count >= 4; count -= 4) sum += *d++; addr = (const uint8_t *)d; if (count >= 2) { sum += *(const uint16_t *)addr; addr += 2; } /* Add left-over byte, if any */ if (count & 1) sum += *addr; sum = REDUCE32(sum); return REDUCE16(sum); } uint32_t sum32u(const unsigned char *addr, int count) { uint64_t sum = 0; const uint32_t *p = (uint32_t *)addr; for (; count >= 32; count -= 32) { sum += (uint64_t)p[0] + p[1] + p[2] + p[3] + p[4] + p[5] + p[6] + p[7]; p += 8; } if (count & 0x10) { sum += (uint64_t)p[0] + p[1] + p[2] + p[3]; p += 4; } if (count & 8) { sum += (uint64_t)p[0] + p[1]; p += 2; } if (count & 4) sum += *p++; addr = (const unsigned char *)p; if (count & 2) { sum += *(uint16_t *)addr; addr += 2; } if (count & 1) sum += *addr; sum = REDUCE32(sum); return REDUCE16(sum); } uint32_t sum32a(const unsigned char *addr, int count) { uint32_t sum32 = 0; uint64_t sum; const uint32_t *p = (const uint32_t *)addr; for (;count >= 32; count -= 32) { __asm( "add %1, %0\n" "adc %2, %0\n" "adc %3, %0\n" "adc %4, %0\n" "adc %5, %0\n" "adc %6, %0\n" "adc %7, %0\n" "adc %8, %0\n" "adc $0, %0" : "+r" (sum32) : "g" (p[0]), "g" (p[1]), "g" (p[2]), "g" (p[3]), "g" (p[4]), "g" (p[5]), "g" (p[6]), "g" (p[7]) : "cc" ); p += 8; } sum = sum32; for (;1 && count >= 16; count -= 16) { sum += (uint64_t)p[0] + p[1] + p[2] + p[3]; p += 4; } for (; count >= 4; count -= 4) { sum += *p++; } addr = (unsigned char *)p; if (count > 1) { sum += *(uint16_t *)addr; addr += 2; } if (count & 1) sum += *addr; sum = REDUCE32(sum); return REDUCE16(sum); } struct ftab { char *name; uint32_t (*fn)(const unsigned char *, int); }; struct ftab f[] = { { "dummy", dummy }, { "sum16", sum16 }, { "sum32", sum32 }, { "sum32u", sum32u }, { "sum32a", sum32a }, { NULL, NULL } }; int main(int argc, char *argv[]) { int i, j, n; int lim = argc > 1 ? atoi(argv[1]) : 100; int len = argc > 2 ? atoi(argv[2]) : 1024; char *fn = argc > 3 ? argv[3] : "sum16"; int ring_size = argc > 4 ? atoi(argv[4]) : 0; unsigned char *buf0, *buf; #define MAXLEN 2048 #define NBUFS 65536 /* 128MB */ uint32_t (*fnp)(const unsigned char *, int) = NULL; struct timeval ta, tb; if (ring_size < 1 || ring_size > NBUFS) ring_size = 1; buf0 = calloc(1, MAXLEN * NBUFS); if (!buf0) return 1; for (i = 0; f[i].name; i++) { if (!strcmp(f[i].name, fn)) { fnp = f[i].fn; break; } } if (fnp == NULL) { fnp = sum16; fn = "sum16-default"; } if (len > MAXLEN) len = MAXLEN; for (n = 0; n < NBUFS; n++) { buf = buf0 + n*MAXLEN; for (i = 0; i < len; i++) buf[i] = i *i - i + 5; } fprintf(stderr, "function %s len %d count %dM ring_size %d\n", fn, len, lim, ring_size); gettimeofday(&ta, NULL); for (n = 0; n < lim; n++) { for (i = j = 0; i < 1000000; i++) { const unsigned char *x = buf0 + j*MAXLEN; prefetch(x + MAXLEN); prefetch(x + MAXLEN + 64); res = fnp(x, len); if (++j == ring_size) j = 0; } } gettimeofday(&tb, NULL); tb.tv_sec -= ta.tv_sec; tb.tv_usec -= ta.tv_usec; if (tb.tv_usec < 0) { tb.tv_sec--; tb.tv_usec += 1000000; } n = tb.tv_sec * 1000000 + tb.tv_usec; fprintf(stderr, "%dM cycles in %d.%06ds, %dns/cycle\n", lim, (int)tb.tv_sec, (int)tb.tv_usec, n/(lim*1000) ); fprintf(stderr, "%s %u sum16 %u sum32 %d sum32u %u\n", fn, res, sum16((unsigned char *)buf0, len), sum32((unsigned char *)buf0, len), sum32u((unsigned char *)buf0, len)); return 0; } netmap-release/examples/test_select.c000644 000423 000000 00000003102 11727367774 020537 0ustar00luigiwheel000000 000000 /* * test minimum select time * * ./prog usec [method [duration]] */ #include #include #include #include #include #include #include enum { M_SELECT =0 , M_POLL, M_USLEEP }; static const char *names[] = { "select", "poll", "usleep" }; int main(int argc, char *argv[]) { struct timeval ta, tb, prev; int usec = 1, total = 0, method = M_SELECT; uint32_t *vals = NULL; uint32_t i, count = 0; #define LIM 1000000 if (argc > 1) usec = atoi(argv[1]); if (usec <= 0) usec = 1; else if (usec > 500000) usec = 500000; if (argc > 2) { if (!strcmp(argv[2], "poll")) method = M_POLL; else if (!strcmp(argv[2], "usleep")) method = M_USLEEP; } if (argc > 3) total = atoi(argv[3]); if (total < 1) total = 1; else if (total > 10) total = 10; fprintf(stderr, "testing %s for %dus over %ds\n", names[method], usec, total); gettimeofday(&ta, NULL); prev = ta; vals = calloc(LIM, sizeof(uint32_t)); for (;;) { if (method == M_SELECT) { struct timeval to = { 0, usec }; select(0, NULL, NULL, NULL, &to); } else if (method == M_POLL) { poll(NULL, 0, usec/1000); } else { usleep(usec); } gettimeofday(&tb, NULL); timersub(&tb, &prev, &prev); if (count < LIM) vals[count] = prev.tv_usec; count++; prev = tb; timersub(&tb, &ta, &tb); if (tb.tv_sec > total) break; } fprintf(stderr, "%dus actually took %dus\n", usec, (int)(tb.tv_sec * 1000000 + tb.tv_usec) / count ); for (i = 0; i < count && i < LIM; i++) fprintf(stdout, "%d\n", vals[i]); return 0; } netmap-release/examples/patch-zz-netmap-1000644 000423 000000 00000006722 11764426333 021157 0ustar00luigiwheel000000 000000 diff -ubwr ../../work.patched/qemu-1.0.1/Makefile.objs ./Makefile.objs --- ../../work.patched/qemu-1.0.1/Makefile.objs 2012-02-17 20:45:39.000000000 +0100 +++ ./Makefile.objs 2012-05-30 21:20:36.000000000 +0200 @@ -47,9 +47,9 @@ net-nested-y += socket.o net-nested-y += dump.o net-nested-$(CONFIG_POSIX) += tap.o -net-nested-$(CONFIG_LINUX) += tap-linux.o +net-nested-$(CONFIG_LINUX) += tap-linux.o qemu-netmap.o net-nested-$(CONFIG_WIN32) += tap-win32.o -net-nested-$(CONFIG_BSD) += tap-bsd.o +net-nested-$(CONFIG_BSD) += tap-bsd.o qemu-netmap.o net-nested-$(CONFIG_SOLARIS) += tap-solaris.o net-nested-$(CONFIG_AIX) += tap-aix.o net-nested-$(CONFIG_HAIKU) += tap-haiku.o diff -ubwr ../../work.patched/qemu-1.0.1/net/tap.h ./net/tap.h --- ../../work.patched/qemu-1.0.1/net/tap.h 2012-05-28 19:14:09.000000000 +0200 +++ ./net/tap.h 2012-05-28 19:46:57.000000000 +0200 @@ -32,6 +32,10 @@ #define DEFAULT_NETWORK_SCRIPT PREFIX "/etc/qemu-ifup" #define DEFAULT_NETWORK_DOWN_SCRIPT PREFIX "/etc/qemu-ifdown" +#if 1 // DEV_NETMAP +int net_init_netmap(QemuOpts *opts, Monitor *mon, const char *name, VLANState *vlan); +#endif // DEV_NETMAP + int net_init_tap(QemuOpts *opts, Monitor *mon, const char *name, VLANState *vlan); int tap_open(char *ifname, int ifname_size, int *vnet_hdr, int vnet_hdr_required); diff -ubwr ../../work.patched/qemu-1.0.1/net.c ./net.c --- ../../work.patched/qemu-1.0.1/net.c 2012-05-28 19:14:09.000000000 +0200 +++ ./net.c 2012-06-01 09:16:06.000000000 +0200 @@ -1152,6 +1157,22 @@ }, }, #endif + +#if 1 // DEV_NETMAP + [NET_CLIENT_TYPE_NETMAP] = { + .type = "netmap", + .init = net_init_netmap, + .desc = { + NET_COMMON_PARAMS_DESC, + { + .name = "ifname", + .type = QEMU_OPT_STRING, + .help = "interface name", + }, + }, + }, +#endif // DEV_NETMAP + [NET_CLIENT_TYPE_TAP] = { .type = "tap", .init = net_init_tap, diff -ubwr ../../work.patched/qemu-1.0.1/net.h ./net.h --- ../../work.patched/qemu-1.0.1/net.h 2012-05-28 19:14:09.000000000 +0200 +++ ./net.h 2012-05-30 21:25:30.000000000 +0200 @@ -37,6 +37,7 @@ NET_CLIENT_TYPE_VDE, NET_CLIENT_TYPE_PCAP, NET_CLIENT_TYPE_DUMP, + NET_CLIENT_TYPE_NETMAP, // XXX lr 20120528 NET_CLIENT_TYPE_MAX } net_client_type; diff -ubwr ../../work.patched/qemu-1.0.1/qemu-common.h ./qemu-common.h --- ../../work.patched/qemu-1.0.1/qemu-common.h 2012-02-17 20:45:39.000000000 +0100 +++ ./qemu-common.h 2012-05-30 15:48:54.000000000 +0200 @@ -38,6 +38,30 @@ #include #include +#ifndef RATE_ME +/* + * XXX the following routine is used to compute average rates. + */ +struct nm_rate { + uint64_t prev, curr, delta; + struct timeval t_prev, t_curr; + char name[128]; +}; + +/* report. Delta = -1 resets the count, delta < -1 sets delta */ +void nm_report_rate(struct nm_rate *r, int delta); +void nm_report_name(struct nm_rate *r, char *name); + +#define RATE_ME(_nm, _de, _inc) \ + do { static struct nm_rate __r; \ + if (__r.delta == 0) { \ + __r.delta = _de; \ + strcpy(__r.name, _nm); \ + } \ + nm_report_rate(&__r, _inc); \ + } while (0) + +#endif /* RATE_ME */ #ifdef _WIN32 #include "qemu-os-win32.h" #endif netmap-release/examples/qemu-netmap.c000644 000423 000000 00000031526 11764426345 020454 0ustar00luigiwheel000000 000000 /* * netmap access for qemu (from tap-bsd.c and tap.c) * * Copyright (c) 2012 Luigi Rizzo * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "qemu-common.h" #include "sysemu.h" #include "qemu-error.h" #include #include #include "/home/luigi/FreeBSD/head/sys/net/netmap.h" #include "/home/luigi/FreeBSD/head/sys/net/netmap_user.h" #include #include "config-host.h" #include #include #include #include #include #include "net.h" #include "sysemu.h" #include "qemu-char.h" #include "qemu-common.h" #include "qemu-error.h" static int nm_verbose=0; #define TAP_BUFSIZE (4096 + 65536) /* * private netmap info */ struct netmap_state { int fd; int memsize; void *mem; struct netmap_if *nifp; struct netmap_ring *rx, *tx; char fdname[128]; /* normally /dev/netmap */ char ifname[128]; /* maybe the nmreq here ? */ uint8_t _buf[TAP_BUFSIZE]; }; struct nm_state { VLANClientState nc; struct netmap_state me; unsigned int read_poll; unsigned int write_poll; }; // XXX only for multiples of 64 bytes, non overlapped. static inline void pkt_copy(const void *_src, void *_dst, int l) { const uint64_t *src = _src; uint64_t *dst = _dst; #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) if (unlikely(l >= 1024)) { bcopy(src, dst, l); return; } for (; l > 0; l-=64) { *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; } } static void pkt_dump(const uint8_t *buf, int len) { // ....: .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ________ ________ int i; char t[128]; char hex[] = "0123456789abcdef"; #define P(x) ((c >= ' ' && c < 0x7f) ? c : '.') fprintf(stderr, "--- %d bytes at %p\n", len, buf); if (len > 160) len = 160; for (i = 0; i < len; i++) { uint8_t c = buf[i]; int o = i % 16; if (o == 0) { if (i > 0) fprintf(stderr, "%s\n", t); memset(t, ' ', 79); t[80] = '\0'; t[0] = hex[(i>>12) & 0xf]; t[1] = hex[(i>>8) & 0xf]; t[2] = hex[(i>>4) & 0xf]; t[3] = hex[(i>>0) & 0xf]; t[4] = ':'; } t[6 + 3*o + (o >> 3)] = hex[c >> 4]; t[7 + 3*o + (o >> 3)] = hex[c & 0xf]; t[56 + o + (o >> 3)] = P(c); } if (i % 16 != 0) fprintf(stderr, "%s\n", t); } #if 1 // NM_RATE void nm_report_name(struct nm_rate *r, char *name) { int lim = sizeof(r->name); int l = strlen(name); if (l > lim - 1) l = lim - 1; bzero(&r->name, lim); bcopy(name, r->name, l); } /* * init or report the current receive rate */ void nm_report_rate(struct nm_rate *r, int delta) { uint64_t cnt, us; double rate; if (delta < -1) { r->delta = -delta; fprintf(stderr, "%p set delta %llu\n", r, r->delta); delta = -1; } if (delta == -1) { r->prev = r->curr = 0; gettimeofday(&r->t_prev, NULL); return; } r->curr += delta; cnt = r->curr - r->prev; if (r->delta == 0) { r->delta = 100000; fprintf(stderr, "%p force delta %llu\n", r, r->delta); } if (cnt < r->delta) return; gettimeofday(&r->t_curr, NULL); us = 1000000*(r->t_curr.tv_sec - r->t_prev.tv_sec) + (r->t_curr.tv_usec - r->t_prev.tv_usec) + 1; /* avoid div-0 */ rate = cnt*1.0 / us; r->t_prev = r->t_curr; r->prev = r->curr; fprintf(stderr, "%s delta %llu rate %8.6f Mpps\n", r->name, cnt, rate); } #endif // NM_RATE /* * open a netmap device. We assume there is only one queue * (which is the case for the VALE bridge). */ static int netmap_open(struct netmap_state *me) { int fd, l, err; struct nmreq req; fprintf(stderr, "%s for %s\n", __FUNCTION__, me->ifname); me->fd = fd = open(me->fdname, O_RDWR); if (fd < 0) { error_report("Unable to open netmap device '%s'", me->fdname); return -1; } bzero(&req, sizeof(req)); strncpy(req.nr_name, me->ifname, sizeof(req.nr_name)); req.nr_ringid = 0; req.nr_version = NETMAP_API; err = ioctl(fd, NIOCGINFO, &req); if (err) { error_report("cannot get info on %s", me->ifname); goto error; } l = me->memsize = req.nr_memsize; err = ioctl(fd, NIOCREGIF, &req); if (err) { error_report("Unable to register %s", me->ifname); goto error; } me->mem = mmap(0, l, PROT_WRITE | PROT_READ, MAP_SHARED, fd, 0); if (me->mem == MAP_FAILED) { error_report("Unable to mmap"); me->mem = NULL; goto error; } me->nifp = NETMAP_IF(me->mem, req.nr_offset); me->tx = NETMAP_TXRING(me->nifp, 0); me->rx = NETMAP_RXRING(me->nifp, 0); fprintf(stderr, " %d MB at %p, tx %p rx %p slots %d\n", me->memsize >> 20, me->mem, me->tx, me->rx, me->tx->num_slots); return 0; error: // testing, if name is not /dev/netmap still return ok if (strcmp(me->fdname, "/dev/netmap") != 0) return 0; close(me->fd); return -1; } /* * XXX check whether this is necessary */ static int netmap_can_send(void *opaque) { struct nm_state *s = opaque; int ret; RATE_ME(__FUNCTION__, 1000000, 1); ret = qemu_can_send_packet(&s->nc); // fprintf(stderr, "%s for %s gives %d\n", __FUNCTION__, s->me.ifname, ret); return ret; } static void netmap_send(void *opaque); static void netmap_writable(void *opaque); /* * set the handlers for the device */ static void netmap_update_fd_handler(struct nm_state *s) { RATE_ME(__FUNCTION__, 1000000, 1); // fprintf(stderr, "%s for %s\n", __FUNCTION__, s->me.ifname); #if 1 qemu_set_fd_handler2(s->me.fd, s->read_poll ? netmap_can_send : NULL, s->read_poll ? netmap_send : NULL, s->write_poll ? netmap_writable : NULL, s); #else qemu_set_fd_handler(s->me.fd, s->read_poll ? netmap_send : NULL, s->write_poll ? netmap_writable : NULL, s); #endif } /* * prepare for reading */ static void netmap_read_poll(struct nm_state *s, int enable) { RATE_ME(__FUNCTION__, 1000000, 1); if (nm_verbose) fprintf(stderr, "%s for %s\n", __FUNCTION__, s->me.ifname); s->read_poll = !!enable; netmap_update_fd_handler(s); } /* * prepare for writing. * But we should almost never do that with netmap. */ static void netmap_write_poll(struct nm_state *s, int enable) { RATE_ME(__FUNCTION__, 1000000, 1); if (nm_verbose) fprintf(stderr, "%s for %s: %s\n", __FUNCTION__, s->me.ifname, enable ? "enable" : "disable"); s->write_poll = !!enable; netmap_update_fd_handler(s); } static void netmap_writable(void *opaque) { struct nm_state *s = opaque; RATE_ME(__FUNCTION__, 1000000, 1); if (nm_verbose) fprintf(stderr, "%s for %s\n", __FUNCTION__, s->me.ifname); netmap_write_poll(s, 0); qemu_flush_queued_packets(&s->nc); } /* * receive from the virtual machine means pushing to the stack */ static ssize_t netmap_receive_raw(VLANClientState *nc, const uint8_t *buf, size_t size) { struct nm_state *s = DO_UPCAST(struct nm_state, nc, nc); struct netmap_ring *ring = s->me.tx; RATE_ME(__FUNCTION__, 1000000, 1); if (nm_verbose) { fprintf(stderr, "TX %s for %s size %d at %p\n", __FUNCTION__, s->me.ifname, (int)size, buf); pkt_dump(buf, size); } if (ring) { if (ring->avail == 0) { // cannot write RATE_ME( "rx_raw cannot write", 1000000, 1); if (nm_verbose) fprintf(stderr, "cannot write, set poll\n"); netmap_write_poll(s, 1); return 0; } uint32_t i = ring->cur; uint32_t idx = ring->slot[i].buf_idx; uint8_t *dst = (u_char *)NETMAP_BUF(ring, idx); ring->slot[i].len = size; pkt_copy(buf, dst, size); ring->cur = NETMAP_RING_NEXT(ring, i); ring->avail--; RATE_ME( "rx_raw written", 1000000, 1); if (nm_verbose) fprintf(stderr, "written %d at %d, avail %d\n", (int)size, ring->cur, ring->avail); // netmap_write_poll(s, 0); // XXX lr 20120607 } return size; } /* * complete a previous send */ static void netmap_send_completed(VLANClientState *nc, ssize_t len) { struct nm_state *s = DO_UPCAST(struct nm_state, nc, nc); struct netmap_ring *ring = s->me.rx; int i = ring->cur; RATE_ME(__FUNCTION__, 1000000, 1); if (nm_verbose) fprintf(stderr, "RXok %s for %s cur %d avail %d\n", __FUNCTION__, s->me.ifname, ring->cur, ring->avail); ring->cur = NETMAP_RING_NEXT(ring, i); ring->avail--; //netmap_read_poll(s, 1); // XXX only if avail == 0 ? } /* * there is traffic available from the network, try to send it up. */ static void netmap_send(void *opaque) { struct nm_state *s = opaque; static int sent_max = 0; int sent = 0; struct netmap_ring *ring = s->me.rx; RATE_ME(__FUNCTION__, 1000000, 1); if (nm_verbose) fprintf(stderr, "RX %s for %s cur %d avail %d\n", __FUNCTION__, s->me.ifname, ring->cur, ring->avail); while (ring->avail > 0 && qemu_can_send_packet(&s->nc) ) { uint32_t i = ring->cur; uint32_t idx = ring->slot[i].buf_idx; uint8_t *src = (u_char *)NETMAP_BUF(ring, idx); int size = ring->slot[i].len; /* XXX is this a busy wait loop ? */ size = qemu_send_packet_async(&s->nc, src, size, netmap_send_completed); if (size == 0) { if (1 || nm_verbose) fprintf(stderr, "RX %d -> to host blocking\n", ring->cur); netmap_read_poll(s, 0); return; } // fprintf(stderr, "RX %d -> to host was successful\n", ring->cur); ring->cur = NETMAP_RING_NEXT(ring, i); ring->avail--; sent++; } if (sent > sent_max) { fprintf(stderr, "%s burst of %d\n", __FUNCTION__, sent); sent_max = sent; } netmap_read_poll(s, 1); // XXX only if avail == 0 ? } /* * flush and close */ static void netmap_cleanup(VLANClientState *nc) { struct nm_state *s = DO_UPCAST(struct nm_state, nc, nc); fprintf(stderr, "%s for %s\n", __FUNCTION__, s->me.ifname); qemu_purge_queued_packets(nc); netmap_read_poll(s, 0); netmap_write_poll(s, 0); close(s->me.fd); s->me.fd = -1; } static void netmap_poll(VLANClientState *nc, bool enable) { struct nm_state *s = DO_UPCAST(struct nm_state, nc, nc); RATE_ME(__FUNCTION__, 1000000, 1); if (nm_verbose) fprintf(stderr, "PPP %s for %s\n", __FUNCTION__, s->me.ifname); netmap_read_poll(s, enable); netmap_write_poll(s, enable); } /* fd support */ static NetClientInfo net_netmap_info = { .type = NET_CLIENT_TYPE_NETMAP, .size = sizeof(struct nm_state), .receive = netmap_receive_raw, // .receive_raw = netmap_receive_raw, // .receive_iov = netmap_receive_iov, .poll = netmap_poll, .cleanup = netmap_cleanup, }; /* the external calls */ /* * net_init_netmap() is called from the outside, this is why we need * a prototype. Should try to open the device, and if successful * also qemu_new_net_client() * * opts are the command line options ?) * name is passed with -net netmap,name=... * vlan is ... * mon is ... * * We need to be sure it can be opened before calling qemu_new_net_client */ int net_init_netmap(QemuOpts *opts, Monitor *mon, const char *name, VLANState *vlan); int net_init_netmap(QemuOpts *opts, Monitor *mon, const char *name, VLANState *vlan) { VLANClientState *nc; struct netmap_state me; struct nm_state *s; fprintf(stderr, "=== %s for %s vlan %p\n", __FUNCTION__, name, vlan); /* force a default name */ if (!qemu_opt_get(opts, "ifname")) qemu_opt_set(opts, "ifname", "vale0"); pstrcpy(me.fdname, sizeof(me.fdname), name ? name : "/dev/netmap"); pstrcpy(me.ifname, sizeof(me.ifname), qemu_opt_get(opts, "ifname")); if (netmap_open(&me)) return -1; /* create the object -- use name or ifname ? */ nc = qemu_new_net_client(&net_netmap_info, vlan, NULL, "netmap", name); s = DO_UPCAST(struct nm_state, nc, nc); s->me = me; netmap_read_poll(s, 1); return 0; } netmap-release/examples/nm_util.h000644 000423 000000 00000012127 12040345175 017660 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2012 Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $Id$ * * Some utilities to build netmap-based programs. */ #ifndef _NM_UTIL_H #define _NM_UTIL_H #include #include /* signal */ #include #include #include /* PRI* macros */ #include /* strcmp */ #include /* open */ #include /* close */ #include /* getifaddrs */ #include /* PROT_* */ #include /* ioctl */ #include #include /* sockaddr.. */ #include /* ntohs */ #include #include /* sysctl */ #include /* timersub */ #include #include /* ifreq */ #include #include #include #include #include #ifndef MY_PCAP /* use the system's pcap if available */ #ifdef NO_PCAP #define PCAP_ERRBUF_SIZE 512 typedef void pcap_t; struct pcap_pkthdr; #define pcap_inject(a,b,c) ((void)a, (void)b, (void)c, -1) #define pcap_dispatch(a, b, c, d) (void)c #define pcap_open_live(a, b, c, d, e) ((void)e, NULL) #else /* !NO_PCAP */ #include // XXX do we need it ? #endif /* !NO_PCAP */ #endif // XXX hack #include /* pthread_* */ #ifdef linux #define ifr_flagshigh ifr_flags #define ifr_curcap ifr_flags #define ifr_reqcap ifr_flags #define IFF_PPROMISC IFF_PROMISC #include #include #define CLOCK_REALTIME_PRECISE CLOCK_REALTIME #include /* ether_aton */ #include /* sockaddr_ll */ #endif /* linux */ #ifdef __FreeBSD__ #include /* le64toh */ #include #include /* pthread w/ affinity */ #include /* cpu_set */ #include /* LLADDR */ #endif /* __FreeBSD__ */ #ifdef __APPLE__ #define ifr_flagshigh ifr_flags // XXX #define IFF_PPROMISC IFF_PROMISC #include /* LLADDR */ #define clock_gettime(a,b) \ do {struct timespec t0 = {0,0}; *(b) = t0; } while (0) #endif /* __APPLE__ */ static inline int min(int a, int b) { return a < b ? a : b; } extern int time_second; /* debug support */ #define ND(format, ...) do {} while(0) #define D(format, ...) \ fprintf(stderr, "%s [%d] " format "\n", \ __FUNCTION__, __LINE__, ##__VA_ARGS__) #define RD(lps, format, ...) \ do { \ static int t0, cnt; \ if (t0 != time_second) { \ t0 = time_second; \ cnt = 0; \ } \ if (cnt++ < lps) \ D(format, ##__VA_ARGS__); \ } while (0) // XXX does it work on 32-bit machines ? static inline void prefetch (const void *x) { __asm volatile("prefetcht0 %0" :: "m" (*(const unsigned long *)x)); } // XXX only for multiples of 64 bytes, non overlapped. static inline void pkt_copy(const void *_src, void *_dst, int l) { const uint64_t *src = _src; uint64_t *dst = _dst; #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) if (unlikely(l >= 1024)) { bcopy(src, dst, l); return; } for (; l > 0; l-=64) { *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; } } /* * info on a ring we handle */ struct my_ring { const char *ifname; int fd; char *mem; /* userspace mmap address */ u_int memsize; u_int queueid; u_int begin, end; /* first..last+1 rings to check */ struct netmap_if *nifp; struct netmap_ring *tx, *rx; /* shortcuts */ uint32_t if_flags; uint32_t if_reqcap; uint32_t if_curcap; }; int netmap_open(struct my_ring *me, int ringid, int promisc); int netmap_close(struct my_ring *me); int nm_do_ioctl(struct my_ring *me, u_long what, int subcmd); #endif /* _NM_UTIL_H */ netmap-release/examples/testmmap.c000644 000423 000000 00000030377 12024226107 020040 0ustar00luigiwheel000000 000000 #include "nm_util.h" #include #define MAX_VARS 100 char *variables[MAX_VARS]; int curr_var; #define VAR_FAILED ((void*)1) char *firstarg(char *buf) { int v; char *arg = strtok(buf, " \t\n"); char *ret; if (!arg) return NULL; if (arg[0] != '$' && arg[0] != '?') return arg; v = atoi(arg+1); if (v < 0 || v >= MAX_VARS) return ""; ret = variables[v]; if (ret == NULL) return "NULL"; if (ret == VAR_FAILED) { printf("reading failed var, exit\n"); exit(1); } if (arg[0] == '?') return ret; ret = rindex(ret, '=') + 1; return ret; } char *nextarg() { return firstarg(NULL); } char *restofline() { return strtok(NULL, "\n"); } void resetvar(int v, char *b) { if (variables[v] != VAR_FAILED) free(variables[v]); variables[v] = b; } #define outecho(format, args...) \ do {\ printf("%u:%lu: " format "\n", getpid(), (unsigned long) pthread_self(), ##args);\ fflush(stdout);\ } while (0) #define output(format, args...) \ do {\ resetvar(curr_var, (char*)malloc(1024));\ snprintf(variables[curr_var], 1024, format, ##args);\ outecho(format, ##args);\ } while (0) #define output_err(ret, format, args...)\ do {\ if (ret < 0) {\ resetvar(curr_var, VAR_FAILED);\ outecho(format, ##args);\ outecho("error: %s", strerror(errno));\ } else {\ output(format, ##args);\ }\ } while (0) struct chan { FILE *out; pid_t pid; pthread_t tid; }; int chan_search_free(struct chan* c[], int max) { int i; for (i = 0; i < max && c[i]; i++) ; return i; } void chan_clear_all(struct chan *c[], int max) { int i; for (i = 0; i < max; i++) { if (c[i]) { fclose(c[i]->out); free(c[i]); c[i] = NULL; } } } int last_fd = -1; size_t last_memsize = 0; void * last_mmap_addr = NULL; void do_open() { last_fd = open("/dev/netmap", O_RDWR); output_err(last_fd, "open(\"/dev/netmap\", O_RDWR)=%d", last_fd); } void do_close() { int ret, fd; char *arg = nextarg(); fd = arg ? atoi(arg) : last_fd; ret = close(fd); output_err(ret, "close(%d)=%d", fd, ret); } void do_getinfo() { struct nmreq nmr; int ret; char *arg, *name = "any"; int fd; bzero(&nmr, sizeof(nmr)); nmr.nr_version = NETMAP_API; arg = nextarg(); if (!arg) { fd = last_fd; goto doit; } fd = atoi(arg); name = nextarg(); if (name) { strncpy(nmr.nr_name, name, sizeof(nmr.nr_name)); } doit: ret = ioctl(fd, NIOCGINFO, &nmr); last_memsize = nmr.nr_memsize; output_err(ret, "ioctl(%d, NIOCGINFO) for %s: memsize=%zu", fd, name, last_memsize); } void do_regif() { struct nmreq nmr; int ret; char *arg, *name; int fd; bzero(&nmr, sizeof(nmr)); nmr.nr_version = NETMAP_API; name = nextarg(); if (!name) { output("missing ifname"); return; } strncpy(nmr.nr_name, name, sizeof(nmr.nr_name)); arg = nextarg(); fd = arg ? atoi(arg) : last_fd; ret = ioctl(fd, NIOCREGIF, &nmr); output_err(ret, "ioctl(%d, NIOCREGIF) for %s =%d", fd, name, ret); } void do_unregif() { struct nmreq nmr; int ret; char *arg; int fd; char *name; bzero(&nmr, sizeof(nmr)); nmr.nr_version = NETMAP_API; name = nextarg(); if (!name) { output("missing ifname"); return; } strncpy(nmr.nr_name, name, sizeof(nmr.nr_name)); arg = nextarg(); fd = arg ? atoi(arg) : last_fd; ret = ioctl(fd, NIOCUNREGIF, &nmr); output_err(ret, "ioctl(%d, NIOCUNREGIF) for %s =%d", fd, name, ret); } volatile char tmp1; void do_access() { char *arg = nextarg(); char *p; if (!arg) { output("missing address"); return; } p = (char *)strtoul((void *)arg, NULL, 0); tmp1 = *p; } void do_mmap() { size_t memsize; off_t off = 0; int fd; char *arg; arg = nextarg(); if (!arg) { memsize = last_memsize; fd = last_fd; goto doit; } memsize = atoi(arg); arg = nextarg(); if (!arg) { fd = last_fd; goto doit; } fd = atoi(arg); arg = nextarg(); if (arg) { off = (off_t)atol(arg); } doit: last_mmap_addr = mmap(0, memsize, PROT_WRITE | PROT_READ, MAP_SHARED, fd, off); output_err(last_mmap_addr == MAP_FAILED ? -1 : 0, "mmap(0, %zu, PROT_WRITE|PROT_READ, MAP_SHARED, %d, %jd)=%p", memsize, fd, (intmax_t)off, last_mmap_addr); } void do_munmap() { void *mmap_addr; size_t memsize; char *arg; int ret; arg = nextarg(); if (!arg) { mmap_addr = last_mmap_addr; memsize = last_memsize; goto doit; } mmap_addr = (void*)strtoul(arg, NULL, 0); arg = nextarg(); if (!arg) { memsize = last_memsize; goto doit; } memsize = (size_t)strtoul(arg, NULL, 0); doit: ret = munmap(mmap_addr, memsize); output_err(ret, "munmap(%p, %zu)=%d", mmap_addr, memsize, ret); } void do_poll() { /* timeout fd fd... */ nfds_t nfds = 0, allocated_fds = 10, i; struct pollfd *fds; int timeout = 500; /* 1/2 second */ char *arg; int ret; arg = nextarg(); if (arg) timeout = atoi(arg); fds = malloc(allocated_fds * sizeof(struct pollfd)); if (fds == NULL) { output_err(-1, "out of memory"); return; } while ( (arg = nextarg()) ) { if (nfds >= allocated_fds) { allocated_fds *= 2; fds = realloc(fds, allocated_fds * sizeof(struct pollfd)); if (fds == NULL) { output_err(-1, "out of memory"); return; } } fds[nfds].fd = atoi(arg); fds[nfds].events = POLLIN; nfds++; } ret = poll(fds, nfds, timeout); for (i = 0; i < nfds; i++) { output("poll(%d)=%s%s%s%s%s", fds[i].fd, (fds[i].revents & POLLIN) ? "IN " : "- ", (fds[i].revents & POLLOUT)? "OUT " : "- ", (fds[i].revents & POLLERR)? "ERR " : "- ", (fds[i].revents & POLLHUP)? "HUP " : "- ", (fds[i].revents & POLLNVAL)?"NVAL" : "-"); } output_err(ret, "poll(...)=%d", ret); free(fds); } void do_txsync() { char *arg = nextarg(); int fd = arg ? atoi(arg) : last_fd; int ret = ioctl(fd, NIOCTXSYNC, NULL); output_err(ret, "ioctl(%d, NIOCTXSYNC)=%d", fd, ret); } void do_rxsync() { char *arg = nextarg(); int fd = arg ? atoi(arg) : last_fd; int ret = ioctl(fd, NIOCRXSYNC, NULL); output_err(ret, "ioctl(%d, NIOCRXSYNC)=%d", fd, ret); } void do_expr() { unsigned long stack[11]; int top = 10; char *arg; int err = 0; stack[10] = ULONG_MAX; while ( (arg = nextarg()) ) { errno = 0; char *rest; unsigned long n = strtoul(arg, &rest, 0); if (!errno && rest != arg) { if (top <= 0) { err = -1; break; } stack[--top] = n; continue; } if (top <= 8) { unsigned long n1 = stack[top++]; unsigned long n2 = stack[top++]; unsigned long r = 0; switch (arg[0]) { case '+': r = n1 + n2; break; case '-': r = n1 - n2; break; case '*': r = n1 * n2; break; case '/': if (n2) r = n1 / n2; else { errno = EDOM; err = -1; } break; default: err = -1; break; } stack[--top] = r; continue; } err = -1; break; } output_err(err, "expr=%lu", stack[top]); } void do_echo() { char *arg; for (arg = nextarg(); arg; arg = nextarg()) { printf("%s\n", arg); } } void do_vars() { int i; for (i = 0; i < MAX_VARS; i++) { const char *v = variables[i]; if (v == NULL) continue; printf("?%d\t%s\n", i, v == VAR_FAILED ? "FAILED" : v); } } struct cmd_def { const char *name; void (*f)(void); }; struct cmd_def commands[] = { { .name = "open", .f = do_open, }, { .name = "close", .f = do_close, }, { .name = "getinfo", .f = do_getinfo, }, { .name = "regif", .f = do_regif, }, { .name = "unregif", .f = do_unregif, }, { .name = "mmap", .f = do_mmap, }, { .name = "access", .f = do_access, }, { .name = "munmap", .f = do_munmap, }, { .name = "poll", .f = do_poll, }, { .name = "txsync", .f = do_txsync, }, { .name = "rxsync", .f = do_rxsync, }, { .name = "expr", .f = do_expr, }, { .name = "echo", .f = do_echo, }, { .name = "vars", .f = do_vars, } }; const int N_CMDS = sizeof(commands) / sizeof(struct cmd_def); int find_command(const char* cmd) { int i; for (i = 0; i < N_CMDS; i++) { if (strcmp(commands[i].name, cmd) == 0) break; } return i; } #define MAX_CHAN 10 void prompt() { if (isatty(STDIN_FILENO)) { printf("> "); } } struct chan *channels[MAX_CHAN]; void* thread_cmd_loop(void *arg) { char buf[1024]; FILE *in = (FILE*)arg; while (fgets(buf, 1024, in)) { char *cmd; int i; cmd = firstarg(buf); i = find_command(cmd); if (i < N_CMDS) { commands[i].f(); continue; } output("unknown cmd %s", cmd); } fclose(in); return NULL; } void do_exit() { output("quit"); } void cmd_loop() { char buf[1024]; int i; struct chan *c; bzero(channels, sizeof(*channels) * MAX_CHAN); atexit(do_exit); for (prompt(); fgets(buf, 1024, stdin); prompt()) { char *cmd; int slot; cmd = firstarg(buf); if (!cmd) continue; if (cmd[0] == '@') { curr_var = atoi(cmd + 1); if (curr_var < 0 || curr_var >= MAX_VARS) curr_var = 0; cmd = nextarg(); if (!cmd) continue; } else { curr_var = 0; } if (strcmp(cmd, "fork") == 0) { int slot = chan_search_free(channels, MAX_CHAN); struct chan *c = NULL; pid_t pid; int p1[2] = { -1, -1}; if (slot == MAX_CHAN) { output("too many channels"); continue; } c = channels[slot] = (struct chan*)malloc(sizeof(struct chan)); if (c == NULL) { output_err(-1, "malloc"); continue; } bzero(c, sizeof(*c)); if (pipe(p1) < 0) { output_err(-1, "pipe"); goto clean1; } c->out = fdopen(p1[1], "w"); if (c->out == NULL) { output_err(-1, "fdopen"); goto clean1; } pid = fork(); switch (pid) { case -1: output_err(-1, "fork"); goto clean1; case 0: fclose(stdin); if (dup(p1[0]) < 0) { output_err(-1, "dup"); exit(1); } close(p1[1]); stdin = fdopen(0, "r"); chan_clear_all(channels, MAX_CHAN); goto out; default: break; } c->pid = pid; close(p1[0]); output("fork()=%d slot=%d", pid, slot); continue; clean1: if (c) { fclose(c->out); } close(p1[0]); close(p1[1]); free(c); out: continue; } if (strcmp(cmd, "kill") == 0) { int ret; cmd = nextarg(); if (!cmd) { output("missing slot"); continue; } slot = atoi(cmd); if (slot < 0 || slot >= MAX_CHAN || !channels[slot]) { output("invalid slot: %s", cmd); continue; } c = channels[slot]; ret = kill(c->pid, SIGTERM); output_err(ret, "kill(%d, SIGTERM)=%d", c->pid, ret); if (ret != -1) { wait(NULL); fclose(c->out); free(c); channels[slot] = NULL; } continue; } if (strcmp(cmd, "thread") == 0) { int slot = chan_search_free(channels, MAX_CHAN); struct chan *c = NULL; pthread_t tid; int p1[2] = { -1, -1}; int ret; FILE *in = NULL; if (slot == MAX_CHAN) { output("too many channels"); continue; } c = channels[slot] = (struct chan*)malloc(sizeof(struct chan)); bzero(c, sizeof(*c)); if (pipe(p1) < 0) { output_err(-1, "pipe"); goto clean2; } c->out = fdopen(p1[1], "w"); if (c->out == NULL) { output_err(-1, "fdopen"); goto clean2; } in = fdopen(p1[0], "r"); if (in == NULL) { output_err(-1, "fdopen"); goto clean2; } ret = pthread_create(&tid, NULL, thread_cmd_loop, in); output_err(ret, "pthread_create() tid=%lu slot=%d", (unsigned long) tid, slot); if (ret < 0) goto clean2; c->pid = getpid(); c->tid = tid; continue; clean2: fclose(in); fclose(c->out); close(p1[0]); close(p1[1]); free(c); continue; } if (strcmp(cmd, "cancel") == 0) { int ret; cmd = nextarg(); if (!cmd) { output("missing slot"); continue; } slot = atoi(cmd); if (slot < 0 || slot >= MAX_CHAN || !channels[slot]) { output("invalid slot: %s", cmd); continue; } c = channels[slot]; fclose(c->out); ret = pthread_join(c->tid, NULL); output_err(ret, "pthread_join(%lu)=%d", (unsigned long) c->tid, ret); if (ret > 0) { free(c); channels[slot] = NULL; } continue; } i = find_command(cmd); if (i < N_CMDS) { commands[i].f(); continue; } slot = atoi(cmd); if (slot < 0 || slot > MAX_CHAN || !channels[slot]) { output("invalid cmd/slot: %s", cmd); continue; } cmd = restofline(); if (!cmd) { output("missing command"); continue; } fprintf(channels[slot]->out, "%s\n", cmd); fflush(channels[slot]->out); sleep(1); } } int main(int argc, char **argv) { (void) argc; (void) argv; cmd_loop(); return 0; } netmap-release/examples/nm_util.c000644 000423 000000 00000014440 12066760142 017656 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2012 Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $FreeBSD$ * $Id$ * * utilities to use netmap devices. * This does the basic functions of opening a device and issuing * ioctls() */ #include "nm_util.h" extern int verbose; int nm_do_ioctl(struct my_ring *me, u_long what, int subcmd) { struct ifreq ifr; int error; #if defined( __FreeBSD__ ) || defined (__APPLE__) int fd = me->fd; #endif #ifdef linux struct ethtool_value eval; int fd; fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { printf("Error: cannot get device control socket.\n"); return -1; } #endif /* linux */ (void)subcmd; // unused bzero(&ifr, sizeof(ifr)); strncpy(ifr.ifr_name, me->ifname, sizeof(ifr.ifr_name)); switch (what) { case SIOCSIFFLAGS: #ifndef __APPLE__ ifr.ifr_flagshigh = me->if_flags >> 16; #endif ifr.ifr_flags = me->if_flags & 0xffff; break; #if defined( __FreeBSD__ ) case SIOCSIFCAP: ifr.ifr_reqcap = me->if_reqcap; ifr.ifr_curcap = me->if_curcap; break; #endif #ifdef linux case SIOCETHTOOL: eval.cmd = subcmd; eval.data = 0; ifr.ifr_data = (caddr_t)&eval; break; #endif /* linux */ } error = ioctl(fd, what, &ifr); if (error) goto done; switch (what) { case SIOCGIFFLAGS: #ifndef __APPLE__ me->if_flags = (ifr.ifr_flagshigh << 16) | (0xffff & ifr.ifr_flags); #endif if (verbose) D("flags are 0x%x", me->if_flags); break; #if defined( __FreeBSD__ ) case SIOCGIFCAP: me->if_reqcap = ifr.ifr_reqcap; me->if_curcap = ifr.ifr_curcap; if (verbose) D("curcap are 0x%x", me->if_curcap); break; #endif /* __FreeBSD__ */ } done: #ifdef linux close(fd); #endif if (error) D("ioctl error %d %lu", error, what); return error; } /* * open a device. if me->mem is null then do an mmap. * Returns the file descriptor. * The extra flag checks configures promisc mode. */ int netmap_open(struct my_ring *me, int ringid, int promisc) { int fd, err, l; struct nmreq req; me->fd = fd = open("/dev/netmap", O_RDWR); if (fd < 0) { D("Unable to open /dev/netmap"); return (-1); } bzero(&req, sizeof(req)); req.nr_version = NETMAP_API; strncpy(req.nr_name, me->ifname, sizeof(req.nr_name)); req.nr_ringid = ringid; err = ioctl(fd, NIOCGINFO, &req); if (err) { D("cannot get info on %s, errno %d ver %d", me->ifname, errno, req.nr_version); goto error; } me->memsize = l = req.nr_memsize; if (verbose) D("memsize is %d MB", l>>20); err = ioctl(fd, NIOCREGIF, &req); if (err) { D("Unable to register %s", me->ifname); goto error; } if (me->mem == NULL) { me->mem = mmap(0, l, PROT_WRITE | PROT_READ, MAP_SHARED, fd, 0); if (me->mem == MAP_FAILED) { D("Unable to mmap"); me->mem = NULL; goto error; } } /* Set the operating mode. */ if (ringid != NETMAP_SW_RING) { nm_do_ioctl(me, SIOCGIFFLAGS, 0); if ((me[0].if_flags & IFF_UP) == 0) { D("%s is down, bringing up...", me[0].ifname); me[0].if_flags |= IFF_UP; } if (promisc) { me[0].if_flags |= IFF_PPROMISC; nm_do_ioctl(me, SIOCSIFFLAGS, 0); } #ifdef __FreeBSD__ /* also disable checksums etc. */ nm_do_ioctl(me, SIOCGIFCAP, 0); me[0].if_reqcap = me[0].if_curcap; me[0].if_reqcap &= ~(IFCAP_HWCSUM | IFCAP_TSO | IFCAP_TOE); nm_do_ioctl(me+0, SIOCSIFCAP, 0); #endif #ifdef linux /* disable: * - generic-segmentation-offload * - tcp-segmentation-offload * - rx-checksumming * - tx-checksumming * XXX check how to set back the caps. */ nm_do_ioctl(me, SIOCETHTOOL, ETHTOOL_SGSO); nm_do_ioctl(me, SIOCETHTOOL, ETHTOOL_STSO); nm_do_ioctl(me, SIOCETHTOOL, ETHTOOL_SRXCSUM); nm_do_ioctl(me, SIOCETHTOOL, ETHTOOL_STXCSUM); #endif /* linux */ } me->nifp = NETMAP_IF(me->mem, req.nr_offset); me->queueid = ringid; if (ringid & NETMAP_SW_RING) { me->begin = req.nr_rx_rings; me->end = me->begin + 1; me->tx = NETMAP_TXRING(me->nifp, req.nr_tx_rings); me->rx = NETMAP_RXRING(me->nifp, req.nr_rx_rings); } else if (ringid & NETMAP_HW_RING) { D("XXX check multiple threads"); me->begin = ringid & NETMAP_RING_MASK; me->end = me->begin + 1; me->tx = NETMAP_TXRING(me->nifp, me->begin); me->rx = NETMAP_RXRING(me->nifp, me->begin); } else { me->begin = 0; me->end = req.nr_rx_rings; // XXX max of the two me->tx = NETMAP_TXRING(me->nifp, 0); me->rx = NETMAP_RXRING(me->nifp, 0); } return (0); error: close(me->fd); return -1; } int netmap_close(struct my_ring *me) { D(""); if (me->mem) munmap(me->mem, me->memsize); ioctl(me->fd, NIOCUNREGIF, NULL); close(me->fd); return (0); } /* * how many packets on this set of queues ? */ int pkt_queued(struct my_ring *me, int tx) { u_int i, tot = 0; ND("me %p begin %d end %d", me, me->begin, me->end); for (i = me->begin; i < me->end; i++) { struct netmap_ring *ring = tx ? NETMAP_TXRING(me->nifp, i) : NETMAP_RXRING(me->nifp, i); tot += ring->avail; } if (0 && verbose && tot && !tx) D("ring %s %s %s has %d avail at %d", me->ifname, tx ? "tx": "rx", me->end >= me->nifp->ni_tx_rings ? // XXX who comes first ? "host":"net", tot, NETMAP_TXRING(me->nifp, me->begin)->cur); return tot; } netmap-release/examples/if_epair.diff000644 000423 000000 00000017410 12014455441 020447 0ustar00luigiwheel000000 000000 Index: if_epair.c =================================================================== --- if_epair.c (revision 239227) +++ if_epair.c (working copy) @@ -666,7 +666,230 @@ return (error); } +#ifdef DEV_NETMAP +#include +#include // XXX busdma* routines +#include +#include + +/* + * Use only one lock per pair (the node with smallest ifp) + * XXX do we lock if the other node is not enabled ? + */ static void +epair_netmap_lock(struct ifnet *ifp, int what, u_int ring_nr) +{ + struct epair_softc *epa = ifp->if_softc; + struct netmap_adapter *na = ifp < epa->oifp ? NA(ifp) : NA(epa->oifp); + + KASSERT(ring_nr == 0, ("bad ring number %d", ring_nr)); + switch (what) { + case NETMAP_CORE_LOCK: + case NETMAP_TX_LOCK: + case NETMAP_RX_LOCK: + mtx_lock(&na->core_lock); + break; + case NETMAP_CORE_UNLOCK: + case NETMAP_TX_UNLOCK: + case NETMAP_RX_UNLOCK: + mtx_unlock(&na->core_lock); + break; + } +} + + +static int +epair_netmap_register(struct ifnet *ifp, int enable) +{ + //struct tap_softc *tp = ifp->if_softc; + struct netmap_adapter *na = NA(ifp); + + if (na == NULL) + return (EINVAL); + + mtx_assert(&ifp->if_softc->tap_mtx, MA_OWNED); + /* mtx_lock(&tp->tap_mtx); XXX we are called locked */ + ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); + + if (enable) { + ifp->if_capenable |= IFCAP_NETMAP; + na->if_transmit = ifp->if_transmit; + ifp->if_transmit = netmap_start; + netmap_reset(na, NR_RX, 0, 0); + } else { + ifp->if_transmit = na->if_transmit; + ifp->if_capenable &= ~IFCAP_NETMAP; + } + return (0); +} + +/* + * push packets to the other side if possible. + * XXX If the other side is not netmap enabled, what do we do ? + */ +static int +epair_netmap_txsync(struct ifnet *ifp, u_int ring_nr, int do_lock) +{ + struct epair_softc *epa = ifp->if_softc; + struct netmap_adapter *na = NA(ifp); + struct netmap_kring *kring = &na->tx_rings[ring_nr]; + + struct netmap_ring *ring = kring->ring; + u_int j, k = ring->cur, l, n = 0, lim = kring->nkr_num_slots - 1; + /* the other side */ + struct netmap_adapter *nb = NA(epa->oifp); + struct netmap_kring *rx_kring = &nb->rx_rings[ring_nr]; + + if (k > lim) + return netmap_ring_reinit(kring); + if (do_lock) + epair_netmap_lock(ifp, NETMAP_CORE_LOCK, 0); + + /* process packets to send */ + j = kring->nr_hwcur; + if (j != k) { /* we have new packets to send */ + u_int j1 = rx_kring->nr_hwcur + rx_kring->nr_hwavail; + if (j1 > lim) + j1 -= lim + 1; + l = netmap_idx_k2n(rx_kring, j1); /* rx NIC index */ + ND("rx offset %d for %d tx packets", (int)(l - j1), (int)(k - j)); + for (n = 0; j != k; n++) { + struct netmap_slot *slot = &ring->slot[j]; + struct netmap_slot *dst; + uint32_t tmp; + u_int len = slot->len; + void *addr = NMB(slot); + + ND("len %d tx[%d] -> rx[%d] (%p -> %p)", len, j, l, slot, dst); + j = (j == lim) ? 0 : j + 1; + l = (l == lim) ? 0 : l + 1; + // prefetch(&ring->slot[j]); + + if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) { +ring_reset: + if (do_lock) + epair_netmap_lock(ifp, NETMAP_CORE_UNLOCK, 0); + return netmap_ring_reinit(kring); + } + if ((epa->oifp->if_capenable & IFCAP_NETMAP) == 0) { + ND("dropping %d, other side not ready", + slot - ring->slot); + continue; + } + dst = &rx_kring->ring->slot[l]; + /* swap buf with the rx ring */ + tmp = slot->buf_idx; + slot->buf_idx = dst->buf_idx; + dst->buf_idx = tmp; + dst->len = len; + dst->flags = NS_BUF_CHANGED; + } + kring->nr_hwcur = k; /* the saved ring->cur */ + /* decrease avail by number of packets sent */ + kring->nr_hwavail -= n; + // XXX signal receive ring up to slot l (excluded) + rx_kring->nr_hwavail += n; + ND("pushed %d packets, wake up receiver", n); + selwakeuppri(&rx_kring->si, PI_NET); + } + /* the previous end was kring->nr_hwcur + kring->nr_hwavail. + * Now it moves to rx_kring->nr_hwcur - 1 which may have + * increased since + */ + l = kring->nr_hwcur + kring->nr_hwavail + 1; + if (l > lim) /* wrap */ + l -= lim + 1; + if (l != rx_kring->nr_hwcur) { /* new bufs avail */ + int delta = rx_kring->nr_hwcur - kring->nr_hwcur; + kring->nr_hwavail = (delta > 0) ? delta : lim + 1 - delta ; + if (delta < 0) + delta += kring->nkr_num_slots; + } + // XXX rate limit + ND("%s rx bufs avail %d", + (l == rx_kring->nr_hwcur) ? "old" : "new", kring->nr_hwavail); + /* update avail to what the kernel knows */ + ring->avail = kring->nr_hwavail; + if (do_lock) + epair_netmap_lock(ifp, NETMAP_CORE_UNLOCK, 0); + return 0; +} + +static int +epair_netmap_rxsync(struct ifnet *ifp, u_int ring_nr, int do_lock) +{ + struct epair_softc *epa = ifp->if_softc; /* my side */ + struct netmap_adapter *na = NA(ifp); + + struct netmap_kring *kring = &na->rx_rings[ring_nr]; + struct netmap_ring *ring = kring->ring; + u_int j, l, n, lim = kring->nkr_num_slots - 1; + u_int k = ring->cur, resvd = ring->reserved; + + if (do_lock) + epair_netmap_lock(ifp, NETMAP_CORE_LOCK, 0); + j = kring->nr_hwcur; + if (resvd > 0) { + if (resvd + ring->avail >= lim + 1) { + D("XXX invalid reserve/avail %d %d", resvd, ring->avail); + ring->reserved = resvd = 0; // XXX panic... + } + k = (k >= resvd) ? k - resvd : k + lim + 1 - resvd; + } + if (j != k) { /* userspace has released some packets. */ + struct netmap_adapter *nb = NA(epa->oifp); + struct netmap_kring *tx_kring = &nb->tx_rings[ring_nr]; + + l = netmap_idx_k2n(kring, j); + for (n = 0; j != k; n++) { + struct netmap_slot *slot = &ring->slot[j]; + void *addr = NMB(slot); + if (addr == netmap_buffer_base) /* bad buf */ + goto ring_reset; + slot->flags &= ~NS_BUF_CHANGED; + j = (j == lim) ? 0 : j + 1; + l = (l == lim) ? 0 : l + 1; + } + ND("receiver freed %d bufs, wakeup sender", n); + kring->nr_hwavail -= n; + kring->nr_hwcur = k; + selwakeuppri(&tx_kring->si, PI_NET); + // XXX wakeup other side ? + } + /* tell userspace that there are new packets */ + ring->avail = kring->nr_hwavail - resvd; + + if (do_lock) + epair_netmap_lock(ifp, NETMAP_CORE_UNLOCK, 0); + return 0; + +ring_reset: + // XXX wakeup other side ? + if (do_lock) + epair_netmap_lock(ifp, NETMAP_CORE_UNLOCK, 0); + return netmap_ring_reinit(kring); +} + +static void +epair_netmap_attach(struct epair_softc *sc) +{ + struct netmap_adapter na; + + bzero(&na, sizeof(na)); + na.ifp = sc->ifp; + na.num_tx_desc = 1024; + na.num_rx_desc = 1024; + na.nm_txsync = epair_netmap_txsync; + na.nm_rxsync = epair_netmap_rxsync; + na.nm_lock = epair_netmap_lock; + na.nm_register = epair_netmap_register; + netmap_attach(&na, 1); +} + + +#endif /* DEV_NETMAP */ + +static void epair_init(void *dummy __unused) { } @@ -729,6 +952,9 @@ ether_ifattach(ifp, eaddr); /* Correctly set the name for the cloner list. */ strlcpy(name, scb->ifp->if_xname, len); +#ifdef DEV_NETMAP + epair_netmap_attach(scb); +#endif /* DEV_NETMAP */ return (0); } @@ -822,6 +1048,9 @@ eaddr[4] = ifp->if_index & 0xff; eaddr[5] = 0x0a; ether_ifattach(ifp, eaddr); +#ifdef DEV_NETMAP + epair_netmap_attach(sca); +#endif /* DEV_NETMAP */ sca->if_qflush = ifp->if_qflush; ifp->if_qflush = epair_qflush; ifp->if_transmit = epair_transmit; @@ -925,6 +1154,9 @@ if (error) panic("%s: if_clone_destroyif() for our 2nd iface failed: %d", __func__, error); +#ifdef DEV_NETMAP + netmap_detach(oifp); +#endif /* DEV_NETMAP */ if_free(oifp); ifmedia_removeall(&scb->media); free(scb, M_EPAIR); @@ -937,6 +1169,9 @@ DPRINTF("sca refcnt=%u\n", sca->refcount); EPAIR_REFCOUNT_ASSERT(sca->refcount == 1, ("%s: ifp=%p sca->refcount!=1: %d", __func__, ifp, sca->refcount)); +#ifdef DEV_NETMAP + netmap_detach(ifp); +#endif /* DEV_NETMAP */ if_free(ifp); ifmedia_removeall(&sca->media); free(sca, M_EPAIR); netmap-release/README000644 000423 000000 00000012007 12014455441 015076 0ustar00luigiwheel000000 000000 Netmap - a framework for fast packet I/O VALE - a Virtual Local Ethernet using the netmap API =================================================================== NETMAP is a framework for very fast packet I/O from userspace. VALE implements an equally fast software switch using the netmap API. Both can deal with line rate on real or emulated 10 Gbit ports. See details at http://info.iet.unipi.it/~luigi/netmap/ http://info.iet.unipi.it/~luigi/vale/ In this directory you can find source code (BSD-Copyright) for FreeBSD and Linux. Note that recent FreeBSD distributions already include both NETMAP and VALE. Last update: 2012-08-13 Installation instructions ------------------------- A kernel module (netmap.ko or netmap_lin.ko) implements the whole VALE switch and the core NETMAP routines. Netmap-aware device drivers are needed to use netmap on ethernet ports. To date, we have support for Intel ixgbe (10G), e1000/e1000e/igb (1G), Realtek 8169 (1G) and Nvidia (1G). FreeBSD -------- (FreeBSD HEAD and stable/9 already include netmap in the source tree so you should not need the code in this distribution.) + add 'device netmap' to your kernel config file and rebuild a kernel. This will include the netmap module and netmap support in the device drivers. Alternatively, you can build standalone modules (netmap, ixgbe, em, lem, re, igb) Linux ------- + make sure you have kernel sources matching your installed kernel, so the build system can patch the sources and build netmap-enabled drivers. If kernel sources are in /a/b/c/linux-A.B.C/ , then you should do cd netmap/LINUX make KSRC=/a/b/c/linux-A.B.C/ # builds the kernel modules make KSRC=/a/b/c/linux-A.B.C/ apps # builds sample applications You can omit KSRC if your kernel sources are in a standard place. Applications ------------- The directory examples/ contains some programs that use the netmap API pkt-gen a packet generator/receiver working at line rate at 10Gbit/s bridge a utility that bridges two interfaces or one interface with the host stack pcap.c a simple libpcap-over-netmap library, and some test code, to help porting pcap applications to netmap. The library compiles as libnetmap.so, you can use it to replace your libpcap.so.* Testing ------- pkt-gen is a generic test program which can act as a sender or receiver. It has a large number of options, but the simplest form is: pkt-gen -i ix0 -f rx # receive and print stats pkt-gen -i ix0 -f tx -l 60 # send a stream of 60-byte packets (replace ix0 with the name of the interface or VALE port). This should be able to work at line rate (up to 14.88 Mpps on 10 Gbit/interfaces, even higher on VALE) but note the following CAVEATS ------- Before reporting slow send or receive speed on a physical interface, check ALL of the following: + make sure the interface is up before invoking pkt-gen + make sure that the netmap module and drivers are correctly loaded and can allocate all the memory they need (check into /var/log/messages or equivalent) These errors will generally cause a failure to register the netmap port + some switches/interfaces take a long time to (re)negotiate the link after starting pkt-gen; in case, use the -w N option to increase the initial delay to N seconds; This may cause inability to transmit, or lost packets for the first few seconds of transmission + make sure that the interface and switch you connect to has flow control (FC) disabled (either via sysctl or ethtool). If FC is enabled and the receiving end is unable to cope with the traffic, the driver will try to slow down transmission, sometimes to very low rates. + a lot of hardware is not able to sustain line rate. For instance, ixgbe has problems with receiving frames that are not multiple of 64 bytes (with/without CRC depending on the driver); also on transmissions, ixgbe tops at about 12.5 Mpps unless the driver prefetches tx descriptors. igb does line rate in all configurations. e1000/e1000e vary between 1.15 and 1.32 Mpps. re/r8169 is extremely slow in sending (max 4-500 Kpps) Credits ------- NETMAP and VALE are projects of the Universita` di Pisa, partially supported by Intel Research Berkeley, EU FP7 projects CHANGE and OPENLAB. Author: Luigi Rizzo Contributors: Giuseppe Lettieri Marta Carbone Gaetano Catalli Matteo Landi References ---------- There are a few academic papers describing netmap, VALE and applications. You can find the papers at http://info.iet.unipi.it/~luigi/research.html + Luigi Rizzo, netmap: a novel framework for fast packet I/O, Usenix ATC'12, Boston, June 2012 + Luigi Rizzo, Revisiting network I/O APIs: the netmap framework, Communications of the ACM 55 (3), 45-51, March 2012 + Luigi Rizzo, Marta Carbone, Gaetano Catalli, Transparent acceleration of software packet forwarding using netmap, IEEE Infocom 2012, Orlando, March 2012 + Luigi Rizzo, Giuseppe Lettieri, VALE: a switched ethernet for virtual machines, DEIT Tech report, June 2012 netmap-release/LINUX/000755 000423 000000 00000000000 12110024375 015110 5ustar00luigiwheel000000 000000 netmap-release/LINUX/if_e1000e_netmap.h000644 000423 000000 00000024156 12064741110 020206 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2012 Gaetano Catalli, Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * BSD Copyright * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $Id: if_e1000e_netmap.h 10670 2012-02-27 21:15:38Z luigi $ * * netmap support for e1000e (em) * For details on netmap support please see ixgbe_netmap.h * * The driver supports 1 TX and 1 RX ring. Single lock. * tx buffer address only written on change. * Advanced descriptors ? Rx Crc stripping ? */ #include #include #include #define SOFTC_T e1000_adapter /* * Register/unregister, similar to e1000_reinit_safe() */ static int e1000_netmap_reg(struct ifnet *ifp, int onoff) { struct SOFTC_T *adapter = netdev_priv(ifp); struct netmap_adapter *na = NA(ifp); int error = 0; if (na == NULL) return EINVAL; if (!(ifp->flags & IFF_UP)) { /* e1000_open has not been called yet, so resources * are not allocated */ D("Interface is down!"); return EINVAL; } while (test_and_set_bit(__E1000_RESETTING, &adapter->state)) msleep(1); //rtnl_lock(); // XXX do we need it ? e1000e_down(adapter); if (onoff) { /* enable netmap mode */ ifp->if_capenable |= IFCAP_NETMAP; na->if_transmit = (void *)ifp->netdev_ops; ifp->netdev_ops = &na->nm_ndo; } else { ifp->if_capenable &= ~IFCAP_NETMAP; ifp->netdev_ops = (void *)na->if_transmit; } e1000e_up(adapter); //rtnl_unlock(); // XXX do we need it ? clear_bit(__E1000_RESETTING, &adapter->state); return (error); } /* * Reconcile kernel and user view of the transmit ring. */ static int e1000_netmap_txsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct SOFTC_T *adapter = netdev_priv(ifp); struct e1000_ring* txr = &adapter->tx_ring[ring_nr]; struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->tx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, k, l, n = 0, lim = kring->nkr_num_slots - 1; /* generate an interrupt approximately every half ring */ int report_frequency = kring->nkr_num_slots >> 1; /* take a copy of ring->cur now, and never read it again */ k = ring->cur; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) mtx_lock(&kring->q_lock); rmb(); /* * Process new packets to send. j is the current index in the * netmap ring, l is the corresponding index in the NIC ring. */ j = kring->nr_hwcur; if (j != k) { /* we have new packets to send */ l = netmap_idx_k2n(kring, j); for (n = 0; j != k; n++) { /* slot is the current slot in the netmap ring */ struct netmap_slot *slot = &ring->slot[j]; /* curr is the current slot in the nic ring */ struct e1000_tx_desc *curr = E1000_TX_DESC(*txr, l); int flags = ((slot->flags & NS_REPORT) || j == 0 || j == report_frequency) ? E1000_TXD_CMD_RS : 0; uint64_t paddr; void *addr = PNMB(slot, &paddr); u_int len = slot->len; if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) { if (do_lock) mtx_unlock(&kring->q_lock); return netmap_ring_reinit(kring); } slot->flags &= ~NS_REPORT; if (slot->flags & NS_BUF_CHANGED) { // netmap_reload_map(pdev, DMA_TO_DEVICE, old_paddr, addr) curr->buffer_addr = htole64(paddr); slot->flags &= ~NS_BUF_CHANGED; } curr->upper.data = 0; curr->lower.data = htole32(adapter->txd_cmd | len | (E1000_TXD_CMD_EOP | flags) ); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwcur = k; /* the saved ring->cur */ kring->nr_hwavail -= n; wmb(); /* synchronize writes to the NIC ring */ txr->next_to_use = l; writel(l, adapter->hw.hw_addr + txr->tail); mmiowb(); // XXX where do we need this ? } if (n == 0 || kring->nr_hwavail < 1) { int delta; /* record completed transmissions using TDH */ l = readl(adapter->hw.hw_addr + txr->head); if (l >= kring->nkr_num_slots) { /* XXX can it happen ? */ D("TDH wrap %d", l); l -= kring->nkr_num_slots; } delta = l - txr->next_to_clean; if (delta) { /* some tx completed, increment hwavail. */ if (delta < 0) delta += kring->nkr_num_slots; txr->next_to_clean = l; kring->nr_hwavail += delta; } } /* update avail to what the kernel knows */ ring->avail = kring->nr_hwavail; if (do_lock) mtx_unlock(&kring->q_lock); return 0; } /* * Reconcile kernel and user view of the receive ring. */ static int e1000_netmap_rxsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct SOFTC_T *adapter = netdev_priv(ifp); struct netmap_adapter *na = NA(ifp); struct e1000_ring *rxr = &adapter->rx_ring[ring_nr]; struct netmap_kring *kring = &na->rx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, l, n, lim = kring->nkr_num_slots - 1; int force_update = do_lock || kring->nr_kflags & NKR_PENDINTR; int strip_crc = (adapter->flags2 & FLAG2_CRC_STRIPPING) ? 0 : 4; u_int k = ring->cur, resvd = ring->reserved; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) mtx_lock(&kring->q_lock); rmb(); /* * Import newly received packets into the netmap ring. * j is an index in the netmap ring, l in the NIC ring. */ l = rxr->next_to_clean; j = netmap_idx_n2k(kring, l); if (netmap_no_pendintr || force_update) { for (n = 0; ; n++) { struct e1000_rx_desc *curr = E1000_RX_DESC(*rxr, l); uint32_t staterr = le32toh(curr->status); if ((staterr & E1000_RXD_STAT_DD) == 0) break; ring->slot[j].len = le16toh(curr->length) - strip_crc; ring->slot[j].flags = NS_FORWARD; j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } if (n) { /* update the state variables */ rxr->next_to_clean = l; kring->nr_hwavail += n; } kring->nr_kflags &= ~NKR_PENDINTR; } /* skip past packets that userspace has released */ j = kring->nr_hwcur; /* netmap ring index */ if (resvd > 0) { if (resvd + ring->avail >= lim + 1) { D("XXX invalid reserve/avail %d %d", resvd, ring->avail); ring->reserved = resvd = 0; // XXX panic... } k = (k >= resvd) ? k - resvd : k + lim + 1 - resvd; } if (j != k) { /* userspace has released some packets. */ l = netmap_idx_k2n(kring, j); /* NIC ring index */ for (n = 0; j != k; n++) { struct netmap_slot *slot = &ring->slot[j]; struct e1000_rx_desc *curr = E1000_RX_DESC(*rxr, j); uint64_t paddr; void *addr = PNMB(slot, &paddr); if (addr == netmap_buffer_base) { /* bad buf */ if (do_lock) mtx_unlock(&kring->q_lock); return netmap_ring_reinit(kring); } if (slot->flags & NS_BUF_CHANGED) { // netmap_reload_map(pdev, DMA_TO_DEVICE, old_paddr, addr) curr->buffer_addr = htole64(paddr); slot->flags &= ~NS_BUF_CHANGED; } curr->status = 0; j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwavail -= n; kring->nr_hwcur = k; wmb(); rxr->next_to_use = l; // XXX not really used /* * IMPORTANT: we must leave one free slot in the ring, * so move l back by one unit */ l = (l == 0) ? lim : l - 1; writel(l, adapter->hw.hw_addr + rxr->tail); } /* tell userspace that there are new packets */ ring->avail = kring->nr_hwavail - resvd; if (do_lock) mtx_unlock(&kring->q_lock); return 0; } /* diagnostic routine to catch errors */ static void e1000e_no_rx_alloc(struct SOFTC_T *a, int n) { D("e1000->alloc_rx_buf should not be called"); } /* * Make the tx and rx rings point to the netmap buffers. */ static int e1000e_netmap_init_buffers(struct SOFTC_T *adapter) { struct ifnet *ifp = adapter->netdev; struct netmap_adapter* na = NA(ifp); struct netmap_slot* slot; struct e1000_ring *rxr = adapter->rx_ring; struct e1000_ring *txr = adapter->tx_ring; int i, si; uint64_t paddr; slot = netmap_reset(na, NR_RX, 0, 0); if (!slot) return 0; // not in netmap mode adapter->alloc_rx_buf = (void*)e1000e_no_rx_alloc; for (i = 0; i < rxr->count; i++) { // XXX the skb check and cleanup can go away struct e1000_buffer *bi = &rxr->buffer_info[i]; si = netmap_idx_n2k(&na->rx_rings[0], i); PNMB(slot + si, &paddr); if (bi->skb) D("rx buf %d was set", i); bi->skb = NULL; // XXX leak if set // netmap_load_map(...) E1000_RX_DESC(*rxr, i)->buffer_addr = htole64(paddr); } rxr->next_to_use = 0; /* preserve buffers already made available to clients */ i = rxr->count - 1 - na->rx_rings[0].nr_hwavail; wmb(); /* Force memory writes to complete */ writel(i, adapter->hw.hw_addr + rxr->tail); /* now initialize the tx ring */ slot = netmap_reset(na, NR_TX, 0, 0); for (i = 0; i < na->num_tx_desc; i++) { si = netmap_idx_n2k(&na->tx_rings[0], i); PNMB(slot + si, &paddr); // netmap_load_map(...) E1000_TX_DESC(*txr, i)->buffer_addr = htole64(paddr); } return 1; } static void e1000_netmap_attach(struct SOFTC_T *adapter) { struct netmap_adapter na; bzero(&na, sizeof(na)); na.ifp = adapter->netdev; na.separate_locks = 0; na.num_tx_desc = adapter->tx_ring->count; na.num_rx_desc = adapter->rx_ring->count; na.nm_register = e1000_netmap_reg; na.nm_txsync = e1000_netmap_txsync; na.nm_rxsync = e1000_netmap_rxsync; netmap_attach(&na, 1); } /* end of file */ netmap-release/LINUX/patches/000755 000423 000000 00000000000 12077774155 016563 5ustar00luigiwheel000000 000000 netmap-release/LINUX/ixgbe_netmap_linux.h000644 000423 000000 00000043643 12064741153 021164 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2012 Matteo Landi, Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $FreeBSD: head/sys/dev/netmap/ixgbe_netmap.h 230572 2012-01-26 09:55:16Z luigi $ * $Id: ixgbe_netmap_linux.h 10670 2012-02-27 21:15:38Z luigi $ * * netmap support for ixgbe (LINUX version) * * supports N TX and RX queues, separate locks, hw crc strip, * address rewrite in txsync * * This file is meant to be a reference on how to implement * netmap support for a network driver. * This file contains code but only static or inline functions * that are used by a single driver. To avoid replication of * code we just #include it near the beginning of the * standard driver. */ #include #include #include #define SOFTC_T ixgbe_adapter /* * Adaptation to various version of the driver. * Recent drivers (3.4 and above) redefine some macros */ #ifndef IXGBE_TX_DESC_ADV #define IXGBE_TX_DESC_ADV IXGBE_TX_DESC #define IXGBE_RX_DESC_ADV IXGBE_RX_DESC #endif /* * Register/unregister. We are already under core lock. * Only called on the first register or the last unregister. */ static int ixgbe_netmap_reg(struct ifnet *ifp, int onoff) { struct SOFTC_T *adapter = netdev_priv(ifp); struct netmap_adapter *na = NA(ifp); int error = 0; if (na == NULL) return EINVAL; /* no netmap support here */ // XXX do a reinit_locked or something else ? /* Tell the stack that the interface is no longer active */ while (test_and_set_bit(__IXGBE_RESETTING, &adapter->state)) usleep_range(1000, 2000); //rtnl_lock(); // XXX do we need it ? ixgbe_down(adapter); if (onoff) { /* enable netmap mode */ ifp->if_capenable |= IFCAP_NETMAP; /* save if_transmit and replace with our routine */ na->if_transmit = (void *)ifp->netdev_ops; ifp->netdev_ops = &na->nm_ndo; /* * reinitialize the adapter, now with netmap flag set, * so the rings will be set accordingly. */ ixgbe_up(adapter); } else { /* reset normal mode (explicit request or netmap failed) */ /* restore if_transmit */ ifp->netdev_ops = (void *)na->if_transmit; ifp->if_capenable &= ~IFCAP_NETMAP; /* initialize the card, this time in standard mode */ ixgbe_up(adapter); /* also enables intr */ } //rtnl_unlock(); // XXX do we need it ? clear_bit(__IXGBE_RESETTING, &adapter->state); return (error); } /* * Reconcile kernel and user view of the transmit ring. * This routine might be called frequently so it must be efficient. * * Userspace has filled tx slots up to ring->cur (excluded). * The last unused slot previously known to the kernel was kring->nkr_hwcur, * and the last interrupt reported kring->nr_hwavail slots available. * * This function runs under lock (acquired from the caller or internally). * It must first update ring->avail to what the kernel knows, * subtract the newly used slots (ring->cur - kring->nkr_hwcur) * from both avail and nr_hwavail, and set ring->nkr_hwcur = ring->cur * issuing a dmamap_sync on all slots. * * Since ring comes from userspace, its content must be read only once, * and validated before being used to update the kernel's structures. * (this is also true for every use of ring in the kernel). * * ring->avail is never used, only checked for bogus values. * * do_lock is set iff the function is called from the ioctl handler. * In this case, grab a lock around the body, and also reclaim transmitted * buffers irrespective of interrupt mitigation. */ static int ixgbe_netmap_txsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct SOFTC_T *adapter = netdev_priv(ifp); struct ixgbe_ring *txr = adapter->tx_ring[ring_nr]; struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->tx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, k = ring->cur, l, n, lim = kring->nkr_num_slots - 1; /* * ixgbe can generate an interrupt on every tx packet, but it * seems very expensive, so we interrupt once every half ring, * or when requested with NS_REPORT */ int report_frequency = kring->nkr_num_slots >> 1; /* if cur is invalid reinitialize the ring. */ if (k > lim) return netmap_ring_reinit(kring); if (do_lock) mtx_lock(&kring->q_lock); /* * Process new packets to send. j is the current index in the * netmap ring, l is the corresponding index in the NIC ring. * The two numbers differ because upon a *_init() we reset * the NIC ring but leave the netmap ring unchanged. * For the transmit ring, we have * * j = kring->nr_hwcur * l = IXGBE_TDT (not tracked in the driver) * and * j == (l + kring->nkr_hwofs) % ring_size * * In this driver kring->nkr_hwofs >= 0, but for other * drivers it might be negative as well. */ j = kring->nr_hwcur; if (j != k) { /* we have new packets to send */ l = netmap_idx_k2n(kring, j); for (n = 0; j != k; n++) { /* * Collect per-slot info. * Note that txbuf and curr are indexed by l. * * In this driver we collect the buffer address * (using the PNMB() macro) because we always * need to rewrite it into the NIC ring. * Many other drivers preserve the address, so * we only need to access it if NS_BUF_CHANGED * is set. */ struct netmap_slot *slot = &ring->slot[j]; union ixgbe_adv_tx_desc *curr = IXGBE_TX_DESC_ADV(txr, l); uint64_t paddr; void *addr = PNMB(slot, &paddr); // XXX type for flags and len ? int flags = ((slot->flags & NS_REPORT) || j == 0 || j == report_frequency) ? IXGBE_TXD_CMD_RS : 0; u_int len = slot->len; /* * Quick check for valid addr and len. * NMB() returns netmap_buffer_base for invalid * buffer indexes (but the address is still a * valid one to be used in a ring). slot->len is * unsigned so no need to check for negative values. */ if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) { ring_reset: if (do_lock) mtx_unlock(&kring->q_lock); return netmap_ring_reinit(kring); } slot->flags &= ~NS_REPORT; if (slot->flags & NS_BUF_CHANGED) { /* buffer has changed, unload and reload map */ // netmap_reload_map(pdev, DMA_TO_DEVICE, old_addr, addr); slot->flags &= ~NS_BUF_CHANGED; } /* * Fill the slot in the NIC ring. * In this driver we need to rewrite the buffer * address in the NIC ring. Other drivers do not * need this. */ curr->read.buffer_addr = htole64(paddr); curr->read.olinfo_status = htole32(len << IXGBE_ADVTXD_PAYLEN_SHIFT); curr->read.cmd_type_len = htole32( len | (IXGBE_ADVTXD_DTYP_DATA | IXGBE_ADVTXD_DCMD_DEXT | IXGBE_ADVTXD_DCMD_IFCS | IXGBE_TXD_CMD_EOP | flags) ); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwcur = k; /* the saved ring->cur */ /* decrease avail by number of packets sent */ kring->nr_hwavail -= n; wmb(); /* synchronize writes to the NIC ring */ /* (re)start the transmitter up to slot l (excluded) */ IXGBE_WRITE_REG(&adapter->hw, IXGBE_TDT(txr->reg_idx), l); } /* * Reclaim buffers for completed transmissions. * Because this is expensive (we read a NIC register etc.) * we only do it in specific cases (see below). * In all cases kring->nr_kflags indicates which slot will be * checked upon a tx interrupt (nkr_num_slots means none). */ if (do_lock) { j = 1; /* forced reclaim, ignore interrupts */ kring->nr_kflags = kring->nkr_num_slots; } else if (kring->nr_hwavail > 0) { j = 0; /* buffers still available: no reclaim, ignore intr. */ kring->nr_kflags = kring->nkr_num_slots; } else { /* * no buffers available, locate a slot for which we request * ReportStatus (approximately half ring after next_to_clean) * and record it in kring->nr_kflags. * If the slot has DD set, do the reclaim looking at TDH, * otherwise we go to sleep (in netmap_poll()) and will be * woken up when slot nr_kflags will be ready. */ union ixgbe_adv_tx_desc *txd = IXGBE_TX_DESC_ADV(txr, 0); j = txr->next_to_clean + kring->nkr_num_slots/2; if (j >= kring->nkr_num_slots) j -= kring->nkr_num_slots; // round to the closest with dd set j= (j < kring->nkr_num_slots / 4 || j >= kring->nkr_num_slots*3/4) ? 0 : report_frequency; kring->nr_kflags = j; /* the slot to check */ j = txd[j].wb.status & IXGBE_TXD_STAT_DD; // XXX cpu_to_le32 ? } if (j) { int delta; /* * Record completed transmissions. * We (re)use the driver's txr->next_to_clean to keep * track of the most recently completed transmission. * * The datasheet discourages the use of TDH to find out the * number of sent packets. We should rather check the DD * status bit in a packet descriptor. However, we only set * the "report status" bit for some descriptors (a kind of * interrupt mitigation), so we can only check on those. * For the time being we use TDH, as we do it infrequently * enough not to pose performance problems. */ l = IXGBE_READ_REG(&adapter->hw, IXGBE_TDH(ring_nr)); if (l >= kring->nkr_num_slots) { /* XXX can happen */ D("TDH wrap %d", l); l -= kring->nkr_num_slots; } delta = l - txr->next_to_clean; if (delta) { /* some tx completed, increment hwavail. */ if (delta < 0) delta += kring->nkr_num_slots; txr->next_to_clean = l; kring->nr_hwavail += delta; if (kring->nr_hwavail > lim) goto ring_reset; } } /* update avail to what the kernel knows */ ring->avail = kring->nr_hwavail; if (do_lock) mtx_unlock(&kring->q_lock); return 0; } /* * Reconcile kernel and user view of the receive ring. * Same as for the txsync, this routine must be efficient and * avoid races in accessing the shared regions. * * When called, userspace has read data from slots kring->nr_hwcur * up to ring->cur (excluded). * * The last interrupt reported kring->nr_hwavail slots available * after kring->nr_hwcur. * We must subtract the newly consumed slots (cur - nr_hwcur) * from nr_hwavail, make the descriptors available for the next reads, * and set kring->nr_hwcur = ring->cur and ring->avail = kring->nr_hwavail. * * do_lock has a special meaning: please refer to txsync. */ static int ixgbe_netmap_rxsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct SOFTC_T *adapter = netdev_priv(ifp); struct ixgbe_ring *rxr = adapter->rx_ring[ring_nr]; struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->rx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, l, n, lim = kring->nkr_num_slots - 1; int force_update = do_lock || kring->nr_kflags & NKR_PENDINTR; u_int k = ring->cur, resvd = ring->reserved; if (k > lim) /* userspace is cheating */ return netmap_ring_reinit(kring); if (do_lock) mtx_lock(&kring->q_lock); rmb(); /* * First part, import newly received packets into the netmap ring. * * j is the index of the next free slot in the netmap ring, * and l is the index of the next received packet in the NIC ring, * and they may differ in case if_init() has been called while * in netmap mode. For the receive ring we have * * j = (kring->nr_hwcur + kring->nr_hwavail) % ring_size * l = rxr->next_to_check; * and * j == (l + kring->nkr_hwofs) % ring_size * * rxr->next_to_check is set to 0 on a ring reinit */ l = rxr->next_to_clean; j = netmap_idx_n2k(kring, l); if (netmap_no_pendintr || force_update) { for (n = 0; ; n++) { union ixgbe_adv_rx_desc *curr = IXGBE_RX_DESC_ADV(rxr, l); uint32_t staterr = le32toh(curr->wb.upper.status_error); if ((staterr & IXGBE_RXD_STAT_DD) == 0) break; ring->slot[j].len = le16toh(curr->wb.upper.length); ring->slot[j].flags = NS_FORWARD; j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } if (n) { /* update the state variables */ rxr->next_to_clean = l; kring->nr_hwavail += n; } kring->nr_kflags &= ~NKR_PENDINTR; } /* * Skip past packets that userspace has already released * (from kring->nr_hwcur to ring->cur-ring->reserved excluded), * and make the buffers available for reception. * As usual j is the index in the netmap ring, l is the index * in the NIC ring, and j == (l + kring->nkr_hwofs) % ring_size */ j = kring->nr_hwcur; /* netmap ring index */ if (resvd > 0) { if (resvd + ring->avail >= lim + 1) { D("XXX invalid reserve/avail %d %d", resvd, ring->avail); ring->reserved = resvd = 0; // XXX panic... } k = (k >= resvd) ? k - resvd : k + lim + 1 - resvd; } if (j != k) { /* userspace has released some packets. */ l = netmap_idx_k2n(kring, j); for (n = 0; j != k; n++) { /* collect per-slot info, with similar validations * and flag handling as in the txsync code. * * NOTE curr and rxbuf are indexed by l. * Also, this driver needs to update the physical * address in the NIC ring, but other drivers * may not have this requirement. */ struct netmap_slot *slot = &ring->slot[j]; union ixgbe_adv_rx_desc *curr = IXGBE_RX_DESC_ADV(rxr, l); uint64_t paddr; void *addr = PNMB(slot, &paddr); if (addr == netmap_buffer_base) /* bad buf */ goto ring_reset; if (slot->flags & NS_BUF_CHANGED) { // netmap_reload_map(pdev, DMA_TO_DEVICE, old_addr, addr); slot->flags &= ~NS_BUF_CHANGED; } curr->wb.upper.status_error = 0; curr->read.pkt_addr = htole64(paddr); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwavail -= n; kring->nr_hwcur = k; rxr->next_to_use = l; // XXX not really used wmb(); /* IMPORTANT: we must leave one free slot in the ring, * so move l back by one unit */ l = (l == 0) ? lim : l - 1; IXGBE_WRITE_REG(&adapter->hw, IXGBE_RDT(rxr->reg_idx), l); } /* tell userspace that there are new packets */ ring->avail = kring->nr_hwavail - resvd; if (do_lock) mtx_unlock(&kring->q_lock); return 0; ring_reset: if (do_lock) mtx_unlock(&kring->q_lock); return netmap_ring_reinit(kring); } /* * if in netmap mode, attach the netmap buffers to the ring and return true. * Otherwise return false. */ static int ixgbe_netmap_configure_tx_ring(struct SOFTC_T *adapter, int ring_nr) { struct netmap_adapter *na = NA(adapter->netdev); struct netmap_slot *slot = netmap_reset(na, NR_TX, ring_nr, 0); //int j; if (!slot) return 0; // not in netmap; #if 0 /* * on a generic card we should set the address in the slot. * But on the ixgbe, the address needs to be rewritten * after a transmission so there is nothing do to except * loading the map. */ for (j = 0; j < na->num_tx_desc; j++) { int sj = netmap_idx_n2k(&na->tx_rings[ring_nr], j); uint64_t paddr; void *addr = PNMB(slot + sj, &paddr); } #endif return 1; } static int ixgbe_netmap_configure_rx_ring(struct SOFTC_T *adapter, int ring_nr) { /* * In netmap mode, we must preserve the buffers made * available to userspace before the if_init() * (this is true by default on the TX side, because * init makes all buffers available to userspace). * * netmap_reset() and the device specific routines * (e.g. ixgbe_setup_receive_rings()) map these * buffers at the end of the NIC ring, so here we * must set the RDT (tail) register to make sure * they are not overwritten. * * In this driver the NIC ring starts at RDH = 0, * RDT points to the last slot available for reception (?), * so RDT = num_rx_desc - 1 means the whole ring is available. */ struct netmap_adapter *na = NA(adapter->netdev); struct netmap_slot *slot = netmap_reset(na, NR_RX, ring_nr, 0); int lim, i; struct ixgbe_ring *ring = adapter->rx_ring[ring_nr]; /* same as in ixgbe_setup_transmit_ring() */ if (!slot) return 0; // not in netmap; lim = na->num_rx_desc - 1 - na->rx_rings[ring_nr].nr_hwavail; for (i = 0; i < na->num_rx_desc; i++) { /* * Fill the map and set the buffer address in the NIC ring, * considering the offset between the netmap and NIC rings * (see comment in ixgbe_setup_transmit_ring() ). */ int si = netmap_idx_n2k(&na->rx_rings[ring_nr], i); uint64_t paddr; PNMB(slot + si, &paddr); // netmap_load_map(rxr->ptag, rxbuf->pmap, addr); /* Update descriptor */ IXGBE_RX_DESC_ADV(ring, i)->read.pkt_addr = htole64(paddr); } IXGBE_WRITE_REG(&adapter->hw, IXGBE_RDT(ring_nr), lim); return 1; } /* * The attach routine, called near the end of ixgbe_attach(), * fills the parameters for netmap_attach() and calls it. * It cannot fail, in the worst case (such as no memory) * netmap mode will be disabled and the driver will only * operate in standard mode. */ static void ixgbe_netmap_attach(struct SOFTC_T *adapter) { struct netmap_adapter na; bzero(&na, sizeof(na)); na.ifp = adapter->netdev; na.separate_locks = 0; /* this card has separate rx/tx locks */ na.num_tx_desc = adapter->tx_ring[0]->count; na.num_rx_desc = adapter->rx_ring[0]->count; na.nm_txsync = ixgbe_netmap_txsync; na.nm_rxsync = ixgbe_netmap_rxsync; na.nm_register = ixgbe_netmap_reg; netmap_attach(&na, adapter->num_tx_queues); } /* end of file */ netmap-release/LINUX/if_igb_netmap.h000644 000423 000000 00000027253 12064741122 020061 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2012 Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $Id: if_igb_netmap.h 10878 2012-04-12 22:28:48Z luigi $ * * netmap support for "igb" (untested) * For details on netmap support please see ixgbe_netmap.h * This supports multiple tx/rx rings, multiple locks ? * CRCstrip, address rewrite ? */ #include #include #include #define SOFTC_T igb_adapter /* * Adapt to different versions. E1000_TX_DESC_ADV etc. have * dropped the _ADV suffix in newer versions. Also the first * argument is now a pointer not the object. */ #ifndef E1000_TX_DESC_ADV #define E1000_TX_DESC_ADV(_r, _i) IGB_TX_DESC(&(_r), _i) #define E1000_RX_DESC_ADV(_r, _i) IGB_RX_DESC(&(_r), _i) #define READ_TDH(_txr) ({struct e1000_hw *hw = &adapter->hw;rd32(E1000_TDH((_txr)->reg_idx));} ) #else /* up to 3.2, approximately */ #define igb_tx_buffer igb_buffer #define tx_buffer_info buffer_info #define igb_rx_buffer igb_buffer #define rx_buffer_info buffer_info #define READ_TDH(_txr) readl((_txr)->head) #endif /* * Register/unregister, similar to e1000_reinit_safe() */ static int igb_netmap_reg(struct ifnet *ifp, int onoff) { struct SOFTC_T *adapter = netdev_priv(ifp); struct netmap_adapter *na = NA(ifp); int error = 0; if (na == NULL) return EINVAL; if (!(ifp->flags & IFF_UP)) { D("Interface is down!"); return EINVAL; } while (test_and_set_bit(__IGB_RESETTING, &adapter->state)) msleep(1); //rtnl_lock(); // XXX do we need it ? igb_down(adapter); if (onoff) { /* enable netmap mode */ ifp->if_capenable |= IFCAP_NETMAP; na->if_transmit = (void *)ifp->netdev_ops; ifp->netdev_ops = &na->nm_ndo; } else { ifp->if_capenable &= ~IFCAP_NETMAP; ifp->netdev_ops = (void *)na->if_transmit; } igb_up(adapter); //rtnl_unlock(); // XXX do we need it ? clear_bit(__IGB_RESETTING, &adapter->state); return (error); } /* * Reconcile kernel and user view of the transmit ring. */ static int igb_netmap_txsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct SOFTC_T *adapter = netdev_priv(ifp); struct igb_ring* txr = adapter->tx_ring[ring_nr]; struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->tx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, k, l, n = 0, lim = kring->nkr_num_slots - 1; /* generate an interrupt approximately every half ring */ int report_frequency = kring->nkr_num_slots >> 1; /* take a copy of ring->cur now, and never read it again */ k = ring->cur; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) mtx_lock(&kring->q_lock); rmb(); /* * Process new packets to send. j is the current index in the * netmap ring, l is the corresponding index in the NIC ring. */ j = kring->nr_hwcur; if (j != k) { /* we have new packets to send */ uint32_t olinfo_status=0; l = netmap_idx_k2n(kring, j); for (n = 0; j != k; n++) { /* slot is the current slot in the netmap ring */ struct netmap_slot *slot = &ring->slot[j]; /* curr is the current slot in the nic ring */ union e1000_adv_tx_desc *curr = E1000_TX_DESC_ADV(*txr, l); int flags = ((slot->flags & NS_REPORT) || j == 0 || j == report_frequency) ? E1000_TXD_CMD_RS : 0; uint64_t paddr; void *addr = PNMB(slot, &paddr); u_int len = slot->len; if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) { if (do_lock) mtx_unlock(&kring->q_lock); return netmap_ring_reinit(kring); } slot->flags &= ~NS_REPORT; if (slot->flags & NS_BUF_CHANGED) { // netmap_reload_map(pdev, DMA_TO_DEVICE, old_paddr, addr); slot->flags &= ~NS_BUF_CHANGED; } curr->read.buffer_addr = htole64(paddr); // XXX check olinfo and cmd_type_len curr->read.olinfo_status = htole32(olinfo_status | (len<< E1000_ADVTXD_PAYLEN_SHIFT)); curr->read.cmd_type_len = htole32(len | E1000_ADVTXD_DTYP_DATA | E1000_ADVTXD_DCMD_IFCS | E1000_ADVTXD_DCMD_DEXT | E1000_TXD_CMD_EOP | flags); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwcur = k; /* the saved ring->cur */ ND("ring %d sent %d", ring_nr, n); kring->nr_hwavail -= n; wmb(); /* synchronize writes to the NIC ring */ txr->next_to_use = l; writel(l, txr->tail); mmiowb(); // XXX where do we need this ? } if (kring->nr_hwavail < 0 || kring->nr_hwavail > lim) D("ouch, hwavail %d", kring->nr_hwavail); if (n == 0 || kring->nr_hwavail < 1) { int delta; /* record completed transmissions using TDH */ l = READ_TDH(txr); if (l >= kring->nkr_num_slots) { /* XXX can happen */ D("TDH wrap %d", l); l -= kring->nkr_num_slots; } delta = l - txr->next_to_clean; ND("ring %d tdh %d delta %d", ring_nr, l, delta); if (delta) { /* some tx completed, increment hwavail. */ if (delta < 0) delta += kring->nkr_num_slots; txr->next_to_clean = l; /* fool the timer so we don't get watchdog resets */ txr->next_to_use = l; kring->nr_hwavail += delta; } } /* update avail to what the kernel knows */ ring->avail = kring->nr_hwavail; if (do_lock) mtx_unlock(&kring->q_lock); return 0; } /* * Reconcile kernel and user view of the receive ring. */ static int igb_netmap_rxsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct SOFTC_T *adapter = netdev_priv(ifp); struct netmap_adapter *na = NA(ifp); struct igb_ring *rxr = adapter->rx_ring[ring_nr]; struct netmap_kring *kring = &na->rx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, l, n, lim = kring->nkr_num_slots - 1; int force_update = do_lock || kring->nr_kflags & NKR_PENDINTR; u_int k = ring->cur, resvd = ring->reserved; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) mtx_lock(&kring->q_lock); rmb(); /* * Import newly received packets into the netmap ring. * j is an index in the netmap ring, l in the NIC ring. */ l = rxr->next_to_clean; j = netmap_idx_n2k(kring, l); if (netmap_no_pendintr || force_update) { for (n = 0; ; n++) { union e1000_adv_rx_desc *curr = E1000_RX_DESC_ADV(*rxr, l); uint32_t staterr = le32toh(curr->wb.upper.status_error); if ((staterr & E1000_RXD_STAT_DD) == 0) break; ring->slot[j].len = le16toh(curr->wb.upper.length); ring->slot[j].flags = NS_FORWARD; j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } if (n) { /* update the state variables */ rxr->next_to_clean = l; kring->nr_hwavail += n; } kring->nr_kflags &= ~NKR_PENDINTR; } /* skip past packets that userspace has released */ j = kring->nr_hwcur; /* netmap ring index */ if (resvd > 0) { if (resvd + ring->avail >= lim + 1) { D("XXX invalid reserve/avail %d %d", resvd, ring->avail); ring->reserved = resvd = 0; // XXX panic... } k = (k >= resvd) ? k - resvd : k + lim + 1 - resvd; } if (j != k) { /* userspace has released some packets. */ l = netmap_idx_k2n(kring, j); /* NIC ring index */ for (n = 0; j != k; n++) { struct netmap_slot *slot = &ring->slot[j]; union e1000_adv_rx_desc *curr = E1000_RX_DESC_ADV(*rxr, j); uint64_t paddr; void *addr = PNMB(slot, &paddr); if (addr == netmap_buffer_base) { /* bad buf */ if (do_lock) mtx_unlock(&kring->q_lock); return netmap_ring_reinit(kring); } if (slot->flags & NS_BUF_CHANGED) { // netmap_reload_map(pdev, DMA_FROM_DEVICE, old_paddr, addr); slot->flags &= ~NS_BUF_CHANGED; } curr->read.pkt_addr = htole64(paddr); curr->wb.upper.status_error = 0; j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwavail -= n; kring->nr_hwcur = k; wmb(); rxr->next_to_use = l; // XXX not really used /* * IMPORTANT: we must leave one free slot in the ring, * so move l back by one unit */ l = (l == 0) ? lim : l - 1; writel(l, rxr->tail); } /* tell userspace that there are new packets */ ring->avail = kring->nr_hwavail - resvd; if (do_lock) mtx_unlock(&kring->q_lock); return 0; } static int igb_netmap_configure_tx_ring(struct SOFTC_T *adapter, int ring_nr) { struct ifnet *ifp = adapter->netdev; struct netmap_adapter* na = NA(ifp); struct netmap_slot* slot = netmap_reset(na, NR_TX, ring_nr, 0); struct igb_ring *txr = adapter->tx_ring[ring_nr]; int i, si; void *addr; uint64_t paddr; if (!slot) return 0; for (i = 0; i < na->num_tx_desc; i++) { union e1000_adv_tx_desc *tx_desc; si = netmap_idx_n2k(&na->tx_rings[ring_nr], i); addr = PNMB(slot + si, &paddr); tx_desc = E1000_TX_DESC_ADV(*txr, i); tx_desc->read.buffer_addr = htole64(paddr); /* actually we don't care to init the rings here */ } return 1; // success } static int igb_netmap_configure_rx_ring(struct igb_ring *rxr) { struct ifnet *ifp = rxr->netdev; struct netmap_adapter* na = NA(ifp); int reg_idx = rxr->reg_idx; struct netmap_slot* slot = netmap_reset(na, NR_RX, reg_idx, 0); u_int i; /* * XXX watch out, rxr->rx_buffer_len should be written * into wr32(E1000_SRRCTL(reg_idx), srrctl) with options * something like * srrctl = ALIGN(ring->rx_buffer_len, 1024) >> * E1000_SRRCTL_BSIZEPKT_SHIFT; * srrctl |= E1000_SRRCTL_DESCTYPE_ADV_ONEBUF; * srrctl |= E1000_SRRCTL_DROP_EN; */ if (!slot) return 0; // not in netmap mode for (i = 0; i < rxr->count; i++) { union e1000_adv_rx_desc *rx_desc; uint64_t paddr; int si = netmap_idx_n2k(&na->rx_rings[reg_idx], i); // XXX the skb check can go away struct igb_rx_buffer *bi = &rxr->rx_buffer_info[i]; if (bi->skb) D("rx buf %d was set", i); bi->skb = NULL; // XXX leak if set PNMB(slot + si, &paddr); rx_desc = E1000_RX_DESC_ADV(*rxr, i); rx_desc->read.hdr_addr = 0; rx_desc->read.pkt_addr = htole64(paddr); } rxr->next_to_use = 0; /* preserve buffers already made available to clients */ i = rxr->count - 1 - na->rx_rings[reg_idx].nr_hwavail; wmb(); /* Force memory writes to complete */ ND("%s rxr%d.tail %d", ifp->if_xname, reg_idx, i); writel(i, rxr->tail); return 1; // success } static void igb_netmap_attach(struct SOFTC_T *adapter) { struct netmap_adapter na; bzero(&na, sizeof(na)); na.ifp = adapter->netdev; na.separate_locks = 0; na.num_tx_desc = adapter->tx_ring_count; na.num_rx_desc = adapter->rx_ring_count; na.nm_register = igb_netmap_reg; na.nm_txsync = igb_netmap_txsync; na.nm_rxsync = igb_netmap_rxsync; na.num_tx_rings = adapter->num_tx_queues; D("using %d TX and %d RX queues", adapter->num_tx_queues, adapter->num_rx_queues); netmap_attach(&na, adapter->num_rx_queues); } /* end of file */ netmap-release/LINUX/bsd_glue.h000644 000423 000000 00000021165 12110024375 017052 0ustar00luigiwheel000000 000000 /* * (C) 2012 Luigi Rizzo - Universita` di Pisa * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * glue code to build the netmap bsd code under linux. * Some of these tweaks are generic, some are specific for * character device drivers and network code/device drivers. */ #ifndef _BSD_GLUE_H #define _BSD_GLUE_H /* a set of headers used in netmap */ #include #include #include #include #include #include #include #include #include #include #include #include //#include // ilog2 #include // eth_type_trans #include #include #include // virt_to_phys #define printf(fmt, arg...) printk(KERN_ERR fmt, ##arg) #define KASSERT(a, b) BUG_ON(!(a)) /* Type redefinitions. XXX check them */ typedef void * bus_dma_tag_t; typedef void * bus_dmamap_t; typedef int bus_size_t; typedef int bus_dma_segment_t; typedef void * bus_addr_t; #define vm_paddr_t phys_addr_t /* XXX the 'off_t' on Linux corresponds to a 'long' */ #define vm_offset_t uint32_t struct thread; /* endianness macros/functions */ #define le16toh le16_to_cpu #define le32toh le32_to_cpu #define le64toh le64_to_cpu #define be64toh be64_to_cpu #define htole32 cpu_to_le32 #define htole64 cpu_to_le64 #include #define time_second (jiffies_to_msecs(jiffies) / 1000U ) #define bzero(a, len) memset(a, 0, len) #define bcopy(_s, _d, len) memcpy(_d, _s, len) // XXX maybe implement it as a proper function somewhere // it is important to set s->len before the copy. #define m_devget(_buf, _len, _ofs, _dev, _fn) ( { \ struct sk_buff *s = netdev_alloc_skb(_dev, _len); \ if (s) { \ s->len += _len; \ skb_copy_to_linear_data_offset(s, _ofs, _buf, _len); \ s->protocol = eth_type_trans(s, _dev); \ } \ s; } ) #define mbuf sk_buff #define m_nextpkt next // chain of mbufs #define m_freem(m) dev_kfree_skb_any(m) // free a sk_buff /* * m_copydata() copies from mbuf to buffer following the mbuf chain. * XXX check which linux equivalent we should use to follow fragmented * skbufs. */ //#define m_copydata(m, o, l, b) skb_copy_bits(m, o, b, l) #define m_copydata(m, o, l, b) skb_copy_from_linear_data_offset(m, o, b, l) /* * struct ifnet is remapped into struct net_device on linux. * ifnet has an if_softc field pointing to the device-specific struct * (adapter). * On linux the ifnet/net_device is at the beginning of the device-specific * structure, so a pointer to the first field of the ifnet works. * We don't use this in netmap, though. * * if_xname name device name * if_capabilities flags // XXX not used * if_capenable priv_flags * we would use "features" but it is all taken. * XXX check for conflict in flags use. * * if_bridge atalk_ptr struct nm_bridge (only for VALE ports) * * In netmap we use if_pspare[0] to point to the netmap_adapter, * in linux we have no spares so we overload ax25_ptr, and the detection * for netmap-capable is some magic in the area pointed by that. */ #define WNA(_ifp) (_ifp)->ax25_ptr #define ifnet net_device /* remap */ #define if_xname name /* field ifnet-> net_device */ //#define if_capabilities flags /* IFCAP_NETMAP */ #define if_capenable priv_flags /* IFCAP_NETMAP */ #define if_bridge atalk_ptr /* remap, only for VALE ports */ #define ifunit_ref(_x) dev_get_by_name(&init_net, _x); #define if_rele(ifp) dev_put(ifp) #define CURVNET_SET(x) #define CURVNET_RESTORE(x) /* * We use spin_lock_irqsave() because we use the lock in the * (hard) interrupt context. */ typedef struct { spinlock_t sl; ulong flags; } safe_spinlock_t; static inline void mtx_lock(safe_spinlock_t *m) { spin_lock_irqsave(&(m->sl), m->flags); } static inline void mtx_unlock(safe_spinlock_t *m) { ulong flags = ACCESS_ONCE(m->flags); spin_unlock_irqrestore(&(m->sl), flags); } #define mtx_init(a, b, c, d) spin_lock_init(&((a)->sl)) #define mtx_destroy(a) // XXX spin_lock_destroy(a) /* use volatile to fix a probable compiler error on 2.6.25 */ #define malloc(_size, type, flags) \ ({ volatile int _v = _size; kmalloc(_v, GFP_ATOMIC | __GFP_ZERO); }) #define free(a, t) kfree(a) // XXX do we need GPF_ZERO ? // XXX do we need GFP_DMA for slots ? // http://www.mjmwired.net/kernel/Documentation/DMA-API.txt #define contigmalloc(sz, ty, flags, a, b, pgsz, c) \ (char *) __get_free_pages(GFP_ATOMIC | __GFP_ZERO, \ ilog2(roundup_pow_of_two((sz)/PAGE_SIZE))) #define contigfree(va, sz, ty) free_pages((unsigned long)va, \ ilog2(roundup_pow_of_two(sz)/PAGE_SIZE)) #define vtophys virt_to_phys /*--- selrecord and friends ---*/ /* wake_up() or wake_up_interruptible() ? */ #define selwakeuppri(sw, pri) wake_up(sw) #define selrecord(x, y) poll_wait((struct file *)x, y, pwait) #define knlist_destroy(x) // XXX todo /* we use tsleep/wakeup to sleep a bit. */ #define tsleep(a, b, c, t) msleep(10) // XXX #define wakeup(sw) // XXX double check #define microtime do_gettimeofday /* * The following trick is to map a struct cdev into a struct miscdevice */ #define cdev miscdevice /* * XXX to complete - the dmamap interface */ #define BUS_DMA_NOWAIT 0 #define bus_dmamap_load(_1, _2, _3, _4, _5, _6, _7) #define bus_dmamap_unload(_1, _2) typedef int (d_mmap_t)(struct file *f, struct vm_area_struct *vma); typedef unsigned int (d_poll_t)(struct file * file, struct poll_table_struct *pwait); /* * make_dev will set an error and return the first argument. * This relies on the availability of the 'error' local variable. */ #define make_dev(_cdev, _zero, _uid, _gid, _perm, _name) \ ({error = misc_register(_cdev); \ D("run mknod /dev/%s c %d %d # error %d", \ (_cdev)->name, MISC_MAJOR, (_cdev)->minor, error); \ _cdev; } ) #define destroy_dev(_cdev) misc_deregister(_cdev) /*--- sysctl API ----*/ /* * linux: sysctl are mapped into /sys/module/ipfw_mod parameters * windows: they are emulated via get/setsockopt */ #define CTLFLAG_RD 1 #define CTLFLAG_RW 2 struct sysctl_oid; struct sysctl_req; #define SYSCTL_DECL(_1) #define SYSCTL_OID(_1, _2, _3, _4, _5, _6, _7, _8) #define SYSCTL_NODE(_1, _2, _3, _4, _5, _6) #define _SYSCTL_BASE(_name, _var, _ty, _perm) \ module_param_named(_name, *(_var), _ty, \ ( (_perm) == CTLFLAG_RD) ? 0444: 0644 ) #define SYSCTL_PROC(_base, _oid, _name, _mode, _var, _val, _desc, _a, _b) #define SYSCTL_INT(_base, _oid, _name, _mode, _var, _val, _desc) \ _SYSCTL_BASE(_name, _var, int, _mode) #define SYSCTL_LONG(_base, _oid, _name, _mode, _var, _val, _desc) \ _SYSCTL_BASE(_name, _var, long, _mode) #define SYSCTL_ULONG(_base, _oid, _name, _mode, _var, _val, _desc) \ _SYSCTL_BASE(_name, _var, ulong, _mode) #define SYSCTL_UINT(_base, _oid, _name, _mode, _var, _val, _desc) \ _SYSCTL_BASE(_name, _var, uint, _mode) #define TUNABLE_INT(_name, _ptr) #define SYSCTL_VNET_PROC SYSCTL_PROC #define SYSCTL_VNET_INT SYSCTL_INT #define SYSCTL_HANDLER_ARGS \ struct sysctl_oid *oidp, void *arg1, int arg2, struct sysctl_req *req int sysctl_handle_int(SYSCTL_HANDLER_ARGS); int sysctl_handle_long(SYSCTL_HANDLER_ARGS); #endif /* _BSD_GLUE_H */ netmap-release/LINUX/Makefile000644 000423 000000 00000007047 12060255770 016571 0ustar00luigiwheel000000 000000 # To build external modules, you must have a prebuilt kernel available # that contains the configuration and header files used in the build. # go in the kernel directory and do a # make oldconfig; make scripts; make prepare # # The list of targets is derived from obj-m # and then the corresponding foo-objs CONFIG_NETMAP:=m CONFIG_R8169:=m CONFIG_FORCEDETH:=m CONFIG_E1000:=m CONFIG_E1000E:=m CONFIG_IXGBE:=m CONFIG_IGB:=m CONFIG_BNX2X:=m netmap_lin-objs := netmap.o obj-$(CONFIG_NETMAP) = netmap_lin.o obj-m += $(DRIVERS) # obj-$(CONFIG_R8169) += r8169.o # obj-$(CONFIG_FORCEDETH) += forcedeth.o # obj-$(CONFIG_E1000) += e1000/ # obj-$(CONFIG_E1000E) += e1000e/ # obj-$(CONFIG_IXGBE) += ixgbe/ # obj-$(CONFIG_IGB) += igb/ # names of the driver sources. In old linuxes are under # KSRC/drivers/net, but depending on where you build they # can be in $(KSRC)/source/drivers/net/ethernet/$(manufacturer) DRIVER_SRCS = r8169.c forcedeth.c e1000/ e1000e/ ixgbe/ igb/ DRIVER_SUBDIRS= nvidia realtek intel DRIVER_SRCS += bnx2x/ mellanox/ mlx4/ DRIVER_SUBDIRS += broadcom . # The following commands are needed to build the modules as out-of-tree, in # fact the kernel sources path must be specified. # Additional compile flags (e.g. header location) M:=$(PWD) EXTRA_CFLAGS := -I$(M) -I$(M)/../sys -I$(M)/../sys/dev -DCONFIG_NETMAP EXTRA_CFLAGS += -Wno-unused-but-set-variable # We use KSRC for the kernel configuration and sources. # If the sources are elsewhere, then use SRC to point to them. KSRC ?= /lib/modules/$(shell uname -r)/build SRC ?= $(KSRC) # extract version number and filter with the available patches. LIN_VER = $(shell grep LINUX_VERSION_CODE $(KSRC)/include/linux/version.h | \ awk '{printf "%03x%02d", $$3/256, $$3%256} ') PATCHES := $(shell \ cd $(PWD)/patches; ls diff--* | awk -v v=$(LIN_VER) -F -- '{ \ if ((!$$3 || $$3 <= v) && (!$$4 || v < $$4)) print $0; }') DRIVERS := $(shell \ cd $(PWD)/patches; ls diff--* | awk -v v=$(LIN_VER) -F -- '{ \ if ((!$$3 || $$3 <= v) && (!$$4 || v < $$4)) { ; \ if (match($$2, ".c")) print $$2 ; else print $$2 "/" } }' ) all: get-drivers build build: make -C $(KSRC) M=$(PWD) CONFIG_NETMAP=m \ CONFIG_E1000=m CONFIG_E1000E=m \ CONFIG_BNX2X=m CONFIG_MLX4=m \ CONFIG_IXGBE=m CONFIG_IGB=m EXTRA_CFLAGS='$(EXTRA_CFLAGS)' \ DRIVERS="$(DRIVERS:%.c=%.o)" modules @ls -l `find . -name \*.ko` test: @echo "version $(LIN_VER)" @echo "patches $(PATCHES)" @echo "drivers $(DRIVERS)" clean: -@ make -C $(KSRC) M=$(PWD) clean -@ (rm -rf $(DRIVER_SRCS) *.orig *.rej *.ko *.o get-drivers ) # the source is not here so we need to specify a dependency $(obj)/netmap.o: $(M)/../sys/dev/netmap/netmap.c $(call cmd,cc_o_c) $(call cmd,modversions) # $(call quiet_cmd,cc_o_c) #-- copy and patch initial files # The location changes depending on the OS version, so ... get-drivers: @echo "LIN_VER $(LIN_VER) subdirs $(DRIVER_SUBDIRS) files $(DRIVERS)" -@( \ cd $(SRC); [ -d source ] && cd source; \ cd drivers/net; s=. ; \ [ -d ethernet ] && cd ethernet && s="$(DRIVER_SUBDIRS)" ; \ for i in $$s; do (cd $$i ; \ echo "Copying from `pwd` "; \ cp -Rp $(DRIVERS) $(PWD) 2>/dev/null ); done ) -@(for i in $(PATCHES) ; do echo "** use patches/$$i"; \ patch --posix --quiet --force -p1 < patches/$$i; done ) @touch get-drivers @echo "Building the following drivers: $(obj-m)" # copy and patch files from the source tree #$(obj)/r8169.c: $(srctree)/drivers/net/r8169.c # # net-r8169.diff # $(call cmd,shipped) # (cd $(obj); patch < net-r8169.diff ) # apps: (cd ../examples; make) netmap-release/LINUX/README000644 000423 000000 00000011455 12014455342 016003 0ustar00luigiwheel000000 000000 # $Id: README 10863 2012-04-11 17:10:39Z luigi $ NETMAP FOR LINUX ---------------- This directory contains a version of the "netmap" and "VALE" code for Linux. Netmap is a BSD-licensed framework that supports line-rate direct packet I/O even on 10GBit/s interfaces (14.88Mpps) with limited system load, and includes a libpcap emulation library to port applications. See http://info.iet.unipi.it/~luigi/netmap/ for more details. There you can also find the latest versions of the code and documentation as well as pre-built TinyCore images based on linux 3.0.3 and containing the netmap modules and some test applications. This version supports r8169, ixgbe, igb, e1000, e1000e and forcedeth. Netmap relies on a kernel module (netmap_lin.ko) and slightly modified device drivers. Userspace programs can use the native API (documented in netmap.4) or a libpcap emulation library. The FreeBSD and Linux versions share the same codebase, which is located in ../sys . For Linux we use some additional glue code, (bsd_glue.h). Device drivers are taken directly from the Linux distributions, and patched using the files in the patches/ directory. Common driver modifications are in the .h files in this directory. HOW TO BUILD THE CODE --------------------- 1. make sure you have kernel sources/headers matching your installed system 2. do the following make clean; make KSRC=/usr/src/linux-kernel-source-or-headers this produces ./netmap_lin.ko and other kernel modules. 3. to build sample applications, run (cd ../examples; make ) (you will need the pthreads and libpcap-dev packages to build them) If you want support for additional drivers please have a look at ixgbe_netmap_linux.h and the patches in patches/ The patch file are named as diff--DRIVER--LOW--HIGH--otherstuff where DRIVER is the driver name to patch, LOW and HIGH are the versions to which the patch applies (LOW included, HIGH excluded, so diff--r8169.c--20638--30300--ok applies from 2.6.38 to 3.3.0 (excluded) HOW TO USE THE CODE ------------------- REMEMBER THIS IS EXPERIMENTAL CODE WHICH MAY CRASH YOUR SYSTEM. USE IT AT YOUR OWN RISk. Whether you built your own modules, or are using the prebuilt TinyCore image, the following steps can be used for initial testing: 1. unload any modules for the network cards you want to use, e.g. sudo rmmod ixgbe sudo rmmod e1000 ... 2. load netmap and device driver module sudo insmod ./netmap_lin.ko sudo insmod ./ixgbe/ixgbe.ko sudo insmod ./e1000/e1000.ko ... 3. turn the interface(s) up sudo ifconfig eth0 up # and same for others 4. Run test applications -- as an example, pkt-gen is a raw packet sender/receiver which can do line rate on a 10G interface # send about 500 million packets of 60 bytes each. # wait 5s before starting, so the link can go up sudo pkt-gen -i eth0 -f tx -n 500111222 -l 60 -w 5 # you should see about 14.88 Mpps sudo pkt-gen -i eth0 -f rx # act as a receiver COMMON PROBLEMS ---------------- * switching in/out of netmap mode causes the link to go down and up. If your card is connected to a switch with spanning tree enabled, the switch will likely MUTE THE LINK FOR 10 SECONDS while it is detecting the new topology. Either disable the spanning tree on the switch or use long pauses before sending data; * Not all cards can do line rate no matter how fast is your software or CPU. Several have hardware limitations that prevent reaching the peak speed, especially for small packet sizes. Examples: - ixgbe cannot receive at line rate with packet sizes that are not multiple of 64 (after CRC stripping). This is especially evident with minimum-sized frames (-l 60 ) - some of the low-end 'e1000' cards can send 1.2 - 1.3Mpps instead of the theoretical maximum (1.488Mpps) - the 'realtek' cards seem unable to send more than 450-500Kpps even though they can receive at least 1.1Mpps * if the link is not up when the packet generator starts, you will see frequent messages about a link reset. While we work on a fix, use the '-w' argument on the generator to specify a longer timeout * the ixgbe driver (and perhaps others) is severely slowed down if the remote party is senting flow control frames to slow down traffic. If that happens try to use the ethtool command to disable flow control. REVISION HISTORY ----------------- 20120813 - updated distribution using common code for FreeBSD and Linux, and inclusion of drivers from the linux source tree 20120322 - fixed the 'igb' driver, now it can send and receive correctly (the problem was in netmap_rx_irq() so it might have affected other multiqueue cards). Also tested the 'r8169' in transmit mode. Added comments on switches and spanning tree. 20120217 - initial version. Only ixgbe, e1000 and e1000e are working. Other drivers (igb, r8169, forcedeth) are supplied only as a proof of concept. netmap-release/LINUX/forcedeth_netmap.h000644 000423 000000 00000026653 12064741066 020617 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2012 Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $Id: forcedeth_netmap.h 10670 2012-02-27 21:15:38Z luigi $ * * netmap support for 'forcedeth' (nfe) driver * For details on netmap support see ixgbe_netmap.h The driver supports ORIGinal and EXtended descriptors through unions. We remove the .orig and .ex suffix for brevity. Pointers in the ring (N slots) are first_rx = 0, last_rx = N-1, get_rx = put_rx = 0 at init Following init there is a call to nv_alloc_rx_optimized() which does less_rx = get_rx - 1 for (put_rx = 0; put_rx != less_rx; put_rx++) put_rx.flags = LEN | NV_RX2_AVAIL; so it leaves one free slot and put_rx pointing at the end. Basically, get_rx is where new packets arrive, put_rx is where new buffers are added. The rx_intr aka nv_rx_process_optimized() scans while (get_rx != put_rx && !(get_rx.flags & NV_RX2_AVAIL)) { ... get_rx++ } followed by a nv_alloc_rx_optimized(). This makes sure that there is always a free slot. */ #include #include #include #define SOFTC_T fe_priv /* * support for netmap register/unregisted. We are already under core lock. * only called on the first register or the last unregister. * The "forcedeth" driver is poorly written, the reinit routine * is replicated multiple times and one way to achieve it is to * nv_change_mtu twice above ETH_DATA_LEN. */ static int forcedeth_netmap_reg(struct ifnet *dev, int onoff) { struct netmap_adapter *na = NA(dev); struct SOFTC_T *np = netdev_priv(dev); int error = 0; u8 __iomem *base = get_hwbase(dev); if (na == NULL) return EINVAL; // first half of nv_change_mtu() - down nv_disable_irq(dev); nv_napi_disable(dev); netif_tx_lock_bh(dev); netif_addr_lock(dev); spin_lock(&np->lock); /* stop engines */ nv_stop_rxtx(dev); nv_txrx_reset(dev); /* drain rx queue */ nv_drain_rxtx(dev); if (onoff) { dev->if_capenable |= IFCAP_NETMAP; na->if_transmit = (void *)dev->netdev_ops; dev->netdev_ops = &na->nm_ndo; } else { /* restore if_transmit */ dev->netdev_ops = (void *)na->if_transmit; dev->if_capenable &= ~IFCAP_NETMAP; } // second half of nv_change_mtu() -- up if (nv_init_ring(dev)) { if (!np->in_shutdown) mod_timer(&np->oom_kick, jiffies + OOM_REFILL); } /* reinit nic view of the rx queue */ writel(np->rx_buf_sz, base + NvRegOffloadConfig); setup_hw_rings(dev, NV_SETUP_RX_RING | NV_SETUP_TX_RING); writel(((np->rx_ring_size-1) << NVREG_RINGSZ_RXSHIFT) + ((np->tx_ring_size-1) << NVREG_RINGSZ_TXSHIFT), base + NvRegRingSizes); pci_push(base); writel(NVREG_TXRXCTL_KICK|np->txrxctl_bits, get_hwbase(dev) + NvRegTxRxControl); pci_push(base); /* restart rx engine */ nv_start_rxtx(dev); spin_unlock(&np->lock); netif_addr_unlock(dev); netif_tx_unlock_bh(dev); nv_napi_enable(dev); nv_enable_irq(dev); return (error); } /* * Reconcile kernel and user view of the transmit ring. */ static int forcedeth_netmap_txsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct SOFTC_T *np = netdev_priv(ifp); struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->tx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, k, l, n, lim = kring->nkr_num_slots - 1; struct ring_desc_ex *txr = np->tx_ring.ex; uint32_t lastpkt = (np->desc_ver == DESC_VER_1 ? NV_TX_LASTPACKET : NV_TX2_LASTPACKET); k = ring->cur; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) mtx_lock(&na->core_lock); /* Sync the TX descriptor list */ rmb(); /* XXX (move after tx) record completed transmissions */ // l is the current pointer, k is the last pointer l = np->get_tx.ex - txr; k = np->put_tx.ex - txr; for (n = 0; l != k; n++) { uint32_t cmdstat = le32toh(txr[l].flaglen); if (cmdstat & NV_TX2_VALID) break; if (++l == np->tx_ring_size) l = 0; } if (n > 0) { np->get_tx.ex = txr + l; kring->nr_hwavail += n; } /* now deal with new transmissions */ j = kring->nr_hwcur; if (j != k) { /* we have new packets to send */ l = np->put_tx.ex - txr; // NIC pointer for (n = 0; j != k; n++) { struct netmap_slot *slot = &ring->slot[j]; struct ring_desc_ex *put_tx = txr + l; int len = slot->len; int cmd = (len - 1) | NV_TX2_VALID | lastpkt; uint64_t paddr; void *addr = PNMB(slot, &paddr); if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) { if (do_lock) mtx_unlock(&na->core_lock); return netmap_ring_reinit(kring); } if (slot->flags & NS_BUF_CHANGED) { /* buffer has changed, unload and reload map */ // netmap_reload_map(pdev, DMA_TO_DEVICE, old_paddr, addr); slot->flags &= ~NS_BUF_CHANGED; } slot->flags &= ~NS_REPORT; put_tx->bufhigh = htole32(dma_high(paddr)); put_tx->buflow = htole32(dma_low(paddr)); put_tx->flaglen = htole32(cmd); put_tx->txvlan = 0; j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } np->put_tx.ex = txr + l; kring->nr_hwcur = k; /* decrease avail by number of sent packets */ kring->nr_hwavail -= n; wmb(); /* start ? */ writel(NVREG_TXRXCTL_KICK|np->txrxctl_bits, get_hwbase(ifp) + NvRegTxRxControl); } /* update avail to what the hardware knows */ ring->avail = kring->nr_hwavail; if (do_lock) mtx_unlock(&na->core_lock); return 0; } /* * Reconcile kernel and user view of the receive ring. */ static int forcedeth_netmap_rxsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct SOFTC_T *np = netdev_priv(ifp); struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->rx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, k, l, n, lim = kring->nkr_num_slots - 1; struct ring_desc_ex *rxr = np->rx_ring.ex; u_int resvd, refill; // refill position k = ring->cur; resvd = ring->cur; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) mtx_lock(&na->core_lock); rmb(); l = np->get_rx.ex - rxr; /* next pkt to check */ /* put_rx is the refill position, one before nr_hwcur. * This slot is not available */ refill = np->put_rx.ex - rxr; /* refill position */ j = netmap_idx_n2k(kring, l); for (n = kring->nr_hwavail; l != refill ; n++) { uint32_t statlen = le32toh(rxr[l].flaglen); if (statlen & NV_RX2_AVAIL) /* still owned by the NIC */ break; kring->ring->slot[j].len = statlen & LEN_MASK_V2; // XXX crc? kring->ring->slot[j].flags = NS_FORWARD; j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } if (n != kring->nr_hwavail) { /* new received buffers */ np->get_rx.ex = rxr + l; ifp->stats.rx_packets += n - kring->nr_hwavail; kring->nr_hwavail = n; } /* skip past packets that userspace has already processed, */ j = kring->nr_hwcur; // refill is one before j if (resvd > 0) { if (resvd + ring->avail >= lim) { D("XXX invalid reserve/avail %d %d", resvd, ring->avail); ring->reserved = resvd = 0; // XXX panic... } k = (k >= resvd) ? k - resvd : k + lim + 1 - resvd; } if (j != k) { /* userspace has returned some packets. */ l = netmap_idx_k2n(kring, j); /* NIC ring index */ for (n = 0; j != k; n++) { struct netmap_slot *slot = ring->slot + j; struct ring_desc_ex *desc = rxr + l; uint64_t paddr; void *addr = PNMB(slot, &paddr); if (addr == netmap_buffer_base) { /* bad buf */ if (do_lock) mtx_unlock(&na->core_lock); return netmap_ring_reinit(kring); } slot->flags &= ~NS_REPORT; if (slot->flags & NS_BUF_CHANGED) { // netmap_reload_map(pdev, DMA_TO_DEVICE, old_paddr, addr); slot->flags &= ~NS_BUF_CHANGED; } desc->flaglen = htole32(NETMAP_BUF_SIZE); desc->bufhigh = htole32(dma_high(paddr)); desc->buflow = htole32(dma_low(paddr)); // enable the previous buffer rxr[refill].flaglen |= htole32(NV_RX2_AVAIL); refill = (refill == lim) ? 0 : refill + 1; j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwavail -= n; kring->nr_hwcur = k; np->put_rx.ex = rxr + refill; /* Flush the RX DMA ring */ wmb(); } /* tell userspace that there are new packets */ ring->avail = kring->nr_hwavail - resvd; if (do_lock) mtx_unlock(&na->core_lock); return 0; } /* * Additional routines to init the tx and rx rings. * In other drivers we do that inline in the main code. */ static int forcedeth_netmap_tx_init(struct SOFTC_T *np) { struct ring_desc_ex *desc; int i, n; struct netmap_adapter *na = NA(np->dev); struct netmap_slot *slot = netmap_reset(na, NR_TX, 0, 0); /* slot is NULL if we are not in netmap mode */ if (!slot) return 0; /* in netmap mode, overwrite addresses and maps */ //txd = np->rl_ldata.rl_tx_desc; desc = np->tx_ring.ex; n = np->tx_ring_size; /* l points in the netmap ring, i points in the NIC ring */ for (i = 0; i < n; i++) { int l = netmap_idx_n2k(&na->tx_rings[0], i); uint64_t paddr; PNMB(slot + l, &paddr); desc[i].flaglen = 0; desc[i].bufhigh = htole32(dma_high(paddr)); desc[i].buflow = htole32(dma_low(paddr)); } return 1; } static int forcedeth_netmap_rx_init(struct SOFTC_T *np) { struct netmap_adapter *na = NA(np->dev); struct netmap_slot *slot = netmap_reset(na, NR_RX, 0, 0); struct ring_desc_ex *desc = np->rx_ring.ex; uint32_t cmdstat; int i, lim; if (!slot) return 0; /* * userspace knows that hwavail packets were ready before the * reset, so we need to tell the NIC that last hwavail * descriptors of the ring are still owned by the driver. */ lim = np->rx_ring_size - 1 - na->rx_rings[0].nr_hwavail; for (i = 0; i < np->rx_ring_size; i++) { uint64_t paddr; int l = netmap_idx_n2k(&na->rx_rings[0], i); PNMB(slot + l, &paddr); netmap_reload_map(np->rl_ldata.rl_rx_mtag, np->rl_ldata.rl_rx_desc[i].rx_dmamap, addr); desc[i].bufhigh = htole32(dma_high(paddr)); desc[i].buflow = htole32(dma_low(paddr)); cmdstat = NETMAP_BUF_SIZE; if (i < lim) cmdstat |= NV_RX2_AVAIL; desc[i].flaglen = htole32(cmdstat); } // XXX ring end anywhere ? np->get_rx.ex = desc; np->put_rx.ex = desc + lim; return 1; } static void forcedeth_netmap_attach(struct SOFTC_T *np) { struct netmap_adapter na; bzero(&na, sizeof(na)); na.ifp = np->dev; na.separate_locks = 0; na.num_tx_desc = np->tx_ring_size; na.num_rx_desc = np->tx_ring_size; na.nm_txsync = forcedeth_netmap_txsync; na.nm_rxsync = forcedeth_netmap_rxsync; na.nm_register = forcedeth_netmap_reg; netmap_attach(&na, 1); } netmap-release/LINUX/if_e1000_netmap.h000644 000423 000000 00000024227 12064741100 020037 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2012 Gaetano Catalli, Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $Id: if_e1000_netmap.h 10878 2012-04-12 22:28:48Z luigi $ * * netmap support for e1000 (lem) * For details on netmap support please see ixgbe_netmap.h */ #include #include #include #define SOFTC_T e1000_adapter /* * Register/unregister, similar to e1000_reinit_safe() */ static int e1000_netmap_reg(struct ifnet *ifp, int onoff) { struct SOFTC_T *adapter = netdev_priv(ifp); struct netmap_adapter *na = NA(ifp); int error = 0; if (na == NULL) return EINVAL; if (!(ifp->flags & IFF_UP)) { /* e1000_open has not been called yet, so resources * are not allocated */ D("Interface is down!"); return EINVAL; } while (test_and_set_bit(__E1000_RESETTING, &adapter->flags)) msleep(1); //rtnl_lock(); // XXX do we need it ? e1000_down(adapter); if (onoff) { /* enable netmap mode */ ifp->if_capenable |= IFCAP_NETMAP; na->if_transmit = (void *)ifp->netdev_ops; ifp->netdev_ops = &na->nm_ndo; } else { ifp->if_capenable &= ~IFCAP_NETMAP; ifp->netdev_ops = (void *)na->if_transmit; } e1000_up(adapter); //rtnl_unlock(); // XXX do we need it ? clear_bit(__E1000_RESETTING, &adapter->flags); return (error); } /* * Reconcile kernel and user view of the transmit ring. */ static int e1000_netmap_txsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct SOFTC_T *adapter = netdev_priv(ifp); struct e1000_tx_ring* txr = &adapter->tx_ring[ring_nr]; struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->tx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, k, l, n = 0, lim = kring->nkr_num_slots - 1; /* generate an interrupt approximately every half ring */ int report_frequency = kring->nkr_num_slots >> 1; /* take a copy of ring->cur now, and never read it again */ k = ring->cur; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) mtx_lock(&kring->q_lock); rmb(); /* * Process new packets to send. j is the current index in the * netmap ring, l is the corresponding index in the NIC ring. */ j = kring->nr_hwcur; if (j != k) { /* we have new packets to send */ l = netmap_idx_k2n(kring, j); for (n = 0; j != k; n++) { /* slot is the current slot in the netmap ring */ struct netmap_slot *slot = &ring->slot[j]; /* curr is the current slot in the nic ring */ struct e1000_tx_desc *curr = E1000_TX_DESC(*txr, l); int flags = ((slot->flags & NS_REPORT) || j == 0 || j == report_frequency) ? E1000_TXD_CMD_RS : 0; uint64_t paddr; void *addr = PNMB(slot, &paddr); u_int len = slot->len; if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) { if (do_lock) mtx_unlock(&kring->q_lock); return netmap_ring_reinit(kring); } slot->flags &= ~NS_REPORT; if (slot->flags & NS_BUF_CHANGED) { // netmap_reload_map(pdev, DMA_TO_DEVICE, old_addr, paddr); curr->buffer_addr = htole64(paddr); slot->flags &= ~NS_BUF_CHANGED; } curr->upper.data = 0; curr->lower.data = htole32(adapter->txd_cmd | len | (E1000_TXD_CMD_EOP | E1000_TXD_CMD_IFCS | flags) ); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwcur = k; /* the saved ring->cur */ kring->nr_hwavail -= n; wmb(); /* synchronize writes to the NIC ring */ txr->next_to_use = l; writel(l, adapter->hw.hw_addr + txr->tdt); mmiowb(); // XXX where do we need this ? } if (n == 0 || kring->nr_hwavail < 1) { int delta; /* record completed transmissions using TDH */ l = readl(adapter->hw.hw_addr + txr->tdh); if (l >= kring->nkr_num_slots) { /* XXX can happen */ D("TDH wrap %d", l); l -= kring->nkr_num_slots; } delta = l - txr->next_to_clean; if (delta) { /* some tx completed, increment hwavail. */ if (delta < 0) delta += kring->nkr_num_slots; txr->next_to_clean = l; kring->nr_hwavail += delta; } } /* update avail to what the kernel knows */ ring->avail = kring->nr_hwavail; if (do_lock) mtx_unlock(&kring->q_lock); return 0; } /* * Reconcile kernel and user view of the receive ring. */ static int e1000_netmap_rxsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct SOFTC_T *adapter = netdev_priv(ifp); struct netmap_adapter *na = NA(ifp); struct e1000_rx_ring *rxr = &adapter->rx_ring[ring_nr]; struct netmap_kring *kring = &na->rx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, l, n, lim = kring->nkr_num_slots - 1; int force_update = do_lock || kring->nr_kflags & NKR_PENDINTR; u_int k = ring->cur, resvd = ring->reserved; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) mtx_lock(&kring->q_lock); rmb(); /* * Import newly received packets into the netmap ring. * j is an index in the netmap ring, l in the NIC ring. */ l = rxr->next_to_clean; j = netmap_idx_n2k(kring, l); if (netmap_no_pendintr || force_update) { for (n = 0; ; n++) { struct e1000_rx_desc *curr = E1000_RX_DESC(*rxr, l); uint32_t staterr = le32toh(curr->status); if ((staterr & E1000_RXD_STAT_DD) == 0) break; ring->slot[j].len = le16toh(curr->length) - 4; ring->slot[j].flags = NS_FORWARD; j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } if (n) { /* update the state variables */ rxr->next_to_clean = l; kring->nr_hwavail += n; } kring->nr_kflags &= ~NKR_PENDINTR; } /* skip past packets that userspace has released */ j = kring->nr_hwcur; /* netmap ring index */ if (resvd > 0) { if (resvd + ring->avail >= lim + 1) { D("XXX invalid reserve/avail %d %d", resvd, ring->avail); ring->reserved = resvd = 0; // XXX panic... } k = (k >= resvd) ? k - resvd : k + lim + 1 - resvd; } if (j != k) { /* userspace has released some packets. */ l = netmap_idx_k2n(kring, j); /* NIC ring index */ for (n = 0; j != k; n++) { struct netmap_slot *slot = &ring->slot[j]; struct e1000_rx_desc *curr = E1000_RX_DESC(*rxr, j); uint64_t paddr; void *addr = PNMB(slot, &paddr); if (addr == netmap_buffer_base) { /* bad buf */ if (do_lock) mtx_unlock(&kring->q_lock); return netmap_ring_reinit(kring); } if (slot->flags & NS_BUF_CHANGED) { // netmap_reload_map(...) curr->buffer_addr = htole64(paddr); slot->flags &= ~NS_BUF_CHANGED; } curr->status = 0; j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwavail -= n; kring->nr_hwcur = k; wmb(); rxr->next_to_use = l; // XXX not really used /* * IMPORTANT: we must leave one free slot in the ring, * so move l back by one unit */ l = (l == 0) ? lim : l - 1; writel(l, adapter->hw.hw_addr + rxr->rdt); } /* tell userspace that there are new packets */ ring->avail = kring->nr_hwavail - resvd; if (do_lock) mtx_unlock(&kring->q_lock); return 0; } /* diagnostic routine to catch errors */ static void e1000_no_rx_alloc(struct SOFTC_T *adapter, struct e1000_rx_ring *rxr, int cleaned_count) { D("e1000->alloc_rx_buf should not be called"); } /* * Make the tx and rx rings point to the netmap buffers. */ static int e1000_netmap_init_buffers(struct SOFTC_T *adapter) { struct e1000_hw *hw = &adapter->hw; struct ifnet *ifp = adapter->netdev; struct netmap_adapter* na = NA(ifp); struct netmap_slot* slot; struct e1000_tx_ring* txr = &adapter->tx_ring[0]; unsigned int i, r, si; uint64_t paddr; if (!na || !(na->ifp->if_capenable & IFCAP_NETMAP)) return 0; adapter->alloc_rx_buf = e1000_no_rx_alloc; for (r = 0; r < na->num_rx_rings; r++) { struct e1000_rx_ring *rxr; slot = netmap_reset(na, NR_RX, r, 0); if (!slot) { D("strange, null netmap ring %d", r); return 0; } rxr = &adapter->rx_ring[r]; for (i = 0; i < rxr->count; i++) { // XXX the skb check and cleanup can go away struct e1000_buffer *bi = &rxr->buffer_info[i]; si = netmap_idx_n2k(&na->rx_rings[r], i); PNMB(slot + si, &paddr); if (bi->skb) D("rx buf %d was set", i); bi->skb = NULL; // netmap_load_map(...) E1000_RX_DESC(*rxr, i)->buffer_addr = htole64(paddr); } rxr->next_to_use = 0; /* preserve buffers already made available to clients */ i = rxr->count - 1 - na->rx_rings[0].nr_hwavail; if (i < 0) i += rxr->count; D("i now is %d", i); wmb(); /* Force memory writes to complete */ writel(i, hw->hw_addr + rxr->rdt); } /* now initialize the tx ring(s) */ slot = netmap_reset(na, NR_TX, 0, 0); for (i = 0; i < na->num_tx_desc; i++) { si = netmap_idx_n2k(&na->tx_rings[0], i); PNMB(slot + si, &paddr); // netmap_load_map(...) E1000_TX_DESC(*txr, i)->buffer_addr = htole64(paddr); } return 1; } static void e1000_netmap_attach(struct SOFTC_T *adapter) { struct netmap_adapter na; bzero(&na, sizeof(na)); na.ifp = adapter->netdev; na.separate_locks = 0; na.num_tx_desc = adapter->tx_ring[0].count; na.num_rx_desc = adapter->rx_ring[0].count; na.nm_register = e1000_netmap_reg; na.nm_txsync = e1000_netmap_txsync; na.nm_rxsync = e1000_netmap_rxsync; netmap_attach(&na, 1); } /* end of file */ netmap-release/LINUX/if_re_netmap_linux.h000644 000423 000000 00000022554 12064741140 021144 0ustar00luigiwheel000000 000000 /* * Copyright (C) 2011 Luigi Rizzo. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $Id: if_re_netmap_linux.h 10679 2012-02-28 13:42:18Z luigi $ * * netmap support for "r8169" (re) (UNTESTED) * For details on netmap support please see ixgbe_netmap.h * 1 tx ring, 1 rx ring, 1 lock, crcstrip ? reinit tx addr, */ #include #include #include static void rtl8169_wait_for_quiescence(struct ifnet *); #define SOFTC_T rtl8169_private /* * Register/unregister, mostly the reinit task */ static int re_netmap_reg(struct ifnet *ifp, int onoff) { struct netmap_adapter *na = NA(ifp); int error = 0; if (na == NULL) return EINVAL; rtnl_lock(); rtl8169_wait_for_quiescence(ifp); rtl8169_close(ifp); if (onoff) { /* enable netmap mode */ ifp->if_capenable |= IFCAP_NETMAP; na->if_transmit = (void *)ifp->netdev_ops; ifp->netdev_ops = &na->nm_ndo; if (rtl8169_open(ifp) < 0) { error = ENOMEM; goto fail; } } else { fail: ifp->if_capenable &= ~IFCAP_NETMAP; ifp->netdev_ops = (void *)na->if_transmit; error = rtl8169_open(ifp) ? EINVAL : 0; } rtnl_unlock(); return (error); } /* * Reconcile kernel and user view of the transmit ring. */ static int re_netmap_txsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct SOFTC_T *sc = netdev_priv(ifp); void __iomem *ioaddr = sc->mmio_addr; struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->tx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, k, l, n = 0, lim = kring->nkr_num_slots - 1; k = ring->cur; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) mtx_lock(&na->core_lock); rmb(); /* * Process new packets to send. j is the current index in the * netmap ring, l is the corresponding index in the NIC ring. */ j = kring->nr_hwcur; if (j != k) { /* we have new packets to send */ l = sc->cur_tx; // XXX use internal macro ? for (n = 0; j != k; n++) { /* slot is the current slot in the netmap ring */ struct netmap_slot *slot = &ring->slot[j]; /* curr is the current slot in the nic ring */ struct TxDesc *curr = &sc->TxDescArray[l]; uint32_t flags = slot->len | LastFrag | DescOwn | FirstFrag ; uint64_t paddr; void *addr = PNMB(slot, &paddr); int len = slot->len; if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) { sc->cur_tx = l; // XXX fix if (do_lock) mtx_unlock(&na->core_lock); return netmap_ring_reinit(kring); } if (l == lim) /* mark end of ring */ flags |= RingEnd; if (slot->flags & NS_BUF_CHANGED) { /* buffer has changed, unload and reload map */ // netmap_reload_map(pdev, DMA_TO_DEVICE, old_paddr, addr); curr->addr = htole64(paddr); slot->flags &= ~NS_BUF_CHANGED; } slot->flags &= ~NS_REPORT; curr->opts1 = htole32(flags); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwcur = k; /* the saved ring->cur */ kring->nr_hwavail -= n; sc->cur_tx = l; wmb(); /* synchronize writes to the NIC ring */ RTL_W8(TxPoll, NPQ); /* start ? */ } if (n == 0 || kring->nr_hwavail < 1) { /* record completed transmissions */ for (n = 0, l = sc->dirty_tx; l != sc->cur_tx; n++) { if (le32toh(sc->TxDescArray[l].opts1) & DescOwn) break; if (++l == NUM_TX_DESC) l = 0; } if (n > 0) { sc->dirty_tx = l; kring->nr_hwavail += n; } } /* update avail to what the kernel knows */ ring->avail = kring->nr_hwavail; if (do_lock) mtx_unlock(&na->core_lock); return 0; } /* * Reconcile kernel and user view of the receive ring. */ static int re_netmap_rxsync(struct ifnet *ifp, u_int ring_nr, int do_lock) { struct SOFTC_T *sc = netdev_priv(ifp); struct netmap_adapter *na = NA(ifp); struct netmap_kring *kring = &na->rx_rings[ring_nr]; struct netmap_ring *ring = kring->ring; u_int j, l, n, lim = kring->nkr_num_slots - 1; int force_update = do_lock || kring->nr_kflags & NKR_PENDINTR; u_int k = ring->cur, resvd = ring->reserved; if (k > lim) return netmap_ring_reinit(kring); if (do_lock) mtx_lock(&na->core_lock); rmb(); /* * The device uses all the buffers in the ring, so we need * another termination condition in addition to DescOwn * cleared (all buffers could have it cleared. The easiest one * is to limit the amount of data reported up to 'lim' */ l = sc->cur_rx; /* next pkt to check */ j = netmap_idx_n2k(kring, l); if (netmap_no_pendintr || force_update) { for (n = kring->nr_hwavail; n < lim ; n++) { struct RxDesc *cur_rx = &sc->RxDescArray[l]; uint32_t rxstat = le32toh(cur_rx->opts1); uint32_t total_len; if ((rxstat & DescOwn) != 0) break; total_len = rxstat & 0x00001FFF; /* XXX subtract crc */ total_len = (total_len < 4) ? 0 : total_len - 4; kring->ring->slot[j].len = total_len; kring->ring->slot[j].flags = NS_FORWARD; j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } if (n != kring->nr_hwavail) { sc->cur_rx = l; ifp->stats.rx_packets += n - kring->nr_hwavail; kring->nr_hwavail = n; } } /* skip past packets that userspace has released */ j = kring->nr_hwcur; /* netmap ring index */ if (resvd > 0) { if (resvd + ring->avail >= lim + 1) { D("XXX invalid reserve/avail %d %d", resvd, ring->avail); ring->reserved = resvd = 0; // XXX panic... } k = (k >= resvd) ? k - resvd : k + lim + 1 - resvd; } if (j != k) { /* userspace has released some packets. */ l = netmap_idx_k2n(kring, j); /* NIC ring index */ for (n = 0; j != k; n++) { struct netmap_slot *slot = ring->slot + j; struct RxDesc *curr = &sc->RxDescArray[l]; uint32_t flags = NETMAP_BUF_SIZE | DescOwn; uint64_t paddr; void *addr = PNMB(slot, &paddr); if (addr == netmap_buffer_base) { /* bad buf */ if (do_lock) mtx_unlock(&na->core_lock); return netmap_ring_reinit(kring); } if (l == lim) /* mark end of ring */ flags |= RingEnd; slot->flags &= ~NS_REPORT; if (slot->flags & NS_BUF_CHANGED) { // netmap_reload_map(pdev, DMA_TO_DEVICE, old_paddr, addr); curr->addr = htole64(paddr); slot->flags &= ~NS_BUF_CHANGED; } curr->opts1 = htole32(flags); j = (j == lim) ? 0 : j + 1; l = (l == lim) ? 0 : l + 1; } kring->nr_hwavail -= n; kring->nr_hwcur = k; wmb(); // XXX needed ? } /* tell userspace that there are new packets */ ring->avail = kring->nr_hwavail - resvd; if (do_lock) mtx_unlock(&na->core_lock); return 0; } /* * Additional routines to init the tx and rx rings. * In other drivers we do that inline in the main code. */ static int re_netmap_tx_init(struct SOFTC_T *sc) { struct netmap_adapter *na = NA(sc->dev); struct netmap_slot *slot = netmap_reset(na, NR_TX, 0, 0); struct TxDesc *desc = sc->TxDescArray; int i, l; uint64_t paddr; /* slot is NULL if we are not in netmap mode */ if (!slot) return 0; /* l points in the netmap ring, i points in the NIC ring */ for (i = 0; i < na->num_tx_desc; i++) { l = netmap_idx_n2k(&na->tx_rings[0], i); PNMB(slot + l, &paddr); desc[i].addr = htole64(paddr); } return 1; } static int re_netmap_rx_init(struct SOFTC_T *sc) { struct netmap_adapter *na = NA(sc->dev); struct netmap_slot *slot = netmap_reset(na, NR_RX, 0, 0); struct RxDesc *desc = sc->RxDescArray; uint32_t cmdstat; int i, lim, l; uint64_t paddr; if (!slot) return 0; /* * userspace knows that hwavail packets were ready before * the reset, so only indexes < lim are made available for rx. * XXX we use all slots, so no '-1' here */ lim = na->num_rx_desc /* - 1 */ - na->rx_rings[0].nr_hwavail; for (i = 0; i < na->num_rx_desc; i++) { l = netmap_idx_n2k(&na->rx_rings[0], i); PNMB(slot + l, &paddr); cmdstat = NETMAP_BUF_SIZE; if (i == na->num_rx_desc - 1) cmdstat |= RingEnd; if (i < lim) cmdstat |= DescOwn; desc[i].opts1 = htole32(cmdstat); desc[i].addr = htole64(paddr); } return 1; } static void re_netmap_attach(struct SOFTC_T *sc) { struct netmap_adapter na; bzero(&na, sizeof(na)); na.ifp = sc->dev; na.separate_locks = 0; na.num_tx_desc = NUM_TX_DESC; na.num_rx_desc = NUM_RX_DESC; na.nm_txsync = re_netmap_txsync; na.nm_rxsync = re_netmap_rxsync; na.nm_register = re_netmap_reg; netmap_attach(&na, 1); } /* end of file */ netmap-release/LINUX/patches/diff--forcedeth.c--20638--99999--ok000644 000423 000000 00000003627 12006477730 023664 0ustar00luigiwheel000000 000000 --- net/forcedeth.c 2011-08-05 06:59:21.000000000 +0200 +++ net/forcedeth.c 2012-02-17 11:16:41.404764449 +0100 @@ -1865,12 +1865,25 @@ static void nv_init_tx(struct net_device } } +#if defined(CONFIG_NETMAP) || defined(CONFIG_NETMAP_MODULE) +/* we need a few forward declarations */ +static void nv_drain_rxtx(struct net_device *dev); +static int nv_init_ring(struct net_device *dev); +#include +#endif + static int nv_init_ring(struct net_device *dev) { struct fe_priv *np = netdev_priv(dev); nv_init_tx(dev); nv_init_rx(dev); +#ifdef DEV_NETMAP + forcedeth_netmap_tx_init(np); + if (forcedeth_netmap_rx_init(np)) + return 0; /* success */ +#endif /* DEV_NETMAP */ + if (!nv_optimized(np)) return nv_alloc_rx(dev); @@ -3386,6 +3399,11 @@ static irqreturn_t nv_nic_irq_tx(int foo int i; unsigned long flags; +#ifdef DEV_NETMAP + if (netmap_tx_irq(dev, 0)) + return IRQ_HANDLED; +#endif /* DEV_NETMAP */ + for (i = 0;; i++) { events = readl(base + NvRegMSIXIrqStatus) & NVREG_IRQ_TX_ALL; writel(NVREG_IRQ_TX_ALL, base + NvRegMSIXIrqStatus); @@ -3497,6 +3515,11 @@ static irqreturn_t nv_nic_irq_rx(int foo int i; unsigned long flags; +#ifdef DEV_NETMAP + if (netmap_rx_irq(dev, 0, &i)) + return IRQ_HANDLED; +#endif /* DEV_NETMAP */ + for (i = 0;; i++) { events = readl(base + NvRegMSIXIrqStatus) & NVREG_IRQ_RX_ALL; writel(NVREG_IRQ_RX_ALL, base + NvRegMSIXIrqStatus); @@ -5615,6 +5638,10 @@ static int __devinit nv_probe(struct pci goto out_error; } +#ifdef DEV_NETMAP + forcedeth_netmap_attach(np); +#endif /* DEV_NETMAP */ + netif_carrier_off(dev); dev_info(&pci_dev->dev, "ifname %s, PHY OUI 0x%x @ %d, addr %pM\n", @@ -5698,6 +5725,10 @@ static void __devexit nv_remove(struct p unregister_netdev(dev); +#ifdef DEV_NETMAP + netmap_detach(dev); +#endif /* DEV_NETMAP */ + nv_restore_mac_addr(pci_dev); /* restore any phy related changes */ netmap-release/LINUX/patches/diff--ixgbe--20638--30100--ok000644 000423 000000 00000005610 12006477730 022517 0ustar00luigiwheel000000 000000 diff -urp net/ixgbe/ixgbe_main.c net/ixgbe/ixgbe_main.c --- net/ixgbe/ixgbe_main.c 2011-08-05 06:59:21.000000000 +0200 +++ net/ixgbe/ixgbe_main.c 2012-02-17 11:55:06.740825826 +0100 @@ -247,6 +247,22 @@ static const struct ixgbe_reg_info ixgbe {} }; +#if defined(CONFIG_NETMAP) || defined(CONFIG_NETMAP_MODULE) +/* + * The #ifdef DEV_NETMAP / #endif blocks in this file are meant to + * be a reference on how to implement netmap support in a driver. + * Additional comments are in ixgbe_netmap_linux.h . + * + * The code is originally developed on FreeBSD and in the interest + * of maintainability we try to limit differences between the two systems. + * + * contains functions for netmap support + * that extend the standard driver. + * It also defines DEV_NETMAP so further conditional sections use + * that instead of CONFIG_NETMAP + */ +#include +#endif /* * ixgbe_regdump - register printout routine @@ -864,6 +880,16 @@ static bool ixgbe_clean_tx_irq(struct ix unsigned int total_bytes = 0, total_packets = 0; u16 i, eop, count = 0; +#ifdef DEV_NETMAP + /* + * In netmap mode, all the work is done in the context + * of the client thread. Interrupt handlers only wake up + * clients, which may be sleeping on individual rings + * or on a global resource for all rings. + */ + if (netmap_tx_irq(adapter->netdev, tx_ring->queue_index)) + return 1; /* seems to be ignored */ +#endif /* DEV_NETMAP */ i = tx_ring->next_to_clean; eop = tx_ring->tx_buffer_info[i].next_to_watch; eop_desc = IXGBE_TX_DESC_ADV(tx_ring, eop); @@ -1348,6 +1374,13 @@ static void ixgbe_clean_rx_irq(struct ix u16 cleaned_count = 0; bool pkt_is_rsc = false; +#ifdef DEV_NETMAP + /* + * Same as the txeof routine: only wakeup clients on intr. + */ + if (netmap_rx_irq(adapter->netdev, rx_ring->queue_index, work_done)) + return; +#endif /* DEV_NETMAP */ i = rx_ring->next_to_clean; rx_desc = IXGBE_RX_DESC_ADV(rx_ring, i); staterr = le32_to_cpu(rx_desc->wb.upper.status_error); @@ -2808,6 +2841,9 @@ void ixgbe_configure_tx_ring(struct ixgb } while (--wait_loop && !(txdctl & IXGBE_TXDCTL_ENABLE)); if (!wait_loop) e_err(drv, "Could not enable Tx Queue %d\n", reg_idx); +#ifdef DEV_NETMAP + ixgbe_netmap_configure_tx_ring(adapter, reg_idx); +#endif /* DEV_NETMAP */ } static void ixgbe_setup_mtqc(struct ixgbe_adapter *adapter) @@ -3183,6 +3219,10 @@ void ixgbe_configure_rx_ring(struct ixgb IXGBE_WRITE_REG(hw, IXGBE_RXDCTL(reg_idx), rxdctl); ixgbe_rx_desc_queue_enable(adapter, ring); +#ifdef DEV_NETMAP + if (ixgbe_netmap_configure_rx_ring(adapter, reg_idx)) + return; +#endif /* DEV_NETMAP */ ixgbe_alloc_rx_buffers(ring, IXGBE_DESC_UNUSED(ring)); } @@ -5586,6 +5626,9 @@ static int ixgbe_open(struct net_device goto err_up; netif_tx_start_all_queues(netdev); +#ifdef DEV_NETMAP + ixgbe_netmap_attach(adapter); +#endif /* DEV_NETMAP */ return 0; netmap-release/LINUX/patches/diff--igb--20635--30200--ok000644 000423 000000 00000004351 12006477730 022161 0ustar00luigiwheel000000 000000 diff -urp net/igb/igb_main.c net/igb/igb_main.c --- net/igb/igb_main.c 2011-08-05 06:59:21.000000000 +0200 +++ net/igb/igb_main.c 2012-04-12 12:02:14.360023460 +0200 @@ -214,6 +214,10 @@ MODULE_DESCRIPTION("Intel(R) Gigabit Eth MODULE_LICENSE("GPL"); MODULE_VERSION(DRV_VERSION); +#if defined(CONFIG_NETMAP) || defined(CONFIG_NETMAP_MODULE) +#include +#endif + struct igb_reg_info { u32 ofs; char *name; @@ -2042,6 +2046,10 @@ static int __devinit igb_probe(struct pc /* carrier off reporting is important to ethtool even BEFORE open */ netif_carrier_off(netdev); +#ifdef DEV_NETMAP + igb_netmap_attach(adapter); +#endif /* DEV_NETMAP */ + #ifdef CONFIG_IGB_DCA if (dca_add_requester(&pdev->dev) == 0) { adapter->flags |= IGB_FLAG_DCA_ENABLED; @@ -2163,6 +2171,10 @@ static void __devexit igb_remove(struct dev_info(&pdev->dev, "IOV Disabled\n"); } #endif +#ifdef DEV_NETMAP + netmap_detach(netdev); +#endif /* DEV_NETMAP */ + iounmap(hw->hw_addr); if (hw->flash_address) @@ -2651,6 +2663,9 @@ void igb_configure_tx_ring(struct igb_ad txdctl |= E1000_TXDCTL_QUEUE_ENABLE; wr32(E1000_TXDCTL(reg_idx), txdctl); +#ifdef DEV_NETMAP + igb_netmap_configure_tx_ring(adapter, reg_idx); +#endif /* DEV_NETMAP */ } /** @@ -5583,6 +5606,11 @@ static bool igb_clean_tx_irq(struct igb_ unsigned int i, eop, count = 0; bool cleaned = false; +#ifdef DEV_NETMAP + if (netmap_tx_irq(netdev, tx_ring->queue_index)) + return 1; /* cleaned ok */ +#endif /* DEV_NETMAP */ + i = tx_ring->next_to_clean; eop = tx_ring->buffer_info[i].next_to_watch; eop_desc = E1000_TX_DESC_ADV(*tx_ring, eop); @@ -5793,6 +5821,11 @@ static bool igb_clean_rx_irq_adv(struct u16 length; u16 vlan_tag; +#ifdef DEV_NETMAP + if (netmap_rx_irq(netdev, rx_ring->queue_index, work_done)) + return 1; +#endif /* DEV_NETMAP */ + i = rx_ring->next_to_clean; buffer_info = &rx_ring->buffer_info[i]; rx_desc = E1000_RX_DESC_ADV(*rx_ring, i); @@ -5924,6 +5957,10 @@ void igb_alloc_rx_buffers_adv(struct igb unsigned int i; int bufsz; +#ifdef DEV_NETMAP + if (igb_netmap_configure_rx_ring(rx_ring)) + return; +#endif /* DEV_NETMAP */ i = rx_ring->next_to_use; buffer_info = &rx_ring->buffer_info[i]; netmap-release/LINUX/patches/diff--r8169.c--30300--30400--ok000644 000423 000000 00000003440 12006477730 022420 0ustar00luigiwheel000000 000000 --- /home/giuseppe/Compile/linux/drivers/net/ethernet/realtek/r8169.c 2012-07-31 22:13:23.758823540 +0200 +++ net/r8169.c 2012-07-31 22:23:25.738823980 +0200 @@ -784,6 +784,10 @@ static void rtl_tx_performance_tweak(str } } +#if defined(CONFIG_NETMAP) || defined(CONFIG_NETMAP_MODULE) +#include +#endif + static u32 ocp_read(struct rtl8169_private *tp, u8 mask, u16 reg) { void __iomem *ioaddr = tp->mmio_addr; @@ -4175,6 +4179,9 @@ rtl8169_init_one(struct pci_dev *pdev, c if (pci_dev_run_wake(pdev)) pm_runtime_put_noidle(&pdev->dev); +#ifdef DEV_NETMAP + re_netmap_attach(tp); +#endif /* DEV_NETMAP */ netif_carrier_off(dev); out: @@ -4210,6 +4217,10 @@ static void __devexit rtl8169_remove_one rtl_release_firmware(tp); +#ifdef DEV_NETMAP + netmap_detach(dev); +#endif /* DEV_NETMAP */ + if (pci_dev_run_wake(pdev)) pm_runtime_get_noresume(&pdev->dev); @@ -5260,6 +5271,11 @@ static inline void rtl8169_mark_as_last_ static int rtl8169_rx_fill(struct rtl8169_private *tp) { unsigned int i; +#ifdef DEV_NETMAP + re_netmap_tx_init(tp); + if (re_netmap_rx_init(tp)) + return 0; // success +#endif /* DEV_NETMAP */ for (i = 0; i < NUM_RX_DESC; i++) { void *data; @@ -5635,6 +5651,11 @@ static void rtl8169_tx_interrupt(struct { unsigned int dirty_tx, tx_left; +#ifdef DEV_NETMAP + if (netmap_tx_irq(dev, 0)) + return; +#endif /* DEV_NETMAP */ + dirty_tx = tp->dirty_tx; smp_rmb(); tx_left = tp->cur_tx - dirty_tx; @@ -5722,6 +5743,11 @@ static int rtl8169_rx_interrupt(struct n unsigned int cur_rx, rx_left; unsigned int count; +#ifdef DEV_NETMAP + if (netmap_rx_irq(dev, 0, &count)) + return count; +#endif /* DEV_NETMAP */ + cur_rx = tp->cur_rx; rx_left = NUM_RX_DESC + tp->dirty_rx - cur_rx; rx_left = min(rx_left, budget); netmap-release/LINUX/patches/diff--e1000e--20632--20638--ok000644 000423 000000 00000004240 12006477730 022322 0ustar00luigiwheel000000 000000 --- /home/luigi/ksrc/linux-2.6.32.1/drivers/net/e1000e//netdev.c 2009-12-14 18:47:25.000000000 +0100 +++ net/e1000e/netdev.c 2012-07-31 13:14:44.000000000 +0200 @@ -446,6 +446,10 @@ bool cleaned = 0; unsigned int total_rx_bytes = 0, total_rx_packets = 0; +#ifdef DEV_NETMAP$ + if (netmap_tx_irq(netdev, 0)) + return 1; /* cleaned ok */ +#endif /* DEV_NETMAP */ i = rx_ring->next_to_clean; rx_desc = E1000_RX_DESC(*rx_ring, i); buffer_info = &rx_ring->buffer_info[i]; @@ -624,6 +628,10 @@ unsigned int count = 0; unsigned int total_tx_bytes = 0, total_tx_packets = 0; +#ifdef DEV_NETMAP + if (netmap_tx_irq(netdev, 0)) + return 1; /* cleaned ok */ +#endif /* DEV_NETMAP */ i = tx_ring->next_to_clean; eop = tx_ring->buffer_info[i].next_to_watch; eop_desc = E1000_TX_DESC(*tx_ring, eop); @@ -718,6 +726,10 @@ bool cleaned = 0; unsigned int total_rx_bytes = 0, total_rx_packets = 0; +#ifdef DEV_NETMAP + if (netmap_rx_irq(netdev, 0, work_done)) + return 1; /* seems to be ignored */ +#endif /* DEV_NETMAP */ i = rx_ring->next_to_clean; rx_desc = E1000_RX_DESC_PS(*rx_ring, i); staterr = le32_to_cpu(rx_desc->wb.middle.status_error); @@ -2632,6 +2644,10 @@ e1000_configure_tx(adapter); e1000_setup_rctl(adapter); e1000_configure_rx(adapter); +#ifdef DEV_NETMAP + if (e1000e_netmap_init_buffers(adapter)) + return; +#endif /* DEV_NETMAP */ adapter->alloc_rx_buf(adapter, e1000_desc_unused(adapter->rx_ring)); } @@ -3288,6 +3304,10 @@ e1000_get_phy_info(&adapter->hw); } +#if defined(CONFIG_NETMAP) || defined(CONFIG_NETMAP_MODULE) +#include +#endif + /* * Need to wait a few seconds after link up to get diagnostic information from * the phy @@ -5227,6 +5247,9 @@ if (err) goto err_register; +#ifdef DEV_NETMAP + e1000_netmap_attach(adapter); +#endif /* DEV_NETMAP */ /* carrier off reporting is important to ethtool even BEFORE open */ netif_carrier_off(netdev); @@ -5300,6 +5323,10 @@ kfree(adapter->tx_ring); kfree(adapter->rx_ring); +#ifdef DEV_NETMAP + netmap_detach(netdev); +#endif /* DEV_NETMAP */ + iounmap(adapter->hw.hw_addr); if (adapter->hw.flash_address) iounmap(adapter->hw.flash_address); netmap-release/LINUX/patches/diff--igb--20632--20633--ok000644 000423 000000 00000004354 12006477730 022172 0ustar00luigiwheel000000 000000 --- /home/luigi/ksrc/linux-2.6.32.1/drivers/net/igb/igb_main.c 2009-12-14 18:47:25.000000000 +0100 +++ net/igb/igb_main.c 2012-07-31 13:30:30.000000000 +0200 @@ -235,6 +235,10 @@ MODULE_LICENSE("GPL"); MODULE_VERSION(DRV_VERSION); +#if defined(CONFIG_NETMAP) || defined(CONFIG_NETMAP_MODULE) +#include +#endif + /** * Scale the NIC clock cycle by a large factor so that * relatively small clock corrections can be added or @@ -1502,6 +1506,10 @@ /* carrier off reporting is important to ethtool even BEFORE open */ netif_carrier_off(netdev); +#ifdef DEV_NETMAP + igb_netmap_attach(adapter); +#endif /* DEV_NETMAP */ + #ifdef CONFIG_IGB_DCA if (dca_add_requester(&pdev->dev) == 0) { adapter->flags |= IGB_FLAG_DCA_ENABLED; @@ -1640,6 +1648,10 @@ wr32(E1000_DCA_CTRL, E1000_DCA_CTRL_DCA_MODE_DISABLE); } #endif +#ifdef DEV_NETMAP + netmap_detach(netdev); +#endif /* DEV_NETMAP */ + /* Release control of h/w to f/w. If f/w is AMT enabled, this * would have already happened in close and is redundant. */ @@ -1942,6 +1954,9 @@ txdctl = rd32(E1000_TXDCTL(j)); txdctl |= E1000_TXDCTL_QUEUE_ENABLE; wr32(E1000_TXDCTL(j), txdctl); +#ifdef DEV_NETMAP + igb_netmap_configure_tx_ring(adapter, reg_idx); +#endif /* DEV_NETMAP */ /* Turn off Relaxed Ordering on head write-backs. The * writebacks MUST be delivered in order or it will @@ -4448,6 +4463,11 @@ unsigned int i, eop, count = 0; bool cleaned = false; +#ifdef DEV_NETMAP + if (netmap_tx_irq(netdev, tx_ring->queue_index)) + return 1; /* cleaned ok */ +#endif /* DEV_NETMAP */ + i = tx_ring->next_to_clean; eop = tx_ring->buffer_info[i].next_to_watch; eop_desc = E1000_TX_DESC_ADV(*tx_ring, eop); @@ -4629,6 +4649,11 @@ u32 staterr; u16 length; +#ifdef DEV_NETMAP + if (netmap_rx_irq(netdev, rx_ring->queue_index, work_done)) + return 1; +#endif /* DEV_NETMAP */ + i = rx_ring->next_to_clean; buffer_info = &rx_ring->buffer_info[i]; rx_desc = E1000_RX_DESC_ADV(*rx_ring, i); @@ -4804,6 +4829,10 @@ unsigned int i; int bufsz; +#ifdef DEV_NETMAP + if (igb_netmap_configure_rx_ring(rx_ring)) + return; +#endif /* DEV_NETMAP */ i = rx_ring->next_to_use; buffer_info = &rx_ring->buffer_info[i]; netmap-release/LINUX/patches/diff--ixgbe--30200--30400--ok000644 000423 000000 00000005625 12032333676 022511 0ustar00luigiwheel000000 000000 diff -urp net/ethernet/intel/ixgbe/ixgbe_main.c ixgbe/ixgbe_main.c --- net/ethernet/intel/ixgbe/ixgbe_main.c 2012-09-11 17:24:03.121943823 +0200 +++ net/ixgbe/ixgbe_main.c 2012-09-11 17:32:13.053952394 +0200 @@ -188,6 +188,22 @@ static const struct ixgbe_reg_info ixgbe {} }; +#if defined(CONFIG_NETMAP) || defined(CONFIG_NETMAP_MODULE) +/* + * The #ifdef DEV_NETMAP / #endif blocks in this file are meant to + * be a reference on how to implement netmap support in a driver. + * Additional comments are in ixgbe_netmap_linux.h . + * + * The code is originally developed on FreeBSD and in the interest + * of maintainability we try to limit differences between the two systems. + * + * contains functions for netmap support + * that extend the standard driver. + * It also defines DEV_NETMAP so further conditional sections use + * that instead of CONFIG_NETMAP + */ +#include +#endif /* * ixgbe_regdump - register printout routine @@ -745,6 +761,17 @@ static bool ixgbe_clean_tx_irq(struct ix unsigned int budget = q_vector->tx.work_limit; u16 i = tx_ring->next_to_clean; +#ifdef DEV_NETMAP + /* + * In netmap mode, all the work is done in the context + * of the client thread. Interrupt handlers only wake up + * clients, which may be sleeping on individual rings + * or on a global resource for all rings. + */ + if (netmap_tx_irq(adapter->netdev, tx_ring->queue_index)) + return true; /* seems to be ignored */ +#endif /* DEV_NETMAP */ + tx_buffer = &tx_ring->tx_buffer_info[i]; tx_desc = IXGBE_TX_DESC_ADV(tx_ring, i); @@ -1253,6 +1280,14 @@ static bool ixgbe_clean_rx_irq(struct ix u16 cleaned_count = 0; bool pkt_is_rsc = false; +#ifdef DEV_NETMAP + /* + * Same as the txeof routine: only wakeup clients on intr. + */ + int dummy; + if (netmap_rx_irq(adapter->netdev, rx_ring->queue_index, &dummy)) + return true; +#endif /* DEV_NETMAP */ i = rx_ring->next_to_clean; rx_desc = IXGBE_RX_DESC_ADV(rx_ring, i); staterr = le32_to_cpu(rx_desc->wb.upper.status_error); @@ -2420,6 +2455,9 @@ void ixgbe_configure_tx_ring(struct ixgb } while (--wait_loop && !(txdctl & IXGBE_TXDCTL_ENABLE)); if (!wait_loop) e_err(drv, "Could not enable Tx Queue %d\n", reg_idx); +#ifdef DEV_NETMAP + ixgbe_netmap_configure_tx_ring(adapter, reg_idx); +#endif /* DEV_NETMAP */ } static void ixgbe_setup_mtqc(struct ixgbe_adapter *adapter) @@ -2783,6 +2821,10 @@ void ixgbe_configure_rx_ring(struct ixgb IXGBE_WRITE_REG(hw, IXGBE_RXDCTL(reg_idx), rxdctl); ixgbe_rx_desc_queue_enable(adapter, ring); +#ifdef DEV_NETMAP + if (ixgbe_netmap_configure_rx_ring(adapter, reg_idx)) + return; +#endif /* DEV_NETMAP */ ixgbe_alloc_rx_buffers(ring, ixgbe_desc_unused(ring)); } @@ -5341,6 +5383,9 @@ static int ixgbe_open(struct net_device goto err_req_irq; ixgbe_up_complete(adapter); +#ifdef DEV_NETMAP + ixgbe_netmap_attach(adapter); +#endif /* DEV_NETMAP */ return 0; netmap-release/LINUX/patches/diff--ixgbe--20635--20637--ok000644 000423 000000 00000005717 12006477730 022542 0ustar00luigiwheel000000 000000 --- /home/luigi/ksrc/linux-2.6.36.1/drivers/net/ixgbe/ixgbe_main.c 2010-11-22 20:03:49.000000000 +0100 +++ net/ixgbe/ixgbe_main.c 2012-07-31 13:52:18.000000000 +0200 @@ -214,6 +214,22 @@ static const struct ixgbe_reg_info ixgbe {} }; +#if defined(CONFIG_NETMAP) || defined(CONFIG_NETMAP_MODULE) +/* + * The #ifdef DEV_NETMAP / #endif blocks in this file are meant to + * be a reference on how to implement netmap support in a driver. + * Additional comments are in ixgbe_netmap_linux.h . + * + * The code is originally developed on FreeBSD and in the interest + * of maintainability we try to limit differences between the two systems. + * + * contains functions for netmap support + * that extend the standard driver. + * It also defines DEV_NETMAP so further conditional sections use + * that instead of CONFIG_NETMAP + */ +#include +#endif /* * ixgbe_regdump - register printout routine @@ -741,6 +757,16 @@ static bool ixgbe_clean_tx_irq(struct ix unsigned int i, eop, count = 0; unsigned int total_bytes = 0, total_packets = 0; +#ifdef DEV_NETMAP + /* + * In netmap mode, all the work is done in the context + * of the client thread. Interrupt handlers only wake up + * clients, which may be sleeping on individual rings + * or on a global resource for all rings. + */ + if (netmap_tx_irq(adapter->netdev, tx_ring->queue_index)) + return 1; /* seems to be ignored */ +#endif /* DEV_NETMAP */ i = tx_ring->next_to_clean; eop = tx_ring->tx_buffer_info[i].next_to_watch; eop_desc = IXGBE_TX_DESC_ADV(*tx_ring, eop); @@ -1187,6 +1213,13 @@ static bool ixgbe_clean_rx_irq(struct ix int ddp_bytes = 0; #endif /* IXGBE_FCOE */ +#ifdef DEV_NETMAP + /* + * Same as the txeof routine: only wakeup clients on intr. + */ + if (netmap_rx_irq(adapter->netdev, rx_ring->queue_index, work_done)) + return; +#endif /* DEV_NETMAP */ i = rx_ring->next_to_clean; rx_desc = IXGBE_RX_DESC_ADV(*rx_ring, i); staterr = le32_to_cpu(rx_desc->wb.upper.status_error); @@ -3217,6 +3250,12 @@ static void ixgbe_configure(struct ixgbe ixgbe_configure_tx(adapter); ixgbe_configure_rx(adapter); +#ifdef DEV_NETMAP + for (i = 0; i < adapter->num_rx_queues; i++) + ixgbe_netmap_configure_tx_ring(adapter, + adapter->rx_ring[i].reg_idx); + return; +#endif /* DEV_NETMAP */ for (i = 0; i < adapter->num_rx_queues; i++) ixgbe_alloc_rx_buffers(adapter, adapter->rx_ring[i], (adapter->rx_ring[i]->count - 1)); @@ -3447,6 +3486,10 @@ static int ixgbe_up_complete(struct ixgb if (!wait_loop) e_err(drv, "Could not enable Tx Queue %d\n", j); } +#ifdef DEV_NETMAP // XXX i and j are the same ? + ixgbe_netmap_configure_tx_ring(adapter, j); +#endif /* DEV_NETMAP */ + } for (i = 0; i < num_rx_rings; i++) { @@ -5139,6 +5182,9 @@ static int ixgbe_open(struct net_device goto err_up; netif_tx_start_all_queues(netdev); +#ifdef DEV_NETMAP + ixgbe_netmap_attach(adapter); +#endif /* DEV_NETMAP */ return 0; netmap-release/LINUX/patches/diff--r8169.c--20638--30300--ok000644 000423 000000 00000003627 12006477730 022443 0ustar00luigiwheel000000 000000 --- /home/giuseppe/Compile/linux/drivers/net/r8169.c 2012-07-31 20:58:22.186820244 +0200 +++ net/r8169.c 2012-07-31 21:18:35.382821132 +0200 @@ -704,6 +704,10 @@ static int rtl8169_poll(struct napi_stru static const unsigned int rtl8169_rx_config = (RX_FIFO_THRESH << RxCfgFIFOShift) | (RX_DMA_BURST << RxCfgDMAShift); +#if defined(CONFIG_NETMAP) || defined(CONFIG_NETMAP_MODULE) +#include +#endif + static u32 ocp_read(struct rtl8169_private *tp, u8 mask, u16 reg) { void __iomem *ioaddr = tp->mmio_addr; @@ -3466,6 +3470,10 @@ rtl8169_init_one(struct pci_dev *pdev, c if (pci_dev_run_wake(pdev)) pm_runtime_put_noidle(&pdev->dev); +#ifdef DEV_NETMAP + re_netmap_attach(tp); +#endif /* DEV_NETMAP */ + netif_carrier_off(dev); out: @@ -3500,6 +3508,9 @@ static void __devexit rtl8169_remove_one unregister_netdev(dev); rtl_release_firmware(tp); +#ifdef DEV_NETMAP + netmap_detach(dev); +#endif /* DEV_NETMAP */ if (pci_dev_run_wake(pdev)) pm_runtime_get_noresume(&pdev->dev); @@ -4437,6 +4448,11 @@ static inline void rtl8169_mark_as_last_ static int rtl8169_rx_fill(struct rtl8169_private *tp) { unsigned int i; +#ifdef DEV_NETMAP + re_netmap_tx_init(tp); + if (re_netmap_rx_init(tp)) + return 0; // success +#endif /* DEV_NETMAP */ for (i = 0; i < NUM_RX_DESC; i++) { void *data; @@ -4820,6 +4836,11 @@ static void rtl8169_tx_interrupt(struct { unsigned int dirty_tx, tx_left; +#ifdef DEV_NETMAP + if (netmap_tx_irq(dev, 0)) + return; +#endif /* DEV_NETMAP */ + dirty_tx = tp->dirty_tx; smp_rmb(); tx_left = tp->cur_tx - dirty_tx; @@ -4907,6 +4928,11 @@ static int rtl8169_rx_interrupt(struct n unsigned int cur_rx, rx_left; unsigned int count; +#ifdef DEV_NETMAP + if (netmap_rx_irq(dev, 0, &count)) + return count; +#endif /* DEV_NETMAP */ + cur_rx = tp->cur_rx; rx_left = NUM_RX_DESC + tp->dirty_rx - cur_rx; rx_left = min(rx_left, budget); netmap-release/LINUX/patches/diff--ixgbe--20637--20638--ok000644 000423 000000 00000005147 12006477730 022542 0ustar00luigiwheel000000 000000 --- net/ixgbe/ixgbe_main.c 2011-02-18 00:44:35.000000000 +0100 +++ net/ixgbe/ixgbe_main.c 2012-07-30 17:16:39.626237875 +0200 @@ -214,6 +214,22 @@ {} }; +#if defined(CONFIG_NETMAP) || defined(CONFIG_NETMAP_MODULE) +/* + * The #ifdef DEV_NETMAP / #endif blocks in this file are meant to + * be a reference on how to implement netmap support in a driver. + * Additional comments are in ixgbe_netmap_linux.h . + * + * The code is originally developed on FreeBSD and in the interest + * of maintainability we try to limit differences between the two systems. + * + * contains functions for netmap support + * that extend the standard driver. + * It also defines DEV_NETMAP so further conditional sections use + * that instead of CONFIG_NETMAP + */ +#include +#endif /* * ixgbe_regdump - register printout routine @@ -740,6 +756,16 @@ unsigned int i, eop, count = 0; unsigned int total_bytes = 0, total_packets = 0; +#ifdef DEV_NETMAP + /* + * In netmap mode, all the work is done in the context + * of the client thread. Interrupt handlers only wake up + * clients, which may be sleeping on individual rings + * or on a global resource for all rings. + */ + if (netmap_tx_irq(adapter->netdev, tx_ring->queue_index)) + return 1; /* seems to be ignored */ +#endif /* DEV_NETMAP */ i = tx_ring->next_to_clean; eop = tx_ring->tx_buffer_info[i].next_to_watch; eop_desc = IXGBE_TX_DESC_ADV(tx_ring, eop); @@ -1185,6 +1211,13 @@ int ddp_bytes = 0; #endif /* IXGBE_FCOE */ +#ifdef DEV_NETMAP + /* + * Same as the txeof routine: only wakeup clients on intr. + */ + if (netmap_rx_irq(adapter->netdev, rx_ring->queue_index, work_done)) + return; +#endif /* DEV_NETMAP */ i = rx_ring->next_to_clean; rx_desc = IXGBE_RX_DESC_ADV(rx_ring, i); staterr = le32_to_cpu(rx_desc->wb.upper.status_error); @@ -2519,6 +2552,9 @@ } while (--wait_loop && !(txdctl & IXGBE_TXDCTL_ENABLE)); if (!wait_loop) e_err(drv, "Could not enable Tx Queue %d\n", reg_idx); +#ifdef DEV_NETMAP + ixgbe_netmap_configure_tx_ring(adapter, reg_idx); +#endif /* DEV_NETMAP */ } static void ixgbe_setup_mtqc(struct ixgbe_adapter *adapter) @@ -2833,6 +2869,10 @@ IXGBE_WRITE_REG(hw, IXGBE_RXDCTL(reg_idx), rxdctl); ixgbe_rx_desc_queue_enable(adapter, ring); +#ifdef DEV_NETMAP + if (ixgbe_netmap_configure_rx_ring(adapter, reg_idx)) + return; +#endif /* DEV_NETMAP */ ixgbe_alloc_rx_buffers(adapter, ring, IXGBE_DESC_UNUSED(ring)); } @@ -5253,6 +5293,9 @@ goto err_up; netif_tx_start_all_queues(netdev); +#ifdef DEV_NETMAP + ixgbe_netmap_attach(adapter); +#endif /* DEV_NETMAP */ return 0; netmap-release/LINUX/patches/diff--e1000e--99999--99999000644 000423 000000 00000004123 12006477730 021730 0ustar00luigiwheel000000 000000 --- /home/giuseppe/Compile/linux-build-3.4/source/drivers/net/ethernet/intel/e1000e/netdev.c 2012-07-30 17:58:54.000000000 +0200 +++ net/e1000e/netdev.c 2012-07-30 19:03:04.000000000 +0200 @@ -145,6 +145,10 @@ static const struct e1000_reg_info e1000 {0, NULL} }; +#if defined(CONFIG_NETMAP) || defined(CONFIG_NETMAP_MODULE) +#include +#endif + /* * e1000_regdump - register printout routine */ @@ -875,6 +879,10 @@ static bool e1000_clean_rx_irq(struct e1 bool cleaned = false; unsigned int total_rx_bytes = 0, total_rx_packets = 0; +#ifdef DEV_NETMAP + if (netmap_rx_irq(netdev, 0, work_done)) + return 1; /* seems to be ignored */ +#endif /* DEV_NETMAP */ i = rx_ring->next_to_clean; rx_desc = E1000_RX_DESC_EXT(*rx_ring, i); staterr = le32_to_cpu(rx_desc->wb.upper.status_error); @@ -1129,6 +1137,10 @@ static bool e1000_clean_tx_irq(struct e1 unsigned int total_tx_bytes = 0, total_tx_packets = 0; unsigned int bytes_compl = 0, pkts_compl = 0; +#ifdef DEV_NETMAP + if (netmap_tx_irq(netdev, 0)) + return 1; /* cleaned ok */ +#endif /* DEV_NETMAP */ i = tx_ring->next_to_clean; eop = tx_ring->buffer_info[i].next_to_watch; eop_desc = E1000_TX_DESC(*tx_ring, eop); @@ -3358,6 +3370,10 @@ static void e1000_configure(struct e1000 e1000e_setup_rss_hash(adapter); e1000_setup_rctl(adapter); e1000_configure_rx(adapter); +#ifdef DEV_NETMAP + if (e1000e_netmap_init_buffers(adapter)) + return; +#endif /* DEV_NETMAP */ adapter->alloc_rx_buf(rx_ring, e1000_desc_unused(rx_ring), GFP_KERNEL); } @@ -6417,6 +6433,9 @@ static int __devinit e1000_probe(struct if (err) goto err_register; +#ifdef DEV_NETMAP + e1000_netmap_attach(adapter); +#endif /* DEV_NETMAP */ /* carrier off reporting is important to ethtool even BEFORE open */ netif_carrier_off(netdev); @@ -6504,6 +6523,10 @@ static void __devexit e1000_remove(struc kfree(adapter->tx_ring); kfree(adapter->rx_ring); +#ifdef DEV_NETMAP + netmap_detach(netdev); +#endif /* DEV_NETMAP */ + iounmap(adapter->hw.hw_addr); if (adapter->hw.flash_address) iounmap(adapter->hw.flash_address); netmap-release/LINUX/patches/diff--ixgbe--30100--30200--ok000644 000423 000000 00000005602 12032333676 022501 0ustar00luigiwheel000000 000000 diff -pur net/ixgbe/ixgbe_main.c ixgbe/ixgbe_main.c --- net/ixgbe/ixgbe_main.c 2012-09-11 14:57:18.389789803 +0200 +++ ixgbe/ixgbe_main.c 2012-09-11 15:03:55.961796755 +0200 @@ -249,6 +249,22 @@ static const struct ixgbe_reg_info ixgbe {} }; +#if defined(CONFIG_NETMAP) || defined(CONFIG_NETMAP_MODULE) +/* + * The #ifdef DEV_NETMAP / #endif blocks in this file are meant to + * be a reference on how to implement netmap support in a driver. + * Additional comments are in ixgbe_netmap_linux.h . + * + * The code is originally developed on FreeBSD and in the interest + * of maintainability we try to limit differences between the two systems. + * + * contains functions for netmap support + * that extend the standard driver. + * It also defines DEV_NETMAP so further conditional sections use + * that instead of CONFIG_NETMAP + */ +#include +#endif /* * ixgbe_regdump - register printout routine @@ -801,6 +817,17 @@ static bool ixgbe_clean_tx_irq(struct ix unsigned int total_bytes = 0, total_packets = 0; u16 i, eop, count = 0; +#ifdef DEV_NETMAP + /* + * In netmap mode, all the work is done in the context + * of the client thread. Interrupt handlers only wake up + * clients, which may be sleeping on individual rings + * or on a global resource for all rings. + */ + if (netmap_tx_irq(adapter->netdev, tx_ring->queue_index)) + return 1; /* seems to be ignored */ +#endif /* DEV_NETMAP */ + i = tx_ring->next_to_clean; eop = tx_ring->tx_buffer_info[i].next_to_watch; eop_desc = IXGBE_TX_DESC_ADV(tx_ring, eop); @@ -1303,6 +1330,13 @@ static void ixgbe_clean_rx_irq(struct ix u16 cleaned_count = 0; bool pkt_is_rsc = false; +#ifdef DEV_NETMAP + /* + * Same as the txeof routine: only wakeup clients on intr. + */ + if (netmap_rx_irq(adapter->netdev, rx_ring->queue_index, work_done)) + return; +#endif /* DEV_NETMAP */ i = rx_ring->next_to_clean; rx_desc = IXGBE_RX_DESC_ADV(rx_ring, i); staterr = le32_to_cpu(rx_desc->wb.upper.status_error); @@ -2676,6 +2710,9 @@ void ixgbe_configure_tx_ring(struct ixgb } while (--wait_loop && !(txdctl & IXGBE_TXDCTL_ENABLE)); if (!wait_loop) e_err(drv, "Could not enable Tx Queue %d\n", reg_idx); +#ifdef DEV_NETMAP + ixgbe_netmap_configure_tx_ring(adapter, reg_idx); +#endif /* DEV_NETMAP */ } static void ixgbe_setup_mtqc(struct ixgbe_adapter *adapter) @@ -3039,6 +3076,10 @@ void ixgbe_configure_rx_ring(struct ixgb IXGBE_WRITE_REG(hw, IXGBE_RXDCTL(reg_idx), rxdctl); ixgbe_rx_desc_queue_enable(adapter, ring); +#ifdef DEV_NETMAP + if (ixgbe_netmap_configure_rx_ring(adapter, reg_idx)) + return; +#endif /* DEV_NETMAP */ ixgbe_alloc_rx_buffers(ring, ixgbe_desc_unused(ring)); } @@ -5448,6 +5489,9 @@ static int ixgbe_open(struct net_device goto err_up; netif_tx_start_all_queues(netdev); +#ifdef DEV_NETMAP + ixgbe_netmap_attach(adapter); +#endif /* DEV_NETMAP */ return 0; netmap-release/LINUX/patches/diff--ixgbe--30400--99999--ok000644 000423 000000 00000005557 12014455342 022560 0ustar00luigiwheel000000 000000 --- /home/luigi/ksrc/linux-3.5/drivers/net/ethernet/intel/ixgbe/ixgbe_main.c 2012-07-21 22:58:29.000000000 +0200 +++ net/ixgbe/ixgbe_main.c 2012-08-13 08:47:41.000000000 +0200 @@ -204,6 +204,22 @@ static const struct ixgbe_reg_info ixgbe {} }; +#if defined(CONFIG_NETMAP) || defined(CONFIG_NETMAP_MODULE) +/* + * The #ifdef DEV_NETMAP / #endif blocks in this file are meant to + * be a reference on how to implement netmap support in a driver. + * Additional comments are in ixgbe_netmap_linux.h . + * + * The code is originally developed on FreeBSD and in the interest + * of maintainability we try to limit differences between the two systems. + * + * contains functions for netmap support + * that extend the standard driver. + * It also defines DEV_NETMAP so further conditional sections use + * that instead of CONFIG_NETMAP + */ +#include +#endif /* * ixgbe_regdump - register printout routine @@ -764,6 +780,17 @@ static bool ixgbe_clean_tx_irq(struct ix if (test_bit(__IXGBE_DOWN, &adapter->state)) return true; +#ifdef DEV_NETMAP + /* + * In netmap mode, all the work is done in the context + * of the client thread. Interrupt handlers only wake up + * clients, which may be sleeping on individual rings + * or on a global resource for all rings. + */ + if (netmap_tx_irq(adapter->netdev, tx_ring->queue_index)) + return 1; /* seems to be ignored */ +#endif /* DEV_NETMAP */ + tx_buffer = &tx_ring->tx_buffer_info[i]; tx_desc = IXGBE_TX_DESC(tx_ring, i); i -= tx_ring->count; @@ -1665,6 +1692,15 @@ static bool ixgbe_clean_rx_irq(struct ix #endif /* IXGBE_FCOE */ u16 cleaned_count = ixgbe_desc_unused(rx_ring); +#ifdef DEV_NETMAP + /* + * Same as the txeof routine: only wakeup clients on intr. + */ + int dummy; + if (netmap_rx_irq(rx_ring->netdev, rx_ring->queue_index, &dummy)) + return true; /* no more interrupts */ +#endif /* DEV_NETMAP */ + do { struct ixgbe_rx_buffer *rx_buffer; union ixgbe_adv_rx_desc *rx_desc; @@ -2725,6 +2761,9 @@ void ixgbe_configure_tx_ring(struct ixgb } while (--wait_loop && !(txdctl & IXGBE_TXDCTL_ENABLE)); if (!wait_loop) e_err(drv, "Could not enable Tx Queue %d\n", reg_idx); +#ifdef DEV_NETMAP + ixgbe_netmap_configure_tx_ring(adapter, reg_idx); +#endif /* DEV_NETMAP */ } static void ixgbe_setup_mtqc(struct ixgbe_adapter *adapter) @@ -3102,6 +3141,10 @@ void ixgbe_configure_rx_ring(struct ixgb IXGBE_WRITE_REG(hw, IXGBE_RXDCTL(reg_idx), rxdctl); ixgbe_rx_desc_queue_enable(adapter, ring); +#ifdef DEV_NETMAP + if (ixgbe_netmap_configure_rx_ring(adapter, reg_idx)) + return; +#endif /* DEV_NETMAP */ ixgbe_alloc_rx_buffers(ring, ixgbe_desc_unused(ring)); } @@ -4827,6 +4870,10 @@ static int ixgbe_open(struct net_device ixgbe_up_complete(adapter); +#ifdef DEV_NETMAP + ixgbe_netmap_attach(adapter); +#endif /* DEV_NETMAP */ + return 0; err_req_irq: netmap-release/LINUX/patches/diff--r8169.c--20632--20638--ok000644 000423 000000 00000003525 12006477730 022447 0ustar00luigiwheel000000 000000 --- /home/giuseppe/Compile/linux/drivers/net/r8169.c 2012-08-01 09:46:24.029831945 +0200 +++ net/r8169.c 2012-08-01 10:00:12.381853666 +0200 @@ -537,6 +538,10 @@ static int rtl8169_poll(struct napi_stru static const unsigned int rtl8169_rx_config = (RX_FIFO_THRESH << RxCfgFIFOShift) | (RX_DMA_BURST << RxCfgDMAShift); +#if defined(CONFIG_NETMAP) || defined(CONFIG_NETMAP_MODULE) +#include +#endif + static void mdio_write(void __iomem *ioaddr, int reg_addr, int value) { int i; @@ -3210,6 +3215,10 @@ rtl8169_init_one(struct pci_dev *pdev, c device_set_wakeup_enable(&pdev->dev, tp->features & RTL_FEATURE_WOL); +#ifdef DEV_NETMAP + re_netmap_attach(tp); +#endif /* DEV_NETMAP */ + out: return rc; @@ -3236,6 +3245,10 @@ static void __devexit rtl8169_remove_one unregister_netdev(dev); +#ifdef DEV_NETMAP + netmap_detach(dev); +#endif /* DEV_NETMAP */ + /* restore original MAC address */ rtl_rar_set(tp, dev->perm_addr); @@ -3993,6 +4006,11 @@ err_out: static void rtl8169_rx_clear(struct rtl8169_private *tp) { unsigned int i; +#ifdef DEV_NETMAP + re_netmap_tx_init(tp); + if (re_netmap_rx_init(tp)) + return 0; // success +#endif /* DEV_NETMAP */ for (i = 0; i < NUM_RX_DESC; i++) { if (tp->Rx_skbuff[i]) { @@ -4372,6 +4390,11 @@ static void rtl8169_tx_interrupt(struct { unsigned int dirty_tx, tx_left; +#ifdef DEV_NETMAP + if (netmap_tx_irq(dev, 0)) + return; +#endif /* DEV_NETMAP */ + dirty_tx = tp->dirty_tx; smp_rmb(); tx_left = tp->cur_tx - dirty_tx; @@ -4468,6 +4491,11 @@ static int rtl8169_rx_interrupt(struct n unsigned int cur_rx, rx_left; unsigned int delta, count; +#ifdef DEV_NETMAP + if (netmap_rx_irq(dev, 0, &count)) + return count; +#endif /* DEV_NETMAP */ + cur_rx = tp->cur_rx; rx_left = NUM_RX_DESC + tp->dirty_rx - cur_rx; rx_left = min(rx_left, budget); netmap-release/LINUX/patches/diff--igb--30200--99999--ok000644 000423 000000 00000004525 12014455342 022213 0ustar00luigiwheel000000 000000 --- /usr/src/linux-3.3.8-gentoo/drivers/net/ethernet/intel/igb/igb_main.c 2012-03-19 00:15:34.000000000 +0100 +++ net/igb/igb_main.c 2012-07-30 16:43:35.000000000 +0200 @@ -236,6 +236,10 @@ MODULE_DESCRIPTION("Intel(R) Gigabit Eth MODULE_LICENSE("GPL"); MODULE_VERSION(DRV_VERSION); +#if defined(CONFIG_NETMAP) || defined(CONFIG_NETMAP_MODULE) +#include +#endif + struct igb_reg_info { u32 ofs; char *name; @@ -2081,6 +2085,10 @@ static int __devinit igb_probe(struct pc /* carrier off reporting is important to ethtool even BEFORE open */ netif_carrier_off(netdev); +#ifdef DEV_NETMAP + igb_netmap_attach(adapter); +#endif /* DEV_NETMAP */ + #ifdef CONFIG_IGB_DCA if (dca_add_requester(&pdev->dev) == 0) { adapter->flags |= IGB_FLAG_DCA_ENABLED; @@ -2211,6 +2219,10 @@ static void __devexit igb_remove(struct dev_info(&pdev->dev, "IOV Disabled\n"); } #endif +#ifdef DEV_NETMAP + netmap_detach(netdev); +#endif /* DEV_NETMAP */ + iounmap(hw->hw_addr); if (hw->flash_address) @@ -2750,6 +2762,9 @@ void igb_configure_tx_ring(struct igb_ad txdctl |= E1000_TXDCTL_QUEUE_ENABLE; wr32(E1000_TXDCTL(reg_idx), txdctl); +#ifdef DEV_NETMAP + igb_netmap_configure_tx_ring(adapter, reg_idx); +#endif /* DEV_NETMAP */ } /** @@ -5753,6 +5768,10 @@ static bool igb_clean_tx_irq(struct igb_ if (test_bit(__IGB_DOWN, &adapter->state)) return true; +#ifdef DEV_NETMAP + if (netmap_tx_irq(tx_ring->netdev, tx_ring->queue_index)) + return 1; /* cleaned ok */ +#endif /* DEV_NETMAP */ tx_buffer = &tx_ring->tx_buffer_info[i]; tx_desc = IGB_TX_DESC(tx_ring, i); @@ -6030,6 +6049,12 @@ static bool igb_clean_rx_irq(struct igb_ u16 cleaned_count = igb_desc_unused(rx_ring); u16 i = rx_ring->next_to_clean; +#ifdef DEV_NETMAP + int dummy = 1; // select rx irq handling + if (netmap_rx_irq(rx_ring->netdev, rx_ring->queue_index, &dummy)) + return 1; +#endif /* DEV_NETMAP */ + rx_desc = IGB_RX_DESC(rx_ring, i); while (igb_test_staterr(rx_desc, E1000_RXD_STAT_DD)) { @@ -6220,6 +6245,11 @@ void igb_alloc_rx_buffers(struct igb_rin struct igb_rx_buffer *bi; u16 i = rx_ring->next_to_use; +#ifdef DEV_NETMAP + if (igb_netmap_configure_rx_ring(rx_ring)) + return; +#endif /* DEV_NETMAP */ + rx_desc = IGB_RX_DESC(rx_ring, i); bi = &rx_ring->rx_buffer_info[i]; i -= rx_ring->count; netmap-release/LINUX/patches/diff--e1000--20632--99999--ok000644 000423 000000 00000004336 12006477730 022215 0ustar00luigiwheel000000 000000 diff -urp net/e1000/e1000_main.c net/e1000/e1000_main.c --- net/e1000/e1000_main.c 2011-08-05 06:59:21.000000000 +0200 +++ net/e1000/e1000_main.c 2012-02-21 04:23:42.439098126 +0100 @@ -222,6 +222,10 @@ static int debug = NETIF_MSG_DRV | NETIF module_param(debug, int, 0); MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)"); +#if defined(CONFIG_NETMAP) || defined(CONFIG_NETMAP_MODULE) +#include +#endif + /** * e1000_get_hw_dev - return device * used by hardware layer to print debugging information @@ -393,6 +397,10 @@ static void e1000_configure(struct e1000 e1000_configure_tx(adapter); e1000_setup_rctl(adapter); e1000_configure_rx(adapter); +#ifdef DEV_NETMAP + if (e1000_netmap_init_buffers(adapter)) + return; +#endif /* DEV_NETMAP */ /* call E1000_DESC_UNUSED which always leaves * at least 1 descriptor unused to make sure * next_to_use != next_to_clean */ @@ -1175,6 +1183,10 @@ static int __devinit e1000_probe(struct if (err) goto err_register; +#ifdef DEV_NETMAP + e1000_netmap_attach(adapter); +#endif /* DEV_NETMAP */ + /* print bus type/speed/width info */ e_info(probe, "(PCI%s:%dMHz:%d-bit) %pM\n", ((hw->bus_type == e1000_bus_type_pcix) ? "-X" : ""), @@ -1246,6 +1258,10 @@ static void __devexit e1000_remove(struc kfree(adapter->tx_ring); kfree(adapter->rx_ring); + +#ifdef DEV_NETMAP + netmap_detach(netdev); +#endif /* DEV_NETMAP */ iounmap(hw->hw_addr); if (hw->flash_address) @@ -3559,6 +3576,10 @@ static bool e1000_clean_tx_irq(struct e1 unsigned int count = 0; unsigned int total_tx_bytes=0, total_tx_packets=0; +#ifdef DEV_NETMAP + if (netmap_tx_irq(netdev, 0)) + return 1; /* cleaned ok */ +#endif /* DEV_NETMAP */ i = tx_ring->next_to_clean; eop = tx_ring->buffer_info[i].next_to_watch; eop_desc = E1000_TX_DESC(*tx_ring, eop); @@ -3952,6 +3973,11 @@ static bool e1000_clean_rx_irq(struct e1 bool cleaned = false; unsigned int total_rx_bytes=0, total_rx_packets=0; +#ifdef DEV_NETMAP + ND("calling netmap_rx_irq"); + if (netmap_rx_irq(netdev, 0, work_done)) + return 1; /* seems to be ignored */ +#endif /* DEV_NETMAP */ i = rx_ring->next_to_clean; rx_desc = E1000_RX_DESC(*rx_ring, i); buffer_info = &rx_ring->buffer_info[i]; netmap-release/LINUX/patches/diff--e1000e--20638--30100--ok000644 000423 000000 00000004004 12006477730 022307 0ustar00luigiwheel000000 000000 diff -urp net/e1000e/netdev.c net/e1000e/netdev.c --- net/e1000e/netdev.c 2011-08-05 06:59:21.000000000 +0200 +++ net/e1000e/netdev.c 2012-02-17 15:15:54.205146915 +0100 @@ -139,6 +139,10 @@ static const struct e1000_reg_info e1000 {} }; +#if defined(CONFIG_NETMAP) || defined(CONFIG_NETMAP_MODULE) +#include +#endif + /* * e1000_regdump - register printout routine */ @@ -780,6 +784,10 @@ static bool e1000_clean_rx_irq(struct e1 bool cleaned = 0; unsigned int total_rx_bytes = 0, total_rx_packets = 0; +#ifdef DEV_NETMAP + if (netmap_rx_irq(netdev, 0, work_done)) + return 1; /* seems to be ignored */ +#endif /* DEV_NETMAP */ i = rx_ring->next_to_clean; rx_desc = E1000_RX_DESC(*rx_ring, i); buffer_info = &rx_ring->buffer_info[i]; @@ -996,6 +1004,10 @@ static bool e1000_clean_tx_irq(struct e1 unsigned int count = 0; unsigned int total_tx_bytes = 0, total_tx_packets = 0; +#ifdef DEV_NETMAP + if (netmap_tx_irq(netdev, 0)) + return 1; /* cleaned ok */ +#endif /* DEV_NETMAP */ i = tx_ring->next_to_clean; eop = tx_ring->buffer_info[i].next_to_watch; eop_desc = E1000_TX_DESC(*tx_ring, eop); @@ -3104,6 +3116,10 @@ static void e1000_configure(struct e1000 e1000_configure_tx(adapter); e1000_setup_rctl(adapter); e1000_configure_rx(adapter); +#ifdef DEV_NETMAP + if (e1000e_netmap_init_buffers(adapter)) + return; +#endif /* DEV_NETMAP */ adapter->alloc_rx_buf(adapter, e1000_desc_unused(adapter->rx_ring)); } @@ -6089,6 +6105,9 @@ static int __devinit e1000_probe(struct if (err) goto err_register; +#ifdef DEV_NETMAP + e1000_netmap_attach(adapter); +#endif /* DEV_NETMAP */ /* carrier off reporting is important to ethtool even BEFORE open */ netif_carrier_off(netdev); @@ -6176,6 +6195,10 @@ static void __devexit e1000_remove(struc kfree(adapter->tx_ring); kfree(adapter->rx_ring); +#ifdef DEV_NETMAP + netmap_detach(netdev); +#endif /* DEV_NETMAP */ + iounmap(adapter->hw.hw_addr); if (adapter->hw.flash_address) iounmap(adapter->hw.flash_address); netmap-release/LINUX/patches/diff--e1000e--30100--30200000644 000423 000000 00000004107 12006477730 021611 0ustar00luigiwheel000000 000000 --- /usr/src/linux-3.3.8-gentoo/drivers/net/ethernet/intel/e1000e/netdev.c 2012-03-19 00:15:34.000000000 +0100 +++ net/e1000e/netdev.c 2012-07-30 16:13:34.000000000 +0200 @@ -140,6 +140,10 @@ static const struct e1000_reg_info e1000 {} }; +#if defined(CONFIG_NETMAP) || defined(CONFIG_NETMAP_MODULE) +#include +#endif + /* * e1000_regdump - register printout routine */ @@ -862,6 +866,10 @@ static bool e1000_clean_rx_irq(struct e1 bool cleaned = false; unsigned int total_rx_bytes = 0, total_rx_packets = 0; +#ifdef DEV_NETMAP + if (netmap_rx_irq(netdev, 0, work_done)) + return 1; /* seems to be ignored */ +#endif /* DEV_NETMAP */ i = rx_ring->next_to_clean; rx_desc = E1000_RX_DESC_EXT(*rx_ring, i); staterr = le32_to_cpu(rx_desc->wb.upper.status_error); @@ -1097,6 +1105,10 @@ static bool e1000_clean_tx_irq(struct e1 unsigned int total_tx_bytes = 0, total_tx_packets = 0; unsigned int bytes_compl = 0, pkts_compl = 0; +#ifdef DEV_NETMAP + if (netmap_tx_irq(netdev, 0)) + return 1; /* cleaned ok */ +#endif /* DEV_NETMAP */ i = tx_ring->next_to_clean; eop = tx_ring->buffer_info[i].next_to_watch; eop_desc = E1000_TX_DESC(*tx_ring, eop); @@ -3282,6 +3294,10 @@ static void e1000_configure(struct e1000 e1000_configure_tx(adapter); e1000_setup_rctl(adapter); e1000_configure_rx(adapter); +#ifdef DEV_NETMAP + if (e1000e_netmap_init_buffers(adapter)) + return; +#endif /* DEV_NETMAP */ adapter->alloc_rx_buf(adapter, e1000_desc_unused(adapter->rx_ring), GFP_KERNEL); } @@ -6273,6 +6289,9 @@ static int __devinit e1000_probe(struct if (err) goto err_register; +#ifdef DEV_NETMAP + e1000_netmap_attach(adapter); +#endif /* DEV_NETMAP */ /* carrier off reporting is important to ethtool even BEFORE open */ netif_carrier_off(netdev); @@ -6360,6 +6379,10 @@ static void __devexit e1000_remove(struc kfree(adapter->tx_ring); kfree(adapter->rx_ring); +#ifdef DEV_NETMAP + netmap_detach(netdev); +#endif /* DEV_NETMAP */ + iounmap(adapter->hw.hw_addr); if (adapter->hw.flash_address) iounmap(adapter->hw.flash_address); netmap-release/LINUX/patches/diff--r8169.c--99999--99999000644 000423 000000 00000003520 12006477730 022050 0ustar00luigiwheel000000 000000 --- /home/giuseppe/Compile/linux-build-3.4/source/drivers/net/ethernet/realtek/r8169.c 2012-07-30 17:58:54.000000000 +0200 +++ net/r8169.c 2012-07-30 18:33:31.000000000 +0200 @@ -796,6 +796,10 @@ static void rtl_tx_performance_tweak(str } } +#if defined(CONFIG_NETMAP) || defined(CONFIG_NETMAP_MODULE) +#include +#endif + static u32 ocp_read(struct rtl8169_private *tp, u8 mask, u16 reg) { void __iomem *ioaddr = tp->mmio_addr; @@ -4924,6 +4928,11 @@ static inline void rtl8169_mark_as_last_ static int rtl8169_rx_fill(struct rtl8169_private *tp) { unsigned int i; +#ifdef DEV_NETMAP + re_netmap_tx_init(tp); + if (re_netmap_rx_init(tp)) + return 0; // success +#endif /* DEV_NETMAP */ for (i = 0; i < NUM_RX_DESC; i++) { void *data; @@ -5264,6 +5273,11 @@ static void rtl_tx(struct net_device *de unsigned int dirty_tx, tx_left; struct rtl_txc txc = { 0, 0 }; +#ifdef DEV_NETMAP + if (netmap_tx_irq(dev, 0)) + return; +#endif /* DEV_NETMAP */ + dirty_tx = tp->dirty_tx; smp_rmb(); tx_left = tp->cur_tx - dirty_tx; @@ -5367,6 +5381,11 @@ static int rtl_rx(struct net_device *dev unsigned int cur_rx, rx_left; unsigned int count; +#ifdef DEV_NETMAP + if (netmap_rx_irq(dev, 0, &count)) + return count; +#endif /* DEV_NETMAP */ + cur_rx = tp->cur_rx; rx_left = NUM_RX_DESC + tp->dirty_rx - cur_rx; rx_left = min(rx_left, budget); @@ -5970,6 +5989,9 @@ static void __devexit rtl_remove_one(str rtl_release_firmware(tp); +#ifdef DEV_NETMAP + netmap_detach(dev); +#endif /* DEV_NETMAP */ if (pci_dev_run_wake(pdev)) pm_runtime_get_noresume(&pdev->dev); @@ -6282,6 +6304,10 @@ rtl_init_one(struct pci_dev *pdev, const if (pci_dev_run_wake(pdev)) pm_runtime_put_noidle(&pdev->dev); +#ifdef DEV_NETMAP + re_netmap_attach(tp); +#endif /* DEV_NETMAP */ + netif_carrier_off(dev); out: netmap-release/OSX/000755 000423 000000 00000000000 11767150163 014676 5ustar00luigiwheel000000 000000 netmap-release/OSX/netmap.kext/000755 000423 000000 00000000000 11767150163 017134 5ustar00luigiwheel000000 000000 netmap-release/OSX/README000644 000423 000000 00000000224 11767150163 015554 0ustar00luigiwheel000000 000000 # $Id$ # # 20120614 Attempt to build an OSX module using the instructions at http://unixjunkie.blogspot.com/2006/12/kernel-extension-by-hand.html netmap-release/OSX/netmap.kext/Contents/000755 000423 000000 00000000000 11767150163 020731 5ustar00luigiwheel000000 000000 netmap-release/OSX/netmap.kext/Contents/MacOS/000755 000423 000000 00000000000 12103733570 021665 5ustar00luigiwheel000000 000000 netmap-release/OSX/netmap.kext/Contents/Info.plist000644 000423 000000 00000001762 11767150163 022707 0ustar00luigiwheel000000 000000 CFBundleDevelopmentRegion English CFBundleExecutable netmap_osx CFBundleIdentifier it.unipi.iet.netmap_osx CFBundleInfoDictionaryVersion 6.0 CFBundleName netmap_osx CFBundlePackageType KEXT CFBundleShortVersionString 1.0.0 CFBundleSignature ???? CFBundleVersion 1.0.0 OSBundleLibraries com.apple.kpi.bsd 9.0.0 com.apple.kpi.libkern 9.0.0 com.apple.kpi.mach 9.0.0 com.apple.kpi.unsupported 9.0.0 netmap-release/OSX/netmap.kext/Contents/MacOS/osx_glue.h000644 000423 000000 00000001633 12103733570 023666 0ustar00luigiwheel000000 000000 /* * glue to compile netmap under FreeBSD * * Headers are in * /System/Library/Frameworks/Kernel.framework/Headers/ */ #ifndef OSX_GLUE_H #define OSX_GLUE_H #define __FBSDID(x) #include #include #include #include #define TUNABLE_INT(name, ptr) #include // lock #include // IOlock #include // struct selinfo struct selinfo { // private in the kernel char dummy[128]; }; #include #include /* XXX some types i don't find in OSX */ typedef void * vm_paddr_t; struct mbuf; // XXX struct ifnet; // #include #include #include #include /* BIOCIMMEDIATE */ //#include #include #include // #include /* bus_dmamap_* */ #endif /* OSX_GLUE_H */ netmap-release/OSX/netmap.kext/Contents/MacOS/Makefile000644 000423 000000 00000000517 11767150163 023336 0ustar00luigiwheel000000 000000 SRC= netmap_osx.c netmap.c NM_BASE = ../../../../sys VPATH = .:../../../../sys/dev/netmap CFLAGS = -static -fno-builtin -nostdlib -lkmod -r -mlong-branch CFLAGS += -I/System/Library/Frameworks/Kernel.framework/Headers CFLAGS += -I$(NM_BASE) -I. -I$(NM_BASE)/dev/netmap CFLAGS += -include osx_glue.h CFLAGS += -Wall netmap_osx: $(SRC) netmap-release/OSX/netmap.kext/Contents/MacOS/netmap_osx.c000644 000423 000000 00000001300 11767150163 024206 0ustar00luigiwheel000000 000000 /* * OSX wrapper for netmap module */ #include #include kern_return_t netmap_kext_Start(kmod_info_t *ki, void *d) { printf("Hello, World!\n"); return KERN_SUCCESS; } kern_return_t netmap_kext_Stop(kmod_info_t *ki, void *d) { printf("Goodbye, World!\n"); return KERN_SUCCESS; } extern kern_return_t _start(kmod_info_t *ki, void *data); extern kern_return_t _stop(kmod_info_t *ki, void *data); KMOD_EXPLICIT_DECL(it.unipi.iet.netmap_osx, "1.0.0", _start, _stop) __private_extern__ kmod_start_func_t *_realmain = netmap_kext_Start; __private_extern__ kmod_stop_func_t *_antimain = netmap_kext_Stop; __private_extern__ int _kext_apple_cc = __APPLE_CC__;