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 MBUF_RXQ(m) ((m)->m_pkthdr.flowid)
93 * FreeBSD mbuf allocator/deallocator in emulation mode:
95 #if __FreeBSD_version < 1100000
98 * For older versions of FreeBSD:
100 * We allocate EXT_PACKET mbuf+clusters, but need to set M_NOFREE
101 * so that the destructor, if invoked, will not free the packet.
102 * In principle we should set the destructor only on demand,
103 * but since there might be a race we better do it on allocation.
104 * As a consequence, we also need to set the destructor or we
105 * would leak buffers.
108 /* mbuf destructor, also need to change the type to EXT_EXTREF,
109 * add an M_NOFREE flag, and then clear the flag and
110 * chain into uma_zfree(zone_pack, mf)
111 * (or reinstall the buffer ?)
113 #define SET_MBUF_DESTRUCTOR(m, fn) do { \
114 (m)->m_ext.ext_free = (void *)fn; \
115 (m)->m_ext.ext_type = EXT_EXTREF; \
119 void_mbuf_dtor(struct mbuf *m, void *arg1, void *arg2)
121 /* restore original mbuf */
122 m->m_ext.ext_buf = m->m_data = m->m_ext.ext_arg1;
123 m->m_ext.ext_arg1 = NULL;
124 m->m_ext.ext_type = EXT_PACKET;
125 m->m_ext.ext_free = NULL;
126 if (MBUF_REFCNT(m) == 0)
127 SET_MBUF_REFCNT(m, 1);
128 uma_zfree(zone_pack, m);
133 static inline struct mbuf *
134 nm_os_get_mbuf(struct ifnet *ifp, int len)
139 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
141 /* m_getcl() (mb_ctor_mbuf) has an assert that checks that
142 * M_NOFREE flag is not specified as third argument,
143 * so we have to set M_NOFREE after m_getcl(). */
144 m->m_flags |= M_NOFREE;
145 m->m_ext.ext_arg1 = m->m_ext.ext_buf; // XXX save
146 m->m_ext.ext_free = (void *)void_mbuf_dtor;
147 m->m_ext.ext_type = EXT_EXTREF;
148 ND(5, "create m %p refcnt %d", m, MBUF_REFCNT(m));
153 #else /* __FreeBSD_version >= 1100000 */
156 * Newer versions of FreeBSD, using a straightforward scheme.
158 * We allocate mbufs with m_gethdr(), since the mbuf header is needed
159 * by the driver. We also attach a customly-provided external storage,
160 * which in this case is a netmap buffer. When calling m_extadd(), however
161 * we pass a NULL address, since the real address (and length) will be
162 * filled in by nm_os_generic_xmit_frame() right before calling
165 * The dtor function does nothing, however we need it since mb_free_ext()
166 * has a KASSERT(), checking that the mbuf dtor function is not NULL.
169 #if __FreeBSD_version <= 1200050
170 static void void_mbuf_dtor(struct mbuf *m, void *arg1, void *arg2) { }
171 #else /* __FreeBSD_version >= 1200051 */
172 /* The arg1 and arg2 pointers argument were removed by r324446, which
173 * in included since version 1200051. */
174 static void void_mbuf_dtor(struct mbuf *m) { }
175 #endif /* __FreeBSD_version >= 1200051 */
177 #define SET_MBUF_DESTRUCTOR(m, fn) do { \
178 (m)->m_ext.ext_free = (fn != NULL) ? \
179 (void *)fn : (void *)void_mbuf_dtor; \
182 static inline struct mbuf *
183 nm_os_get_mbuf(struct ifnet *ifp, int len)
190 m = m_gethdr(M_NOWAIT, MT_DATA);
195 m_extadd(m, NULL /* buf */, 0 /* size */, void_mbuf_dtor,
196 NULL, NULL, 0, EXT_NET_DRV);
201 #endif /* __FreeBSD_version >= 1100000 */
205 #include "win_glue.h"
207 #define MBUF_TXQ(m) 0//((m)->m_pkthdr.flowid)
208 #define MBUF_RXQ(m) 0//((m)->m_pkthdr.flowid)
209 #define smp_mb() //XXX: to be correctly defined
213 #include "bsd_glue.h"
215 #include <linux/ethtool.h> /* struct ethtool_ops, get_ringparam */
216 #include <linux/hrtimer.h>
218 static inline struct mbuf *
219 nm_os_get_mbuf(struct ifnet *ifp, int len)
221 return alloc_skb(ifp->needed_headroom + len +
222 ifp->needed_tailroom, GFP_ATOMIC);
228 /* Common headers. */
229 #include <net/netmap.h>
230 #include <dev/netmap/netmap_kern.h>
231 #include <dev/netmap/netmap_mem2.h>
234 #define for_each_kring_n(_i, _k, _karr, _n) \
235 for ((_k)=*(_karr), (_i) = 0; (_i) < (_n); (_i)++, (_k) = (_karr)[(_i)])
237 #define for_each_tx_kring(_i, _k, _na) \
238 for_each_kring_n(_i, _k, (_na)->tx_rings, (_na)->num_tx_rings)
239 #define for_each_tx_kring_h(_i, _k, _na) \
240 for_each_kring_n(_i, _k, (_na)->tx_rings, (_na)->num_tx_rings + 1)
242 #define for_each_rx_kring(_i, _k, _na) \
243 for_each_kring_n(_i, _k, (_na)->rx_rings, (_na)->num_rx_rings)
244 #define for_each_rx_kring_h(_i, _k, _na) \
245 for_each_kring_n(_i, _k, (_na)->rx_rings, (_na)->num_rx_rings + 1)
248 /* ======================== PERFORMANCE STATISTICS =========================== */
254 unsigned long txsync;
256 unsigned long txrepl;
257 unsigned long txdrop;
260 unsigned long rxsync;
263 struct rate_context {
265 struct timer_list timer;
266 struct rate_stats new;
267 struct rate_stats old;
270 #define RATE_PRINTK(_NAME_) \
271 printk( #_NAME_ " = %lu Hz\n", (cur._NAME_ - ctx->old._NAME_)/RATE_PERIOD);
272 #define RATE_PERIOD 2
273 static void rate_callback(unsigned long arg)
275 struct rate_context * ctx = (struct rate_context *)arg;
276 struct rate_stats cur = ctx->new;
290 r = mod_timer(&ctx->timer, jiffies +
291 msecs_to_jiffies(RATE_PERIOD * 1000));
293 D("[v1000] Error: mod_timer()");
296 static struct rate_context rate_ctx;
298 void generic_rate(int txp, int txs, int txi, int rxp, int rxs, int rxi)
300 if (txp) rate_ctx.new.txpkt++;
301 if (txs) rate_ctx.new.txsync++;
302 if (txi) rate_ctx.new.txirq++;
303 if (rxp) rate_ctx.new.rxpkt++;
304 if (rxs) rate_ctx.new.rxsync++;
305 if (rxi) rate_ctx.new.rxirq++;
313 /* ========== GENERIC (EMULATED) NETMAP ADAPTER SUPPORT ============= */
316 * Wrapper used by the generic adapter layer to notify
317 * the poller threads. Differently from netmap_rx_irq(), we check
318 * only NAF_NETMAP_ON instead of NAF_NATIVE_ON to enable the irq.
321 netmap_generic_irq(struct netmap_adapter *na, u_int q, u_int *work_done)
323 if (unlikely(!nm_netmap_on(na)))
326 netmap_common_irq(na, q, work_done);
329 rate_ctx.new.rxirq++;
331 rate_ctx.new.txirq++;
332 #endif /* RATE_GENERIC */
336 generic_netmap_unregister(struct netmap_adapter *na)
338 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na;
339 struct netmap_kring *kring = NULL;
342 if (na->active_fds == 0) {
343 na->na_flags &= ~NAF_NETMAP_ON;
345 /* Stop intercepting packets on the RX path. */
346 nm_os_catch_rx(gna, 0);
348 /* Release packet steering control. */
349 nm_os_catch_tx(gna, 0);
352 for_each_rx_kring_h(r, kring, na) {
353 if (nm_kring_pending_off(kring)) {
354 D("Emulated adapter: ring '%s' deactivated", kring->name);
355 kring->nr_mode = NKR_NETMAP_OFF;
358 for_each_tx_kring_h(r, kring, na) {
359 if (nm_kring_pending_off(kring)) {
360 kring->nr_mode = NKR_NETMAP_OFF;
361 D("Emulated adapter: ring '%s' deactivated", kring->name);
365 for_each_rx_kring(r, kring, na) {
366 /* Free the mbufs still pending in the RX queues,
367 * that did not end up into the corresponding netmap
369 mbq_safe_purge(&kring->rx_queue);
370 nm_os_mitigation_cleanup(&gna->mit[r]);
373 /* Decrement reference counter for the mbufs in the
374 * TX pools. These mbufs can be still pending in drivers,
375 * (e.g. this happens with virtio-net driver, which
376 * does lazy reclaiming of transmitted mbufs). */
377 for_each_tx_kring(r, kring, na) {
378 /* We must remove the destructor on the TX event,
379 * because the destructor invokes netmap code, and
380 * the netmap module may disappear before the
381 * TX event is consumed. */
382 mtx_lock_spin(&kring->tx_event_lock);
383 if (kring->tx_event) {
384 SET_MBUF_DESTRUCTOR(kring->tx_event, NULL);
386 kring->tx_event = NULL;
387 mtx_unlock_spin(&kring->tx_event_lock);
390 if (na->active_fds == 0) {
391 nm_os_free(gna->mit);
393 for_each_rx_kring(r, kring, na) {
394 mbq_safe_fini(&kring->rx_queue);
397 for_each_tx_kring(r, kring, na) {
398 mtx_destroy(&kring->tx_event_lock);
399 if (kring->tx_pool == NULL) {
403 for (i=0; i<na->num_tx_desc; i++) {
404 if (kring->tx_pool[i]) {
405 m_freem(kring->tx_pool[i]);
408 nm_os_free(kring->tx_pool);
409 kring->tx_pool = NULL;
413 if (--rate_ctx.refcount == 0) {
415 del_timer(&rate_ctx.timer);
418 D("Emulated adapter for %s deactivated", na->name);
424 /* Enable/disable netmap mode for a generic network interface. */
426 generic_netmap_register(struct netmap_adapter *na, int enable)
428 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na;
429 struct netmap_kring *kring = NULL;
438 /* This is actually an unregif. */
439 return generic_netmap_unregister(na);
442 if (na->active_fds == 0) {
443 D("Emulated adapter for %s activated", na->name);
444 /* Do all memory allocations when (na->active_fds == 0), to
445 * simplify error management. */
447 /* Allocate memory for mitigation support on all the rx queues. */
448 gna->mit = nm_os_malloc(na->num_rx_rings * sizeof(struct nm_generic_mit));
450 D("mitigation allocation failed");
455 for_each_rx_kring(r, kring, na) {
456 /* Init mitigation support. */
457 nm_os_mitigation_init(&gna->mit[r], r, na);
459 /* Initialize the rx queue, as generic_rx_handler() can
460 * be called as soon as nm_os_catch_rx() returns.
462 mbq_safe_init(&kring->rx_queue);
466 * Prepare mbuf pools (parallel to the tx rings), for packet
467 * transmission. Don't preallocate the mbufs here, it's simpler
468 * to leave this task to txsync.
470 for_each_tx_kring(r, kring, na) {
471 kring->tx_pool = NULL;
473 for_each_tx_kring(r, kring, na) {
475 nm_os_malloc(na->num_tx_desc * sizeof(struct mbuf *));
476 if (!kring->tx_pool) {
477 D("tx_pool allocation failed");
481 mtx_init(&kring->tx_event_lock, "tx_event_lock",
486 for_each_rx_kring_h(r, kring, na) {
487 if (nm_kring_pending_on(kring)) {
488 D("Emulated adapter: ring '%s' activated", kring->name);
489 kring->nr_mode = NKR_NETMAP_ON;
493 for_each_tx_kring_h(r, kring, na) {
494 if (nm_kring_pending_on(kring)) {
495 D("Emulated adapter: ring '%s' activated", kring->name);
496 kring->nr_mode = NKR_NETMAP_ON;
500 for_each_tx_kring(r, kring, na) {
501 /* Initialize tx_pool and tx_event. */
502 for (i=0; i<na->num_tx_desc; i++) {
503 kring->tx_pool[i] = NULL;
506 kring->tx_event = NULL;
509 if (na->active_fds == 0) {
510 /* Prepare to intercept incoming traffic. */
511 error = nm_os_catch_rx(gna, 1);
513 D("nm_os_catch_rx(1) failed (%d)", error);
517 /* Let netmap control the packet steering. */
518 error = nm_os_catch_tx(gna, 1);
520 D("nm_os_catch_tx(1) failed (%d)", error);
524 na->na_flags |= NAF_NETMAP_ON;
527 if (rate_ctx.refcount == 0) {
529 memset(&rate_ctx, 0, sizeof(rate_ctx));
530 setup_timer(&rate_ctx.timer, &rate_callback, (unsigned long)&rate_ctx);
531 if (mod_timer(&rate_ctx.timer, jiffies + msecs_to_jiffies(1500))) {
532 D("Error: mod_timer()");
541 /* Here (na->active_fds == 0) holds. */
543 nm_os_catch_rx(gna, 0);
545 for_each_tx_kring(r, kring, na) {
546 mtx_destroy(&kring->tx_event_lock);
547 if (kring->tx_pool == NULL) {
550 nm_os_free(kring->tx_pool);
551 kring->tx_pool = NULL;
553 for_each_rx_kring(r, kring, na) {
554 mbq_safe_fini(&kring->rx_queue);
556 nm_os_free(gna->mit);
563 * Callback invoked when the device driver frees an mbuf used
564 * by netmap to transmit a packet. This usually happens when
565 * the NIC notifies the driver that transmission is completed.
568 generic_mbuf_destructor(struct mbuf *m)
570 struct netmap_adapter *na = NA(GEN_TX_MBUF_IFP(m));
571 struct netmap_kring *kring;
572 unsigned int r = MBUF_TXQ(m);
573 unsigned int r_orig = r;
575 if (unlikely(!nm_netmap_on(na) || r >= na->num_tx_rings)) {
576 D("Error: no netmap adapter on device %p",
582 * First, clear the event mbuf.
583 * In principle, the event 'm' should match the one stored
584 * on ring 'r'. However we check it explicitely to stay
585 * safe against lower layers (qdisc, driver, etc.) changing
586 * MBUF_TXQ(m) under our feet. If the match is not found
587 * on 'r', we try to see if it belongs to some other ring.
592 kring = na->tx_rings[r];
593 mtx_lock_spin(&kring->tx_event_lock);
594 if (kring->tx_event == m) {
595 kring->tx_event = NULL;
598 mtx_unlock_spin(&kring->tx_event_lock);
602 RD(1, "event %p migrated: ring %u --> %u",
608 if (++r == na->num_tx_rings) r = 0;
611 RD(1, "Cannot match event %p", m);
616 /* Second, wake up clients. They will reclaim the event through
618 netmap_generic_irq(na, r, NULL);
620 #if __FreeBSD_version <= 1200050
621 void_mbuf_dtor(m, NULL, NULL);
622 #else /* __FreeBSD_version >= 1200051 */
624 #endif /* __FreeBSD_version >= 1200051 */
628 /* Record completed transmissions and update hwtail.
630 * The oldest tx buffer not yet completed is at nr_hwtail + 1,
631 * nr_hwcur is the first unsent buffer.
634 generic_netmap_tx_clean(struct netmap_kring *kring, int txqdisc)
636 u_int const lim = kring->nkr_num_slots - 1;
637 u_int nm_i = nm_next(kring->nr_hwtail, lim);
638 u_int hwcur = kring->nr_hwcur;
640 struct mbuf **tx_pool = kring->tx_pool;
642 ND("hwcur = %d, hwtail = %d", kring->nr_hwcur, kring->nr_hwtail);
644 while (nm_i != hwcur) { /* buffers not completed */
645 struct mbuf *m = tx_pool[nm_i];
649 /* Nothing to do, this is going
650 * to be replenished. */
651 RD(3, "Is this happening?");
653 } else if (MBUF_QUEUED(m)) {
654 break; /* Not dequeued yet. */
656 } else if (MBUF_REFCNT(m) != 1) {
657 /* This mbuf has been dequeued but is still busy
659 * Leave it to the driver and replenish. */
661 tx_pool[nm_i] = NULL;
665 if (unlikely(m == NULL)) {
668 /* This slot was used to place an event. */
669 mtx_lock_spin(&kring->tx_event_lock);
670 event_consumed = (kring->tx_event == NULL);
671 mtx_unlock_spin(&kring->tx_event_lock);
672 if (!event_consumed) {
673 /* The event has not been consumed yet,
674 * still busy in the driver. */
677 /* The event has been consumed, we can go
680 } else if (MBUF_REFCNT(m) != 1) {
681 /* This mbuf is still busy: its refcnt is 2. */
687 nm_i = nm_next(nm_i, lim);
689 kring->nr_hwtail = nm_prev(nm_i, lim);
690 ND("tx completed [%d] -> hwtail %d", n, kring->nr_hwtail);
695 /* Compute a slot index in the middle between inf and sup. */
697 ring_middle(u_int inf, u_int sup, u_int lim)
704 } else { /* wrap around */
705 e = (sup + n + inf) / 2;
711 if (unlikely(e >= n)) {
712 D("This cannot happen");
720 generic_set_tx_event(struct netmap_kring *kring, u_int hwcur)
722 u_int lim = kring->nkr_num_slots - 1;
725 u_int ntc = nm_next(kring->nr_hwtail, lim); /* next to clean */
728 return; /* all buffers are free */
732 * We have pending packets in the driver between hwtail+1
733 * and hwcur, and we have to chose one of these slot to
734 * generate a notification.
735 * There is a race but this is only called within txsync which
736 * does a double check.
739 /* Choose a slot in the middle, so that we don't risk ending
740 * up in a situation where the client continuously wake up,
741 * fills one or a few TX slots and go to sleep again. */
742 e = ring_middle(ntc, hwcur, lim);
744 /* Choose the first pending slot, to be safe against driver
745 * reordering mbuf transmissions. */
749 m = kring->tx_pool[e];
751 /* An event is already in place. */
755 mtx_lock_spin(&kring->tx_event_lock);
756 if (kring->tx_event) {
757 /* An event is already in place. */
758 mtx_unlock_spin(&kring->tx_event_lock);
762 SET_MBUF_DESTRUCTOR(m, generic_mbuf_destructor);
764 mtx_unlock_spin(&kring->tx_event_lock);
766 kring->tx_pool[e] = NULL;
768 ND(5, "Request Event at %d mbuf %p refcnt %d", e, m, m ? MBUF_REFCNT(m) : -2 );
770 /* Decrement the refcount. This will free it if we lose the race
771 * with the driver. */
778 * generic_netmap_txsync() transforms netmap buffers into mbufs
779 * and passes them to the standard device driver
780 * (ndo_start_xmit() or ifp->if_transmit() ).
781 * On linux this is not done directly, but using dev_queue_xmit(),
782 * since it implements the TX flow control (and takes some locks).
785 generic_netmap_txsync(struct netmap_kring *kring, int flags)
787 struct netmap_adapter *na = kring->na;
788 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na;
789 struct ifnet *ifp = na->ifp;
790 struct netmap_ring *ring = kring->ring;
791 u_int nm_i; /* index into the netmap ring */ // j
792 u_int const lim = kring->nkr_num_slots - 1;
793 u_int const head = kring->rhead;
794 u_int ring_nr = kring->ring_id;
796 IFRATE(rate_ctx.new.txsync++);
801 * First part: process new packets to send.
803 nm_i = kring->nr_hwcur;
804 if (nm_i != head) { /* we have new packets to send */
805 struct nm_os_gen_arg a;
808 if (gna->txqdisc && nm_kr_txempty(kring)) {
809 /* In txqdisc mode, we ask for a delayed notification,
810 * but only when cur == hwtail, which means that the
811 * client is going to block. */
812 event = ring_middle(nm_i, head, lim);
813 ND(3, "Place txqdisc event (hwcur=%u,event=%u,"
814 "head=%u,hwtail=%u)", nm_i, event, head,
820 a.head = a.tail = NULL;
822 while (nm_i != head) {
823 struct netmap_slot *slot = &ring->slot[nm_i];
824 u_int len = slot->len;
825 void *addr = NMB(na, slot);
826 /* device-specific */
830 NM_CHECK_ADDR_LEN(na, addr, len);
832 /* Tale a mbuf from the tx pool (replenishing the pool
833 * entry if necessary) and copy in the user packet. */
834 m = kring->tx_pool[nm_i];
835 if (unlikely(m == NULL)) {
836 kring->tx_pool[nm_i] = m =
837 nm_os_get_mbuf(ifp, NETMAP_BUF_SIZE(na));
839 RD(2, "Failed to replenish mbuf");
840 /* Here we could schedule a timer which
841 * retries to replenish after a while,
842 * and notifies the client when it
843 * manages to replenish some slots. In
844 * any case we break early to avoid
848 IFRATE(rate_ctx.new.txrepl++);
854 a.qevent = (nm_i == event);
855 /* When not in txqdisc mode, we should ask
856 * notifications when NS_REPORT is set, or roughly
857 * every half ring. To optimize this, we set a
858 * notification event when the client runs out of
859 * TX ring space, or when transmission fails. In
860 * the latter case we also break early.
862 tx_ret = nm_os_generic_xmit_frame(&a);
863 if (unlikely(tx_ret)) {
866 * No room for this mbuf in the device driver.
867 * Request a notification FOR A PREVIOUS MBUF,
868 * then call generic_netmap_tx_clean(kring) to do the
869 * double check and see if we can free more buffers.
870 * If there is space continue, else break;
871 * NOTE: the double check is necessary if the problem
872 * occurs in the txsync call after selrecord().
873 * Also, we need some way to tell the caller that not
874 * all buffers were queued onto the device (this was
875 * not a problem with native netmap driver where space
876 * is preallocated). The bridge has a similar problem
877 * and we solve it there by dropping the excess packets.
879 generic_set_tx_event(kring, nm_i);
880 if (generic_netmap_tx_clean(kring, gna->txqdisc)) {
881 /* space now available */
888 /* In txqdisc mode, the netmap-aware qdisc
889 * queue has the same length as the number of
890 * netmap slots (N). Since tail is advanced
891 * only when packets are dequeued, qdisc
892 * queue overrun cannot happen, so
893 * nm_os_generic_xmit_frame() did not fail
895 * However, packets can be dropped because
896 * carrier is off, or because our qdisc is
897 * being deactivated, or possibly for other
898 * reasons. In these cases, we just let the
899 * packet to be dropped. */
900 IFRATE(rate_ctx.new.txdrop++);
903 slot->flags &= ~(NS_REPORT | NS_BUF_CHANGED);
904 nm_i = nm_next(nm_i, lim);
905 IFRATE(rate_ctx.new.txpkt++);
907 if (a.head != NULL) {
909 nm_os_generic_xmit_frame(&a);
911 /* Update hwcur to the next slot to transmit. Here nm_i
912 * is not necessarily head, we could break early. */
913 kring->nr_hwcur = nm_i;
917 * Second, reclaim completed buffers
919 if (!gna->txqdisc && (flags & NAF_FORCE_RECLAIM || nm_kr_txempty(kring))) {
920 /* No more available slots? Set a notification event
921 * on a netmap slot that will be cleaned in the future.
922 * No doublecheck is performed, since txsync() will be
923 * called twice by netmap_poll().
925 generic_set_tx_event(kring, nm_i);
928 generic_netmap_tx_clean(kring, gna->txqdisc);
935 * This handler is registered (through nm_os_catch_rx())
936 * within the attached network interface
937 * in the RX subsystem, so that every mbuf passed up by
938 * the driver can be stolen to the network stack.
939 * Stolen packets are put in a queue where the
940 * generic_netmap_rxsync() callback can extract them.
941 * Returns 1 if the packet was stolen, 0 otherwise.
944 generic_rx_handler(struct ifnet *ifp, struct mbuf *m)
946 struct netmap_adapter *na = NA(ifp);
947 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na;
948 struct netmap_kring *kring;
950 u_int r = MBUF_RXQ(m); /* receive ring number */
952 if (r >= na->num_rx_rings) {
953 r = r % na->num_rx_rings;
956 kring = na->rx_rings[r];
958 if (kring->nr_mode == NKR_NETMAP_OFF) {
959 /* We must not intercept this mbuf. */
963 /* limit the size of the queue */
964 if (unlikely(!gna->rxsg && MBUF_LEN(m) > NETMAP_BUF_SIZE(na))) {
965 /* This may happen when GRO/LRO features are enabled for
966 * the NIC driver when the generic adapter does not
967 * support RX scatter-gather. */
968 RD(2, "Warning: driver pushed up big packet "
969 "(size=%d)", (int)MBUF_LEN(m));
971 } else if (unlikely(mbq_len(&kring->rx_queue) > 1024)) {
974 mbq_safe_enqueue(&kring->rx_queue, m);
977 if (netmap_generic_mit < 32768) {
978 /* no rx mitigation, pass notification up */
979 netmap_generic_irq(na, r, &work_done);
981 /* same as send combining, filter notification if there is a
982 * pending timer, otherwise pass it up and start a timer.
984 if (likely(nm_os_mitigation_active(&gna->mit[r]))) {
985 /* Record that there is some pending work. */
986 gna->mit[r].mit_pending = 1;
988 netmap_generic_irq(na, r, &work_done);
989 nm_os_mitigation_start(&gna->mit[r]);
993 /* We have intercepted the mbuf. */
998 * generic_netmap_rxsync() extracts mbufs from the queue filled by
999 * generic_netmap_rx_handler() and puts their content in the netmap
1001 * Access must be protected because the rx handler is asynchronous,
1004 generic_netmap_rxsync(struct netmap_kring *kring, int flags)
1006 struct netmap_ring *ring = kring->ring;
1007 struct netmap_adapter *na = kring->na;
1008 u_int nm_i; /* index into the netmap ring */ //j,
1010 u_int const lim = kring->nkr_num_slots - 1;
1011 u_int const head = kring->rhead;
1012 int force_update = (flags & NAF_FORCE_READ) || kring->nr_kflags & NKR_PENDINTR;
1014 /* Adapter-specific variables. */
1015 u_int nm_buf_len = NETMAP_BUF_SIZE(na);
1018 int avail; /* in bytes */
1023 return netmap_ring_reinit(kring);
1025 IFRATE(rate_ctx.new.rxsync++);
1028 * First part: skip past packets that userspace has released.
1029 * This can possibly make room for the second part.
1031 nm_i = kring->nr_hwcur;
1033 /* Userspace has released some packets. */
1034 for (n = 0; nm_i != head; n++) {
1035 struct netmap_slot *slot = &ring->slot[nm_i];
1037 slot->flags &= ~NS_BUF_CHANGED;
1038 nm_i = nm_next(nm_i, lim);
1040 kring->nr_hwcur = head;
1044 * Second part: import newly received packets.
1046 if (!netmap_no_pendintr && !force_update) {
1050 nm_i = kring->nr_hwtail; /* First empty slot in the receive ring. */
1052 /* Compute the available space (in bytes) in this netmap ring.
1053 * The first slot that is not considered in is the one before
1056 avail = nm_prev(kring->nr_hwcur, lim) - nm_i;
1059 avail *= nm_buf_len;
1061 /* First pass: While holding the lock on the RX mbuf queue,
1062 * extract as many mbufs as they fit the available space,
1063 * and put them in a temporary queue.
1064 * To avoid performing a per-mbuf division (mlen / nm_buf_len) to
1065 * to update avail, we do the update in a while loop that we
1066 * also use to set the RX slots, but without performing the copy. */
1068 mbq_lock(&kring->rx_queue);
1070 m = mbq_peek(&kring->rx_queue);
1072 /* No more packets from the driver. */
1078 /* No more space in the ring. */
1082 mbq_dequeue(&kring->rx_queue);
1090 avail -= nm_buf_len;
1092 ring->slot[nm_i].len = copy;
1093 ring->slot[nm_i].flags = (mlen ? NS_MOREFRAG : 0);
1094 nm_i = nm_next(nm_i, lim);
1097 mbq_enqueue(&tmpq, m);
1099 mbq_unlock(&kring->rx_queue);
1101 /* Second pass: Drain the temporary queue, going over the used RX slots,
1102 * and perform the copy out of the RX queue lock. */
1103 nm_i = kring->nr_hwtail;
1110 m = mbq_dequeue(&tmpq);
1116 nmaddr = NMB(na, &ring->slot[nm_i]);
1117 /* We only check the address here on generic rx rings. */
1118 if (nmaddr == NETMAP_BUF_BASE(na)) { /* Bad buffer */
1122 return netmap_ring_reinit(kring);
1125 copy = ring->slot[nm_i].len;
1126 m_copydata(m, ofs, copy, nmaddr);
1128 morefrag = ring->slot[nm_i].flags & NS_MOREFRAG;
1129 nm_i = nm_next(nm_i, lim);
1138 kring->nr_hwtail = nm_i;
1139 IFRATE(rate_ctx.new.rxpkt += n);
1141 kring->nr_kflags &= ~NKR_PENDINTR;
1147 generic_netmap_dtor(struct netmap_adapter *na)
1149 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter*)na;
1150 struct ifnet *ifp = netmap_generic_getifp(gna);
1151 struct netmap_adapter *prev_na = gna->prev;
1153 if (prev_na != NULL) {
1154 netmap_adapter_put(prev_na);
1155 if (nm_iszombie(na)) {
1157 * The driver has been removed without releasing
1158 * the reference so we need to do it here.
1160 netmap_adapter_put(prev_na);
1162 D("Native netmap adapter %p restored", prev_na);
1164 NM_ATTACH_NA(ifp, prev_na);
1166 * netmap_detach_common(), that it's called after this function,
1167 * overrides WNA(ifp) if na->ifp is not NULL.
1170 D("Emulated netmap adapter for %s destroyed", na->name);
1174 na_is_generic(struct netmap_adapter *na)
1176 return na->nm_register == generic_netmap_register;
1180 * generic_netmap_attach() makes it possible to use netmap on
1181 * a device without native netmap support.
1182 * This is less performant than native support but potentially
1183 * faster than raw sockets or similar schemes.
1185 * In this "emulated" mode, netmap rings do not necessarily
1186 * have the same size as those in the NIC. We use a default
1187 * value and possibly override it if the OS has ways to fetch the
1188 * actual configuration.
1191 generic_netmap_attach(struct ifnet *ifp)
1193 struct netmap_adapter *na;
1194 struct netmap_generic_adapter *gna;
1196 u_int num_tx_desc, num_rx_desc;
1199 if (ifp->if_type == IFT_LOOP) {
1200 D("if_loop is not supported by %s", __func__);
1205 if (NA(ifp) && !NM_NA_VALID(ifp)) {
1206 /* If NA(ifp) is not null but there is no valid netmap
1207 * adapter it means that someone else is using the same
1208 * pointer (e.g. ax25_ptr on linux). This happens for
1209 * instance when also PF_RING is in use. */
1210 D("Error: netmap adapter hook is busy");
1214 num_tx_desc = num_rx_desc = netmap_generic_ringsize; /* starting point */
1216 nm_os_generic_find_num_desc(ifp, &num_tx_desc, &num_rx_desc); /* ignore errors */
1217 ND("Netmap ring size: TX = %d, RX = %d", num_tx_desc, num_rx_desc);
1218 if (num_tx_desc == 0 || num_rx_desc == 0) {
1219 D("Device has no hw slots (tx %u, rx %u)", num_tx_desc, num_rx_desc);
1223 gna = nm_os_malloc(sizeof(*gna));
1225 D("no memory on attach, give up");
1228 na = (struct netmap_adapter *)gna;
1229 strncpy(na->name, ifp->if_xname, sizeof(na->name));
1231 na->num_tx_desc = num_tx_desc;
1232 na->num_rx_desc = num_rx_desc;
1233 na->nm_register = &generic_netmap_register;
1234 na->nm_txsync = &generic_netmap_txsync;
1235 na->nm_rxsync = &generic_netmap_rxsync;
1236 na->nm_dtor = &generic_netmap_dtor;
1237 /* when using generic, NAF_NETMAP_ON is set so we force
1238 * NAF_SKIP_INTR to use the regular interrupt handler
1240 na->na_flags = NAF_SKIP_INTR | NAF_HOST_RINGS;
1242 ND("[GNA] num_tx_queues(%d), real_num_tx_queues(%d), len(%lu)",
1243 ifp->num_tx_queues, ifp->real_num_tx_queues,
1245 ND("[GNA] num_rx_queues(%d), real_num_rx_queues(%d)",
1246 ifp->num_rx_queues, ifp->real_num_rx_queues);
1248 nm_os_generic_find_num_queues(ifp, &na->num_tx_rings, &na->num_rx_rings);
1250 retval = netmap_attach_common(na);
1256 gna->prev = NA(ifp); /* save old na */
1257 if (gna->prev != NULL) {
1258 netmap_adapter_get(gna->prev);
1260 NM_ATTACH_NA(ifp, na);
1262 nm_os_generic_set_features(gna);
1264 D("Emulated adapter for %s created (prev was %p)", na->name, gna->prev);