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