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