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