2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (C) 2013-2016 Vincenzo Maffione
5 * Copyright (C) 2013-2016 Luigi Rizzo
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * This module implements netmap support on top of standard,
32 * unmodified device drivers.
34 * A NIOCREGIF request is handled here if the device does not
35 * have native support. TX and RX rings are emulated as follows:
38 * We preallocate a block of TX mbufs (roughly as many as
39 * tx descriptors; the number is not critical) to speed up
40 * operation during transmissions. The refcount on most of
41 * these buffers is artificially bumped up so we can recycle
42 * them more easily. Also, the destructor is intercepted
43 * so we use it as an interrupt notification to wake up
44 * processes blocked on a poll().
46 * For each receive ring we allocate one "struct mbq"
47 * (an mbuf tailq plus a spinlock). We intercept packets
49 * on the receive path and put them in the mbq from which
50 * netmap receive routines can grab them.
53 * in the generic_txsync() routine, netmap buffers are copied
54 * (or linked, in a future) to the preallocated mbufs
55 * and pushed to the transmit queue. Some of these mbufs
56 * (those with NS_REPORT, or otherwise every half ring)
57 * have the refcount=1, others have refcount=2.
58 * When the destructor is invoked, we take that as
59 * a notification that all mbufs up to that one in
60 * the specific ring have been completed, and generate
61 * the equivalent of a transmit interrupt.
69 #include <sys/cdefs.h> /* prerequisite */
70 __FBSDID("$FreeBSD$");
72 #include <sys/types.h>
73 #include <sys/errno.h>
74 #include <sys/malloc.h>
75 #include <sys/lock.h> /* PROT_EXEC */
76 #include <sys/rwlock.h>
77 #include <sys/socket.h> /* sockaddrs */
78 #include <sys/selinfo.h>
80 #include <net/if_types.h>
81 #include <net/if_var.h>
82 #include <machine/bus.h> /* bus_dmamap_* in netmap_kern.h */
84 // XXX temporary - D() defined here
85 #include <net/netmap.h>
86 #include <dev/netmap/netmap_kern.h>
87 #include <dev/netmap/netmap_mem2.h>
89 #define rtnl_lock() ND("rtnl_lock called")
90 #define rtnl_unlock() ND("rtnl_unlock called")
91 #define MBUF_RXQ(m) ((m)->m_pkthdr.flowid)
95 * FreeBSD mbuf allocator/deallocator in emulation mode:
97 #if __FreeBSD_version < 1100000
100 * For older versions of FreeBSD:
102 * We allocate EXT_PACKET mbuf+clusters, but need to set M_NOFREE
103 * so that the destructor, if invoked, will not free the packet.
104 * In principle we should set the destructor only on demand,
105 * but since there might be a race we better do it on allocation.
106 * As a consequence, we also need to set the destructor or we
107 * would leak buffers.
110 /* mbuf destructor, also need to change the type to EXT_EXTREF,
111 * add an M_NOFREE flag, and then clear the flag and
112 * chain into uma_zfree(zone_pack, mf)
113 * (or reinstall the buffer ?)
115 #define SET_MBUF_DESTRUCTOR(m, fn) do { \
116 (m)->m_ext.ext_free = (void *)fn; \
117 (m)->m_ext.ext_type = EXT_EXTREF; \
121 void_mbuf_dtor(struct mbuf *m, void *arg1, void *arg2)
123 /* restore original mbuf */
124 m->m_ext.ext_buf = m->m_data = m->m_ext.ext_arg1;
125 m->m_ext.ext_arg1 = NULL;
126 m->m_ext.ext_type = EXT_PACKET;
127 m->m_ext.ext_free = NULL;
128 if (MBUF_REFCNT(m) == 0)
129 SET_MBUF_REFCNT(m, 1);
130 uma_zfree(zone_pack, m);
135 static inline struct mbuf *
136 nm_os_get_mbuf(struct ifnet *ifp, int len)
141 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
143 /* m_getcl() (mb_ctor_mbuf) has an assert that checks that
144 * M_NOFREE flag is not specified as third argument,
145 * so we have to set M_NOFREE after m_getcl(). */
146 m->m_flags |= M_NOFREE;
147 m->m_ext.ext_arg1 = m->m_ext.ext_buf; // XXX save
148 m->m_ext.ext_free = (void *)void_mbuf_dtor;
149 m->m_ext.ext_type = EXT_EXTREF;
150 ND(5, "create m %p refcnt %d", m, MBUF_REFCNT(m));
155 #else /* __FreeBSD_version >= 1100000 */
158 * Newer versions of FreeBSD, using a straightforward scheme.
160 * We allocate mbufs with m_gethdr(), since the mbuf header is needed
161 * by the driver. We also attach a customly-provided external storage,
162 * which in this case is a netmap buffer. When calling m_extadd(), however
163 * we pass a NULL address, since the real address (and length) will be
164 * filled in by nm_os_generic_xmit_frame() right before calling
167 * The dtor function does nothing, however we need it since mb_free_ext()
168 * has a KASSERT(), checking that the mbuf dtor function is not NULL.
171 static void void_mbuf_dtor(struct mbuf *m) { }
173 #define SET_MBUF_DESTRUCTOR(m, fn) do { \
174 (m)->m_ext.ext_free = (fn != NULL) ? \
175 (void *)fn : (void *)void_mbuf_dtor; \
178 static inline struct mbuf *
179 nm_os_get_mbuf(struct ifnet *ifp, int len)
186 m = m_gethdr(M_NOWAIT, MT_DATA);
191 m_extadd(m, NULL /* buf */, 0 /* size */, void_mbuf_dtor,
192 NULL, NULL, 0, EXT_NET_DRV);
197 #endif /* __FreeBSD_version >= 1100000 */
201 #include "win_glue.h"
203 #define rtnl_lock() ND("rtnl_lock called")
204 #define rtnl_unlock() ND("rtnl_unlock called")
205 #define MBUF_TXQ(m) 0//((m)->m_pkthdr.flowid)
206 #define MBUF_RXQ(m) 0//((m)->m_pkthdr.flowid)
207 #define smp_mb() //XXX: to be correctly defined
211 #include "bsd_glue.h"
213 #include <linux/rtnetlink.h> /* rtnl_[un]lock() */
214 #include <linux/ethtool.h> /* struct ethtool_ops, get_ringparam */
215 #include <linux/hrtimer.h>
217 static inline struct mbuf *
218 nm_os_get_mbuf(struct ifnet *ifp, int len)
220 return alloc_skb(ifp->needed_headroom + len +
221 ifp->needed_tailroom, GFP_ATOMIC);
227 /* Common headers. */
228 #include <net/netmap.h>
229 #include <dev/netmap/netmap_kern.h>
230 #include <dev/netmap/netmap_mem2.h>
233 #define for_each_kring_n(_i, _k, _karr, _n) \
234 for (_k=_karr, _i = 0; _i < _n; (_k)++, (_i)++)
236 #define for_each_tx_kring(_i, _k, _na) \
237 for_each_kring_n(_i, _k, (_na)->tx_rings, (_na)->num_tx_rings)
238 #define for_each_tx_kring_h(_i, _k, _na) \
239 for_each_kring_n(_i, _k, (_na)->tx_rings, (_na)->num_tx_rings + 1)
241 #define for_each_rx_kring(_i, _k, _na) \
242 for_each_kring_n(_i, _k, (_na)->rx_rings, (_na)->num_rx_rings)
243 #define for_each_rx_kring_h(_i, _k, _na) \
244 for_each_kring_n(_i, _k, (_na)->rx_rings, (_na)->num_rx_rings + 1)
247 /* ======================== PERFORMANCE STATISTICS =========================== */
253 unsigned long txsync;
255 unsigned long txrepl;
256 unsigned long txdrop;
259 unsigned long rxsync;
262 struct rate_context {
264 struct timer_list timer;
265 struct rate_stats new;
266 struct rate_stats old;
269 #define RATE_PRINTK(_NAME_) \
270 printk( #_NAME_ " = %lu Hz\n", (cur._NAME_ - ctx->old._NAME_)/RATE_PERIOD);
271 #define RATE_PERIOD 2
272 static void rate_callback(unsigned long arg)
274 struct rate_context * ctx = (struct rate_context *)arg;
275 struct rate_stats cur = ctx->new;
289 r = mod_timer(&ctx->timer, jiffies +
290 msecs_to_jiffies(RATE_PERIOD * 1000));
292 D("[v1000] Error: mod_timer()");
295 static struct rate_context rate_ctx;
297 void generic_rate(int txp, int txs, int txi, int rxp, int rxs, int rxi)
299 if (txp) rate_ctx.new.txpkt++;
300 if (txs) rate_ctx.new.txsync++;
301 if (txi) rate_ctx.new.txirq++;
302 if (rxp) rate_ctx.new.rxpkt++;
303 if (rxs) rate_ctx.new.rxsync++;
304 if (rxi) rate_ctx.new.rxirq++;
312 /* ========== GENERIC (EMULATED) NETMAP ADAPTER SUPPORT ============= */
315 * Wrapper used by the generic adapter layer to notify
316 * the poller threads. Differently from netmap_rx_irq(), we check
317 * only NAF_NETMAP_ON instead of NAF_NATIVE_ON to enable the irq.
320 netmap_generic_irq(struct netmap_adapter *na, u_int q, u_int *work_done)
322 if (unlikely(!nm_netmap_on(na)))
325 netmap_common_irq(na, q, work_done);
328 rate_ctx.new.rxirq++;
330 rate_ctx.new.txirq++;
331 #endif /* RATE_GENERIC */
335 generic_netmap_unregister(struct netmap_adapter *na)
337 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na;
338 struct netmap_kring *kring = NULL;
341 if (na->active_fds == 0) {
344 na->na_flags &= ~NAF_NETMAP_ON;
346 /* Release packet steering control. */
347 nm_os_catch_tx(gna, 0);
349 /* Stop intercepting packets on the RX path. */
350 nm_os_catch_rx(gna, 0);
355 for_each_rx_kring_h(r, kring, na) {
356 if (nm_kring_pending_off(kring)) {
357 D("Emulated adapter: ring '%s' deactivated", kring->name);
358 kring->nr_mode = NKR_NETMAP_OFF;
361 for_each_tx_kring_h(r, kring, na) {
362 if (nm_kring_pending_off(kring)) {
363 kring->nr_mode = NKR_NETMAP_OFF;
364 D("Emulated adapter: ring '%s' deactivated", kring->name);
368 for_each_rx_kring(r, kring, na) {
369 /* Free the mbufs still pending in the RX queues,
370 * that did not end up into the corresponding netmap
372 mbq_safe_purge(&kring->rx_queue);
373 nm_os_mitigation_cleanup(&gna->mit[r]);
376 /* Decrement reference counter for the mbufs in the
377 * TX pools. These mbufs can be still pending in drivers,
378 * (e.g. this happens with virtio-net driver, which
379 * does lazy reclaiming of transmitted mbufs). */
380 for_each_tx_kring(r, kring, na) {
381 /* We must remove the destructor on the TX event,
382 * because the destructor invokes netmap code, and
383 * the netmap module may disappear before the
384 * TX event is consumed. */
385 mtx_lock_spin(&kring->tx_event_lock);
386 if (kring->tx_event) {
387 SET_MBUF_DESTRUCTOR(kring->tx_event, NULL);
389 kring->tx_event = NULL;
390 mtx_unlock_spin(&kring->tx_event_lock);
393 if (na->active_fds == 0) {
394 nm_os_free(gna->mit);
396 for_each_rx_kring(r, kring, na) {
397 mbq_safe_fini(&kring->rx_queue);
400 for_each_tx_kring(r, kring, na) {
401 mtx_destroy(&kring->tx_event_lock);
402 if (kring->tx_pool == NULL) {
406 for (i=0; i<na->num_tx_desc; i++) {
407 if (kring->tx_pool[i]) {
408 m_freem(kring->tx_pool[i]);
411 nm_os_free(kring->tx_pool);
412 kring->tx_pool = NULL;
416 if (--rate_ctx.refcount == 0) {
418 del_timer(&rate_ctx.timer);
421 D("Emulated adapter for %s deactivated", na->name);
427 /* Enable/disable netmap mode for a generic network interface. */
429 generic_netmap_register(struct netmap_adapter *na, int enable)
431 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na;
432 struct netmap_kring *kring = NULL;
441 /* This is actually an unregif. */
442 return generic_netmap_unregister(na);
445 if (na->active_fds == 0) {
446 D("Emulated adapter for %s activated", na->name);
447 /* Do all memory allocations when (na->active_fds == 0), to
448 * simplify error management. */
450 /* Allocate memory for mitigation support on all the rx queues. */
451 gna->mit = nm_os_malloc(na->num_rx_rings * sizeof(struct nm_generic_mit));
453 D("mitigation allocation failed");
458 for_each_rx_kring(r, kring, na) {
459 /* Init mitigation support. */
460 nm_os_mitigation_init(&gna->mit[r], r, na);
462 /* Initialize the rx queue, as generic_rx_handler() can
463 * be called as soon as nm_os_catch_rx() returns.
465 mbq_safe_init(&kring->rx_queue);
469 * Prepare mbuf pools (parallel to the tx rings), for packet
470 * transmission. Don't preallocate the mbufs here, it's simpler
471 * to leave this task to txsync.
473 for_each_tx_kring(r, kring, na) {
474 kring->tx_pool = NULL;
476 for_each_tx_kring(r, kring, na) {
478 nm_os_malloc(na->num_tx_desc * sizeof(struct mbuf *));
479 if (!kring->tx_pool) {
480 D("tx_pool allocation failed");
484 mtx_init(&kring->tx_event_lock, "tx_event_lock",
489 for_each_rx_kring_h(r, kring, na) {
490 if (nm_kring_pending_on(kring)) {
491 D("Emulated adapter: ring '%s' activated", kring->name);
492 kring->nr_mode = NKR_NETMAP_ON;
496 for_each_tx_kring_h(r, kring, na) {
497 if (nm_kring_pending_on(kring)) {
498 D("Emulated adapter: ring '%s' activated", kring->name);
499 kring->nr_mode = NKR_NETMAP_ON;
503 for_each_tx_kring(r, kring, na) {
504 /* Initialize tx_pool and tx_event. */
505 for (i=0; i<na->num_tx_desc; i++) {
506 kring->tx_pool[i] = NULL;
509 kring->tx_event = NULL;
512 if (na->active_fds == 0) {
515 /* Prepare to intercept incoming traffic. */
516 error = nm_os_catch_rx(gna, 1);
518 D("nm_os_catch_rx(1) failed (%d)", error);
519 goto register_handler;
522 /* Make netmap control the packet steering. */
523 error = nm_os_catch_tx(gna, 1);
525 D("nm_os_catch_tx(1) failed (%d)", error);
531 na->na_flags |= NAF_NETMAP_ON;
534 if (rate_ctx.refcount == 0) {
536 memset(&rate_ctx, 0, sizeof(rate_ctx));
537 setup_timer(&rate_ctx.timer, &rate_callback, (unsigned long)&rate_ctx);
538 if (mod_timer(&rate_ctx.timer, jiffies + msecs_to_jiffies(1500))) {
539 D("Error: mod_timer()");
548 /* Here (na->active_fds == 0) holds. */
550 nm_os_catch_rx(gna, 0);
554 for_each_tx_kring(r, kring, na) {
555 mtx_destroy(&kring->tx_event_lock);
556 if (kring->tx_pool == NULL) {
559 nm_os_free(kring->tx_pool);
560 kring->tx_pool = NULL;
562 for_each_rx_kring(r, kring, na) {
563 mbq_safe_fini(&kring->rx_queue);
565 nm_os_free(gna->mit);
572 * Callback invoked when the device driver frees an mbuf used
573 * by netmap to transmit a packet. This usually happens when
574 * the NIC notifies the driver that transmission is completed.
577 generic_mbuf_destructor(struct mbuf *m)
579 struct netmap_adapter *na = NA(GEN_TX_MBUF_IFP(m));
580 struct netmap_kring *kring;
581 unsigned int r = MBUF_TXQ(m);
582 unsigned int r_orig = r;
584 if (unlikely(!nm_netmap_on(na) || r >= na->num_tx_rings)) {
585 D("Error: no netmap adapter on device %p",
591 * First, clear the event mbuf.
592 * In principle, the event 'm' should match the one stored
593 * on ring 'r'. However we check it explicitely to stay
594 * safe against lower layers (qdisc, driver, etc.) changing
595 * MBUF_TXQ(m) under our feet. If the match is not found
596 * on 'r', we try to see if it belongs to some other ring.
601 kring = &na->tx_rings[r];
602 mtx_lock_spin(&kring->tx_event_lock);
603 if (kring->tx_event == m) {
604 kring->tx_event = NULL;
607 mtx_unlock_spin(&kring->tx_event_lock);
611 RD(1, "event %p migrated: ring %u --> %u",
617 if (++r == na->num_tx_rings) r = 0;
620 RD(1, "Cannot match event %p", m);
625 /* Second, wake up clients. They will reclaim the event through
627 netmap_generic_irq(na, r, NULL);
633 /* Record completed transmissions and update hwtail.
635 * The oldest tx buffer not yet completed is at nr_hwtail + 1,
636 * nr_hwcur is the first unsent buffer.
639 generic_netmap_tx_clean(struct netmap_kring *kring, int txqdisc)
641 u_int const lim = kring->nkr_num_slots - 1;
642 u_int nm_i = nm_next(kring->nr_hwtail, lim);
643 u_int hwcur = kring->nr_hwcur;
645 struct mbuf **tx_pool = kring->tx_pool;
647 ND("hwcur = %d, hwtail = %d", kring->nr_hwcur, kring->nr_hwtail);
649 while (nm_i != hwcur) { /* buffers not completed */
650 struct mbuf *m = tx_pool[nm_i];
654 /* Nothing to do, this is going
655 * to be replenished. */
656 RD(3, "Is this happening?");
658 } else if (MBUF_QUEUED(m)) {
659 break; /* Not dequeued yet. */
661 } else if (MBUF_REFCNT(m) != 1) {
662 /* This mbuf has been dequeued but is still busy
664 * Leave it to the driver and replenish. */
666 tx_pool[nm_i] = NULL;
670 if (unlikely(m == NULL)) {
673 /* This slot was used to place an event. */
674 mtx_lock_spin(&kring->tx_event_lock);
675 event_consumed = (kring->tx_event == NULL);
676 mtx_unlock_spin(&kring->tx_event_lock);
677 if (!event_consumed) {
678 /* The event has not been consumed yet,
679 * still busy in the driver. */
682 /* The event has been consumed, we can go
685 } else if (MBUF_REFCNT(m) != 1) {
686 /* This mbuf is still busy: its refcnt is 2. */
692 nm_i = nm_next(nm_i, lim);
694 kring->nr_hwtail = nm_prev(nm_i, lim);
695 ND("tx completed [%d] -> hwtail %d", n, kring->nr_hwtail);
700 /* Compute a slot index in the middle between inf and sup. */
702 ring_middle(u_int inf, u_int sup, u_int lim)
709 } else { /* wrap around */
710 e = (sup + n + inf) / 2;
716 if (unlikely(e >= n)) {
717 D("This cannot happen");
725 generic_set_tx_event(struct netmap_kring *kring, u_int hwcur)
727 u_int lim = kring->nkr_num_slots - 1;
730 u_int ntc = nm_next(kring->nr_hwtail, lim); /* next to clean */
733 return; /* all buffers are free */
737 * We have pending packets in the driver between hwtail+1
738 * and hwcur, and we have to chose one of these slot to
739 * generate a notification.
740 * There is a race but this is only called within txsync which
741 * does a double check.
744 /* Choose a slot in the middle, so that we don't risk ending
745 * up in a situation where the client continuously wake up,
746 * fills one or a few TX slots and go to sleep again. */
747 e = ring_middle(ntc, hwcur, lim);
749 /* Choose the first pending slot, to be safe against driver
750 * reordering mbuf transmissions. */
754 m = kring->tx_pool[e];
756 /* An event is already in place. */
760 mtx_lock_spin(&kring->tx_event_lock);
761 if (kring->tx_event) {
762 /* An event is already in place. */
763 mtx_unlock_spin(&kring->tx_event_lock);
767 SET_MBUF_DESTRUCTOR(m, generic_mbuf_destructor);
769 mtx_unlock_spin(&kring->tx_event_lock);
771 kring->tx_pool[e] = NULL;
773 ND(5, "Request Event at %d mbuf %p refcnt %d", e, m, m ? MBUF_REFCNT(m) : -2 );
775 /* Decrement the refcount. This will free it if we lose the race
776 * with the driver. */
783 * generic_netmap_txsync() transforms netmap buffers into mbufs
784 * and passes them to the standard device driver
785 * (ndo_start_xmit() or ifp->if_transmit() ).
786 * On linux this is not done directly, but using dev_queue_xmit(),
787 * since it implements the TX flow control (and takes some locks).
790 generic_netmap_txsync(struct netmap_kring *kring, int flags)
792 struct netmap_adapter *na = kring->na;
793 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na;
794 struct ifnet *ifp = na->ifp;
795 struct netmap_ring *ring = kring->ring;
796 u_int nm_i; /* index into the netmap ring */ // j
797 u_int const lim = kring->nkr_num_slots - 1;
798 u_int const head = kring->rhead;
799 u_int ring_nr = kring->ring_id;
801 IFRATE(rate_ctx.new.txsync++);
806 * First part: process new packets to send.
808 nm_i = kring->nr_hwcur;
809 if (nm_i != head) { /* we have new packets to send */
810 struct nm_os_gen_arg a;
813 if (gna->txqdisc && nm_kr_txempty(kring)) {
814 /* In txqdisc mode, we ask for a delayed notification,
815 * but only when cur == hwtail, which means that the
816 * client is going to block. */
817 event = ring_middle(nm_i, head, lim);
818 ND(3, "Place txqdisc event (hwcur=%u,event=%u,"
819 "head=%u,hwtail=%u)", nm_i, event, head,
825 a.head = a.tail = NULL;
827 while (nm_i != head) {
828 struct netmap_slot *slot = &ring->slot[nm_i];
829 u_int len = slot->len;
830 void *addr = NMB(na, slot);
831 /* device-specific */
835 NM_CHECK_ADDR_LEN(na, addr, len);
837 /* Tale a mbuf from the tx pool (replenishing the pool
838 * entry if necessary) and copy in the user packet. */
839 m = kring->tx_pool[nm_i];
840 if (unlikely(m == NULL)) {
841 kring->tx_pool[nm_i] = m =
842 nm_os_get_mbuf(ifp, NETMAP_BUF_SIZE(na));
844 RD(2, "Failed to replenish mbuf");
845 /* Here we could schedule a timer which
846 * retries to replenish after a while,
847 * and notifies the client when it
848 * manages to replenish some slots. In
849 * any case we break early to avoid
853 IFRATE(rate_ctx.new.txrepl++);
859 a.qevent = (nm_i == event);
860 /* When not in txqdisc mode, we should ask
861 * notifications when NS_REPORT is set, or roughly
862 * every half ring. To optimize this, we set a
863 * notification event when the client runs out of
864 * TX ring space, or when transmission fails. In
865 * the latter case we also break early.
867 tx_ret = nm_os_generic_xmit_frame(&a);
868 if (unlikely(tx_ret)) {
871 * No room for this mbuf in the device driver.
872 * Request a notification FOR A PREVIOUS MBUF,
873 * then call generic_netmap_tx_clean(kring) to do the
874 * double check and see if we can free more buffers.
875 * If there is space continue, else break;
876 * NOTE: the double check is necessary if the problem
877 * occurs in the txsync call after selrecord().
878 * Also, we need some way to tell the caller that not
879 * all buffers were queued onto the device (this was
880 * not a problem with native netmap driver where space
881 * is preallocated). The bridge has a similar problem
882 * and we solve it there by dropping the excess packets.
884 generic_set_tx_event(kring, nm_i);
885 if (generic_netmap_tx_clean(kring, gna->txqdisc)) {
886 /* space now available */
893 /* In txqdisc mode, the netmap-aware qdisc
894 * queue has the same length as the number of
895 * netmap slots (N). Since tail is advanced
896 * only when packets are dequeued, qdisc
897 * queue overrun cannot happen, so
898 * nm_os_generic_xmit_frame() did not fail
900 * However, packets can be dropped because
901 * carrier is off, or because our qdisc is
902 * being deactivated, or possibly for other
903 * reasons. In these cases, we just let the
904 * packet to be dropped. */
905 IFRATE(rate_ctx.new.txdrop++);
908 slot->flags &= ~(NS_REPORT | NS_BUF_CHANGED);
909 nm_i = nm_next(nm_i, lim);
910 IFRATE(rate_ctx.new.txpkt++);
912 if (a.head != NULL) {
914 nm_os_generic_xmit_frame(&a);
916 /* Update hwcur to the next slot to transmit. Here nm_i
917 * is not necessarily head, we could break early. */
918 kring->nr_hwcur = nm_i;
922 * Second, reclaim completed buffers
924 if (!gna->txqdisc && (flags & NAF_FORCE_RECLAIM || nm_kr_txempty(kring))) {
925 /* No more available slots? Set a notification event
926 * on a netmap slot that will be cleaned in the future.
927 * No doublecheck is performed, since txsync() will be
928 * called twice by netmap_poll().
930 generic_set_tx_event(kring, nm_i);
933 generic_netmap_tx_clean(kring, gna->txqdisc);
940 * This handler is registered (through nm_os_catch_rx())
941 * within the attached network interface
942 * in the RX subsystem, so that every mbuf passed up by
943 * the driver can be stolen to the network stack.
944 * Stolen packets are put in a queue where the
945 * generic_netmap_rxsync() callback can extract them.
946 * Returns 1 if the packet was stolen, 0 otherwise.
949 generic_rx_handler(struct ifnet *ifp, struct mbuf *m)
951 struct netmap_adapter *na = NA(ifp);
952 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na;
953 struct netmap_kring *kring;
955 u_int r = MBUF_RXQ(m); /* receive ring number */
957 if (r >= na->num_rx_rings) {
958 r = r % na->num_rx_rings;
961 kring = &na->rx_rings[r];
963 if (kring->nr_mode == NKR_NETMAP_OFF) {
964 /* We must not intercept this mbuf. */
968 /* limit the size of the queue */
969 if (unlikely(!gna->rxsg && MBUF_LEN(m) > NETMAP_BUF_SIZE(na))) {
970 /* This may happen when GRO/LRO features are enabled for
971 * the NIC driver when the generic adapter does not
972 * support RX scatter-gather. */
973 RD(2, "Warning: driver pushed up big packet "
974 "(size=%d)", (int)MBUF_LEN(m));
976 } else if (unlikely(mbq_len(&kring->rx_queue) > 1024)) {
979 mbq_safe_enqueue(&kring->rx_queue, m);
982 if (netmap_generic_mit < 32768) {
983 /* no rx mitigation, pass notification up */
984 netmap_generic_irq(na, r, &work_done);
986 /* same as send combining, filter notification if there is a
987 * pending timer, otherwise pass it up and start a timer.
989 if (likely(nm_os_mitigation_active(&gna->mit[r]))) {
990 /* Record that there is some pending work. */
991 gna->mit[r].mit_pending = 1;
993 netmap_generic_irq(na, r, &work_done);
994 nm_os_mitigation_start(&gna->mit[r]);
998 /* We have intercepted the mbuf. */
1003 * generic_netmap_rxsync() extracts mbufs from the queue filled by
1004 * generic_netmap_rx_handler() and puts their content in the netmap
1006 * Access must be protected because the rx handler is asynchronous,
1009 generic_netmap_rxsync(struct netmap_kring *kring, int flags)
1011 struct netmap_ring *ring = kring->ring;
1012 struct netmap_adapter *na = kring->na;
1013 u_int nm_i; /* index into the netmap ring */ //j,
1015 u_int const lim = kring->nkr_num_slots - 1;
1016 u_int const head = kring->rhead;
1017 int force_update = (flags & NAF_FORCE_READ) || kring->nr_kflags & NKR_PENDINTR;
1019 /* Adapter-specific variables. */
1020 uint16_t slot_flags = kring->nkr_slot_flags;
1021 u_int nm_buf_len = NETMAP_BUF_SIZE(na);
1024 int avail; /* in bytes */
1029 return netmap_ring_reinit(kring);
1031 IFRATE(rate_ctx.new.rxsync++);
1034 * First part: skip past packets that userspace has released.
1035 * This can possibly make room for the second part.
1037 nm_i = kring->nr_hwcur;
1039 /* Userspace has released some packets. */
1040 for (n = 0; nm_i != head; n++) {
1041 struct netmap_slot *slot = &ring->slot[nm_i];
1043 slot->flags &= ~NS_BUF_CHANGED;
1044 nm_i = nm_next(nm_i, lim);
1046 kring->nr_hwcur = head;
1050 * Second part: import newly received packets.
1052 if (!netmap_no_pendintr && !force_update) {
1056 nm_i = kring->nr_hwtail; /* First empty slot in the receive ring. */
1058 /* Compute the available space (in bytes) in this netmap ring.
1059 * The first slot that is not considered in is the one before
1062 avail = nm_prev(kring->nr_hwcur, lim) - nm_i;
1065 avail *= nm_buf_len;
1067 /* First pass: While holding the lock on the RX mbuf queue,
1068 * extract as many mbufs as they fit the available space,
1069 * and put them in a temporary queue.
1070 * To avoid performing a per-mbuf division (mlen / nm_buf_len) to
1071 * to update avail, we do the update in a while loop that we
1072 * also use to set the RX slots, but without performing the copy. */
1074 mbq_lock(&kring->rx_queue);
1076 m = mbq_peek(&kring->rx_queue);
1078 /* No more packets from the driver. */
1084 /* No more space in the ring. */
1088 mbq_dequeue(&kring->rx_queue);
1096 avail -= nm_buf_len;
1098 ring->slot[nm_i].len = copy;
1099 ring->slot[nm_i].flags = slot_flags | (mlen ? NS_MOREFRAG : 0);
1100 nm_i = nm_next(nm_i, lim);
1103 mbq_enqueue(&tmpq, m);
1105 mbq_unlock(&kring->rx_queue);
1107 /* Second pass: Drain the temporary queue, going over the used RX slots,
1108 * and perform the copy out of the RX queue lock. */
1109 nm_i = kring->nr_hwtail;
1116 m = mbq_dequeue(&tmpq);
1122 nmaddr = NMB(na, &ring->slot[nm_i]);
1123 /* We only check the address here on generic rx rings. */
1124 if (nmaddr == NETMAP_BUF_BASE(na)) { /* Bad buffer */
1128 return netmap_ring_reinit(kring);
1131 copy = ring->slot[nm_i].len;
1132 m_copydata(m, ofs, copy, nmaddr);
1134 morefrag = ring->slot[nm_i].flags & NS_MOREFRAG;
1135 nm_i = nm_next(nm_i, lim);
1144 kring->nr_hwtail = nm_i;
1145 IFRATE(rate_ctx.new.rxpkt += n);
1147 kring->nr_kflags &= ~NKR_PENDINTR;
1153 generic_netmap_dtor(struct netmap_adapter *na)
1155 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter*)na;
1156 struct ifnet *ifp = netmap_generic_getifp(gna);
1157 struct netmap_adapter *prev_na = gna->prev;
1159 if (prev_na != NULL) {
1160 netmap_adapter_put(prev_na);
1161 if (nm_iszombie(na)) {
1163 * The driver has been removed without releasing
1164 * the reference so we need to do it here.
1166 netmap_adapter_put(prev_na);
1168 D("Native netmap adapter %p restored", prev_na);
1170 NM_ATTACH_NA(ifp, prev_na);
1172 * netmap_detach_common(), that it's called after this function,
1173 * overrides WNA(ifp) if na->ifp is not NULL.
1176 D("Emulated netmap adapter for %s destroyed", na->name);
1180 na_is_generic(struct netmap_adapter *na)
1182 return na->nm_register == generic_netmap_register;
1186 * generic_netmap_attach() makes it possible to use netmap on
1187 * a device without native netmap support.
1188 * This is less performant than native support but potentially
1189 * faster than raw sockets or similar schemes.
1191 * In this "emulated" mode, netmap rings do not necessarily
1192 * have the same size as those in the NIC. We use a default
1193 * value and possibly override it if the OS has ways to fetch the
1194 * actual configuration.
1197 generic_netmap_attach(struct ifnet *ifp)
1199 struct netmap_adapter *na;
1200 struct netmap_generic_adapter *gna;
1202 u_int num_tx_desc, num_rx_desc;
1205 if (ifp->if_type == IFT_LOOP) {
1206 D("if_loop is not supported by %s", __func__);
1211 num_tx_desc = num_rx_desc = netmap_generic_ringsize; /* starting point */
1213 nm_os_generic_find_num_desc(ifp, &num_tx_desc, &num_rx_desc); /* ignore errors */
1214 ND("Netmap ring size: TX = %d, RX = %d", num_tx_desc, num_rx_desc);
1215 if (num_tx_desc == 0 || num_rx_desc == 0) {
1216 D("Device has no hw slots (tx %u, rx %u)", num_tx_desc, num_rx_desc);
1220 gna = nm_os_malloc(sizeof(*gna));
1222 D("no memory on attach, give up");
1225 na = (struct netmap_adapter *)gna;
1226 strncpy(na->name, ifp->if_xname, sizeof(na->name));
1228 na->num_tx_desc = num_tx_desc;
1229 na->num_rx_desc = num_rx_desc;
1230 na->nm_register = &generic_netmap_register;
1231 na->nm_txsync = &generic_netmap_txsync;
1232 na->nm_rxsync = &generic_netmap_rxsync;
1233 na->nm_dtor = &generic_netmap_dtor;
1234 /* when using generic, NAF_NETMAP_ON is set so we force
1235 * NAF_SKIP_INTR to use the regular interrupt handler
1237 na->na_flags = NAF_SKIP_INTR | NAF_HOST_RINGS;
1239 ND("[GNA] num_tx_queues(%d), real_num_tx_queues(%d), len(%lu)",
1240 ifp->num_tx_queues, ifp->real_num_tx_queues,
1242 ND("[GNA] num_rx_queues(%d), real_num_rx_queues(%d)",
1243 ifp->num_rx_queues, ifp->real_num_rx_queues);
1245 nm_os_generic_find_num_queues(ifp, &na->num_tx_rings, &na->num_rx_rings);
1247 retval = netmap_attach_common(na);
1253 gna->prev = NA(ifp); /* save old na */
1254 if (gna->prev != NULL) {
1255 netmap_adapter_get(gna->prev);
1257 NM_ATTACH_NA(ifp, na);
1259 nm_os_generic_set_features(gna);
1261 D("Emulated adapter for %s created (prev was %p)", na->name, gna->prev);