xref: /freebsd/sys/dev/netmap/netmap_generic.c (revision f4b37ed0f8b307b1f3f0f630ca725d68f1dff30d)
1 /*
2  * Copyright (C) 2013-2014 Universita` di Pisa. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *   1. Redistributions of source code must retain the above copyright
8  *      notice, this list of conditions and the following disclaimer.
9  *   2. Redistributions in binary form must reproduce the above copyright
10  *      notice, this list of conditions and the following disclaimer in the
11  *      documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  */
25 
26 /*
27  * This module implements netmap support on top of standard,
28  * unmodified device drivers.
29  *
30  * A NIOCREGIF request is handled here if the device does not
31  * have native support. TX and RX rings are emulated as follows:
32  *
33  * NIOCREGIF
34  *	We preallocate a block of TX mbufs (roughly as many as
35  *	tx descriptors; the number is not critical) to speed up
36  *	operation during transmissions. The refcount on most of
37  *	these buffers is artificially bumped up so we can recycle
38  *	them more easily. Also, the destructor is intercepted
39  *	so we use it as an interrupt notification to wake up
40  *	processes blocked on a poll().
41  *
42  *	For each receive ring we allocate one "struct mbq"
43  *	(an mbuf tailq plus a spinlock). We intercept packets
44  *	(through if_input)
45  *	on the receive path and put them in the mbq from which
46  *	netmap receive routines can grab them.
47  *
48  * TX:
49  *	in the generic_txsync() routine, netmap buffers are copied
50  *	(or linked, in a future) to the preallocated mbufs
51  *	and pushed to the transmit queue. Some of these mbufs
52  *	(those with NS_REPORT, or otherwise every half ring)
53  *	have the refcount=1, others have refcount=2.
54  *	When the destructor is invoked, we take that as
55  *	a notification that all mbufs up to that one in
56  *	the specific ring have been completed, and generate
57  *	the equivalent of a transmit interrupt.
58  *
59  * RX:
60  *
61  */
62 
63 #ifdef __FreeBSD__
64 
65 #include <sys/cdefs.h> /* prerequisite */
66 __FBSDID("$FreeBSD$");
67 
68 #include <sys/types.h>
69 #include <sys/errno.h>
70 #include <sys/malloc.h>
71 #include <sys/lock.h>   /* PROT_EXEC */
72 #include <sys/rwlock.h>
73 #include <sys/socket.h> /* sockaddrs */
74 #include <sys/selinfo.h>
75 #include <net/if.h>
76 #include <net/if_var.h>
77 #include <machine/bus.h>        /* bus_dmamap_* in netmap_kern.h */
78 
79 // XXX temporary - D() defined here
80 #include <net/netmap.h>
81 #include <dev/netmap/netmap_kern.h>
82 #include <dev/netmap/netmap_mem2.h>
83 
84 #define rtnl_lock()	ND("rtnl_lock called")
85 #define rtnl_unlock()	ND("rtnl_unlock called")
86 #define MBUF_TXQ(m)	((m)->m_pkthdr.flowid)
87 #define MBUF_RXQ(m)	((m)->m_pkthdr.flowid)
88 #define smp_mb()
89 
90 /*
91  * FreeBSD mbuf allocator/deallocator in emulation mode:
92  *
93  * We allocate EXT_PACKET mbuf+clusters, but need to set M_NOFREE
94  * so that the destructor, if invoked, will not free the packet.
95  *    In principle we should set the destructor only on demand,
96  * but since there might be a race we better do it on allocation.
97  * As a consequence, we also need to set the destructor or we
98  * would leak buffers.
99  */
100 
101 /*
102  * mbuf wrappers
103  */
104 
105 /* mbuf destructor, also need to change the type to EXT_EXTREF,
106  * add an M_NOFREE flag, and then clear the flag and
107  * chain into uma_zfree(zone_pack, mf)
108  * (or reinstall the buffer ?)
109  */
110 #define SET_MBUF_DESTRUCTOR(m, fn)	do {		\
111 	(m)->m_ext.ext_free = (void *)fn;	\
112 	(m)->m_ext.ext_type = EXT_EXTREF;	\
113 } while (0)
114 
115 static void
116 netmap_default_mbuf_destructor(struct mbuf *m)
117 {
118 	/* restore original mbuf */
119 	m->m_ext.ext_buf = m->m_data = m->m_ext.ext_arg1;
120 	m->m_ext.ext_arg1 = NULL;
121 	m->m_ext.ext_type = EXT_PACKET;
122 	m->m_ext.ext_free = NULL;
123 	if (GET_MBUF_REFCNT(m) == 0)
124 		SET_MBUF_REFCNT(m, 1);
125 	uma_zfree(zone_pack, m);
126 }
127 
128 static inline struct mbuf *
129 netmap_get_mbuf(int len)
130 {
131 	struct mbuf *m;
132 	m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR | M_NOFREE);
133 	if (m) {
134 		m->m_ext.ext_arg1 = m->m_ext.ext_buf; // XXX save
135 		m->m_ext.ext_free = (void *)netmap_default_mbuf_destructor;
136 		m->m_ext.ext_type = EXT_EXTREF;
137 		ND(5, "create m %p refcnt %d", m, GET_MBUF_REFCNT(m));
138 	}
139 	return m;
140 }
141 
142 
143 
144 #else /* linux */
145 
146 #include "bsd_glue.h"
147 
148 #include <linux/rtnetlink.h>    /* rtnl_[un]lock() */
149 #include <linux/ethtool.h>      /* struct ethtool_ops, get_ringparam */
150 #include <linux/hrtimer.h>
151 
152 //#define REG_RESET
153 
154 #endif /* linux */
155 
156 
157 /* Common headers. */
158 #include <net/netmap.h>
159 #include <dev/netmap/netmap_kern.h>
160 #include <dev/netmap/netmap_mem2.h>
161 
162 
163 
164 /* ======================== usage stats =========================== */
165 
166 #ifdef RATE_GENERIC
167 #define IFRATE(x) x
168 struct rate_stats {
169 	unsigned long txpkt;
170 	unsigned long txsync;
171 	unsigned long txirq;
172 	unsigned long rxpkt;
173 	unsigned long rxirq;
174 	unsigned long rxsync;
175 };
176 
177 struct rate_context {
178 	unsigned refcount;
179 	struct timer_list timer;
180 	struct rate_stats new;
181 	struct rate_stats old;
182 };
183 
184 #define RATE_PRINTK(_NAME_) \
185 	printk( #_NAME_ " = %lu Hz\n", (cur._NAME_ - ctx->old._NAME_)/RATE_PERIOD);
186 #define RATE_PERIOD  2
187 static void rate_callback(unsigned long arg)
188 {
189 	struct rate_context * ctx = (struct rate_context *)arg;
190 	struct rate_stats cur = ctx->new;
191 	int r;
192 
193 	RATE_PRINTK(txpkt);
194 	RATE_PRINTK(txsync);
195 	RATE_PRINTK(txirq);
196 	RATE_PRINTK(rxpkt);
197 	RATE_PRINTK(rxsync);
198 	RATE_PRINTK(rxirq);
199 	printk("\n");
200 
201 	ctx->old = cur;
202 	r = mod_timer(&ctx->timer, jiffies +
203 			msecs_to_jiffies(RATE_PERIOD * 1000));
204 	if (unlikely(r))
205 		D("[v1000] Error: mod_timer()");
206 }
207 
208 static struct rate_context rate_ctx;
209 
210 void generic_rate(int txp, int txs, int txi, int rxp, int rxs, int rxi)
211 {
212     if (txp) rate_ctx.new.txpkt++;
213     if (txs) rate_ctx.new.txsync++;
214     if (txi) rate_ctx.new.txirq++;
215     if (rxp) rate_ctx.new.rxpkt++;
216     if (rxs) rate_ctx.new.rxsync++;
217     if (rxi) rate_ctx.new.rxirq++;
218 }
219 
220 #else /* !RATE */
221 #define IFRATE(x)
222 #endif /* !RATE */
223 
224 
225 /* =============== GENERIC NETMAP ADAPTER SUPPORT ================= */
226 
227 /*
228  * Wrapper used by the generic adapter layer to notify
229  * the poller threads. Differently from netmap_rx_irq(), we check
230  * only NAF_NETMAP_ON instead of NAF_NATIVE_ON to enable the irq.
231  */
232 static void
233 netmap_generic_irq(struct ifnet *ifp, u_int q, u_int *work_done)
234 {
235 	struct netmap_adapter *na = NA(ifp);
236 	if (unlikely(!nm_netmap_on(na)))
237 		return;
238 
239 	netmap_common_irq(ifp, q, work_done);
240 }
241 
242 
243 /* Enable/disable netmap mode for a generic network interface. */
244 static int
245 generic_netmap_register(struct netmap_adapter *na, int enable)
246 {
247 	struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na;
248 	struct mbuf *m;
249 	int error;
250 	int i, r;
251 
252 	if (!na)
253 		return EINVAL;
254 
255 #ifdef REG_RESET
256 	error = ifp->netdev_ops->ndo_stop(ifp);
257 	if (error) {
258 		return error;
259 	}
260 #endif /* REG_RESET */
261 
262 	if (enable) { /* Enable netmap mode. */
263 		/* Init the mitigation support on all the rx queues. */
264 		gna->mit = malloc(na->num_rx_rings * sizeof(struct nm_generic_mit),
265 					M_DEVBUF, M_NOWAIT | M_ZERO);
266 		if (!gna->mit) {
267 			D("mitigation allocation failed");
268 			error = ENOMEM;
269 			goto out;
270 		}
271 		for (r=0; r<na->num_rx_rings; r++)
272 			netmap_mitigation_init(&gna->mit[r], r, na);
273 
274 		/* Initialize the rx queue, as generic_rx_handler() can
275 		 * be called as soon as netmap_catch_rx() returns.
276 		 */
277 		for (r=0; r<na->num_rx_rings; r++) {
278 			mbq_safe_init(&na->rx_rings[r].rx_queue);
279 		}
280 
281 		/*
282 		 * Preallocate packet buffers for the tx rings.
283 		 */
284 		for (r=0; r<na->num_tx_rings; r++)
285 			na->tx_rings[r].tx_pool = NULL;
286 		for (r=0; r<na->num_tx_rings; r++) {
287 			na->tx_rings[r].tx_pool = malloc(na->num_tx_desc * sizeof(struct mbuf *),
288 					M_DEVBUF, M_NOWAIT | M_ZERO);
289 			if (!na->tx_rings[r].tx_pool) {
290 				D("tx_pool allocation failed");
291 				error = ENOMEM;
292 				goto free_tx_pools;
293 			}
294 			for (i=0; i<na->num_tx_desc; i++)
295 				na->tx_rings[r].tx_pool[i] = NULL;
296 			for (i=0; i<na->num_tx_desc; i++) {
297 				m = netmap_get_mbuf(NETMAP_BUF_SIZE(na));
298 				if (!m) {
299 					D("tx_pool[%d] allocation failed", i);
300 					error = ENOMEM;
301 					goto free_tx_pools;
302 				}
303 				na->tx_rings[r].tx_pool[i] = m;
304 			}
305 		}
306 		rtnl_lock();
307 		/* Prepare to intercept incoming traffic. */
308 		error = netmap_catch_rx(gna, 1);
309 		if (error) {
310 			D("netdev_rx_handler_register() failed (%d)", error);
311 			goto register_handler;
312 		}
313 		na->na_flags |= NAF_NETMAP_ON;
314 
315 		/* Make netmap control the packet steering. */
316 		netmap_catch_tx(gna, 1);
317 
318 		rtnl_unlock();
319 
320 #ifdef RATE_GENERIC
321 		if (rate_ctx.refcount == 0) {
322 			D("setup_timer()");
323 			memset(&rate_ctx, 0, sizeof(rate_ctx));
324 			setup_timer(&rate_ctx.timer, &rate_callback, (unsigned long)&rate_ctx);
325 			if (mod_timer(&rate_ctx.timer, jiffies + msecs_to_jiffies(1500))) {
326 				D("Error: mod_timer()");
327 			}
328 		}
329 		rate_ctx.refcount++;
330 #endif /* RATE */
331 
332 	} else if (na->tx_rings[0].tx_pool) {
333 		/* Disable netmap mode. We enter here only if the previous
334 		   generic_netmap_register(na, 1) was successfull.
335 		   If it was not, na->tx_rings[0].tx_pool was set to NULL by the
336 		   error handling code below. */
337 		rtnl_lock();
338 
339 		na->na_flags &= ~NAF_NETMAP_ON;
340 
341 		/* Release packet steering control. */
342 		netmap_catch_tx(gna, 0);
343 
344 		/* Do not intercept packets on the rx path. */
345 		netmap_catch_rx(gna, 0);
346 
347 		rtnl_unlock();
348 
349 		/* Free the mbufs going to the netmap rings */
350 		for (r=0; r<na->num_rx_rings; r++) {
351 			mbq_safe_purge(&na->rx_rings[r].rx_queue);
352 			mbq_safe_destroy(&na->rx_rings[r].rx_queue);
353 		}
354 
355 		for (r=0; r<na->num_rx_rings; r++)
356 			netmap_mitigation_cleanup(&gna->mit[r]);
357 		free(gna->mit, M_DEVBUF);
358 
359 		for (r=0; r<na->num_tx_rings; r++) {
360 			for (i=0; i<na->num_tx_desc; i++) {
361 				m_freem(na->tx_rings[r].tx_pool[i]);
362 			}
363 			free(na->tx_rings[r].tx_pool, M_DEVBUF);
364 		}
365 
366 #ifdef RATE_GENERIC
367 		if (--rate_ctx.refcount == 0) {
368 			D("del_timer()");
369 			del_timer(&rate_ctx.timer);
370 		}
371 #endif
372 	}
373 
374 #ifdef REG_RESET
375 	error = ifp->netdev_ops->ndo_open(ifp);
376 	if (error) {
377 		goto free_tx_pools;
378 	}
379 #endif
380 
381 	return 0;
382 
383 register_handler:
384 	rtnl_unlock();
385 free_tx_pools:
386 	for (r=0; r<na->num_tx_rings; r++) {
387 		if (na->tx_rings[r].tx_pool == NULL)
388 			continue;
389 		for (i=0; i<na->num_tx_desc; i++)
390 			if (na->tx_rings[r].tx_pool[i])
391 				m_freem(na->tx_rings[r].tx_pool[i]);
392 		free(na->tx_rings[r].tx_pool, M_DEVBUF);
393 		na->tx_rings[r].tx_pool = NULL;
394 	}
395 	for (r=0; r<na->num_rx_rings; r++) {
396 		netmap_mitigation_cleanup(&gna->mit[r]);
397 		mbq_safe_destroy(&na->rx_rings[r].rx_queue);
398 	}
399 	free(gna->mit, M_DEVBUF);
400 out:
401 
402 	return error;
403 }
404 
405 /*
406  * Callback invoked when the device driver frees an mbuf used
407  * by netmap to transmit a packet. This usually happens when
408  * the NIC notifies the driver that transmission is completed.
409  */
410 static void
411 generic_mbuf_destructor(struct mbuf *m)
412 {
413 	netmap_generic_irq(MBUF_IFP(m), MBUF_TXQ(m), NULL);
414 #ifdef __FreeBSD__
415 	if (netmap_verbose)
416 		RD(5, "Tx irq (%p) queue %d index %d" , m, MBUF_TXQ(m), (int)(uintptr_t)m->m_ext.ext_arg1);
417 	netmap_default_mbuf_destructor(m);
418 #endif /* __FreeBSD__ */
419 	IFRATE(rate_ctx.new.txirq++);
420 }
421 
422 extern int netmap_adaptive_io;
423 
424 /* Record completed transmissions and update hwtail.
425  *
426  * The oldest tx buffer not yet completed is at nr_hwtail + 1,
427  * nr_hwcur is the first unsent buffer.
428  */
429 static u_int
430 generic_netmap_tx_clean(struct netmap_kring *kring)
431 {
432 	u_int const lim = kring->nkr_num_slots - 1;
433 	u_int nm_i = nm_next(kring->nr_hwtail, lim);
434 	u_int hwcur = kring->nr_hwcur;
435 	u_int n = 0;
436 	struct mbuf **tx_pool = kring->tx_pool;
437 
438 	while (nm_i != hwcur) { /* buffers not completed */
439 		struct mbuf *m = tx_pool[nm_i];
440 
441 		if (unlikely(m == NULL)) {
442 			/* this is done, try to replenish the entry */
443 			tx_pool[nm_i] = m = netmap_get_mbuf(NETMAP_BUF_SIZE(kring->na));
444 			if (unlikely(m == NULL)) {
445 				D("mbuf allocation failed, XXX error");
446 				// XXX how do we proceed ? break ?
447 				return -ENOMEM;
448 			}
449 		} else if (GET_MBUF_REFCNT(m) != 1) {
450 			break; /* This mbuf is still busy: its refcnt is 2. */
451 		}
452 		n++;
453 		nm_i = nm_next(nm_i, lim);
454 #if 0 /* rate adaptation */
455 		if (netmap_adaptive_io > 1) {
456 			if (n >= netmap_adaptive_io)
457 				break;
458 		} else if (netmap_adaptive_io) {
459 			/* if hwcur - nm_i < lim/8 do an early break
460 			 * so we prevent the sender from stalling. See CVT.
461 			 */
462 			if (hwcur >= nm_i) {
463 				if (hwcur - nm_i < lim/2)
464 					break;
465 			} else {
466 				if (hwcur + lim + 1 - nm_i < lim/2)
467 					break;
468 			}
469 		}
470 #endif
471 	}
472 	kring->nr_hwtail = nm_prev(nm_i, lim);
473 	ND("tx completed [%d] -> hwtail %d", n, kring->nr_hwtail);
474 
475 	return n;
476 }
477 
478 
479 /*
480  * We have pending packets in the driver between nr_hwtail +1 and hwcur.
481  * Compute a position in the middle, to be used to generate
482  * a notification.
483  */
484 static inline u_int
485 generic_tx_event_middle(struct netmap_kring *kring, u_int hwcur)
486 {
487 	u_int n = kring->nkr_num_slots;
488 	u_int ntc = nm_next(kring->nr_hwtail, n-1);
489 	u_int e;
490 
491 	if (hwcur >= ntc) {
492 		e = (hwcur + ntc) / 2;
493 	} else { /* wrap around */
494 		e = (hwcur + n + ntc) / 2;
495 		if (e >= n) {
496 			e -= n;
497 		}
498 	}
499 
500 	if (unlikely(e >= n)) {
501 		D("This cannot happen");
502 		e = 0;
503 	}
504 
505 	return e;
506 }
507 
508 /*
509  * We have pending packets in the driver between nr_hwtail+1 and hwcur.
510  * Schedule a notification approximately in the middle of the two.
511  * There is a race but this is only called within txsync which does
512  * a double check.
513  */
514 static void
515 generic_set_tx_event(struct netmap_kring *kring, u_int hwcur)
516 {
517 	struct mbuf *m;
518 	u_int e;
519 
520 	if (nm_next(kring->nr_hwtail, kring->nkr_num_slots -1) == hwcur) {
521 		return; /* all buffers are free */
522 	}
523 	e = generic_tx_event_middle(kring, hwcur);
524 
525 	m = kring->tx_pool[e];
526 	ND(5, "Request Event at %d mbuf %p refcnt %d", e, m, m ? GET_MBUF_REFCNT(m) : -2 );
527 	if (m == NULL) {
528 		/* This can happen if there is already an event on the netmap
529 		   slot 'e': There is nothing to do. */
530 		return;
531 	}
532 	kring->tx_pool[e] = NULL;
533 	SET_MBUF_DESTRUCTOR(m, generic_mbuf_destructor);
534 
535 	// XXX wmb() ?
536 	/* Decrement the refcount an free it if we have the last one. */
537 	m_freem(m);
538 	smp_mb();
539 }
540 
541 
542 /*
543  * generic_netmap_txsync() transforms netmap buffers into mbufs
544  * and passes them to the standard device driver
545  * (ndo_start_xmit() or ifp->if_transmit() ).
546  * On linux this is not done directly, but using dev_queue_xmit(),
547  * since it implements the TX flow control (and takes some locks).
548  */
549 static int
550 generic_netmap_txsync(struct netmap_kring *kring, int flags)
551 {
552 	struct netmap_adapter *na = kring->na;
553 	struct ifnet *ifp = na->ifp;
554 	struct netmap_ring *ring = kring->ring;
555 	u_int nm_i;	/* index into the netmap ring */ // j
556 	u_int const lim = kring->nkr_num_slots - 1;
557 	u_int const head = kring->rhead;
558 	u_int ring_nr = kring->ring_id;
559 
560 	IFRATE(rate_ctx.new.txsync++);
561 
562 	// TODO: handle the case of mbuf allocation failure
563 
564 	rmb();
565 
566 	/*
567 	 * First part: process new packets to send.
568 	 */
569 	nm_i = kring->nr_hwcur;
570 	if (nm_i != head) {	/* we have new packets to send */
571 		while (nm_i != head) {
572 			struct netmap_slot *slot = &ring->slot[nm_i];
573 			u_int len = slot->len;
574 			void *addr = NMB(na, slot);
575 
576 			/* device-specific */
577 			struct mbuf *m;
578 			int tx_ret;
579 
580 			NM_CHECK_ADDR_LEN(na, addr, len);
581 
582 			/* Tale a mbuf from the tx pool and copy in the user packet. */
583 			m = kring->tx_pool[nm_i];
584 			if (unlikely(!m)) {
585 				RD(5, "This should never happen");
586 				kring->tx_pool[nm_i] = m = netmap_get_mbuf(NETMAP_BUF_SIZE(na));
587 				if (unlikely(m == NULL)) {
588 					D("mbuf allocation failed");
589 					break;
590 				}
591 			}
592 			/* XXX we should ask notifications when NS_REPORT is set,
593 			 * or roughly every half frame. We can optimize this
594 			 * by lazily requesting notifications only when a
595 			 * transmission fails. Probably the best way is to
596 			 * break on failures and set notifications when
597 			 * ring->cur == ring->tail || nm_i != cur
598 			 */
599 			tx_ret = generic_xmit_frame(ifp, m, addr, len, ring_nr);
600 			if (unlikely(tx_ret)) {
601 				ND(5, "start_xmit failed: err %d [nm_i %u, head %u, hwtail %u]",
602 						tx_ret, nm_i, head, kring->nr_hwtail);
603 				/*
604 				 * No room for this mbuf in the device driver.
605 				 * Request a notification FOR A PREVIOUS MBUF,
606 				 * then call generic_netmap_tx_clean(kring) to do the
607 				 * double check and see if we can free more buffers.
608 				 * If there is space continue, else break;
609 				 * NOTE: the double check is necessary if the problem
610 				 * occurs in the txsync call after selrecord().
611 				 * Also, we need some way to tell the caller that not
612 				 * all buffers were queued onto the device (this was
613 				 * not a problem with native netmap driver where space
614 				 * is preallocated). The bridge has a similar problem
615 				 * and we solve it there by dropping the excess packets.
616 				 */
617 				generic_set_tx_event(kring, nm_i);
618 				if (generic_netmap_tx_clean(kring)) { /* space now available */
619 					continue;
620 				} else {
621 					break;
622 				}
623 			}
624 			slot->flags &= ~(NS_REPORT | NS_BUF_CHANGED);
625 			nm_i = nm_next(nm_i, lim);
626 			IFRATE(rate_ctx.new.txpkt ++);
627 		}
628 
629 		/* Update hwcur to the next slot to transmit. */
630 		kring->nr_hwcur = nm_i; /* not head, we could break early */
631 	}
632 
633 	/*
634 	 * Second, reclaim completed buffers
635 	 */
636 	if (flags & NAF_FORCE_RECLAIM || nm_kr_txempty(kring)) {
637 		/* No more available slots? Set a notification event
638 		 * on a netmap slot that will be cleaned in the future.
639 		 * No doublecheck is performed, since txsync() will be
640 		 * called twice by netmap_poll().
641 		 */
642 		generic_set_tx_event(kring, nm_i);
643 	}
644 	ND("tx #%d, hwtail = %d", n, kring->nr_hwtail);
645 
646 	generic_netmap_tx_clean(kring);
647 
648 	return 0;
649 }
650 
651 
652 /*
653  * This handler is registered (through netmap_catch_rx())
654  * within the attached network interface
655  * in the RX subsystem, so that every mbuf passed up by
656  * the driver can be stolen to the network stack.
657  * Stolen packets are put in a queue where the
658  * generic_netmap_rxsync() callback can extract them.
659  */
660 void
661 generic_rx_handler(struct ifnet *ifp, struct mbuf *m)
662 {
663 	struct netmap_adapter *na = NA(ifp);
664 	struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na;
665 	u_int work_done;
666 	u_int rr = MBUF_RXQ(m); // receive ring number
667 
668 	if (rr >= na->num_rx_rings) {
669 		rr = rr % na->num_rx_rings; // XXX expensive...
670 	}
671 
672 	/* limit the size of the queue */
673 	if (unlikely(mbq_len(&na->rx_rings[rr].rx_queue) > 1024)) {
674 		m_freem(m);
675 	} else {
676 		mbq_safe_enqueue(&na->rx_rings[rr].rx_queue, m);
677 	}
678 
679 	if (netmap_generic_mit < 32768) {
680 		/* no rx mitigation, pass notification up */
681 		netmap_generic_irq(na->ifp, rr, &work_done);
682 		IFRATE(rate_ctx.new.rxirq++);
683 	} else {
684 		/* same as send combining, filter notification if there is a
685 		 * pending timer, otherwise pass it up and start a timer.
686 		 */
687 		if (likely(netmap_mitigation_active(&gna->mit[rr]))) {
688 			/* Record that there is some pending work. */
689 			gna->mit[rr].mit_pending = 1;
690 		} else {
691 			netmap_generic_irq(na->ifp, rr, &work_done);
692 			IFRATE(rate_ctx.new.rxirq++);
693 			netmap_mitigation_start(&gna->mit[rr]);
694 		}
695 	}
696 }
697 
698 /*
699  * generic_netmap_rxsync() extracts mbufs from the queue filled by
700  * generic_netmap_rx_handler() and puts their content in the netmap
701  * receive ring.
702  * Access must be protected because the rx handler is asynchronous,
703  */
704 static int
705 generic_netmap_rxsync(struct netmap_kring *kring, int flags)
706 {
707 	struct netmap_ring *ring = kring->ring;
708 	struct netmap_adapter *na = kring->na;
709 	u_int nm_i;	/* index into the netmap ring */ //j,
710 	u_int n;
711 	u_int const lim = kring->nkr_num_slots - 1;
712 	u_int const head = kring->rhead;
713 	int force_update = (flags & NAF_FORCE_READ) || kring->nr_kflags & NKR_PENDINTR;
714 
715 	if (head > lim)
716 		return netmap_ring_reinit(kring);
717 
718 	/*
719 	 * First part: import newly received packets.
720 	 */
721 	if (netmap_no_pendintr || force_update) {
722 		/* extract buffers from the rx queue, stop at most one
723 		 * slot before nr_hwcur (stop_i)
724 		 */
725 		uint16_t slot_flags = kring->nkr_slot_flags;
726 		u_int stop_i = nm_prev(kring->nr_hwcur, lim);
727 
728 		nm_i = kring->nr_hwtail; /* first empty slot in the receive ring */
729 		for (n = 0; nm_i != stop_i; n++) {
730 			int len;
731 			void *addr = NMB(na, &ring->slot[nm_i]);
732 			struct mbuf *m;
733 
734 			/* we only check the address here on generic rx rings */
735 			if (addr == NETMAP_BUF_BASE(na)) { /* Bad buffer */
736 				return netmap_ring_reinit(kring);
737 			}
738 			/*
739 			 * Call the locked version of the function.
740 			 * XXX Ideally we could grab a batch of mbufs at once
741 			 * and save some locking overhead.
742 			 */
743 			m = mbq_safe_dequeue(&kring->rx_queue);
744 			if (!m)	/* no more data */
745 				break;
746 			len = MBUF_LEN(m);
747 			m_copydata(m, 0, len, addr);
748 			ring->slot[nm_i].len = len;
749 			ring->slot[nm_i].flags = slot_flags;
750 			m_freem(m);
751 			nm_i = nm_next(nm_i, lim);
752 		}
753 		if (n) {
754 			kring->nr_hwtail = nm_i;
755 			IFRATE(rate_ctx.new.rxpkt += n);
756 		}
757 		kring->nr_kflags &= ~NKR_PENDINTR;
758 	}
759 
760 	// XXX should we invert the order ?
761 	/*
762 	 * Second part: skip past packets that userspace has released.
763 	 */
764 	nm_i = kring->nr_hwcur;
765 	if (nm_i != head) {
766 		/* Userspace has released some packets. */
767 		for (n = 0; nm_i != head; n++) {
768 			struct netmap_slot *slot = &ring->slot[nm_i];
769 
770 			slot->flags &= ~NS_BUF_CHANGED;
771 			nm_i = nm_next(nm_i, lim);
772 		}
773 		kring->nr_hwcur = head;
774 	}
775 	IFRATE(rate_ctx.new.rxsync++);
776 
777 	return 0;
778 }
779 
780 static void
781 generic_netmap_dtor(struct netmap_adapter *na)
782 {
783 	struct netmap_generic_adapter *gna = (struct netmap_generic_adapter*)na;
784 	struct ifnet *ifp = netmap_generic_getifp(gna);
785 	struct netmap_adapter *prev_na = gna->prev;
786 
787 	if (prev_na != NULL) {
788 		D("Released generic NA %p", gna);
789 		if_rele(ifp);
790 		netmap_adapter_put(prev_na);
791 		if (na->ifp == NULL) {
792 		        /*
793 		         * The driver has been removed without releasing
794 		         * the reference so we need to do it here.
795 		         */
796 		        netmap_adapter_put(prev_na);
797 		}
798 	}
799 	WNA(ifp) = prev_na;
800 	D("Restored native NA %p", prev_na);
801 	na->ifp = NULL;
802 }
803 
804 /*
805  * generic_netmap_attach() makes it possible to use netmap on
806  * a device without native netmap support.
807  * This is less performant than native support but potentially
808  * faster than raw sockets or similar schemes.
809  *
810  * In this "emulated" mode, netmap rings do not necessarily
811  * have the same size as those in the NIC. We use a default
812  * value and possibly override it if the OS has ways to fetch the
813  * actual configuration.
814  */
815 int
816 generic_netmap_attach(struct ifnet *ifp)
817 {
818 	struct netmap_adapter *na;
819 	struct netmap_generic_adapter *gna;
820 	int retval;
821 	u_int num_tx_desc, num_rx_desc;
822 
823 	num_tx_desc = num_rx_desc = netmap_generic_ringsize; /* starting point */
824 
825 	generic_find_num_desc(ifp, &num_tx_desc, &num_rx_desc); /* ignore errors */
826 	ND("Netmap ring size: TX = %d, RX = %d", num_tx_desc, num_rx_desc);
827 	if (num_tx_desc == 0 || num_rx_desc == 0) {
828 		D("Device has no hw slots (tx %u, rx %u)", num_tx_desc, num_rx_desc);
829 		return EINVAL;
830 	}
831 
832 	gna = malloc(sizeof(*gna), M_DEVBUF, M_NOWAIT | M_ZERO);
833 	if (gna == NULL) {
834 		D("no memory on attach, give up");
835 		return ENOMEM;
836 	}
837 	na = (struct netmap_adapter *)gna;
838 	strncpy(na->name, ifp->if_xname, sizeof(na->name));
839 	na->ifp = ifp;
840 	na->num_tx_desc = num_tx_desc;
841 	na->num_rx_desc = num_rx_desc;
842 	na->nm_register = &generic_netmap_register;
843 	na->nm_txsync = &generic_netmap_txsync;
844 	na->nm_rxsync = &generic_netmap_rxsync;
845 	na->nm_dtor = &generic_netmap_dtor;
846 	/* when using generic, NAF_NETMAP_ON is set so we force
847 	 * NAF_SKIP_INTR to use the regular interrupt handler
848 	 */
849 	na->na_flags = NAF_SKIP_INTR | NAF_HOST_RINGS;
850 
851 	ND("[GNA] num_tx_queues(%d), real_num_tx_queues(%d), len(%lu)",
852 			ifp->num_tx_queues, ifp->real_num_tx_queues,
853 			ifp->tx_queue_len);
854 	ND("[GNA] num_rx_queues(%d), real_num_rx_queues(%d)",
855 			ifp->num_rx_queues, ifp->real_num_rx_queues);
856 
857 	generic_find_num_queues(ifp, &na->num_tx_rings, &na->num_rx_rings);
858 
859 	retval = netmap_attach_common(na);
860 	if (retval) {
861 		free(gna, M_DEVBUF);
862 	}
863 
864 	return retval;
865 }
866