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