1 /*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (C) 2013-2016 Vincenzo Maffione
5 * Copyright (C) 2013-2016 Luigi Rizzo
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
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.
16 *
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
27 * SUCH DAMAGE.
28 */
29
30 /*
31 * This module implements netmap support on top of standard,
32 * unmodified device drivers.
33 *
34 * A NIOCREGIF request is handled here if the device does not
35 * have native support. TX and RX rings are emulated as follows:
36 *
37 * NIOCREGIF
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().
45 *
46 * For each receive ring we allocate one "struct mbq"
47 * (an mbuf tailq plus a spinlock). We intercept packets
48 * (through if_input)
49 * on the receive path and put them in the mbq from which
50 * netmap receive routines can grab them.
51 *
52 * TX:
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.
62 *
63 * RX:
64 *
65 */
66
67 #ifdef __FreeBSD__
68
69 #include <sys/cdefs.h> /* prerequisite */
70 #include <sys/types.h>
71 #include <sys/errno.h>
72 #include <sys/malloc.h>
73 #include <sys/lock.h> /* PROT_EXEC */
74 #include <sys/rwlock.h>
75 #include <sys/socket.h> /* sockaddrs */
76 #include <sys/selinfo.h>
77 #include <net/if.h>
78 #include <net/if_types.h>
79 #include <net/if_var.h>
80 #include <machine/bus.h> /* bus_dmamap_* in netmap_kern.h */
81
82 #include <net/netmap.h>
83 #include <dev/netmap/netmap_kern.h>
84 #include <dev/netmap/netmap_mem2.h>
85
86 #define MBUF_RXQ(m) ((m)->m_pkthdr.flowid)
87 #define smp_mb()
88
89 #elif defined _WIN32
90
91 #include "win_glue.h"
92
93 #define MBUF_TXQ(m) 0//((m)->m_pkthdr.flowid)
94 #define MBUF_RXQ(m) 0//((m)->m_pkthdr.flowid)
95 #define smp_mb() //XXX: to be correctly defined
96
97 #else /* linux */
98
99 #include "bsd_glue.h"
100
101 #include <linux/ethtool.h> /* struct ethtool_ops, get_ringparam */
102 #include <linux/hrtimer.h>
103
104 static inline struct mbuf *
nm_os_get_mbuf(struct ifnet * ifp,int len)105 nm_os_get_mbuf(struct ifnet *ifp, int len)
106 {
107 return alloc_skb(ifp->needed_headroom + len +
108 ifp->needed_tailroom, GFP_ATOMIC);
109 }
110
111 #endif /* linux */
112
113
114 /* Common headers. */
115 #include <net/netmap.h>
116 #include <dev/netmap/netmap_kern.h>
117 #include <dev/netmap/netmap_mem2.h>
118
119
120 #define for_each_kring_n(_i, _k, _karr, _n) \
121 for ((_k)=*(_karr), (_i) = 0; (_i) < (_n); (_i)++, (_k) = (_karr)[(_i)])
122
123 #define for_each_tx_kring(_i, _k, _na) \
124 for_each_kring_n(_i, _k, (_na)->tx_rings, (_na)->num_tx_rings)
125 #define for_each_tx_kring_h(_i, _k, _na) \
126 for_each_kring_n(_i, _k, (_na)->tx_rings, (_na)->num_tx_rings + 1)
127
128 #define for_each_rx_kring(_i, _k, _na) \
129 for_each_kring_n(_i, _k, (_na)->rx_rings, (_na)->num_rx_rings)
130 #define for_each_rx_kring_h(_i, _k, _na) \
131 for_each_kring_n(_i, _k, (_na)->rx_rings, (_na)->num_rx_rings + 1)
132
133
134 /* ======================== PERFORMANCE STATISTICS =========================== */
135
136 #ifdef RATE_GENERIC
137 #define IFRATE(x) x
138 struct rate_stats {
139 unsigned long txpkt;
140 unsigned long txsync;
141 unsigned long txirq;
142 unsigned long txrepl;
143 unsigned long txdrop;
144 unsigned long rxpkt;
145 unsigned long rxirq;
146 unsigned long rxsync;
147 };
148
149 struct rate_context {
150 unsigned refcount;
151 struct timer_list timer;
152 struct rate_stats new;
153 struct rate_stats old;
154 };
155
156 #define RATE_PRINTK(_NAME_) \
157 printk( #_NAME_ " = %lu Hz\n", (cur._NAME_ - ctx->old._NAME_)/RATE_PERIOD);
158 #define RATE_PERIOD 2
rate_callback(unsigned long arg)159 static void rate_callback(unsigned long arg)
160 {
161 struct rate_context * ctx = (struct rate_context *)arg;
162 struct rate_stats cur = ctx->new;
163 int r;
164
165 RATE_PRINTK(txpkt);
166 RATE_PRINTK(txsync);
167 RATE_PRINTK(txirq);
168 RATE_PRINTK(txrepl);
169 RATE_PRINTK(txdrop);
170 RATE_PRINTK(rxpkt);
171 RATE_PRINTK(rxsync);
172 RATE_PRINTK(rxirq);
173 printk("\n");
174
175 ctx->old = cur;
176 r = mod_timer(&ctx->timer, jiffies +
177 msecs_to_jiffies(RATE_PERIOD * 1000));
178 if (unlikely(r))
179 nm_prerr("mod_timer() failed");
180 }
181
182 static struct rate_context rate_ctx;
183
generic_rate(int txp,int txs,int txi,int rxp,int rxs,int rxi)184 void generic_rate(int txp, int txs, int txi, int rxp, int rxs, int rxi)
185 {
186 if (txp) rate_ctx.new.txpkt++;
187 if (txs) rate_ctx.new.txsync++;
188 if (txi) rate_ctx.new.txirq++;
189 if (rxp) rate_ctx.new.rxpkt++;
190 if (rxs) rate_ctx.new.rxsync++;
191 if (rxi) rate_ctx.new.rxirq++;
192 }
193
194 #else /* !RATE */
195 #define IFRATE(x)
196 #endif /* !RATE */
197
198
199 /* ========== GENERIC (EMULATED) NETMAP ADAPTER SUPPORT ============= */
200
201 /*
202 * Wrapper used by the generic adapter layer to notify
203 * the poller threads. Differently from netmap_rx_irq(), we check
204 * only NAF_NETMAP_ON instead of NAF_NATIVE_ON to enable the irq.
205 */
206 void
netmap_generic_irq(struct netmap_adapter * na,u_int q,u_int * work_done)207 netmap_generic_irq(struct netmap_adapter *na, u_int q, u_int *work_done)
208 {
209 if (unlikely(!nm_netmap_on(na)))
210 return;
211
212 netmap_common_irq(na, q, work_done);
213 #ifdef RATE_GENERIC
214 if (work_done)
215 rate_ctx.new.rxirq++;
216 else
217 rate_ctx.new.txirq++;
218 #endif /* RATE_GENERIC */
219 }
220
221 static int
generic_netmap_unregister(struct netmap_adapter * na)222 generic_netmap_unregister(struct netmap_adapter *na)
223 {
224 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na;
225 struct netmap_kring *kring = NULL;
226 int i, r;
227
228 if (na->active_fds == 0) {
229 na->na_flags &= ~NAF_NETMAP_ON;
230
231 /* Stop intercepting packets on the RX path. */
232 nm_os_catch_rx(gna, 0);
233
234 /* Release packet steering control. */
235 nm_os_catch_tx(gna, 0);
236 }
237
238 netmap_krings_mode_commit(na, /*onoff=*/0);
239
240 for_each_rx_kring(r, kring, na) {
241 /* Free the mbufs still pending in the RX queues,
242 * that did not end up into the corresponding netmap
243 * RX rings. */
244 mbq_safe_purge(&kring->rx_queue);
245 nm_os_mitigation_cleanup(&gna->mit[r]);
246 }
247
248 /* Decrement reference counter for the mbufs in the
249 * TX pools. These mbufs can be still pending in drivers,
250 * (e.g. this happens with virtio-net driver, which
251 * does lazy reclaiming of transmitted mbufs). */
252 for_each_tx_kring(r, kring, na) {
253 /* We must remove the destructor on the TX event,
254 * because the destructor invokes netmap code, and
255 * the netmap module may disappear before the
256 * TX event is consumed. */
257 mtx_lock_spin(&kring->tx_event_lock);
258 if (kring->tx_event) {
259 SET_MBUF_DESTRUCTOR(kring->tx_event, NULL);
260 }
261 kring->tx_event = NULL;
262 mtx_unlock_spin(&kring->tx_event_lock);
263 }
264
265 if (na->active_fds == 0) {
266 nm_os_free(gna->mit);
267
268 for_each_rx_kring(r, kring, na) {
269 mbq_safe_fini(&kring->rx_queue);
270 }
271
272 for_each_tx_kring(r, kring, na) {
273 mtx_destroy(&kring->tx_event_lock);
274 if (kring->tx_pool == NULL) {
275 continue;
276 }
277
278 for (i=0; i<na->num_tx_desc; i++) {
279 if (kring->tx_pool[i]) {
280 m_freem(kring->tx_pool[i]);
281 }
282 }
283 nm_os_free(kring->tx_pool);
284 kring->tx_pool = NULL;
285 }
286
287 #ifdef RATE_GENERIC
288 if (--rate_ctx.refcount == 0) {
289 nm_prinf("del_timer()");
290 del_timer(&rate_ctx.timer);
291 }
292 #endif
293 nm_prinf("Emulated adapter for %s deactivated", na->name);
294 }
295
296 return 0;
297 }
298
299 /* Enable/disable netmap mode for a generic network interface. */
300 static int
generic_netmap_register(struct netmap_adapter * na,int enable)301 generic_netmap_register(struct netmap_adapter *na, int enable)
302 {
303 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na;
304 struct netmap_kring *kring = NULL;
305 int error;
306 int i, r;
307
308 if (!na) {
309 return EINVAL;
310 }
311
312 if (!enable) {
313 /* This is actually an unregif. */
314 return generic_netmap_unregister(na);
315 }
316
317 if (na->active_fds == 0) {
318 nm_prinf("Emulated adapter for %s activated", na->name);
319 /* Do all memory allocations when (na->active_fds == 0), to
320 * simplify error management. */
321
322 /* Allocate memory for mitigation support on all the rx queues. */
323 gna->mit = nm_os_malloc(na->num_rx_rings * sizeof(struct nm_generic_mit));
324 if (!gna->mit) {
325 nm_prerr("mitigation allocation failed");
326 error = ENOMEM;
327 goto out;
328 }
329
330 for_each_rx_kring(r, kring, na) {
331 /* Init mitigation support. */
332 nm_os_mitigation_init(&gna->mit[r], r, na);
333
334 /* Initialize the rx queue, as generic_rx_handler() can
335 * be called as soon as nm_os_catch_rx() returns.
336 */
337 mbq_safe_init(&kring->rx_queue);
338 }
339
340 /*
341 * Prepare mbuf pools (parallel to the tx rings), for packet
342 * transmission. Don't preallocate the mbufs here, it's simpler
343 * to leave this task to txsync.
344 */
345 for_each_tx_kring(r, kring, na) {
346 kring->tx_pool = NULL;
347 }
348 for_each_tx_kring(r, kring, na) {
349 kring->tx_pool =
350 nm_os_malloc(na->num_tx_desc * sizeof(struct mbuf *));
351 if (!kring->tx_pool) {
352 nm_prerr("tx_pool allocation failed");
353 error = ENOMEM;
354 goto free_tx_pools;
355 }
356 mtx_init(&kring->tx_event_lock, "tx_event_lock",
357 NULL, MTX_SPIN);
358 }
359 }
360
361 netmap_krings_mode_commit(na, /*onoff=*/1);
362
363 for_each_tx_kring(r, kring, na) {
364 /* Initialize tx_pool and tx_event. */
365 for (i=0; i<na->num_tx_desc; i++) {
366 kring->tx_pool[i] = NULL;
367 }
368
369 kring->tx_event = NULL;
370 }
371
372 if (na->active_fds == 0) {
373 /* Prepare to intercept incoming traffic. */
374 error = nm_os_catch_rx(gna, 1);
375 if (error) {
376 nm_prerr("nm_os_catch_rx(1) failed (%d)", error);
377 goto free_tx_pools;
378 }
379
380 /* Let netmap control the packet steering. */
381 error = nm_os_catch_tx(gna, 1);
382 if (error) {
383 nm_prerr("nm_os_catch_tx(1) failed (%d)", error);
384 goto catch_rx;
385 }
386
387 na->na_flags |= NAF_NETMAP_ON;
388
389 #ifdef RATE_GENERIC
390 if (rate_ctx.refcount == 0) {
391 nm_prinf("setup_timer()");
392 memset(&rate_ctx, 0, sizeof(rate_ctx));
393 setup_timer(&rate_ctx.timer, &rate_callback, (unsigned long)&rate_ctx);
394 if (mod_timer(&rate_ctx.timer, jiffies + msecs_to_jiffies(1500))) {
395 nm_prerr("Error: mod_timer()");
396 }
397 }
398 rate_ctx.refcount++;
399 #endif /* RATE */
400 }
401
402 return 0;
403
404 /* Here (na->active_fds == 0) holds. */
405 catch_rx:
406 nm_os_catch_rx(gna, 0);
407 free_tx_pools:
408 for_each_tx_kring(r, kring, na) {
409 mtx_destroy(&kring->tx_event_lock);
410 if (kring->tx_pool == NULL) {
411 continue;
412 }
413 nm_os_free(kring->tx_pool);
414 kring->tx_pool = NULL;
415 }
416 for_each_rx_kring(r, kring, na) {
417 mbq_safe_fini(&kring->rx_queue);
418 }
419 nm_os_free(gna->mit);
420 out:
421
422 return error;
423 }
424
425 /*
426 * Callback invoked when the device driver frees an mbuf used
427 * by netmap to transmit a packet. This usually happens when
428 * the NIC notifies the driver that transmission is completed.
429 */
430 static void
generic_mbuf_destructor(struct mbuf * m)431 generic_mbuf_destructor(struct mbuf *m)
432 {
433 struct netmap_adapter *na = NA(GEN_TX_MBUF_IFP(m));
434 struct netmap_kring *kring;
435 unsigned int r = MBUF_TXQ(m);
436 unsigned int r_orig = r;
437
438 if (unlikely(!nm_netmap_on(na) || r >= na->num_tx_rings)) {
439 nm_prerr("Error: no netmap adapter on device %p",
440 GEN_TX_MBUF_IFP(m));
441 return;
442 }
443
444 /*
445 * First, clear the event mbuf.
446 * In principle, the event 'm' should match the one stored
447 * on ring 'r'. However we check it explicitly to stay
448 * safe against lower layers (qdisc, driver, etc.) changing
449 * MBUF_TXQ(m) under our feet. If the match is not found
450 * on 'r', we try to see if it belongs to some other ring.
451 */
452 for (;;) {
453 bool match = false;
454
455 kring = na->tx_rings[r];
456 mtx_lock_spin(&kring->tx_event_lock);
457 if (kring->tx_event == m) {
458 kring->tx_event = NULL;
459 match = true;
460 }
461 mtx_unlock_spin(&kring->tx_event_lock);
462
463 if (match) {
464 if (r != r_orig) {
465 nm_prlim(1, "event %p migrated: ring %u --> %u",
466 m, r_orig, r);
467 }
468 break;
469 }
470
471 if (++r == na->num_tx_rings) r = 0;
472
473 if (r == r_orig) {
474 nm_prlim(1, "Cannot match event %p", m);
475 return;
476 }
477 }
478
479 /* Second, wake up clients. They will reclaim the event through
480 * txsync. */
481 netmap_generic_irq(na, r, NULL);
482 #ifdef __FreeBSD__
483 void_mbuf_dtor(m);
484 #endif
485 }
486
487 /* Record completed transmissions and update hwtail.
488 *
489 * The oldest tx buffer not yet completed is at nr_hwtail + 1,
490 * nr_hwcur is the first unsent buffer.
491 */
492 static u_int
generic_netmap_tx_clean(struct netmap_kring * kring,int txqdisc)493 generic_netmap_tx_clean(struct netmap_kring *kring, int txqdisc)
494 {
495 u_int const lim = kring->nkr_num_slots - 1;
496 u_int nm_i = nm_next(kring->nr_hwtail, lim);
497 u_int hwcur = kring->nr_hwcur;
498 u_int n = 0;
499 struct mbuf **tx_pool = kring->tx_pool;
500
501 nm_prdis("hwcur = %d, hwtail = %d", kring->nr_hwcur, kring->nr_hwtail);
502
503 while (nm_i != hwcur) { /* buffers not completed */
504 struct mbuf *m = tx_pool[nm_i];
505
506 if (txqdisc) {
507 if (m == NULL) {
508 /* Nothing to do, this is going
509 * to be replenished. */
510 nm_prlim(3, "Is this happening?");
511
512 } else if (MBUF_QUEUED(m)) {
513 break; /* Not dequeued yet. */
514
515 } else if (MBUF_REFCNT(m) != 1) {
516 /* This mbuf has been dequeued but is still busy
517 * (refcount is 2).
518 * Leave it to the driver and replenish. */
519 m_freem(m);
520 tx_pool[nm_i] = NULL;
521 }
522
523 } else {
524 if (unlikely(m == NULL)) {
525 int event_consumed;
526
527 /* This slot was used to place an event. */
528 mtx_lock_spin(&kring->tx_event_lock);
529 event_consumed = (kring->tx_event == NULL);
530 mtx_unlock_spin(&kring->tx_event_lock);
531 if (!event_consumed) {
532 /* The event has not been consumed yet,
533 * still busy in the driver. */
534 break;
535 }
536 /* The event has been consumed, we can go
537 * ahead. */
538
539 } else if (MBUF_REFCNT(m) != 1) {
540 /* This mbuf is still busy: its refcnt is 2. */
541 break;
542 }
543 }
544
545 n++;
546 nm_i = nm_next(nm_i, lim);
547 }
548 kring->nr_hwtail = nm_prev(nm_i, lim);
549 nm_prdis("tx completed [%d] -> hwtail %d", n, kring->nr_hwtail);
550
551 return n;
552 }
553
554 /* Compute a slot index in the middle between inf and sup. */
555 static inline u_int
ring_middle(u_int inf,u_int sup,u_int lim)556 ring_middle(u_int inf, u_int sup, u_int lim)
557 {
558 u_int n = lim + 1;
559 u_int e;
560
561 if (sup >= inf) {
562 e = (sup + inf) / 2;
563 } else { /* wrap around */
564 e = (sup + n + inf) / 2;
565 if (e >= n) {
566 e -= n;
567 }
568 }
569
570 if (unlikely(e >= n)) {
571 nm_prerr("This cannot happen");
572 e = 0;
573 }
574
575 return e;
576 }
577
578 static void
generic_set_tx_event(struct netmap_kring * kring,u_int hwcur)579 generic_set_tx_event(struct netmap_kring *kring, u_int hwcur)
580 {
581 u_int lim = kring->nkr_num_slots - 1;
582 struct mbuf *m;
583 u_int e;
584 u_int ntc = nm_next(kring->nr_hwtail, lim); /* next to clean */
585
586 if (ntc == hwcur) {
587 return; /* all buffers are free */
588 }
589
590 /*
591 * We have pending packets in the driver between hwtail+1
592 * and hwcur, and we have to chose one of these slot to
593 * generate a notification.
594 * There is a race but this is only called within txsync which
595 * does a double check.
596 */
597 #if 0
598 /* Choose a slot in the middle, so that we don't risk ending
599 * up in a situation where the client continuously wake up,
600 * fills one or a few TX slots and go to sleep again. */
601 e = ring_middle(ntc, hwcur, lim);
602 #else
603 /* Choose the first pending slot, to be safe against driver
604 * reordering mbuf transmissions. */
605 e = ntc;
606 #endif
607
608 m = kring->tx_pool[e];
609 if (m == NULL) {
610 /* An event is already in place. */
611 return;
612 }
613
614 mtx_lock_spin(&kring->tx_event_lock);
615 if (kring->tx_event) {
616 /* An event is already in place. */
617 mtx_unlock_spin(&kring->tx_event_lock);
618 return;
619 }
620
621 SET_MBUF_DESTRUCTOR(m, generic_mbuf_destructor);
622 kring->tx_event = m;
623 mtx_unlock_spin(&kring->tx_event_lock);
624
625 kring->tx_pool[e] = NULL;
626
627 nm_prdis("Request Event at %d mbuf %p refcnt %d", e, m, m ? MBUF_REFCNT(m) : -2 );
628
629 /* Decrement the refcount. This will free it if we lose the race
630 * with the driver. */
631 m_freem(m);
632 smp_mb();
633 }
634
635
636 /*
637 * generic_netmap_txsync() transforms netmap buffers into mbufs
638 * and passes them to the standard device driver
639 * (ndo_start_xmit() or ifp->if_transmit() ).
640 * On linux this is not done directly, but using dev_queue_xmit(),
641 * since it implements the TX flow control (and takes some locks).
642 */
643 static int
generic_netmap_txsync(struct netmap_kring * kring,int flags)644 generic_netmap_txsync(struct netmap_kring *kring, int flags)
645 {
646 struct netmap_adapter *na = kring->na;
647 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na;
648 struct ifnet *ifp = na->ifp;
649 struct netmap_ring *ring = kring->ring;
650 u_int nm_i; /* index into the netmap ring */ // j
651 u_int const lim = kring->nkr_num_slots - 1;
652 u_int const head = kring->rhead;
653 u_int ring_nr = kring->ring_id;
654
655 IFRATE(rate_ctx.new.txsync++);
656
657 rmb();
658
659 /*
660 * First part: process new packets to send.
661 */
662 nm_i = kring->nr_hwcur;
663 if (nm_i != head) { /* we have new packets to send */
664 struct nm_os_gen_arg a;
665 u_int event = -1;
666 #ifdef __FreeBSD__
667 struct epoch_tracker et;
668
669 NET_EPOCH_ENTER(et);
670 #endif
671
672 if (gna->txqdisc && nm_kr_txempty(kring)) {
673 /* In txqdisc mode, we ask for a delayed notification,
674 * but only when cur == hwtail, which means that the
675 * client is going to block. */
676 event = ring_middle(nm_i, head, lim);
677 nm_prdis("Place txqdisc event (hwcur=%u,event=%u,"
678 "head=%u,hwtail=%u)", nm_i, event, head,
679 kring->nr_hwtail);
680 }
681
682 a.ifp = ifp;
683 a.ring_nr = ring_nr;
684 a.head = a.tail = NULL;
685
686 while (nm_i != head) {
687 struct netmap_slot *slot = &ring->slot[nm_i];
688 u_int len = slot->len;
689 void *addr = NMB(na, slot);
690 /* device-specific */
691 struct mbuf *m;
692 int tx_ret;
693
694 NM_CHECK_ADDR_LEN(na, addr, len);
695
696 /* Tale a mbuf from the tx pool (replenishing the pool
697 * entry if necessary) and copy in the user packet. */
698 m = kring->tx_pool[nm_i];
699 if (unlikely(m == NULL)) {
700 kring->tx_pool[nm_i] = m =
701 nm_os_get_mbuf(ifp, NETMAP_BUF_SIZE(na));
702 if (m == NULL) {
703 nm_prlim(2, "Failed to replenish mbuf");
704 /* Here we could schedule a timer which
705 * retries to replenish after a while,
706 * and notifies the client when it
707 * manages to replenish some slots. In
708 * any case we break early to avoid
709 * crashes. */
710 break;
711 }
712 IFRATE(rate_ctx.new.txrepl++);
713 }
714
715 a.m = m;
716 a.addr = addr;
717 a.len = len;
718 a.qevent = (nm_i == event);
719 /* When not in txqdisc mode, we should ask
720 * notifications when NS_REPORT is set, or roughly
721 * every half ring. To optimize this, we set a
722 * notification event when the client runs out of
723 * TX ring space, or when transmission fails. In
724 * the latter case we also break early.
725 */
726 tx_ret = nm_os_generic_xmit_frame(&a);
727 if (unlikely(tx_ret)) {
728 if (!gna->txqdisc) {
729 /*
730 * No room for this mbuf in the device driver.
731 * Request a notification FOR A PREVIOUS MBUF,
732 * then call generic_netmap_tx_clean(kring) to do the
733 * double check and see if we can free more buffers.
734 * If there is space continue, else break;
735 * NOTE: the double check is necessary if the problem
736 * occurs in the txsync call after selrecord().
737 * Also, we need some way to tell the caller that not
738 * all buffers were queued onto the device (this was
739 * not a problem with native netmap driver where space
740 * is preallocated). The bridge has a similar problem
741 * and we solve it there by dropping the excess packets.
742 */
743 generic_set_tx_event(kring, nm_i);
744 if (generic_netmap_tx_clean(kring, gna->txqdisc)) {
745 /* space now available */
746 continue;
747 } else {
748 break;
749 }
750 }
751
752 /* In txqdisc mode, the netmap-aware qdisc
753 * queue has the same length as the number of
754 * netmap slots (N). Since tail is advanced
755 * only when packets are dequeued, qdisc
756 * queue overrun cannot happen, so
757 * nm_os_generic_xmit_frame() did not fail
758 * because of that.
759 * However, packets can be dropped because
760 * carrier is off, or because our qdisc is
761 * being deactivated, or possibly for other
762 * reasons. In these cases, we just let the
763 * packet to be dropped. */
764 IFRATE(rate_ctx.new.txdrop++);
765 }
766
767 slot->flags &= ~(NS_REPORT | NS_BUF_CHANGED);
768 nm_i = nm_next(nm_i, lim);
769 IFRATE(rate_ctx.new.txpkt++);
770 }
771 if (a.head != NULL) {
772 a.addr = NULL;
773 nm_os_generic_xmit_frame(&a);
774 }
775 /* Update hwcur to the next slot to transmit. Here nm_i
776 * is not necessarily head, we could break early. */
777 kring->nr_hwcur = nm_i;
778
779 #ifdef __FreeBSD__
780 NET_EPOCH_EXIT(et);
781 #endif
782 }
783
784 /*
785 * Second, reclaim completed buffers
786 */
787 if (!gna->txqdisc && (flags & NAF_FORCE_RECLAIM || nm_kr_txempty(kring))) {
788 /* No more available slots? Set a notification event
789 * on a netmap slot that will be cleaned in the future.
790 * No doublecheck is performed, since txsync() will be
791 * called twice by netmap_poll().
792 */
793 generic_set_tx_event(kring, nm_i);
794 }
795
796 generic_netmap_tx_clean(kring, gna->txqdisc);
797
798 return 0;
799 }
800
801
802 /*
803 * This handler is registered (through nm_os_catch_rx())
804 * within the attached network interface
805 * in the RX subsystem, so that every mbuf passed up by
806 * the driver can be stolen to the network stack.
807 * Stolen packets are put in a queue where the
808 * generic_netmap_rxsync() callback can extract them.
809 * Returns 1 if the packet was stolen, 0 otherwise.
810 */
811 int
generic_rx_handler(struct ifnet * ifp,struct mbuf * m)812 generic_rx_handler(struct ifnet *ifp, struct mbuf *m)
813 {
814 struct netmap_adapter *na = NA(ifp);
815 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na;
816 struct netmap_kring *kring;
817 u_int work_done;
818 u_int r = MBUF_RXQ(m); /* receive ring number */
819
820 if (r >= na->num_rx_rings) {
821 r = r % na->num_rx_rings;
822 }
823
824 kring = na->rx_rings[r];
825
826 if (kring->nr_mode == NKR_NETMAP_OFF) {
827 /* We must not intercept this mbuf. */
828 return 0;
829 }
830
831 /* limit the size of the queue */
832 if (unlikely(!gna->rxsg && MBUF_LEN(m) > NETMAP_BUF_SIZE(na))) {
833 /* This may happen when GRO/LRO features are enabled for
834 * the NIC driver when the generic adapter does not
835 * support RX scatter-gather. */
836 nm_prlim(2, "Warning: driver pushed up big packet "
837 "(size=%d)", (int)MBUF_LEN(m));
838 m_freem(m);
839 } else if (unlikely(mbq_len(&kring->rx_queue) > na->num_rx_desc)) {
840 m_freem(m);
841 } else {
842 mbq_safe_enqueue(&kring->rx_queue, m);
843 }
844
845 if (netmap_generic_mit < 32768) {
846 /* no rx mitigation, pass notification up */
847 netmap_generic_irq(na, r, &work_done);
848 } else {
849 /* same as send combining, filter notification if there is a
850 * pending timer, otherwise pass it up and start a timer.
851 */
852 if (likely(nm_os_mitigation_active(&gna->mit[r]))) {
853 /* Record that there is some pending work. */
854 gna->mit[r].mit_pending = 1;
855 } else {
856 netmap_generic_irq(na, r, &work_done);
857 nm_os_mitigation_start(&gna->mit[r]);
858 }
859 }
860
861 /* We have intercepted the mbuf. */
862 return 1;
863 }
864
865 /*
866 * generic_netmap_rxsync() extracts mbufs from the queue filled by
867 * generic_netmap_rx_handler() and puts their content in the netmap
868 * receive ring.
869 * Access must be protected because the rx handler is asynchronous,
870 */
871 static int
generic_netmap_rxsync(struct netmap_kring * kring,int flags)872 generic_netmap_rxsync(struct netmap_kring *kring, int flags)
873 {
874 struct netmap_ring *ring = kring->ring;
875 struct netmap_adapter *na = kring->na;
876 u_int nm_i; /* index into the netmap ring */ //j,
877 u_int n;
878 u_int const lim = kring->nkr_num_slots - 1;
879 u_int const head = kring->rhead;
880 int force_update = (flags & NAF_FORCE_READ) || kring->nr_kflags & NKR_PENDINTR;
881
882 /* Adapter-specific variables. */
883 u_int nm_buf_len = NETMAP_BUF_SIZE(na);
884 struct mbq tmpq;
885 struct mbuf *m;
886 int avail; /* in bytes */
887 int mlen;
888 int copy;
889
890 if (head > lim)
891 return netmap_ring_reinit(kring);
892
893 IFRATE(rate_ctx.new.rxsync++);
894
895 /*
896 * First part: skip past packets that userspace has released.
897 * This can possibly make room for the second part.
898 */
899 nm_i = kring->nr_hwcur;
900 if (nm_i != head) {
901 /* Userspace has released some packets. */
902 for (n = 0; nm_i != head; n++) {
903 struct netmap_slot *slot = &ring->slot[nm_i];
904
905 slot->flags &= ~NS_BUF_CHANGED;
906 nm_i = nm_next(nm_i, lim);
907 }
908 kring->nr_hwcur = head;
909 }
910
911 /*
912 * Second part: import newly received packets.
913 */
914 if (!netmap_no_pendintr && !force_update) {
915 return 0;
916 }
917
918 nm_i = kring->nr_hwtail; /* First empty slot in the receive ring. */
919
920 /* Compute the available space (in bytes) in this netmap ring.
921 * The first slot that is not considered in is the one before
922 * nr_hwcur. */
923
924 avail = nm_prev(kring->nr_hwcur, lim) - nm_i;
925 if (avail < 0)
926 avail += lim + 1;
927 avail *= nm_buf_len;
928
929 /* First pass: While holding the lock on the RX mbuf queue,
930 * extract as many mbufs as they fit the available space,
931 * and put them in a temporary queue.
932 * To avoid performing a per-mbuf division (mlen / nm_buf_len) to
933 * to update avail, we do the update in a while loop that we
934 * also use to set the RX slots, but without performing the copy. */
935 mbq_init(&tmpq);
936 mbq_lock(&kring->rx_queue);
937 for (n = 0;; n++) {
938 m = mbq_peek(&kring->rx_queue);
939 if (!m) {
940 /* No more packets from the driver. */
941 break;
942 }
943
944 mlen = MBUF_LEN(m);
945 if (mlen > avail) {
946 /* No more space in the ring. */
947 break;
948 }
949
950 mbq_dequeue(&kring->rx_queue);
951
952 while (mlen) {
953 copy = nm_buf_len;
954 if (mlen < copy) {
955 copy = mlen;
956 }
957 mlen -= copy;
958 avail -= nm_buf_len;
959
960 ring->slot[nm_i].len = copy;
961 ring->slot[nm_i].flags = (mlen ? NS_MOREFRAG : 0);
962 nm_i = nm_next(nm_i, lim);
963 }
964
965 mbq_enqueue(&tmpq, m);
966 }
967 mbq_unlock(&kring->rx_queue);
968
969 /* Second pass: Drain the temporary queue, going over the used RX slots,
970 * and perform the copy out of the RX queue lock. */
971 nm_i = kring->nr_hwtail;
972
973 for (;;) {
974 void *nmaddr;
975 int ofs = 0;
976 int morefrag;
977
978 m = mbq_dequeue(&tmpq);
979 if (!m) {
980 break;
981 }
982
983 do {
984 nmaddr = NMB(na, &ring->slot[nm_i]);
985 /* We only check the address here on generic rx rings. */
986 if (nmaddr == NETMAP_BUF_BASE(na)) { /* Bad buffer */
987 m_freem(m);
988 mbq_purge(&tmpq);
989 mbq_fini(&tmpq);
990 return netmap_ring_reinit(kring);
991 }
992
993 copy = ring->slot[nm_i].len;
994 m_copydata(m, ofs, copy, nmaddr);
995 ofs += copy;
996 morefrag = ring->slot[nm_i].flags & NS_MOREFRAG;
997 nm_i = nm_next(nm_i, lim);
998 } while (morefrag);
999
1000 m_freem(m);
1001 }
1002
1003 mbq_fini(&tmpq);
1004
1005 if (n) {
1006 kring->nr_hwtail = nm_i;
1007 IFRATE(rate_ctx.new.rxpkt += n);
1008 }
1009 kring->nr_kflags &= ~NKR_PENDINTR;
1010
1011 return 0;
1012 }
1013
1014 static void
generic_netmap_dtor(struct netmap_adapter * na)1015 generic_netmap_dtor(struct netmap_adapter *na)
1016 {
1017 struct netmap_generic_adapter *gna = (struct netmap_generic_adapter*)na;
1018 struct ifnet *ifp = netmap_generic_getifp(gna);
1019 struct netmap_adapter *prev_na = gna->prev;
1020
1021 if (prev_na != NULL) {
1022 netmap_adapter_put(prev_na);
1023 if (nm_iszombie(na)) {
1024 /*
1025 * The driver has been removed without releasing
1026 * the reference so we need to do it here.
1027 */
1028 netmap_adapter_put(prev_na);
1029 }
1030 nm_prinf("Native netmap adapter for %s restored", prev_na->name);
1031 }
1032 NM_RESTORE_NA(ifp, prev_na);
1033 /*
1034 * netmap_detach_common(), that it's called after this function,
1035 * overrides WNA(ifp) if na->ifp is not NULL.
1036 */
1037 na->ifp = NULL;
1038 nm_prinf("Emulated netmap adapter for %s destroyed", na->name);
1039 }
1040
1041 int
na_is_generic(struct netmap_adapter * na)1042 na_is_generic(struct netmap_adapter *na)
1043 {
1044 return na->nm_register == generic_netmap_register;
1045 }
1046
1047 /*
1048 * generic_netmap_attach() makes it possible to use netmap on
1049 * a device without native netmap support.
1050 * This is less performant than native support but potentially
1051 * faster than raw sockets or similar schemes.
1052 *
1053 * In this "emulated" mode, netmap rings do not necessarily
1054 * have the same size as those in the NIC. We use a default
1055 * value and possibly override it if the OS has ways to fetch the
1056 * actual configuration.
1057 */
1058 int
generic_netmap_attach(struct ifnet * ifp)1059 generic_netmap_attach(struct ifnet *ifp)
1060 {
1061 struct netmap_adapter *na;
1062 struct netmap_generic_adapter *gna;
1063 int retval;
1064 u_int num_tx_desc, num_rx_desc;
1065
1066 #ifdef __FreeBSD__
1067 if (ifp->if_type == IFT_LOOP) {
1068 nm_prerr("if_loop is not supported by %s", __func__);
1069 return EINVAL;
1070 }
1071 #endif
1072
1073 if (NM_NA_CLASH(ifp)) {
1074 /* If NA(ifp) is not null but there is no valid netmap
1075 * adapter it means that someone else is using the same
1076 * pointer (e.g. ax25_ptr on linux). This happens for
1077 * instance when also PF_RING is in use. */
1078 nm_prerr("Error: netmap adapter hook is busy");
1079 return EBUSY;
1080 }
1081
1082 num_tx_desc = num_rx_desc = netmap_generic_ringsize; /* starting point */
1083
1084 nm_os_generic_find_num_desc(ifp, &num_tx_desc, &num_rx_desc); /* ignore errors */
1085 if (num_tx_desc == 0 || num_rx_desc == 0) {
1086 nm_prerr("Device has no hw slots (tx %u, rx %u)", num_tx_desc, num_rx_desc);
1087 return EINVAL;
1088 }
1089
1090 gna = nm_os_malloc(sizeof(*gna));
1091 if (gna == NULL) {
1092 nm_prerr("no memory on attach, give up");
1093 return ENOMEM;
1094 }
1095 na = (struct netmap_adapter *)gna;
1096 strlcpy(na->name, ifp->if_xname, sizeof(na->name));
1097 na->ifp = ifp;
1098 na->num_tx_desc = num_tx_desc;
1099 na->num_rx_desc = num_rx_desc;
1100 na->rx_buf_maxsize = 32768;
1101 na->nm_register = &generic_netmap_register;
1102 na->nm_txsync = &generic_netmap_txsync;
1103 na->nm_rxsync = &generic_netmap_rxsync;
1104 na->nm_dtor = &generic_netmap_dtor;
1105 /* when using generic, NAF_NETMAP_ON is set so we force
1106 * NAF_SKIP_INTR to use the regular interrupt handler
1107 */
1108 na->na_flags = NAF_SKIP_INTR | NAF_HOST_RINGS;
1109
1110 nm_prdis("[GNA] num_tx_queues(%d), real_num_tx_queues(%d), len(%lu)",
1111 ifp->num_tx_queues, ifp->real_num_tx_queues,
1112 ifp->tx_queue_len);
1113 nm_prdis("[GNA] num_rx_queues(%d), real_num_rx_queues(%d)",
1114 ifp->num_rx_queues, ifp->real_num_rx_queues);
1115
1116 nm_os_generic_find_num_queues(ifp, &na->num_tx_rings, &na->num_rx_rings);
1117
1118 retval = netmap_attach_common(na);
1119 if (retval) {
1120 nm_os_free(gna);
1121 return retval;
1122 }
1123
1124 if (NM_NA_VALID(ifp)) {
1125 gna->prev = NA(ifp); /* save old na */
1126 netmap_adapter_get(gna->prev);
1127 }
1128 NM_ATTACH_NA(ifp, na);
1129
1130 nm_os_generic_set_features(gna);
1131
1132 nm_prinf("Emulated adapter for %s created (prev was %s)", na->name,
1133 gna->prev ? gna->prev->name : "NULL");
1134
1135 return retval;
1136 }
1137