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)
96 #define MBUF_TXQ(m) 0//((m)->m_pkthdr.flowid)
97 #define MBUF_RXQ(m) 0//((m)->m_pkthdr.flowid)
98 #define smp_mb() //XXX: to be correctly defined
102 #include "bsd_glue.h"
104 #include <linux/ethtool.h> /* struct ethtool_ops, get_ringparam */
105 #include <linux/hrtimer.h>
107 static inline struct mbuf *
108 nm_os_get_mbuf(struct ifnet *ifp, int len)
110 return alloc_skb(ifp->needed_headroom + len +
111 ifp->needed_tailroom, GFP_ATOMIC);
117 /* Common headers. */
118 #include <net/netmap.h>
119 #include <dev/netmap/netmap_kern.h>
120 #include <dev/netmap/netmap_mem2.h>
123 #define for_each_kring_n(_i, _k, _karr, _n) \
124 for ((_k)=*(_karr), (_i) = 0; (_i) < (_n); (_i)++, (_k) = (_karr)[(_i)])
126 #define for_each_tx_kring(_i, _k, _na) \
127 for_each_kring_n(_i, _k, (_na)->tx_rings, (_na)->num_tx_rings)
128 #define for_each_tx_kring_h(_i, _k, _na) \
129 for_each_kring_n(_i, _k, (_na)->tx_rings, (_na)->num_tx_rings + 1)
131 #define for_each_rx_kring(_i, _k, _na) \
132 for_each_kring_n(_i, _k, (_na)->rx_rings, (_na)->num_rx_rings)
133 #define for_each_rx_kring_h(_i, _k, _na) \
134 for_each_kring_n(_i, _k, (_na)->rx_rings, (_na)->num_rx_rings + 1)
137 /* ======================== PERFORMANCE STATISTICS =========================== */
143 unsigned long txsync;
145 unsigned long txrepl;
146 unsigned long txdrop;
149 unsigned long rxsync;
152 struct rate_context {
154 struct timer_list timer;
155 struct rate_stats new;
156 struct rate_stats old;
159 #define RATE_PRINTK(_NAME_) \
160 printk( #_NAME_ " = %lu Hz\n", (cur._NAME_ - ctx->old._NAME_)/RATE_PERIOD);
161 #define RATE_PERIOD 2
162 static void rate_callback(unsigned long arg)
164 struct rate_context * ctx = (struct rate_context *)arg;
165 struct rate_stats cur = ctx->new;
179 r = mod_timer(&ctx->timer, jiffies +
180 msecs_to_jiffies(RATE_PERIOD * 1000));
182 D("[v1000] Error: mod_timer()");
185 static struct rate_context rate_ctx;
187 void generic_rate(int txp, int txs, int txi, int rxp, int rxs, int rxi)
189 if (txp) rate_ctx.new.txpkt++;
190 if (txs) rate_ctx.new.txsync++;
191 if (txi) rate_ctx.new.txirq++;
192 if (rxp) rate_ctx.new.rxpkt++;
193 if (rxs) rate_ctx.new.rxsync++;
194 if (rxi) rate_ctx.new.rxirq++;
202 /* ========== GENERIC (EMULATED) NETMAP ADAPTER SUPPORT ============= */
205 * Wrapper used by the generic adapter layer to notify
206 * the poller threads. Differently from netmap_rx_irq(), we check
207 * only NAF_NETMAP_ON instead of NAF_NATIVE_ON to enable the irq.
210 netmap_generic_irq(struct netmap_adapter *na, u_int q, u_int *work_done)
212 if (unlikely(!nm_netmap_on(na)))
215 netmap_common_irq(na, q, work_done);
218 rate_ctx.new.rxirq++;
220 rate_ctx.new.txirq++;
221 #endif /* RATE_GENERIC */
225 generic_netmap_unregister(struct netmap_adapter *na)
227 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na;
228 struct netmap_kring *kring = NULL;
231 if (na->active_fds == 0) {
232 na->na_flags &= ~NAF_NETMAP_ON;
234 /* Stop intercepting packets on the RX path. */
235 nm_os_catch_rx(gna, 0);
237 /* Release packet steering control. */
238 nm_os_catch_tx(gna, 0);
241 for_each_rx_kring_h(r, kring, na) {
242 if (nm_kring_pending_off(kring)) {
243 D("Emulated adapter: ring '%s' deactivated", kring->name);
244 kring->nr_mode = NKR_NETMAP_OFF;
247 for_each_tx_kring_h(r, kring, na) {
248 if (nm_kring_pending_off(kring)) {
249 kring->nr_mode = NKR_NETMAP_OFF;
250 D("Emulated adapter: ring '%s' deactivated", kring->name);
254 for_each_rx_kring(r, kring, na) {
255 /* Free the mbufs still pending in the RX queues,
256 * that did not end up into the corresponding netmap
258 mbq_safe_purge(&kring->rx_queue);
259 nm_os_mitigation_cleanup(&gna->mit[r]);
262 /* Decrement reference counter for the mbufs in the
263 * TX pools. These mbufs can be still pending in drivers,
264 * (e.g. this happens with virtio-net driver, which
265 * does lazy reclaiming of transmitted mbufs). */
266 for_each_tx_kring(r, kring, na) {
267 /* We must remove the destructor on the TX event,
268 * because the destructor invokes netmap code, and
269 * the netmap module may disappear before the
270 * TX event is consumed. */
271 mtx_lock_spin(&kring->tx_event_lock);
272 if (kring->tx_event) {
273 SET_MBUF_DESTRUCTOR(kring->tx_event, NULL);
275 kring->tx_event = NULL;
276 mtx_unlock_spin(&kring->tx_event_lock);
279 if (na->active_fds == 0) {
280 nm_os_free(gna->mit);
282 for_each_rx_kring(r, kring, na) {
283 mbq_safe_fini(&kring->rx_queue);
286 for_each_tx_kring(r, kring, na) {
287 mtx_destroy(&kring->tx_event_lock);
288 if (kring->tx_pool == NULL) {
292 for (i=0; i<na->num_tx_desc; i++) {
293 if (kring->tx_pool[i]) {
294 m_freem(kring->tx_pool[i]);
297 nm_os_free(kring->tx_pool);
298 kring->tx_pool = NULL;
302 if (--rate_ctx.refcount == 0) {
304 del_timer(&rate_ctx.timer);
307 D("Emulated adapter for %s deactivated", na->name);
313 /* Enable/disable netmap mode for a generic network interface. */
315 generic_netmap_register(struct netmap_adapter *na, int enable)
317 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na;
318 struct netmap_kring *kring = NULL;
327 /* This is actually an unregif. */
328 return generic_netmap_unregister(na);
331 if (na->active_fds == 0) {
332 D("Emulated adapter for %s activated", na->name);
333 /* Do all memory allocations when (na->active_fds == 0), to
334 * simplify error management. */
336 /* Allocate memory for mitigation support on all the rx queues. */
337 gna->mit = nm_os_malloc(na->num_rx_rings * sizeof(struct nm_generic_mit));
339 D("mitigation allocation failed");
344 for_each_rx_kring(r, kring, na) {
345 /* Init mitigation support. */
346 nm_os_mitigation_init(&gna->mit[r], r, na);
348 /* Initialize the rx queue, as generic_rx_handler() can
349 * be called as soon as nm_os_catch_rx() returns.
351 mbq_safe_init(&kring->rx_queue);
355 * Prepare mbuf pools (parallel to the tx rings), for packet
356 * transmission. Don't preallocate the mbufs here, it's simpler
357 * to leave this task to txsync.
359 for_each_tx_kring(r, kring, na) {
360 kring->tx_pool = NULL;
362 for_each_tx_kring(r, kring, na) {
364 nm_os_malloc(na->num_tx_desc * sizeof(struct mbuf *));
365 if (!kring->tx_pool) {
366 D("tx_pool allocation failed");
370 mtx_init(&kring->tx_event_lock, "tx_event_lock",
375 for_each_rx_kring_h(r, kring, na) {
376 if (nm_kring_pending_on(kring)) {
377 D("Emulated adapter: ring '%s' activated", kring->name);
378 kring->nr_mode = NKR_NETMAP_ON;
382 for_each_tx_kring_h(r, kring, na) {
383 if (nm_kring_pending_on(kring)) {
384 D("Emulated adapter: ring '%s' activated", kring->name);
385 kring->nr_mode = NKR_NETMAP_ON;
389 for_each_tx_kring(r, kring, na) {
390 /* Initialize tx_pool and tx_event. */
391 for (i=0; i<na->num_tx_desc; i++) {
392 kring->tx_pool[i] = NULL;
395 kring->tx_event = NULL;
398 if (na->active_fds == 0) {
399 /* Prepare to intercept incoming traffic. */
400 error = nm_os_catch_rx(gna, 1);
402 D("nm_os_catch_rx(1) failed (%d)", error);
406 /* Let netmap control the packet steering. */
407 error = nm_os_catch_tx(gna, 1);
409 D("nm_os_catch_tx(1) failed (%d)", error);
413 na->na_flags |= NAF_NETMAP_ON;
416 if (rate_ctx.refcount == 0) {
418 memset(&rate_ctx, 0, sizeof(rate_ctx));
419 setup_timer(&rate_ctx.timer, &rate_callback, (unsigned long)&rate_ctx);
420 if (mod_timer(&rate_ctx.timer, jiffies + msecs_to_jiffies(1500))) {
421 D("Error: mod_timer()");
430 /* Here (na->active_fds == 0) holds. */
432 nm_os_catch_rx(gna, 0);
434 for_each_tx_kring(r, kring, na) {
435 mtx_destroy(&kring->tx_event_lock);
436 if (kring->tx_pool == NULL) {
439 nm_os_free(kring->tx_pool);
440 kring->tx_pool = NULL;
442 for_each_rx_kring(r, kring, na) {
443 mbq_safe_fini(&kring->rx_queue);
445 nm_os_free(gna->mit);
452 * Callback invoked when the device driver frees an mbuf used
453 * by netmap to transmit a packet. This usually happens when
454 * the NIC notifies the driver that transmission is completed.
457 generic_mbuf_destructor(struct mbuf *m)
459 struct netmap_adapter *na = NA(GEN_TX_MBUF_IFP(m));
460 struct netmap_kring *kring;
461 unsigned int r = MBUF_TXQ(m);
462 unsigned int r_orig = r;
464 if (unlikely(!nm_netmap_on(na) || r >= na->num_tx_rings)) {
465 D("Error: no netmap adapter on device %p",
471 * First, clear the event mbuf.
472 * In principle, the event 'm' should match the one stored
473 * on ring 'r'. However we check it explicitely to stay
474 * safe against lower layers (qdisc, driver, etc.) changing
475 * MBUF_TXQ(m) under our feet. If the match is not found
476 * on 'r', we try to see if it belongs to some other ring.
481 kring = na->tx_rings[r];
482 mtx_lock_spin(&kring->tx_event_lock);
483 if (kring->tx_event == m) {
484 kring->tx_event = NULL;
487 mtx_unlock_spin(&kring->tx_event_lock);
491 RD(1, "event %p migrated: ring %u --> %u",
497 if (++r == na->num_tx_rings) r = 0;
500 RD(1, "Cannot match event %p", m);
505 /* Second, wake up clients. They will reclaim the event through
507 netmap_generic_irq(na, r, NULL);
509 #if __FreeBSD_version <= 1200050
510 void_mbuf_dtor(m, NULL, NULL);
511 #else /* __FreeBSD_version >= 1200051 */
513 #endif /* __FreeBSD_version >= 1200051 */
517 /* Record completed transmissions and update hwtail.
519 * The oldest tx buffer not yet completed is at nr_hwtail + 1,
520 * nr_hwcur is the first unsent buffer.
523 generic_netmap_tx_clean(struct netmap_kring *kring, int txqdisc)
525 u_int const lim = kring->nkr_num_slots - 1;
526 u_int nm_i = nm_next(kring->nr_hwtail, lim);
527 u_int hwcur = kring->nr_hwcur;
529 struct mbuf **tx_pool = kring->tx_pool;
531 ND("hwcur = %d, hwtail = %d", kring->nr_hwcur, kring->nr_hwtail);
533 while (nm_i != hwcur) { /* buffers not completed */
534 struct mbuf *m = tx_pool[nm_i];
538 /* Nothing to do, this is going
539 * to be replenished. */
540 RD(3, "Is this happening?");
542 } else if (MBUF_QUEUED(m)) {
543 break; /* Not dequeued yet. */
545 } else if (MBUF_REFCNT(m) != 1) {
546 /* This mbuf has been dequeued but is still busy
548 * Leave it to the driver and replenish. */
550 tx_pool[nm_i] = NULL;
554 if (unlikely(m == NULL)) {
557 /* This slot was used to place an event. */
558 mtx_lock_spin(&kring->tx_event_lock);
559 event_consumed = (kring->tx_event == NULL);
560 mtx_unlock_spin(&kring->tx_event_lock);
561 if (!event_consumed) {
562 /* The event has not been consumed yet,
563 * still busy in the driver. */
566 /* The event has been consumed, we can go
569 } else if (MBUF_REFCNT(m) != 1) {
570 /* This mbuf is still busy: its refcnt is 2. */
576 nm_i = nm_next(nm_i, lim);
578 kring->nr_hwtail = nm_prev(nm_i, lim);
579 ND("tx completed [%d] -> hwtail %d", n, kring->nr_hwtail);
584 /* Compute a slot index in the middle between inf and sup. */
586 ring_middle(u_int inf, u_int sup, u_int lim)
593 } else { /* wrap around */
594 e = (sup + n + inf) / 2;
600 if (unlikely(e >= n)) {
601 D("This cannot happen");
609 generic_set_tx_event(struct netmap_kring *kring, u_int hwcur)
611 u_int lim = kring->nkr_num_slots - 1;
614 u_int ntc = nm_next(kring->nr_hwtail, lim); /* next to clean */
617 return; /* all buffers are free */
621 * We have pending packets in the driver between hwtail+1
622 * and hwcur, and we have to chose one of these slot to
623 * generate a notification.
624 * There is a race but this is only called within txsync which
625 * does a double check.
628 /* Choose a slot in the middle, so that we don't risk ending
629 * up in a situation where the client continuously wake up,
630 * fills one or a few TX slots and go to sleep again. */
631 e = ring_middle(ntc, hwcur, lim);
633 /* Choose the first pending slot, to be safe against driver
634 * reordering mbuf transmissions. */
638 m = kring->tx_pool[e];
640 /* An event is already in place. */
644 mtx_lock_spin(&kring->tx_event_lock);
645 if (kring->tx_event) {
646 /* An event is already in place. */
647 mtx_unlock_spin(&kring->tx_event_lock);
651 SET_MBUF_DESTRUCTOR(m, generic_mbuf_destructor);
653 mtx_unlock_spin(&kring->tx_event_lock);
655 kring->tx_pool[e] = NULL;
657 ND(5, "Request Event at %d mbuf %p refcnt %d", e, m, m ? MBUF_REFCNT(m) : -2 );
659 /* Decrement the refcount. This will free it if we lose the race
660 * with the driver. */
667 * generic_netmap_txsync() transforms netmap buffers into mbufs
668 * and passes them to the standard device driver
669 * (ndo_start_xmit() or ifp->if_transmit() ).
670 * On linux this is not done directly, but using dev_queue_xmit(),
671 * since it implements the TX flow control (and takes some locks).
674 generic_netmap_txsync(struct netmap_kring *kring, int flags)
676 struct netmap_adapter *na = kring->na;
677 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na;
678 struct ifnet *ifp = na->ifp;
679 struct netmap_ring *ring = kring->ring;
680 u_int nm_i; /* index into the netmap ring */ // j
681 u_int const lim = kring->nkr_num_slots - 1;
682 u_int const head = kring->rhead;
683 u_int ring_nr = kring->ring_id;
685 IFRATE(rate_ctx.new.txsync++);
690 * First part: process new packets to send.
692 nm_i = kring->nr_hwcur;
693 if (nm_i != head) { /* we have new packets to send */
694 struct nm_os_gen_arg a;
697 if (gna->txqdisc && nm_kr_txempty(kring)) {
698 /* In txqdisc mode, we ask for a delayed notification,
699 * but only when cur == hwtail, which means that the
700 * client is going to block. */
701 event = ring_middle(nm_i, head, lim);
702 ND(3, "Place txqdisc event (hwcur=%u,event=%u,"
703 "head=%u,hwtail=%u)", nm_i, event, head,
709 a.head = a.tail = NULL;
711 while (nm_i != head) {
712 struct netmap_slot *slot = &ring->slot[nm_i];
713 u_int len = slot->len;
714 void *addr = NMB(na, slot);
715 /* device-specific */
719 NM_CHECK_ADDR_LEN(na, addr, len);
721 /* Tale a mbuf from the tx pool (replenishing the pool
722 * entry if necessary) and copy in the user packet. */
723 m = kring->tx_pool[nm_i];
724 if (unlikely(m == NULL)) {
725 kring->tx_pool[nm_i] = m =
726 nm_os_get_mbuf(ifp, NETMAP_BUF_SIZE(na));
728 RD(2, "Failed to replenish mbuf");
729 /* Here we could schedule a timer which
730 * retries to replenish after a while,
731 * and notifies the client when it
732 * manages to replenish some slots. In
733 * any case we break early to avoid
737 IFRATE(rate_ctx.new.txrepl++);
743 a.qevent = (nm_i == event);
744 /* When not in txqdisc mode, we should ask
745 * notifications when NS_REPORT is set, or roughly
746 * every half ring. To optimize this, we set a
747 * notification event when the client runs out of
748 * TX ring space, or when transmission fails. In
749 * the latter case we also break early.
751 tx_ret = nm_os_generic_xmit_frame(&a);
752 if (unlikely(tx_ret)) {
755 * No room for this mbuf in the device driver.
756 * Request a notification FOR A PREVIOUS MBUF,
757 * then call generic_netmap_tx_clean(kring) to do the
758 * double check and see if we can free more buffers.
759 * If there is space continue, else break;
760 * NOTE: the double check is necessary if the problem
761 * occurs in the txsync call after selrecord().
762 * Also, we need some way to tell the caller that not
763 * all buffers were queued onto the device (this was
764 * not a problem with native netmap driver where space
765 * is preallocated). The bridge has a similar problem
766 * and we solve it there by dropping the excess packets.
768 generic_set_tx_event(kring, nm_i);
769 if (generic_netmap_tx_clean(kring, gna->txqdisc)) {
770 /* space now available */
777 /* In txqdisc mode, the netmap-aware qdisc
778 * queue has the same length as the number of
779 * netmap slots (N). Since tail is advanced
780 * only when packets are dequeued, qdisc
781 * queue overrun cannot happen, so
782 * nm_os_generic_xmit_frame() did not fail
784 * However, packets can be dropped because
785 * carrier is off, or because our qdisc is
786 * being deactivated, or possibly for other
787 * reasons. In these cases, we just let the
788 * packet to be dropped. */
789 IFRATE(rate_ctx.new.txdrop++);
792 slot->flags &= ~(NS_REPORT | NS_BUF_CHANGED);
793 nm_i = nm_next(nm_i, lim);
794 IFRATE(rate_ctx.new.txpkt++);
796 if (a.head != NULL) {
798 nm_os_generic_xmit_frame(&a);
800 /* Update hwcur to the next slot to transmit. Here nm_i
801 * is not necessarily head, we could break early. */
802 kring->nr_hwcur = nm_i;
806 * Second, reclaim completed buffers
808 if (!gna->txqdisc && (flags & NAF_FORCE_RECLAIM || nm_kr_txempty(kring))) {
809 /* No more available slots? Set a notification event
810 * on a netmap slot that will be cleaned in the future.
811 * No doublecheck is performed, since txsync() will be
812 * called twice by netmap_poll().
814 generic_set_tx_event(kring, nm_i);
817 generic_netmap_tx_clean(kring, gna->txqdisc);
824 * This handler is registered (through nm_os_catch_rx())
825 * within the attached network interface
826 * in the RX subsystem, so that every mbuf passed up by
827 * the driver can be stolen to the network stack.
828 * Stolen packets are put in a queue where the
829 * generic_netmap_rxsync() callback can extract them.
830 * Returns 1 if the packet was stolen, 0 otherwise.
833 generic_rx_handler(struct ifnet *ifp, struct mbuf *m)
835 struct netmap_adapter *na = NA(ifp);
836 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na;
837 struct netmap_kring *kring;
839 u_int r = MBUF_RXQ(m); /* receive ring number */
841 if (r >= na->num_rx_rings) {
842 r = r % na->num_rx_rings;
845 kring = na->rx_rings[r];
847 if (kring->nr_mode == NKR_NETMAP_OFF) {
848 /* We must not intercept this mbuf. */
852 /* limit the size of the queue */
853 if (unlikely(!gna->rxsg && MBUF_LEN(m) > NETMAP_BUF_SIZE(na))) {
854 /* This may happen when GRO/LRO features are enabled for
855 * the NIC driver when the generic adapter does not
856 * support RX scatter-gather. */
857 RD(2, "Warning: driver pushed up big packet "
858 "(size=%d)", (int)MBUF_LEN(m));
860 } else if (unlikely(mbq_len(&kring->rx_queue) > 1024)) {
863 mbq_safe_enqueue(&kring->rx_queue, m);
866 if (netmap_generic_mit < 32768) {
867 /* no rx mitigation, pass notification up */
868 netmap_generic_irq(na, r, &work_done);
870 /* same as send combining, filter notification if there is a
871 * pending timer, otherwise pass it up and start a timer.
873 if (likely(nm_os_mitigation_active(&gna->mit[r]))) {
874 /* Record that there is some pending work. */
875 gna->mit[r].mit_pending = 1;
877 netmap_generic_irq(na, r, &work_done);
878 nm_os_mitigation_start(&gna->mit[r]);
882 /* We have intercepted the mbuf. */
887 * generic_netmap_rxsync() extracts mbufs from the queue filled by
888 * generic_netmap_rx_handler() and puts their content in the netmap
890 * Access must be protected because the rx handler is asynchronous,
893 generic_netmap_rxsync(struct netmap_kring *kring, int flags)
895 struct netmap_ring *ring = kring->ring;
896 struct netmap_adapter *na = kring->na;
897 u_int nm_i; /* index into the netmap ring */ //j,
899 u_int const lim = kring->nkr_num_slots - 1;
900 u_int const head = kring->rhead;
901 int force_update = (flags & NAF_FORCE_READ) || kring->nr_kflags & NKR_PENDINTR;
903 /* Adapter-specific variables. */
904 u_int nm_buf_len = NETMAP_BUF_SIZE(na);
907 int avail; /* in bytes */
912 return netmap_ring_reinit(kring);
914 IFRATE(rate_ctx.new.rxsync++);
917 * First part: skip past packets that userspace has released.
918 * This can possibly make room for the second part.
920 nm_i = kring->nr_hwcur;
922 /* Userspace has released some packets. */
923 for (n = 0; nm_i != head; n++) {
924 struct netmap_slot *slot = &ring->slot[nm_i];
926 slot->flags &= ~NS_BUF_CHANGED;
927 nm_i = nm_next(nm_i, lim);
929 kring->nr_hwcur = head;
933 * Second part: import newly received packets.
935 if (!netmap_no_pendintr && !force_update) {
939 nm_i = kring->nr_hwtail; /* First empty slot in the receive ring. */
941 /* Compute the available space (in bytes) in this netmap ring.
942 * The first slot that is not considered in is the one before
945 avail = nm_prev(kring->nr_hwcur, lim) - nm_i;
950 /* First pass: While holding the lock on the RX mbuf queue,
951 * extract as many mbufs as they fit the available space,
952 * and put them in a temporary queue.
953 * To avoid performing a per-mbuf division (mlen / nm_buf_len) to
954 * to update avail, we do the update in a while loop that we
955 * also use to set the RX slots, but without performing the copy. */
957 mbq_lock(&kring->rx_queue);
959 m = mbq_peek(&kring->rx_queue);
961 /* No more packets from the driver. */
967 /* No more space in the ring. */
971 mbq_dequeue(&kring->rx_queue);
981 ring->slot[nm_i].len = copy;
982 ring->slot[nm_i].flags = (mlen ? NS_MOREFRAG : 0);
983 nm_i = nm_next(nm_i, lim);
986 mbq_enqueue(&tmpq, m);
988 mbq_unlock(&kring->rx_queue);
990 /* Second pass: Drain the temporary queue, going over the used RX slots,
991 * and perform the copy out of the RX queue lock. */
992 nm_i = kring->nr_hwtail;
999 m = mbq_dequeue(&tmpq);
1005 nmaddr = NMB(na, &ring->slot[nm_i]);
1006 /* We only check the address here on generic rx rings. */
1007 if (nmaddr == NETMAP_BUF_BASE(na)) { /* Bad buffer */
1011 return netmap_ring_reinit(kring);
1014 copy = ring->slot[nm_i].len;
1015 m_copydata(m, ofs, copy, nmaddr);
1017 morefrag = ring->slot[nm_i].flags & NS_MOREFRAG;
1018 nm_i = nm_next(nm_i, lim);
1027 kring->nr_hwtail = nm_i;
1028 IFRATE(rate_ctx.new.rxpkt += n);
1030 kring->nr_kflags &= ~NKR_PENDINTR;
1036 generic_netmap_dtor(struct netmap_adapter *na)
1038 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter*)na;
1039 struct ifnet *ifp = netmap_generic_getifp(gna);
1040 struct netmap_adapter *prev_na = gna->prev;
1042 if (prev_na != NULL) {
1043 netmap_adapter_put(prev_na);
1044 if (nm_iszombie(na)) {
1046 * The driver has been removed without releasing
1047 * the reference so we need to do it here.
1049 netmap_adapter_put(prev_na);
1051 D("Native netmap adapter %p restored", prev_na);
1053 NM_RESTORE_NA(ifp, prev_na);
1055 * netmap_detach_common(), that it's called after this function,
1056 * overrides WNA(ifp) if na->ifp is not NULL.
1059 D("Emulated netmap adapter for %s destroyed", na->name);
1063 na_is_generic(struct netmap_adapter *na)
1065 return na->nm_register == generic_netmap_register;
1069 * generic_netmap_attach() makes it possible to use netmap on
1070 * a device without native netmap support.
1071 * This is less performant than native support but potentially
1072 * faster than raw sockets or similar schemes.
1074 * In this "emulated" mode, netmap rings do not necessarily
1075 * have the same size as those in the NIC. We use a default
1076 * value and possibly override it if the OS has ways to fetch the
1077 * actual configuration.
1080 generic_netmap_attach(struct ifnet *ifp)
1082 struct netmap_adapter *na;
1083 struct netmap_generic_adapter *gna;
1085 u_int num_tx_desc, num_rx_desc;
1088 if (ifp->if_type == IFT_LOOP) {
1089 D("if_loop is not supported by %s", __func__);
1094 if (NM_NA_CLASH(ifp)) {
1095 /* If NA(ifp) is not null but there is no valid netmap
1096 * adapter it means that someone else is using the same
1097 * pointer (e.g. ax25_ptr on linux). This happens for
1098 * instance when also PF_RING is in use. */
1099 D("Error: netmap adapter hook is busy");
1103 num_tx_desc = num_rx_desc = netmap_generic_ringsize; /* starting point */
1105 nm_os_generic_find_num_desc(ifp, &num_tx_desc, &num_rx_desc); /* ignore errors */
1106 ND("Netmap ring size: TX = %d, RX = %d", num_tx_desc, num_rx_desc);
1107 if (num_tx_desc == 0 || num_rx_desc == 0) {
1108 D("Device has no hw slots (tx %u, rx %u)", num_tx_desc, num_rx_desc);
1112 gna = nm_os_malloc(sizeof(*gna));
1114 D("no memory on attach, give up");
1117 na = (struct netmap_adapter *)gna;
1118 strncpy(na->name, ifp->if_xname, sizeof(na->name));
1120 na->num_tx_desc = num_tx_desc;
1121 na->num_rx_desc = num_rx_desc;
1122 na->rx_buf_maxsize = 32768;
1123 na->nm_register = &generic_netmap_register;
1124 na->nm_txsync = &generic_netmap_txsync;
1125 na->nm_rxsync = &generic_netmap_rxsync;
1126 na->nm_dtor = &generic_netmap_dtor;
1127 /* when using generic, NAF_NETMAP_ON is set so we force
1128 * NAF_SKIP_INTR to use the regular interrupt handler
1130 na->na_flags = NAF_SKIP_INTR | NAF_HOST_RINGS;
1132 ND("[GNA] num_tx_queues(%d), real_num_tx_queues(%d), len(%lu)",
1133 ifp->num_tx_queues, ifp->real_num_tx_queues,
1135 ND("[GNA] num_rx_queues(%d), real_num_rx_queues(%d)",
1136 ifp->num_rx_queues, ifp->real_num_rx_queues);
1138 nm_os_generic_find_num_queues(ifp, &na->num_tx_rings, &na->num_rx_rings);
1140 retval = netmap_attach_common(na);
1146 if (NM_NA_VALID(ifp)) {
1147 gna->prev = NA(ifp); /* save old na */
1148 netmap_adapter_get(gna->prev);
1150 NM_ATTACH_NA(ifp, na);
1152 nm_os_generic_set_features(gna);
1154 D("Emulated adapter for %s created (prev was %p)", na->name, gna->prev);