xref: /freebsd/sys/dev/netmap/netmap.c (revision 74036c4de983981ee2b23f91e285363293aa7c3c)
1 /*
2  * Copyright (C) 2011-2013 Matteo Landi, Luigi Rizzo. 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 #define NM_BRIDGE
27 
28 /*
29  * This module supports memory mapped access to network devices,
30  * see netmap(4).
31  *
32  * The module uses a large, memory pool allocated by the kernel
33  * and accessible as mmapped memory by multiple userspace threads/processes.
34  * The memory pool contains packet buffers and "netmap rings",
35  * i.e. user-accessible copies of the interface's queues.
36  *
37  * Access to the network card works like this:
38  * 1. a process/thread issues one or more open() on /dev/netmap, to create
39  *    select()able file descriptor on which events are reported.
40  * 2. on each descriptor, the process issues an ioctl() to identify
41  *    the interface that should report events to the file descriptor.
42  * 3. on each descriptor, the process issues an mmap() request to
43  *    map the shared memory region within the process' address space.
44  *    The list of interesting queues is indicated by a location in
45  *    the shared memory region.
46  * 4. using the functions in the netmap(4) userspace API, a process
47  *    can look up the occupation state of a queue, access memory buffers,
48  *    and retrieve received packets or enqueue packets to transmit.
49  * 5. using some ioctl()s the process can synchronize the userspace view
50  *    of the queue with the actual status in the kernel. This includes both
51  *    receiving the notification of new packets, and transmitting new
52  *    packets on the output interface.
53  * 6. select() or poll() can be used to wait for events on individual
54  *    transmit or receive queues (or all queues for a given interface).
55  */
56 
57 #ifdef linux
58 #include "bsd_glue.h"
59 static netdev_tx_t linux_netmap_start(struct sk_buff *skb, struct net_device *dev);
60 #endif /* linux */
61 
62 #ifdef __APPLE__
63 #include "osx_glue.h"
64 #endif /* __APPLE__ */
65 
66 #ifdef __FreeBSD__
67 #include <sys/cdefs.h> /* prerequisite */
68 __FBSDID("$FreeBSD$");
69 
70 #include <sys/types.h>
71 #include <sys/module.h>
72 #include <sys/errno.h>
73 #include <sys/param.h>	/* defines used in kernel.h */
74 #include <sys/jail.h>
75 #include <sys/kernel.h>	/* types used in module initialization */
76 #include <sys/conf.h>	/* cdevsw struct */
77 #include <sys/uio.h>	/* uio struct */
78 #include <sys/sockio.h>
79 #include <sys/socketvar.h>	/* struct socket */
80 #include <sys/malloc.h>
81 #include <sys/mman.h>	/* PROT_EXEC */
82 #include <sys/poll.h>
83 #include <sys/proc.h>
84 #include <sys/rwlock.h>
85 #include <vm/vm.h>	/* vtophys */
86 #include <vm/pmap.h>	/* vtophys */
87 #include <sys/socket.h> /* sockaddrs */
88 #include <machine/bus.h>
89 #include <sys/selinfo.h>
90 #include <sys/sysctl.h>
91 #include <net/if.h>
92 #include <net/bpf.h>		/* BIOCIMMEDIATE */
93 #include <net/vnet.h>
94 #include <machine/bus.h>	/* bus_dmamap_* */
95 
96 MALLOC_DEFINE(M_NETMAP, "netmap", "Network memory map");
97 #endif /* __FreeBSD__ */
98 
99 #include <net/netmap.h>
100 #include <dev/netmap/netmap_kern.h>
101 
102 /* XXX the following variables must be deprecated and included in nm_mem */
103 u_int netmap_total_buffers;
104 u_int netmap_buf_size;
105 char *netmap_buffer_base;	/* address of an invalid buffer */
106 
107 /* user-controlled variables */
108 int netmap_verbose;
109 
110 static int netmap_no_timestamp; /* don't timestamp on rxsync */
111 
112 SYSCTL_NODE(_dev, OID_AUTO, netmap, CTLFLAG_RW, 0, "Netmap args");
113 SYSCTL_INT(_dev_netmap, OID_AUTO, verbose,
114     CTLFLAG_RW, &netmap_verbose, 0, "Verbose mode");
115 SYSCTL_INT(_dev_netmap, OID_AUTO, no_timestamp,
116     CTLFLAG_RW, &netmap_no_timestamp, 0, "no_timestamp");
117 int netmap_mitigate = 1;
118 SYSCTL_INT(_dev_netmap, OID_AUTO, mitigate, CTLFLAG_RW, &netmap_mitigate, 0, "");
119 int netmap_no_pendintr = 1;
120 SYSCTL_INT(_dev_netmap, OID_AUTO, no_pendintr,
121     CTLFLAG_RW, &netmap_no_pendintr, 0, "Always look for new received packets.");
122 int netmap_txsync_retry = 2;
123 SYSCTL_INT(_dev_netmap, OID_AUTO, txsync_retry, CTLFLAG_RW,
124     &netmap_txsync_retry, 0 , "Number of txsync loops in bridge's flush.");
125 
126 int netmap_drop = 0;	/* debugging */
127 int netmap_flags = 0;	/* debug flags */
128 int netmap_fwd = 0;	/* force transparent mode */
129 
130 SYSCTL_INT(_dev_netmap, OID_AUTO, drop, CTLFLAG_RW, &netmap_drop, 0 , "");
131 SYSCTL_INT(_dev_netmap, OID_AUTO, flags, CTLFLAG_RW, &netmap_flags, 0 , "");
132 SYSCTL_INT(_dev_netmap, OID_AUTO, fwd, CTLFLAG_RW, &netmap_fwd, 0 , "");
133 
134 #ifdef NM_BRIDGE /* support for netmap virtual switch, called VALE */
135 
136 /*
137  * system parameters (most of them in netmap_kern.h)
138  * NM_NAME	prefix for switch port names, default "vale"
139  * NM_MAXPORTS	number of ports
140  * NM_BRIDGES	max number of switches in the system.
141  *	XXX should become a sysctl or tunable
142  *
143  * Switch ports are named valeX:Y where X is the switch name and Y
144  * is the port. If Y matches a physical interface name, the port is
145  * connected to a physical device.
146  *
147  * Unlike physical interfaces, switch ports use their own memory region
148  * for rings and buffers.
149  * The virtual interfaces use per-queue lock instead of core lock.
150  * In the tx loop, we aggregate traffic in batches to make all operations
151  * faster. The batch size is NM_BDG_BATCH
152  */
153 #define NM_BDG_MAXRINGS		16	/* XXX unclear how many. */
154 #define NM_BRIDGE_RINGSIZE	1024	/* in the device */
155 #define NM_BDG_HASH		1024	/* forwarding table entries */
156 #define NM_BDG_BATCH		1024	/* entries in the forwarding buffer */
157 #define	NM_BRIDGES		8	/* number of bridges */
158 
159 
160 int netmap_bridge = NM_BDG_BATCH; /* bridge batch size */
161 SYSCTL_INT(_dev_netmap, OID_AUTO, bridge, CTLFLAG_RW, &netmap_bridge, 0 , "");
162 
163 #ifdef linux
164 
165 #define	refcount_acquire(_a)	atomic_add(1, (atomic_t *)_a)
166 #define	refcount_release(_a)	atomic_dec_and_test((atomic_t *)_a)
167 
168 #else /* !linux */
169 
170 #ifdef __FreeBSD__
171 #include <sys/endian.h>
172 #include <sys/refcount.h>
173 #endif /* __FreeBSD__ */
174 
175 #define prefetch(x)	__builtin_prefetch(x)
176 
177 #endif /* !linux */
178 
179 /*
180  * These are used to handle reference counters for bridge ports.
181  */
182 #define	ADD_BDG_REF(ifp)	refcount_acquire(&NA(ifp)->na_bdg_refcount)
183 #define	DROP_BDG_REF(ifp)	refcount_release(&NA(ifp)->na_bdg_refcount)
184 
185 static void bdg_netmap_attach(struct netmap_adapter *);
186 static int bdg_netmap_reg(struct ifnet *ifp, int onoff);
187 static int kern_netmap_regif(struct nmreq *nmr);
188 
189 /* per-tx-queue entry */
190 struct nm_bdg_fwd {	/* forwarding entry for a bridge */
191 	void *buf;
192 	uint32_t ft_dst;	/* dst port */
193 	uint16_t ft_len;	/* src len */
194 	uint16_t ft_next;	/* next packet to same destination */
195 };
196 
197 /* We need to build a list of buffers going to each destination.
198  * Each buffer is in one entry of struct nm_bdg_fwd, we use ft_next
199  * to build the list, and struct nm_bdg_q below for the queue.
200  * The structure should compact because potentially we have a lot
201  * of destinations.
202  */
203 struct nm_bdg_q {
204 	uint16_t bq_head;
205 	uint16_t bq_tail;
206 };
207 
208 struct nm_hash_ent {
209 	uint64_t	mac;	/* the top 2 bytes are the epoch */
210 	uint64_t	ports;
211 };
212 
213 /*
214  * Interfaces for a bridge are all in bdg_ports[].
215  * The array has fixed size, an empty entry does not terminate
216  * the search. But lookups only occur on attach/detach so we
217  * don't mind if they are slow.
218  *
219  * The bridge is non blocking on the transmit ports.
220  *
221  * bdg_lock protects accesses to the bdg_ports array.
222  * This is a rw lock (or equivalent).
223  */
224 struct nm_bridge {
225 	int namelen;	/* 0 means free */
226 
227 	/* XXX what is the proper alignment/layout ? */
228 	NM_RWLOCK_T bdg_lock;	/* protects bdg_ports */
229 	struct netmap_adapter *bdg_ports[NM_BDG_MAXPORTS];
230 
231 	char basename[IFNAMSIZ];
232 	/*
233 	 * The function to decide the destination port.
234 	 * It returns either of an index of the destination port,
235 	 * NM_BDG_BROADCAST to broadcast this packet, or NM_BDG_NOPORT not to
236 	 * forward this packet.  ring_nr is the source ring index, and the
237 	 * function may overwrite this value to forward this packet to a
238 	 * different ring index.
239 	 * This function must be set by netmap_bdgctl().
240 	 */
241 	bdg_lookup_fn_t nm_bdg_lookup;
242 
243 	/* the forwarding table, MAC+ports */
244 	struct nm_hash_ent ht[NM_BDG_HASH];
245 };
246 
247 struct nm_bridge nm_bridges[NM_BRIDGES];
248 NM_LOCK_T	netmap_bridge_mutex;
249 
250 /* other OS will have these macros defined in their own glue code. */
251 
252 #ifdef __FreeBSD__
253 #define BDG_LOCK()		mtx_lock(&netmap_bridge_mutex)
254 #define BDG_UNLOCK()		mtx_unlock(&netmap_bridge_mutex)
255 #define BDG_WLOCK(b)		rw_wlock(&(b)->bdg_lock)
256 #define BDG_WUNLOCK(b)		rw_wunlock(&(b)->bdg_lock)
257 #define BDG_RLOCK(b)		rw_rlock(&(b)->bdg_lock)
258 #define BDG_RUNLOCK(b)		rw_runlock(&(b)->bdg_lock)
259 
260 /* set/get variables. OS-specific macros may wrap these
261  * assignments into read/write lock or similar
262  */
263 #define BDG_SET_VAR(lval, p)	(lval = p)
264 #define BDG_GET_VAR(lval)	(lval)
265 #define BDG_FREE(p)		free(p, M_DEVBUF)
266 #endif /* __FreeBSD__ */
267 
268 static __inline int
269 nma_is_vp(struct netmap_adapter *na)
270 {
271 	return na->nm_register == bdg_netmap_reg;
272 }
273 static __inline int
274 nma_is_host(struct netmap_adapter *na)
275 {
276 	return na->nm_register == NULL;
277 }
278 static __inline int
279 nma_is_hw(struct netmap_adapter *na)
280 {
281 	/* In case of sw adapter, nm_register is NULL */
282 	return !nma_is_vp(na) && !nma_is_host(na);
283 }
284 
285 /*
286  * Regarding holding a NIC, if the NIC is owned by the kernel
287  * (i.e., bridge), neither another bridge nor user can use it;
288  * if the NIC is owned by a user, only users can share it.
289  * Evaluation must be done under NMA_LOCK().
290  */
291 #define NETMAP_OWNED_BY_KERN(ifp)	(!nma_is_vp(NA(ifp)) && NA(ifp)->na_bdg)
292 #define NETMAP_OWNED_BY_ANY(ifp) \
293 	(NETMAP_OWNED_BY_KERN(ifp) || (NA(ifp)->refcount > 0))
294 
295 /*
296  * NA(ifp)->bdg_port	port index
297  */
298 
299 // XXX only for multiples of 64 bytes, non overlapped.
300 static inline void
301 pkt_copy(void *_src, void *_dst, int l)
302 {
303         uint64_t *src = _src;
304         uint64_t *dst = _dst;
305         if (unlikely(l >= 1024)) {
306                 bcopy(src, dst, l);
307                 return;
308         }
309         for (; likely(l > 0); l-=64) {
310                 *dst++ = *src++;
311                 *dst++ = *src++;
312                 *dst++ = *src++;
313                 *dst++ = *src++;
314                 *dst++ = *src++;
315                 *dst++ = *src++;
316                 *dst++ = *src++;
317                 *dst++ = *src++;
318         }
319 }
320 
321 
322 /*
323  * locate a bridge among the existing ones.
324  * a ':' in the name terminates the bridge name. Otherwise, just NM_NAME.
325  * We assume that this is called with a name of at least NM_NAME chars.
326  */
327 static struct nm_bridge *
328 nm_find_bridge(const char *name, int create)
329 {
330 	int i, l, namelen;
331 	struct nm_bridge *b = NULL;
332 
333 	namelen = strlen(NM_NAME);	/* base length */
334 	l = strlen(name);		/* actual length */
335 	for (i = namelen + 1; i < l; i++) {
336 		if (name[i] == ':') {
337 			namelen = i;
338 			break;
339 		}
340 	}
341 	if (namelen >= IFNAMSIZ)
342 		namelen = IFNAMSIZ;
343 	ND("--- prefix is '%.*s' ---", namelen, name);
344 
345 	BDG_LOCK();
346 	/* lookup the name, remember empty slot if there is one */
347 	for (i = 0; i < NM_BRIDGES; i++) {
348 		struct nm_bridge *x = nm_bridges + i;
349 
350 		if (x->namelen == 0) {
351 			if (create && b == NULL)
352 				b = x;	/* record empty slot */
353 		} else if (x->namelen != namelen) {
354 			continue;
355 		} else if (strncmp(name, x->basename, namelen) == 0) {
356 			ND("found '%.*s' at %d", namelen, name, i);
357 			b = x;
358 			break;
359 		}
360 	}
361 	if (i == NM_BRIDGES && b) { /* name not found, can create entry */
362 		strncpy(b->basename, name, namelen);
363 		b->namelen = namelen;
364 		/* set the default function */
365 		b->nm_bdg_lookup = netmap_bdg_learning;
366 		/* reset the MAC address table */
367 		bzero(b->ht, sizeof(struct nm_hash_ent) * NM_BDG_HASH);
368 	}
369 	BDG_UNLOCK();
370 	return b;
371 }
372 
373 
374 /*
375  * Free the forwarding tables for rings attached to switch ports.
376  */
377 static void
378 nm_free_bdgfwd(struct netmap_adapter *na)
379 {
380 	int nrings, i;
381 	struct netmap_kring *kring;
382 
383 	nrings = nma_is_vp(na) ? na->num_tx_rings : na->num_rx_rings;
384 	kring = nma_is_vp(na) ? na->tx_rings : na->rx_rings;
385 	for (i = 0; i < nrings; i++) {
386 		if (kring[i].nkr_ft) {
387 			free(kring[i].nkr_ft, M_DEVBUF);
388 			kring[i].nkr_ft = NULL; /* protect from freeing twice */
389 		}
390 	}
391 	if (nma_is_hw(na))
392 		nm_free_bdgfwd(SWNA(na->ifp));
393 }
394 
395 
396 /*
397  * Allocate the forwarding tables for the rings attached to the bridge ports.
398  */
399 static int
400 nm_alloc_bdgfwd(struct netmap_adapter *na)
401 {
402 	int nrings, l, i, num_dstq;
403 	struct netmap_kring *kring;
404 
405 	/* all port:rings + broadcast */
406 	num_dstq = NM_BDG_MAXPORTS * NM_BDG_MAXRINGS + 1;
407 	l = sizeof(struct nm_bdg_fwd) * NM_BDG_BATCH;
408 	l += sizeof(struct nm_bdg_q) * num_dstq;
409 	l += sizeof(uint16_t) * NM_BDG_BATCH;
410 
411 	nrings = nma_is_vp(na) ? na->num_tx_rings : na->num_rx_rings;
412 	kring = nma_is_vp(na) ? na->tx_rings : na->rx_rings;
413 	for (i = 0; i < nrings; i++) {
414 		struct nm_bdg_fwd *ft;
415 		struct nm_bdg_q *dstq;
416 		int j;
417 
418 		ft = malloc(l, M_DEVBUF, M_NOWAIT | M_ZERO);
419 		if (!ft) {
420 			nm_free_bdgfwd(na);
421 			return ENOMEM;
422 		}
423 		dstq = (struct nm_bdg_q *)(ft + NM_BDG_BATCH);
424 		for (j = 0; j < num_dstq; j++)
425 			dstq[j].bq_head = dstq[j].bq_tail = NM_BDG_BATCH;
426 		kring[i].nkr_ft = ft;
427 	}
428 	if (nma_is_hw(na))
429 		nm_alloc_bdgfwd(SWNA(na->ifp));
430 	return 0;
431 }
432 
433 #endif /* NM_BRIDGE */
434 
435 
436 /*
437  * Fetch configuration from the device, to cope with dynamic
438  * reconfigurations after loading the module.
439  */
440 static int
441 netmap_update_config(struct netmap_adapter *na)
442 {
443 	struct ifnet *ifp = na->ifp;
444 	u_int txr, txd, rxr, rxd;
445 
446 	txr = txd = rxr = rxd = 0;
447 	if (na->nm_config) {
448 		na->nm_config(ifp, &txr, &txd, &rxr, &rxd);
449 	} else {
450 		/* take whatever we had at init time */
451 		txr = na->num_tx_rings;
452 		txd = na->num_tx_desc;
453 		rxr = na->num_rx_rings;
454 		rxd = na->num_rx_desc;
455 	}
456 
457 	if (na->num_tx_rings == txr && na->num_tx_desc == txd &&
458 	    na->num_rx_rings == rxr && na->num_rx_desc == rxd)
459 		return 0; /* nothing changed */
460 	if (netmap_verbose || na->refcount > 0) {
461 		D("stored config %s: txring %d x %d, rxring %d x %d",
462 			ifp->if_xname,
463 			na->num_tx_rings, na->num_tx_desc,
464 			na->num_rx_rings, na->num_rx_desc);
465 		D("new config %s: txring %d x %d, rxring %d x %d",
466 			ifp->if_xname, txr, txd, rxr, rxd);
467 	}
468 	if (na->refcount == 0) {
469 		D("configuration changed (but fine)");
470 		na->num_tx_rings = txr;
471 		na->num_tx_desc = txd;
472 		na->num_rx_rings = rxr;
473 		na->num_rx_desc = rxd;
474 		return 0;
475 	}
476 	D("configuration changed while active, this is bad...");
477 	return 1;
478 }
479 
480 /*------------- memory allocator -----------------*/
481 #include "netmap_mem2.c"
482 /*------------ end of memory allocator ----------*/
483 
484 
485 /* Structure associated to each thread which registered an interface.
486  *
487  * The first 4 fields of this structure are written by NIOCREGIF and
488  * read by poll() and NIOC?XSYNC.
489  * There is low contention among writers (actually, a correct user program
490  * should have no contention among writers) and among writers and readers,
491  * so we use a single global lock to protect the structure initialization.
492  * Since initialization involves the allocation of memory, we reuse the memory
493  * allocator lock.
494  * Read access to the structure is lock free. Readers must check that
495  * np_nifp is not NULL before using the other fields.
496  * If np_nifp is NULL initialization has not been performed, so they should
497  * return an error to userlevel.
498  *
499  * The ref_done field is used to regulate access to the refcount in the
500  * memory allocator. The refcount must be incremented at most once for
501  * each open("/dev/netmap"). The increment is performed by the first
502  * function that calls netmap_get_memory() (currently called by
503  * mmap(), NIOCGINFO and NIOCREGIF).
504  * If the refcount is incremented, it is then decremented when the
505  * private structure is destroyed.
506  */
507 struct netmap_priv_d {
508 	struct netmap_if * volatile np_nifp;	/* netmap interface descriptor. */
509 
510 	struct ifnet	*np_ifp;	/* device for which we hold a reference */
511 	int		np_ringid;	/* from the ioctl */
512 	u_int		np_qfirst, np_qlast;	/* range of rings to scan */
513 	uint16_t	np_txpoll;
514 
515 	unsigned long	ref_done;	/* use with NMA_LOCK held */
516 };
517 
518 
519 static int
520 netmap_get_memory(struct netmap_priv_d* p)
521 {
522 	int error = 0;
523 	NMA_LOCK();
524 	if (!p->ref_done) {
525 		error = netmap_memory_finalize();
526 		if (!error)
527 			p->ref_done = 1;
528 	}
529 	NMA_UNLOCK();
530 	return error;
531 }
532 
533 /*
534  * File descriptor's private data destructor.
535  *
536  * Call nm_register(ifp,0) to stop netmap mode on the interface and
537  * revert to normal operation. We expect that np_ifp has not gone.
538  */
539 /* call with NMA_LOCK held */
540 static void
541 netmap_dtor_locked(void *data)
542 {
543 	struct netmap_priv_d *priv = data;
544 	struct ifnet *ifp = priv->np_ifp;
545 	struct netmap_adapter *na = NA(ifp);
546 	struct netmap_if *nifp = priv->np_nifp;
547 
548 	na->refcount--;
549 	if (na->refcount <= 0) {	/* last instance */
550 		u_int i, j, lim;
551 
552 		if (netmap_verbose)
553 			D("deleting last instance for %s", ifp->if_xname);
554 		/*
555 		 * (TO CHECK) This function is only called
556 		 * when the last reference to this file descriptor goes
557 		 * away. This means we cannot have any pending poll()
558 		 * or interrupt routine operating on the structure.
559 		 */
560 		na->nm_register(ifp, 0); /* off, clear IFCAP_NETMAP */
561 		/* Wake up any sleeping threads. netmap_poll will
562 		 * then return POLLERR
563 		 */
564 		for (i = 0; i < na->num_tx_rings + 1; i++)
565 			selwakeuppri(&na->tx_rings[i].si, PI_NET);
566 		for (i = 0; i < na->num_rx_rings + 1; i++)
567 			selwakeuppri(&na->rx_rings[i].si, PI_NET);
568 		selwakeuppri(&na->tx_si, PI_NET);
569 		selwakeuppri(&na->rx_si, PI_NET);
570 #ifdef NM_BRIDGE
571 		nm_free_bdgfwd(na);
572 #endif /* NM_BRIDGE */
573 		/* release all buffers */
574 		for (i = 0; i < na->num_tx_rings + 1; i++) {
575 			struct netmap_ring *ring = na->tx_rings[i].ring;
576 			lim = na->tx_rings[i].nkr_num_slots;
577 			for (j = 0; j < lim; j++)
578 				netmap_free_buf(nifp, ring->slot[j].buf_idx);
579 			/* knlist_destroy(&na->tx_rings[i].si.si_note); */
580 			mtx_destroy(&na->tx_rings[i].q_lock);
581 		}
582 		for (i = 0; i < na->num_rx_rings + 1; i++) {
583 			struct netmap_ring *ring = na->rx_rings[i].ring;
584 			lim = na->rx_rings[i].nkr_num_slots;
585 			for (j = 0; j < lim; j++)
586 				netmap_free_buf(nifp, ring->slot[j].buf_idx);
587 			/* knlist_destroy(&na->rx_rings[i].si.si_note); */
588 			mtx_destroy(&na->rx_rings[i].q_lock);
589 		}
590 		/* XXX kqueue(9) needed; these will mirror knlist_init. */
591 		/* knlist_destroy(&na->tx_si.si_note); */
592 		/* knlist_destroy(&na->rx_si.si_note); */
593 		netmap_free_rings(na);
594 		if (nma_is_hw(na))
595 			SWNA(ifp)->tx_rings = SWNA(ifp)->rx_rings = NULL;
596 	}
597 	netmap_if_free(nifp);
598 }
599 
600 
601 /* we assume netmap adapter exists */
602 static void
603 nm_if_rele(struct ifnet *ifp)
604 {
605 #ifndef NM_BRIDGE
606 	if_rele(ifp);
607 #else /* NM_BRIDGE */
608 	int i, full = 0, is_hw;
609 	struct nm_bridge *b;
610 	struct netmap_adapter *na;
611 
612 	/* I can be called not only for get_ifp()-ed references where netmap's
613 	 * capability is guaranteed, but also for non-netmap-capable NICs.
614 	 */
615 	if (!NETMAP_CAPABLE(ifp) || !NA(ifp)->na_bdg) {
616 		if_rele(ifp);
617 		return;
618 	}
619 	if (!DROP_BDG_REF(ifp))
620 		return;
621 
622 	na = NA(ifp);
623 	b = na->na_bdg;
624 	is_hw = nma_is_hw(na);
625 
626 	BDG_WLOCK(b);
627 	ND("want to disconnect %s from the bridge", ifp->if_xname);
628 	full = 0;
629 	/* remove the entry from the bridge, also check
630 	 * if there are any leftover interfaces
631 	 * XXX we should optimize this code, e.g. going directly
632 	 * to na->bdg_port, and having a counter of ports that
633 	 * are connected. But it is not in a critical path.
634 	 * In NIC's case, index of sw na is always higher than hw na
635 	 */
636 	for (i = 0; i < NM_BDG_MAXPORTS; i++) {
637 		struct netmap_adapter *tmp = BDG_GET_VAR(b->bdg_ports[i]);
638 
639 		if (tmp == na) {
640 			/* disconnect from bridge */
641 			BDG_SET_VAR(b->bdg_ports[i], NULL);
642 			na->na_bdg = NULL;
643 			if (is_hw && SWNA(ifp)->na_bdg) {
644 				/* disconnect sw adapter too */
645 				int j = SWNA(ifp)->bdg_port;
646 				BDG_SET_VAR(b->bdg_ports[j], NULL);
647 				SWNA(ifp)->na_bdg = NULL;
648 			}
649 		} else if (tmp != NULL) {
650 			full = 1;
651 		}
652 	}
653 	BDG_WUNLOCK(b);
654 	if (full == 0) {
655 		ND("marking bridge %d as free", b - nm_bridges);
656 		b->namelen = 0;
657 		b->nm_bdg_lookup = NULL;
658 	}
659 	if (na->na_bdg) { /* still attached to the bridge */
660 		D("ouch, cannot find ifp to remove");
661 	} else if (is_hw) {
662 		if_rele(ifp);
663 	} else {
664 		bzero(na, sizeof(*na));
665 		free(na, M_DEVBUF);
666 		bzero(ifp, sizeof(*ifp));
667 		free(ifp, M_DEVBUF);
668 	}
669 #endif /* NM_BRIDGE */
670 }
671 
672 static void
673 netmap_dtor(void *data)
674 {
675 	struct netmap_priv_d *priv = data;
676 	struct ifnet *ifp = priv->np_ifp;
677 
678 	NMA_LOCK();
679 	if (ifp) {
680 		struct netmap_adapter *na = NA(ifp);
681 
682 		if (na->na_bdg)
683 			BDG_WLOCK(na->na_bdg);
684 		na->nm_lock(ifp, NETMAP_REG_LOCK, 0);
685 		netmap_dtor_locked(data);
686 		na->nm_lock(ifp, NETMAP_REG_UNLOCK, 0);
687 		if (na->na_bdg)
688 			BDG_WUNLOCK(na->na_bdg);
689 
690 		nm_if_rele(ifp); /* might also destroy *na */
691 	}
692 	if (priv->ref_done) {
693 		netmap_memory_deref();
694 	}
695 	NMA_UNLOCK();
696 	bzero(priv, sizeof(*priv));	/* XXX for safety */
697 	free(priv, M_DEVBUF);
698 }
699 
700 
701 #ifdef __FreeBSD__
702 #include <vm/vm.h>
703 #include <vm/vm_param.h>
704 #include <vm/vm_object.h>
705 #include <vm/vm_page.h>
706 #include <vm/vm_pager.h>
707 #include <vm/uma.h>
708 
709 /*
710  * In order to track whether pages are still mapped, we hook into
711  * the standard cdev_pager and intercept the constructor and
712  * destructor.
713  * XXX but then ? Do we really use the information ?
714  * Need to investigate.
715  */
716 static struct cdev_pager_ops saved_cdev_pager_ops;
717 
718 
719 static int
720 netmap_dev_pager_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot,
721     vm_ooffset_t foff, struct ucred *cred, u_short *color)
722 {
723 	if (netmap_verbose)
724 		D("first mmap for %p", handle);
725 	return saved_cdev_pager_ops.cdev_pg_ctor(handle,
726 			size, prot, foff, cred, color);
727 }
728 
729 
730 static void
731 netmap_dev_pager_dtor(void *handle)
732 {
733 	saved_cdev_pager_ops.cdev_pg_dtor(handle);
734 	ND("ready to release memory for %p", handle);
735 }
736 
737 
738 static struct cdev_pager_ops netmap_cdev_pager_ops = {
739         .cdev_pg_ctor = netmap_dev_pager_ctor,
740         .cdev_pg_dtor = netmap_dev_pager_dtor,
741         .cdev_pg_fault = NULL,
742 };
743 
744 
745 // XXX check whether we need netmap_mmap_single _and_ netmap_mmap
746 static int
747 netmap_mmap_single(struct cdev *cdev, vm_ooffset_t *foff,
748 	vm_size_t objsize,  vm_object_t *objp, int prot)
749 {
750 	vm_object_t obj;
751 
752 	ND("cdev %p foff %jd size %jd objp %p prot %d", cdev,
753 	    (intmax_t )*foff, (intmax_t )objsize, objp, prot);
754 	obj = vm_pager_allocate(OBJT_DEVICE, cdev, objsize, prot, *foff,
755             curthread->td_ucred);
756 	ND("returns obj %p", obj);
757 	if (obj == NULL)
758 		return EINVAL;
759 	if (saved_cdev_pager_ops.cdev_pg_fault == NULL) {
760 		ND("initialize cdev_pager_ops");
761 		saved_cdev_pager_ops = *(obj->un_pager.devp.ops);
762 		netmap_cdev_pager_ops.cdev_pg_fault =
763 			saved_cdev_pager_ops.cdev_pg_fault;
764 	};
765 	obj->un_pager.devp.ops = &netmap_cdev_pager_ops;
766 	*objp = obj;
767 	return 0;
768 }
769 #endif /* __FreeBSD__ */
770 
771 
772 /*
773  * mmap(2) support for the "netmap" device.
774  *
775  * Expose all the memory previously allocated by our custom memory
776  * allocator: this way the user has only to issue a single mmap(2), and
777  * can work on all the data structures flawlessly.
778  *
779  * Return 0 on success, -1 otherwise.
780  */
781 
782 #ifdef __FreeBSD__
783 static int
784 netmap_mmap(__unused struct cdev *dev,
785 #if __FreeBSD_version < 900000
786 		vm_offset_t offset, vm_paddr_t *paddr, int nprot
787 #else
788 		vm_ooffset_t offset, vm_paddr_t *paddr, int nprot,
789 		__unused vm_memattr_t *memattr
790 #endif
791 	)
792 {
793 	int error = 0;
794 	struct netmap_priv_d *priv;
795 
796 	if (nprot & PROT_EXEC)
797 		return (-1);	// XXX -1 or EINVAL ?
798 
799 	error = devfs_get_cdevpriv((void **)&priv);
800 	if (error == EBADF) {	/* called on fault, memory is initialized */
801 		ND(5, "handling fault at ofs 0x%x", offset);
802 		error = 0;
803 	} else if (error == 0)	/* make sure memory is set */
804 		error = netmap_get_memory(priv);
805 	if (error)
806 		return (error);
807 
808 	ND("request for offset 0x%x", (uint32_t)offset);
809 	*paddr = netmap_ofstophys(offset);
810 
811 	return (*paddr ? 0 : ENOMEM);
812 }
813 
814 
815 static int
816 netmap_close(struct cdev *dev, int fflag, int devtype, struct thread *td)
817 {
818 	if (netmap_verbose)
819 		D("dev %p fflag 0x%x devtype %d td %p",
820 			dev, fflag, devtype, td);
821 	return 0;
822 }
823 
824 
825 static int
826 netmap_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
827 {
828 	struct netmap_priv_d *priv;
829 	int error;
830 
831 	priv = malloc(sizeof(struct netmap_priv_d), M_DEVBUF,
832 			      M_NOWAIT | M_ZERO);
833 	if (priv == NULL)
834 		return ENOMEM;
835 
836 	error = devfs_set_cdevpriv(priv, netmap_dtor);
837 	if (error)
838 	        return error;
839 
840 	return 0;
841 }
842 #endif /* __FreeBSD__ */
843 
844 
845 /*
846  * Handlers for synchronization of the queues from/to the host.
847  * Netmap has two operating modes:
848  * - in the default mode, the rings connected to the host stack are
849  *   just another ring pair managed by userspace;
850  * - in transparent mode (XXX to be defined) incoming packets
851  *   (from the host or the NIC) are marked as NS_FORWARD upon
852  *   arrival, and the user application has a chance to reset the
853  *   flag for packets that should be dropped.
854  *   On the RXSYNC or poll(), packets in RX rings between
855  *   kring->nr_kcur and ring->cur with NS_FORWARD still set are moved
856  *   to the other side.
857  * The transfer NIC --> host is relatively easy, just encapsulate
858  * into mbufs and we are done. The host --> NIC side is slightly
859  * harder because there might not be room in the tx ring so it
860  * might take a while before releasing the buffer.
861  */
862 
863 
864 /*
865  * pass a chain of buffers to the host stack as coming from 'dst'
866  */
867 static void
868 netmap_send_up(struct ifnet *dst, struct mbuf *head)
869 {
870 	struct mbuf *m;
871 
872 	/* send packets up, outside the lock */
873 	while ((m = head) != NULL) {
874 		head = head->m_nextpkt;
875 		m->m_nextpkt = NULL;
876 		if (netmap_verbose & NM_VERB_HOST)
877 			D("sending up pkt %p size %d", m, MBUF_LEN(m));
878 		NM_SEND_UP(dst, m);
879 	}
880 }
881 
882 struct mbq {
883 	struct mbuf *head;
884 	struct mbuf *tail;
885 	int count;
886 };
887 
888 
889 /*
890  * put a copy of the buffers marked NS_FORWARD into an mbuf chain.
891  * Run from hwcur to cur - reserved
892  */
893 static void
894 netmap_grab_packets(struct netmap_kring *kring, struct mbq *q, int force)
895 {
896 	/* Take packets from hwcur to cur-reserved and pass them up.
897 	 * In case of no buffers we give up. At the end of the loop,
898 	 * the queue is drained in all cases.
899 	 * XXX handle reserved
900 	 */
901 	int k = kring->ring->cur - kring->ring->reserved;
902 	u_int n, lim = kring->nkr_num_slots - 1;
903 	struct mbuf *m, *tail = q->tail;
904 
905 	if (k < 0)
906 		k = k + kring->nkr_num_slots;
907 	for (n = kring->nr_hwcur; n != k;) {
908 		struct netmap_slot *slot = &kring->ring->slot[n];
909 
910 		n = (n == lim) ? 0 : n + 1;
911 		if ((slot->flags & NS_FORWARD) == 0 && !force)
912 			continue;
913 		if (slot->len < 14 || slot->len > NETMAP_BUF_SIZE) {
914 			D("bad pkt at %d len %d", n, slot->len);
915 			continue;
916 		}
917 		slot->flags &= ~NS_FORWARD; // XXX needed ?
918 		m = m_devget(NMB(slot), slot->len, 0, kring->na->ifp, NULL);
919 
920 		if (m == NULL)
921 			break;
922 		if (tail)
923 			tail->m_nextpkt = m;
924 		else
925 			q->head = m;
926 		tail = m;
927 		q->count++;
928 		m->m_nextpkt = NULL;
929 	}
930 	q->tail = tail;
931 }
932 
933 
934 /*
935  * called under main lock to send packets from the host to the NIC
936  * The host ring has packets from nr_hwcur to (cur - reserved)
937  * to be sent down. We scan the tx rings, which have just been
938  * flushed so nr_hwcur == cur. Pushing packets down means
939  * increment cur and decrement avail.
940  * XXX to be verified
941  */
942 static void
943 netmap_sw_to_nic(struct netmap_adapter *na)
944 {
945 	struct netmap_kring *kring = &na->rx_rings[na->num_rx_rings];
946 	struct netmap_kring *k1 = &na->tx_rings[0];
947 	int i, howmany, src_lim, dst_lim;
948 
949 	howmany = kring->nr_hwavail;	/* XXX otherwise cur - reserved - nr_hwcur */
950 
951 	src_lim = kring->nkr_num_slots;
952 	for (i = 0; howmany > 0 && i < na->num_tx_rings; i++, k1++) {
953 		ND("%d packets left to ring %d (space %d)", howmany, i, k1->nr_hwavail);
954 		dst_lim = k1->nkr_num_slots;
955 		while (howmany > 0 && k1->ring->avail > 0) {
956 			struct netmap_slot *src, *dst, tmp;
957 			src = &kring->ring->slot[kring->nr_hwcur];
958 			dst = &k1->ring->slot[k1->ring->cur];
959 			tmp = *src;
960 			src->buf_idx = dst->buf_idx;
961 			src->flags = NS_BUF_CHANGED;
962 
963 			dst->buf_idx = tmp.buf_idx;
964 			dst->len = tmp.len;
965 			dst->flags = NS_BUF_CHANGED;
966 			ND("out len %d buf %d from %d to %d",
967 				dst->len, dst->buf_idx,
968 				kring->nr_hwcur, k1->ring->cur);
969 
970 			if (++kring->nr_hwcur >= src_lim)
971 				kring->nr_hwcur = 0;
972 			howmany--;
973 			kring->nr_hwavail--;
974 			if (++k1->ring->cur >= dst_lim)
975 				k1->ring->cur = 0;
976 			k1->ring->avail--;
977 		}
978 		kring->ring->cur = kring->nr_hwcur; // XXX
979 		k1++;
980 	}
981 }
982 
983 
984 /*
985  * netmap_sync_to_host() passes packets up. We are called from a
986  * system call in user process context, and the only contention
987  * can be among multiple user threads erroneously calling
988  * this routine concurrently.
989  */
990 static void
991 netmap_sync_to_host(struct netmap_adapter *na)
992 {
993 	struct netmap_kring *kring = &na->tx_rings[na->num_tx_rings];
994 	struct netmap_ring *ring = kring->ring;
995 	u_int k, lim = kring->nkr_num_slots - 1;
996 	struct mbq q = { NULL, NULL };
997 
998 	k = ring->cur;
999 	if (k > lim) {
1000 		netmap_ring_reinit(kring);
1001 		return;
1002 	}
1003 	// na->nm_lock(na->ifp, NETMAP_CORE_LOCK, 0);
1004 
1005 	/* Take packets from hwcur to cur and pass them up.
1006 	 * In case of no buffers we give up. At the end of the loop,
1007 	 * the queue is drained in all cases.
1008 	 */
1009 	netmap_grab_packets(kring, &q, 1);
1010 	kring->nr_hwcur = k;
1011 	kring->nr_hwavail = ring->avail = lim;
1012 	// na->nm_lock(na->ifp, NETMAP_CORE_UNLOCK, 0);
1013 
1014 	netmap_send_up(na->ifp, q.head);
1015 }
1016 
1017 
1018 /* SWNA(ifp)->txrings[0] is always NA(ifp)->txrings[NA(ifp)->num_txrings] */
1019 static int
1020 netmap_bdg_to_host(struct ifnet *ifp, u_int ring_nr, int do_lock)
1021 {
1022 	(void)ring_nr;
1023 	(void)do_lock;
1024 	netmap_sync_to_host(NA(ifp));
1025 	return 0;
1026 }
1027 
1028 
1029 /*
1030  * rxsync backend for packets coming from the host stack.
1031  * They have been put in the queue by netmap_start() so we
1032  * need to protect access to the kring using a lock.
1033  *
1034  * This routine also does the selrecord if called from the poll handler
1035  * (we know because td != NULL).
1036  *
1037  * NOTE: on linux, selrecord() is defined as a macro and uses pwait
1038  *     as an additional hidden argument.
1039  */
1040 static void
1041 netmap_sync_from_host(struct netmap_adapter *na, struct thread *td, void *pwait)
1042 {
1043 	struct netmap_kring *kring = &na->rx_rings[na->num_rx_rings];
1044 	struct netmap_ring *ring = kring->ring;
1045 	u_int j, n, lim = kring->nkr_num_slots;
1046 	u_int k = ring->cur, resvd = ring->reserved;
1047 
1048 	(void)pwait;	/* disable unused warnings */
1049 	na->nm_lock(na->ifp, NETMAP_CORE_LOCK, 0);
1050 	if (k >= lim) {
1051 		netmap_ring_reinit(kring);
1052 		return;
1053 	}
1054 	/* new packets are already set in nr_hwavail */
1055 	/* skip past packets that userspace has released */
1056 	j = kring->nr_hwcur;
1057 	if (resvd > 0) {
1058 		if (resvd + ring->avail >= lim + 1) {
1059 			D("XXX invalid reserve/avail %d %d", resvd, ring->avail);
1060 			ring->reserved = resvd = 0; // XXX panic...
1061 		}
1062 		k = (k >= resvd) ? k - resvd : k + lim - resvd;
1063         }
1064 	if (j != k) {
1065 		n = k >= j ? k - j : k + lim - j;
1066 		kring->nr_hwavail -= n;
1067 		kring->nr_hwcur = k;
1068 	}
1069 	k = ring->avail = kring->nr_hwavail - resvd;
1070 	if (k == 0 && td)
1071 		selrecord(td, &kring->si);
1072 	if (k && (netmap_verbose & NM_VERB_HOST))
1073 		D("%d pkts from stack", k);
1074 	na->nm_lock(na->ifp, NETMAP_CORE_UNLOCK, 0);
1075 }
1076 
1077 
1078 /*
1079  * get a refcounted reference to an interface.
1080  * Return ENXIO if the interface does not exist, EINVAL if netmap
1081  * is not supported by the interface.
1082  * If successful, hold a reference.
1083  *
1084  * During the NIC is attached to a bridge, reference is managed
1085  * at na->na_bdg_refcount using ADD/DROP_BDG_REF() as well as
1086  * virtual ports.  Hence, on the final DROP_BDG_REF(), the NIC
1087  * is detached from the bridge, then ifp's refcount is dropped (this
1088  * is equivalent to that ifp is destroyed in case of virtual ports.
1089  *
1090  * This function uses if_rele() when we want to prevent the NIC from
1091  * being detached from the bridge in error handling.  But once refcount
1092  * is acquired by this function, it must be released using nm_if_rele().
1093  */
1094 static int
1095 get_ifp(struct nmreq *nmr, struct ifnet **ifp)
1096 {
1097 	const char *name = nmr->nr_name;
1098 	int namelen = strlen(name);
1099 #ifdef NM_BRIDGE
1100 	struct ifnet *iter = NULL;
1101 	int no_prefix = 0;
1102 
1103 	do {
1104 		struct nm_bridge *b;
1105 		struct netmap_adapter *na;
1106 		int i, cand = -1, cand2 = -1;
1107 
1108 		if (strncmp(name, NM_NAME, sizeof(NM_NAME) - 1)) {
1109 			no_prefix = 1;
1110 			break;
1111 		}
1112 		b = nm_find_bridge(name, 1 /* create a new one if no exist */ );
1113 		if (b == NULL) {
1114 			D("no bridges available for '%s'", name);
1115 			return (ENXIO);
1116 		}
1117 		/* Now we are sure that name starts with the bridge's name */
1118 		BDG_WLOCK(b);
1119 		/* lookup in the local list of ports */
1120 		for (i = 0; i < NM_BDG_MAXPORTS; i++) {
1121 			na = BDG_GET_VAR(b->bdg_ports[i]);
1122 			if (na == NULL) {
1123 				if (cand == -1)
1124 					cand = i; /* potential insert point */
1125 				else if (cand2 == -1)
1126 					cand2 = i; /* for host stack */
1127 				continue;
1128 			}
1129 			iter = na->ifp;
1130 			/* XXX make sure the name only contains one : */
1131 			if (!strcmp(iter->if_xname, name) /* virtual port */ ||
1132 			    (namelen > b->namelen && !strcmp(iter->if_xname,
1133 			    name + b->namelen + 1)) /* NIC */) {
1134 				ADD_BDG_REF(iter);
1135 				ND("found existing interface");
1136 				BDG_WUNLOCK(b);
1137 				break;
1138 			}
1139 		}
1140 		if (i < NM_BDG_MAXPORTS) /* already unlocked */
1141 			break;
1142 		if (cand == -1) {
1143 			D("bridge full, cannot create new port");
1144 no_port:
1145 			BDG_WUNLOCK(b);
1146 			*ifp = NULL;
1147 			return EINVAL;
1148 		}
1149 		ND("create new bridge port %s", name);
1150 		/*
1151 		 * create a struct ifnet for the new port.
1152 		 * The forwarding table is attached to the kring(s).
1153 		 */
1154 		/*
1155 		 * try see if there is a matching NIC with this name
1156 		 * (after the bridge's name)
1157 		 */
1158 		iter = ifunit_ref(name + b->namelen + 1);
1159 		if (!iter) { /* this is a virtual port */
1160 			/* Create a temporary NA with arguments, then
1161 			 * bdg_netmap_attach() will allocate the real one
1162 			 * and attach it to the ifp
1163 			 */
1164 			struct netmap_adapter tmp_na;
1165 
1166 			if (nmr->nr_cmd) /* nr_cmd must be for a NIC */
1167 				goto no_port;
1168 			bzero(&tmp_na, sizeof(tmp_na));
1169 			/* bound checking */
1170 			if (nmr->nr_tx_rings < 1)
1171 				nmr->nr_tx_rings = 1;
1172 			if (nmr->nr_tx_rings > NM_BDG_MAXRINGS)
1173 				nmr->nr_tx_rings = NM_BDG_MAXRINGS;
1174 			tmp_na.num_tx_rings = nmr->nr_tx_rings;
1175 			if (nmr->nr_rx_rings < 1)
1176 				nmr->nr_rx_rings = 1;
1177 			if (nmr->nr_rx_rings > NM_BDG_MAXRINGS)
1178 				nmr->nr_rx_rings = NM_BDG_MAXRINGS;
1179 			tmp_na.num_rx_rings = nmr->nr_rx_rings;
1180 
1181 			iter = malloc(sizeof(*iter), M_DEVBUF, M_NOWAIT | M_ZERO);
1182 			if (!iter)
1183 				goto no_port;
1184 			strcpy(iter->if_xname, name);
1185 			tmp_na.ifp = iter;
1186 			/* bdg_netmap_attach creates a struct netmap_adapter */
1187 			bdg_netmap_attach(&tmp_na);
1188 		} else if (NETMAP_CAPABLE(iter)) { /* this is a NIC */
1189 			/* cannot attach the NIC that any user or another
1190 			 * bridge already holds.
1191 			 */
1192 			if (NETMAP_OWNED_BY_ANY(iter) || cand2 == -1) {
1193 ifunit_rele:
1194 				if_rele(iter); /* don't detach from bridge */
1195 				goto no_port;
1196 			}
1197 			/* bind the host stack to the bridge */
1198 			if (nmr->nr_arg1 == NETMAP_BDG_HOST) {
1199 				BDG_SET_VAR(b->bdg_ports[cand2], SWNA(iter));
1200 				SWNA(iter)->bdg_port = cand2;
1201 				SWNA(iter)->na_bdg = b;
1202 			}
1203 		} else /* not a netmap-capable NIC */
1204 			goto ifunit_rele;
1205 		na = NA(iter);
1206 		na->bdg_port = cand;
1207 		/* bind the port to the bridge (virtual ports are not active) */
1208 		BDG_SET_VAR(b->bdg_ports[cand], na);
1209 		na->na_bdg = b;
1210 		ADD_BDG_REF(iter);
1211 		BDG_WUNLOCK(b);
1212 		ND("attaching virtual bridge %p", b);
1213 	} while (0);
1214 	*ifp = iter;
1215 	if (! *ifp)
1216 #endif /* NM_BRIDGE */
1217 	*ifp = ifunit_ref(name);
1218 	if (*ifp == NULL)
1219 		return (ENXIO);
1220 	/* can do this if the capability exists and if_pspare[0]
1221 	 * points to the netmap descriptor.
1222 	 */
1223 	if (NETMAP_CAPABLE(*ifp)) {
1224 #ifdef NM_BRIDGE
1225 		/* Users cannot use the NIC attached to a bridge directly */
1226 		if (no_prefix && NETMAP_OWNED_BY_KERN(*ifp)) {
1227 			if_rele(*ifp); /* don't detach from bridge */
1228 			return EINVAL;
1229 		} else
1230 #endif /* NM_BRIDGE */
1231 		return 0;	/* valid pointer, we hold the refcount */
1232 	}
1233 	nm_if_rele(*ifp);
1234 	return EINVAL;	// not NETMAP capable
1235 }
1236 
1237 
1238 /*
1239  * Error routine called when txsync/rxsync detects an error.
1240  * Can't do much more than resetting cur = hwcur, avail = hwavail.
1241  * Return 1 on reinit.
1242  *
1243  * This routine is only called by the upper half of the kernel.
1244  * It only reads hwcur (which is changed only by the upper half, too)
1245  * and hwavail (which may be changed by the lower half, but only on
1246  * a tx ring and only to increase it, so any error will be recovered
1247  * on the next call). For the above, we don't strictly need to call
1248  * it under lock.
1249  */
1250 int
1251 netmap_ring_reinit(struct netmap_kring *kring)
1252 {
1253 	struct netmap_ring *ring = kring->ring;
1254 	u_int i, lim = kring->nkr_num_slots - 1;
1255 	int errors = 0;
1256 
1257 	RD(10, "called for %s", kring->na->ifp->if_xname);
1258 	if (ring->cur > lim)
1259 		errors++;
1260 	for (i = 0; i <= lim; i++) {
1261 		u_int idx = ring->slot[i].buf_idx;
1262 		u_int len = ring->slot[i].len;
1263 		if (idx < 2 || idx >= netmap_total_buffers) {
1264 			if (!errors++)
1265 				D("bad buffer at slot %d idx %d len %d ", i, idx, len);
1266 			ring->slot[i].buf_idx = 0;
1267 			ring->slot[i].len = 0;
1268 		} else if (len > NETMAP_BUF_SIZE) {
1269 			ring->slot[i].len = 0;
1270 			if (!errors++)
1271 				D("bad len %d at slot %d idx %d",
1272 					len, i, idx);
1273 		}
1274 	}
1275 	if (errors) {
1276 		int pos = kring - kring->na->tx_rings;
1277 		int n = kring->na->num_tx_rings + 1;
1278 
1279 		RD(10, "total %d errors", errors);
1280 		errors++;
1281 		RD(10, "%s %s[%d] reinit, cur %d -> %d avail %d -> %d",
1282 			kring->na->ifp->if_xname,
1283 			pos < n ?  "TX" : "RX", pos < n ? pos : pos - n,
1284 			ring->cur, kring->nr_hwcur,
1285 			ring->avail, kring->nr_hwavail);
1286 		ring->cur = kring->nr_hwcur;
1287 		ring->avail = kring->nr_hwavail;
1288 	}
1289 	return (errors ? 1 : 0);
1290 }
1291 
1292 
1293 /*
1294  * Set the ring ID. For devices with a single queue, a request
1295  * for all rings is the same as a single ring.
1296  */
1297 static int
1298 netmap_set_ringid(struct netmap_priv_d *priv, u_int ringid)
1299 {
1300 	struct ifnet *ifp = priv->np_ifp;
1301 	struct netmap_adapter *na = NA(ifp);
1302 	u_int i = ringid & NETMAP_RING_MASK;
1303 	/* initially (np_qfirst == np_qlast) we don't want to lock */
1304 	int need_lock = (priv->np_qfirst != priv->np_qlast);
1305 	int lim = na->num_rx_rings;
1306 
1307 	if (na->num_tx_rings > lim)
1308 		lim = na->num_tx_rings;
1309 	if ( (ringid & NETMAP_HW_RING) && i >= lim) {
1310 		D("invalid ring id %d", i);
1311 		return (EINVAL);
1312 	}
1313 	if (need_lock)
1314 		na->nm_lock(ifp, NETMAP_CORE_LOCK, 0);
1315 	priv->np_ringid = ringid;
1316 	if (ringid & NETMAP_SW_RING) {
1317 		priv->np_qfirst = NETMAP_SW_RING;
1318 		priv->np_qlast = 0;
1319 	} else if (ringid & NETMAP_HW_RING) {
1320 		priv->np_qfirst = i;
1321 		priv->np_qlast = i + 1;
1322 	} else {
1323 		priv->np_qfirst = 0;
1324 		priv->np_qlast = NETMAP_HW_RING ;
1325 	}
1326 	priv->np_txpoll = (ringid & NETMAP_NO_TX_POLL) ? 0 : 1;
1327 	if (need_lock)
1328 		na->nm_lock(ifp, NETMAP_CORE_UNLOCK, 0);
1329     if (netmap_verbose) {
1330 	if (ringid & NETMAP_SW_RING)
1331 		D("ringid %s set to SW RING", ifp->if_xname);
1332 	else if (ringid & NETMAP_HW_RING)
1333 		D("ringid %s set to HW RING %d", ifp->if_xname,
1334 			priv->np_qfirst);
1335 	else
1336 		D("ringid %s set to all %d HW RINGS", ifp->if_xname, lim);
1337     }
1338 	return 0;
1339 }
1340 
1341 
1342 /*
1343  * possibly move the interface to netmap-mode.
1344  * If success it returns a pointer to netmap_if, otherwise NULL.
1345  * This must be called with NMA_LOCK held.
1346  */
1347 static struct netmap_if *
1348 netmap_do_regif(struct netmap_priv_d *priv, struct ifnet *ifp,
1349 	uint16_t ringid, int *err)
1350 {
1351 	struct netmap_adapter *na = NA(ifp);
1352 	struct netmap_if *nifp = NULL;
1353 	int i, error;
1354 
1355 	if (na->na_bdg)
1356 		BDG_WLOCK(na->na_bdg);
1357 	na->nm_lock(ifp, NETMAP_REG_LOCK, 0);
1358 
1359 	/* ring configuration may have changed, fetch from the card */
1360 	netmap_update_config(na);
1361 	priv->np_ifp = ifp;     /* store the reference */
1362 	error = netmap_set_ringid(priv, ringid);
1363 	if (error)
1364 		goto out;
1365 	nifp = netmap_if_new(ifp->if_xname, na);
1366 	if (nifp == NULL) { /* allocation failed */
1367 		error = ENOMEM;
1368 	} else if (ifp->if_capenable & IFCAP_NETMAP) {
1369 		/* was already set */
1370 	} else {
1371 		/* Otherwise set the card in netmap mode
1372 		 * and make it use the shared buffers.
1373 		 */
1374 		for (i = 0 ; i < na->num_tx_rings + 1; i++)
1375 			mtx_init(&na->tx_rings[i].q_lock, "nm_txq_lock",
1376 			    MTX_NETWORK_LOCK, MTX_DEF);
1377 		for (i = 0 ; i < na->num_rx_rings + 1; i++) {
1378 			mtx_init(&na->rx_rings[i].q_lock, "nm_rxq_lock",
1379 			    MTX_NETWORK_LOCK, MTX_DEF);
1380 		}
1381 		if (nma_is_hw(na)) {
1382 			SWNA(ifp)->tx_rings = &na->tx_rings[na->num_tx_rings];
1383 			SWNA(ifp)->rx_rings = &na->rx_rings[na->num_rx_rings];
1384 		}
1385 		error = na->nm_register(ifp, 1); /* mode on */
1386 #ifdef NM_BRIDGE
1387 		if (!error)
1388 			error = nm_alloc_bdgfwd(na);
1389 #endif /* NM_BRIDGE */
1390 		if (error) {
1391 			netmap_dtor_locked(priv);
1392 			/* nifp is not yet in priv, so free it separately */
1393 			netmap_if_free(nifp);
1394 			nifp = NULL;
1395 		}
1396 
1397 	}
1398 out:
1399 	*err = error;
1400 	na->nm_lock(ifp, NETMAP_REG_UNLOCK, 0);
1401 	if (na->na_bdg)
1402 		BDG_WUNLOCK(na->na_bdg);
1403 	return nifp;
1404 }
1405 
1406 
1407 /* Process NETMAP_BDG_ATTACH and NETMAP_BDG_DETACH */
1408 static int
1409 kern_netmap_regif(struct nmreq *nmr)
1410 {
1411 	struct ifnet *ifp;
1412 	struct netmap_if *nifp;
1413 	struct netmap_priv_d *npriv;
1414 	int error;
1415 
1416 	npriv = malloc(sizeof(*npriv), M_DEVBUF, M_NOWAIT|M_ZERO);
1417 	if (npriv == NULL)
1418 		return ENOMEM;
1419 	error = netmap_get_memory(npriv);
1420 	if (error) {
1421 free_exit:
1422 		bzero(npriv, sizeof(*npriv));
1423 		free(npriv, M_DEVBUF);
1424 		return error;
1425 	}
1426 
1427 	NMA_LOCK();
1428 	error = get_ifp(nmr, &ifp);
1429 	if (error) { /* no device, or another bridge or user owns the device */
1430 		NMA_UNLOCK();
1431 		goto free_exit;
1432 	} else if (!NETMAP_OWNED_BY_KERN(ifp)) {
1433 		/* got reference to a virtual port or direct access to a NIC.
1434 		 * perhaps specified no bridge's prefix or wrong NIC's name
1435 		 */
1436 		error = EINVAL;
1437 unref_exit:
1438 		nm_if_rele(ifp);
1439 		NMA_UNLOCK();
1440 		goto free_exit;
1441 	}
1442 
1443 	if (nmr->nr_cmd == NETMAP_BDG_DETACH) {
1444 		if (NA(ifp)->refcount == 0) { /* not registered */
1445 			error = EINVAL;
1446 			goto unref_exit;
1447 		}
1448 		NMA_UNLOCK();
1449 
1450 		netmap_dtor(NA(ifp)->na_kpriv); /* unregister */
1451 		NA(ifp)->na_kpriv = NULL;
1452 		nm_if_rele(ifp); /* detach from the bridge */
1453 		goto free_exit;
1454 	} else if (NA(ifp)->refcount > 0) { /* already registered */
1455 		error = EINVAL;
1456 		goto unref_exit;
1457 	}
1458 
1459 	nifp = netmap_do_regif(npriv, ifp, nmr->nr_ringid, &error);
1460 	if (!nifp)
1461 		goto unref_exit;
1462 	wmb(); // XXX do we need it ?
1463 	npriv->np_nifp = nifp;
1464 	NA(ifp)->na_kpriv = npriv;
1465 	NMA_UNLOCK();
1466 	D("registered %s to netmap-mode", ifp->if_xname);
1467 	return 0;
1468 }
1469 
1470 
1471 /* CORE_LOCK is not necessary */
1472 static void
1473 netmap_swlock_wrapper(struct ifnet *dev, int what, u_int queueid)
1474 {
1475 	struct netmap_adapter *na = SWNA(dev);
1476 
1477 	switch (what) {
1478 	case NETMAP_TX_LOCK:
1479 		mtx_lock(&na->tx_rings[queueid].q_lock);
1480 		break;
1481 
1482 	case NETMAP_TX_UNLOCK:
1483 		mtx_unlock(&na->tx_rings[queueid].q_lock);
1484 		break;
1485 
1486 	case NETMAP_RX_LOCK:
1487 		mtx_lock(&na->rx_rings[queueid].q_lock);
1488 		break;
1489 
1490 	case NETMAP_RX_UNLOCK:
1491 		mtx_unlock(&na->rx_rings[queueid].q_lock);
1492 		break;
1493 	}
1494 }
1495 
1496 
1497 /* Initialize necessary fields of sw adapter located in right after hw's
1498  * one.  sw adapter attaches a pair of sw rings of the netmap-mode NIC.
1499  * It is always activated and deactivated at the same tie with the hw's one.
1500  * Thus we don't need refcounting on the sw adapter.
1501  * Regardless of NIC's feature we use separate lock so that anybody can lock
1502  * me independently from the hw adapter.
1503  * Make sure nm_register is NULL to be handled as FALSE in nma_is_hw
1504  */
1505 static void
1506 netmap_attach_sw(struct ifnet *ifp)
1507 {
1508 	struct netmap_adapter *hw_na = NA(ifp);
1509 	struct netmap_adapter *na = SWNA(ifp);
1510 
1511 	na->ifp = ifp;
1512 	na->separate_locks = 1;
1513 	na->nm_lock = netmap_swlock_wrapper;
1514 	na->num_rx_rings = na->num_tx_rings = 1;
1515 	na->num_tx_desc = hw_na->num_tx_desc;
1516 	na->num_rx_desc = hw_na->num_rx_desc;
1517 	na->nm_txsync = netmap_bdg_to_host;
1518 }
1519 
1520 
1521 /* exported to kernel callers */
1522 int
1523 netmap_bdg_ctl(struct nmreq *nmr, bdg_lookup_fn_t func)
1524 {
1525 	struct nm_bridge *b;
1526 	struct netmap_adapter *na;
1527 	struct ifnet *iter;
1528 	char *name = nmr->nr_name;
1529 	int cmd = nmr->nr_cmd, namelen = strlen(name);
1530 	int error = 0, i, j;
1531 
1532 	switch (cmd) {
1533 	case NETMAP_BDG_ATTACH:
1534 	case NETMAP_BDG_DETACH:
1535 		error = kern_netmap_regif(nmr);
1536 		break;
1537 
1538 	case NETMAP_BDG_LIST:
1539 		/* this is used to enumerate bridges and ports */
1540 		if (namelen) { /* look up indexes of bridge and port */
1541 			if (strncmp(name, NM_NAME, strlen(NM_NAME))) {
1542 				error = EINVAL;
1543 				break;
1544 			}
1545 			b = nm_find_bridge(name, 0 /* don't create */);
1546 			if (!b) {
1547 				error = ENOENT;
1548 				break;
1549 			}
1550 
1551 			BDG_RLOCK(b);
1552 			error = ENOENT;
1553 			for (i = 0; i < NM_BDG_MAXPORTS; i++) {
1554 				na = BDG_GET_VAR(b->bdg_ports[i]);
1555 				if (na == NULL)
1556 					continue;
1557 				iter = na->ifp;
1558 				/* the former and the latter identify a
1559 				 * virtual port and a NIC, respectively
1560 				 */
1561 				if (!strcmp(iter->if_xname, name) ||
1562 				    (namelen > b->namelen &&
1563 				    !strcmp(iter->if_xname,
1564 				    name + b->namelen + 1))) {
1565 					/* bridge index */
1566 					nmr->nr_arg1 = b - nm_bridges;
1567 					nmr->nr_arg2 = i; /* port index */
1568 					error = 0;
1569 					break;
1570 				}
1571 			}
1572 			BDG_RUNLOCK(b);
1573 		} else {
1574 			/* return the first non-empty entry starting from
1575 			 * bridge nr_arg1 and port nr_arg2.
1576 			 *
1577 			 * Users can detect the end of the same bridge by
1578 			 * seeing the new and old value of nr_arg1, and can
1579 			 * detect the end of all the bridge by error != 0
1580 			 */
1581 			i = nmr->nr_arg1;
1582 			j = nmr->nr_arg2;
1583 
1584 			for (error = ENOENT; error && i < NM_BRIDGES; i++) {
1585 				b = nm_bridges + i;
1586 				BDG_RLOCK(b);
1587 				for (; j < NM_BDG_MAXPORTS; j++) {
1588 					na = BDG_GET_VAR(b->bdg_ports[j]);
1589 					if (na == NULL)
1590 						continue;
1591 					iter = na->ifp;
1592 					nmr->nr_arg1 = i;
1593 					nmr->nr_arg2 = j;
1594 					strncpy(name, iter->if_xname, IFNAMSIZ);
1595 					error = 0;
1596 					break;
1597 				}
1598 				BDG_RUNLOCK(b);
1599 				j = 0; /* following bridges scan from 0 */
1600 			}
1601 		}
1602 		break;
1603 
1604 	case NETMAP_BDG_LOOKUP_REG:
1605 		/* register a lookup function to the given bridge.
1606 		 * nmr->nr_name may be just bridge's name (including ':'
1607 		 * if it is not just NM_NAME).
1608 		 */
1609 		if (!func) {
1610 			error = EINVAL;
1611 			break;
1612 		}
1613 		b = nm_find_bridge(name, 0 /* don't create */);
1614 		if (!b) {
1615 			error = EINVAL;
1616 			break;
1617 		}
1618 		BDG_WLOCK(b);
1619 		b->nm_bdg_lookup = func;
1620 		BDG_WUNLOCK(b);
1621 		break;
1622 	default:
1623 		D("invalid cmd (nmr->nr_cmd) (0x%x)", cmd);
1624 		error = EINVAL;
1625 		break;
1626 	}
1627 	return error;
1628 }
1629 
1630 
1631 /*
1632  * ioctl(2) support for the "netmap" device.
1633  *
1634  * Following a list of accepted commands:
1635  * - NIOCGINFO
1636  * - SIOCGIFADDR	just for convenience
1637  * - NIOCREGIF
1638  * - NIOCUNREGIF
1639  * - NIOCTXSYNC
1640  * - NIOCRXSYNC
1641  *
1642  * Return 0 on success, errno otherwise.
1643  */
1644 static int
1645 netmap_ioctl(struct cdev *dev, u_long cmd, caddr_t data,
1646 	int fflag, struct thread *td)
1647 {
1648 	struct netmap_priv_d *priv = NULL;
1649 	struct ifnet *ifp;
1650 	struct nmreq *nmr = (struct nmreq *) data;
1651 	struct netmap_adapter *na;
1652 	int error;
1653 	u_int i, lim;
1654 	struct netmap_if *nifp;
1655 
1656 	(void)dev;	/* UNUSED */
1657 	(void)fflag;	/* UNUSED */
1658 #ifdef linux
1659 #define devfs_get_cdevpriv(pp)				\
1660 	({ *(struct netmap_priv_d **)pp = ((struct file *)td)->private_data; 	\
1661 		(*pp ? 0 : ENOENT); })
1662 
1663 /* devfs_set_cdevpriv cannot fail on linux */
1664 #define devfs_set_cdevpriv(p, fn)				\
1665 	({ ((struct file *)td)->private_data = p; (p ? 0 : EINVAL); })
1666 
1667 
1668 #define devfs_clear_cdevpriv()	do {				\
1669 		netmap_dtor(priv); ((struct file *)td)->private_data = 0;	\
1670 	} while (0)
1671 #endif /* linux */
1672 
1673 	CURVNET_SET(TD_TO_VNET(td));
1674 
1675 	error = devfs_get_cdevpriv((void **)&priv);
1676 	if (error) {
1677 		CURVNET_RESTORE();
1678 		/* XXX ENOENT should be impossible, since the priv
1679 		 * is now created in the open */
1680 		return (error == ENOENT ? ENXIO : error);
1681 	}
1682 
1683 	nmr->nr_name[sizeof(nmr->nr_name) - 1] = '\0';	/* truncate name */
1684 	switch (cmd) {
1685 	case NIOCGINFO:		/* return capabilities etc */
1686 		if (nmr->nr_version != NETMAP_API) {
1687 			D("API mismatch got %d have %d",
1688 				nmr->nr_version, NETMAP_API);
1689 			nmr->nr_version = NETMAP_API;
1690 			error = EINVAL;
1691 			break;
1692 		}
1693 		if (nmr->nr_cmd == NETMAP_BDG_LIST) {
1694 			error = netmap_bdg_ctl(nmr, NULL);
1695 			break;
1696 		}
1697 		/* update configuration */
1698 		error = netmap_get_memory(priv);
1699 		ND("get_memory returned %d", error);
1700 		if (error)
1701 			break;
1702 		/* memsize is always valid */
1703 		nmr->nr_memsize = nm_mem.nm_totalsize;
1704 		nmr->nr_offset = 0;
1705 		nmr->nr_rx_slots = nmr->nr_tx_slots = 0;
1706 		if (nmr->nr_name[0] == '\0')	/* just get memory info */
1707 			break;
1708 		/* lock because get_ifp and update_config see na->refcount */
1709 		NMA_LOCK();
1710 		error = get_ifp(nmr, &ifp); /* get a refcount */
1711 		if (error) {
1712 			NMA_UNLOCK();
1713 			break;
1714 		}
1715 		na = NA(ifp); /* retrieve netmap_adapter */
1716 		netmap_update_config(na);
1717 		NMA_UNLOCK();
1718 		nmr->nr_rx_rings = na->num_rx_rings;
1719 		nmr->nr_tx_rings = na->num_tx_rings;
1720 		nmr->nr_rx_slots = na->num_rx_desc;
1721 		nmr->nr_tx_slots = na->num_tx_desc;
1722 		nm_if_rele(ifp);	/* return the refcount */
1723 		break;
1724 
1725 	case NIOCREGIF:
1726 		if (nmr->nr_version != NETMAP_API) {
1727 			nmr->nr_version = NETMAP_API;
1728 			error = EINVAL;
1729 			break;
1730 		}
1731 		/* possibly attach/detach NIC and VALE switch */
1732 		i = nmr->nr_cmd;
1733 		if (i == NETMAP_BDG_ATTACH || i == NETMAP_BDG_DETACH) {
1734 			error = netmap_bdg_ctl(nmr, NULL);
1735 			break;
1736 		} else if (i != 0) {
1737 			D("nr_cmd must be 0 not %d", i);
1738 			error = EINVAL;
1739 			break;
1740 		}
1741 
1742 		/* ensure allocators are ready */
1743 		error = netmap_get_memory(priv);
1744 		ND("get_memory returned %d", error);
1745 		if (error)
1746 			break;
1747 
1748 		/* protect access to priv from concurrent NIOCREGIF */
1749 		NMA_LOCK();
1750 		if (priv->np_ifp != NULL) {	/* thread already registered */
1751 			error = netmap_set_ringid(priv, nmr->nr_ringid);
1752 unlock_out:
1753 			NMA_UNLOCK();
1754 			break;
1755 		}
1756 		/* find the interface and a reference */
1757 		error = get_ifp(nmr, &ifp); /* keep reference */
1758 		if (error)
1759 			goto unlock_out;
1760 		else if (NETMAP_OWNED_BY_KERN(ifp)) {
1761 			nm_if_rele(ifp);
1762 			goto unlock_out;
1763 		}
1764 		nifp = netmap_do_regif(priv, ifp, nmr->nr_ringid, &error);
1765 		if (!nifp) {    /* reg. failed, release priv and ref */
1766 			nm_if_rele(ifp);        /* return the refcount */
1767 			priv->np_ifp = NULL;
1768 			priv->np_nifp = NULL;
1769 			goto unlock_out;
1770 		}
1771 
1772 		/* the following assignment is a commitment.
1773 		 * Readers (i.e., poll and *SYNC) check for
1774 		 * np_nifp != NULL without locking
1775 		 */
1776 		wmb(); /* make sure previous writes are visible to all CPUs */
1777 		priv->np_nifp = nifp;
1778 		NMA_UNLOCK();
1779 
1780 		/* return the offset of the netmap_if object */
1781 		na = NA(ifp); /* retrieve netmap adapter */
1782 		nmr->nr_rx_rings = na->num_rx_rings;
1783 		nmr->nr_tx_rings = na->num_tx_rings;
1784 		nmr->nr_rx_slots = na->num_rx_desc;
1785 		nmr->nr_tx_slots = na->num_tx_desc;
1786 		nmr->nr_memsize = nm_mem.nm_totalsize;
1787 		nmr->nr_offset = netmap_if_offset(nifp);
1788 		break;
1789 
1790 	case NIOCUNREGIF:
1791 		// XXX we have no data here ?
1792 		D("deprecated, data is %p", nmr);
1793 		error = EINVAL;
1794 		break;
1795 
1796 	case NIOCTXSYNC:
1797 	case NIOCRXSYNC:
1798 		nifp = priv->np_nifp;
1799 
1800 		if (nifp == NULL) {
1801 			error = ENXIO;
1802 			break;
1803 		}
1804 		rmb(); /* make sure following reads are not from cache */
1805 
1806 
1807 		ifp = priv->np_ifp;	/* we have a reference */
1808 
1809 		if (ifp == NULL) {
1810 			D("Internal error: nifp != NULL && ifp == NULL");
1811 			error = ENXIO;
1812 			break;
1813 		}
1814 
1815 		na = NA(ifp); /* retrieve netmap adapter */
1816 		if (priv->np_qfirst == NETMAP_SW_RING) { /* host rings */
1817 			if (cmd == NIOCTXSYNC)
1818 				netmap_sync_to_host(na);
1819 			else
1820 				netmap_sync_from_host(na, NULL, NULL);
1821 			break;
1822 		}
1823 		/* find the last ring to scan */
1824 		lim = priv->np_qlast;
1825 		if (lim == NETMAP_HW_RING)
1826 			lim = (cmd == NIOCTXSYNC) ?
1827 			    na->num_tx_rings : na->num_rx_rings;
1828 
1829 		for (i = priv->np_qfirst; i < lim; i++) {
1830 			if (cmd == NIOCTXSYNC) {
1831 				struct netmap_kring *kring = &na->tx_rings[i];
1832 				if (netmap_verbose & NM_VERB_TXSYNC)
1833 					D("pre txsync ring %d cur %d hwcur %d",
1834 					    i, kring->ring->cur,
1835 					    kring->nr_hwcur);
1836 				na->nm_txsync(ifp, i, 1 /* do lock */);
1837 				if (netmap_verbose & NM_VERB_TXSYNC)
1838 					D("post txsync ring %d cur %d hwcur %d",
1839 					    i, kring->ring->cur,
1840 					    kring->nr_hwcur);
1841 			} else {
1842 				na->nm_rxsync(ifp, i, 1 /* do lock */);
1843 				microtime(&na->rx_rings[i].ring->ts);
1844 			}
1845 		}
1846 
1847 		break;
1848 
1849 #ifdef __FreeBSD__
1850 	case BIOCIMMEDIATE:
1851 	case BIOCGHDRCMPLT:
1852 	case BIOCSHDRCMPLT:
1853 	case BIOCSSEESENT:
1854 		D("ignore BIOCIMMEDIATE/BIOCSHDRCMPLT/BIOCSHDRCMPLT/BIOCSSEESENT");
1855 		break;
1856 
1857 	default:	/* allow device-specific ioctls */
1858 	    {
1859 		struct socket so;
1860 		bzero(&so, sizeof(so));
1861 		error = get_ifp(nmr, &ifp); /* keep reference */
1862 		if (error)
1863 			break;
1864 		so.so_vnet = ifp->if_vnet;
1865 		// so->so_proto not null.
1866 		error = ifioctl(&so, cmd, data, td);
1867 		nm_if_rele(ifp);
1868 		break;
1869 	    }
1870 
1871 #else /* linux */
1872 	default:
1873 		error = EOPNOTSUPP;
1874 #endif /* linux */
1875 	}
1876 
1877 	CURVNET_RESTORE();
1878 	return (error);
1879 }
1880 
1881 
1882 /*
1883  * select(2) and poll(2) handlers for the "netmap" device.
1884  *
1885  * Can be called for one or more queues.
1886  * Return true the event mask corresponding to ready events.
1887  * If there are no ready events, do a selrecord on either individual
1888  * selfd or on the global one.
1889  * Device-dependent parts (locking and sync of tx/rx rings)
1890  * are done through callbacks.
1891  *
1892  * On linux, arguments are really pwait, the poll table, and 'td' is struct file *
1893  * The first one is remapped to pwait as selrecord() uses the name as an
1894  * hidden argument.
1895  */
1896 static int
1897 netmap_poll(struct cdev *dev, int events, struct thread *td)
1898 {
1899 	struct netmap_priv_d *priv = NULL;
1900 	struct netmap_adapter *na;
1901 	struct ifnet *ifp;
1902 	struct netmap_kring *kring;
1903 	u_int core_lock, i, check_all, want_tx, want_rx, revents = 0;
1904 	u_int lim_tx, lim_rx, host_forwarded = 0;
1905 	struct mbq q = { NULL, NULL, 0 };
1906 	enum {NO_CL, NEED_CL, LOCKED_CL }; /* see below */
1907 	void *pwait = dev;	/* linux compatibility */
1908 
1909 	(void)pwait;
1910 
1911 	if (devfs_get_cdevpriv((void **)&priv) != 0 || priv == NULL)
1912 		return POLLERR;
1913 
1914 	if (priv->np_nifp == NULL) {
1915 		D("No if registered");
1916 		return POLLERR;
1917 	}
1918 	rmb(); /* make sure following reads are not from cache */
1919 
1920 	ifp = priv->np_ifp;
1921 	// XXX check for deleting() ?
1922 	if ( (ifp->if_capenable & IFCAP_NETMAP) == 0)
1923 		return POLLERR;
1924 
1925 	if (netmap_verbose & 0x8000)
1926 		D("device %s events 0x%x", ifp->if_xname, events);
1927 	want_tx = events & (POLLOUT | POLLWRNORM);
1928 	want_rx = events & (POLLIN | POLLRDNORM);
1929 
1930 	na = NA(ifp); /* retrieve netmap adapter */
1931 
1932 	lim_tx = na->num_tx_rings;
1933 	lim_rx = na->num_rx_rings;
1934 	/* how many queues we are scanning */
1935 	if (priv->np_qfirst == NETMAP_SW_RING) {
1936 		if (priv->np_txpoll || want_tx) {
1937 			/* push any packets up, then we are always ready */
1938 			netmap_sync_to_host(na);
1939 			revents |= want_tx;
1940 		}
1941 		if (want_rx) {
1942 			kring = &na->rx_rings[lim_rx];
1943 			if (kring->ring->avail == 0)
1944 				netmap_sync_from_host(na, td, dev);
1945 			if (kring->ring->avail > 0) {
1946 				revents |= want_rx;
1947 			}
1948 		}
1949 		return (revents);
1950 	}
1951 
1952 	/* if we are in transparent mode, check also the host rx ring */
1953 	kring = &na->rx_rings[lim_rx];
1954 	if ( (priv->np_qlast == NETMAP_HW_RING) // XXX check_all
1955 			&& want_rx
1956 			&& (netmap_fwd || kring->ring->flags & NR_FORWARD) ) {
1957 		if (kring->ring->avail == 0)
1958 			netmap_sync_from_host(na, td, dev);
1959 		if (kring->ring->avail > 0)
1960 			revents |= want_rx;
1961 	}
1962 
1963 	/*
1964 	 * check_all is set if the card has more than one queue and
1965 	 * the client is polling all of them. If true, we sleep on
1966 	 * the "global" selfd, otherwise we sleep on individual selfd
1967 	 * (we can only sleep on one of them per direction).
1968 	 * The interrupt routine in the driver should always wake on
1969 	 * the individual selfd, and also on the global one if the card
1970 	 * has more than one ring.
1971 	 *
1972 	 * If the card has only one lock, we just use that.
1973 	 * If the card has separate ring locks, we just use those
1974 	 * unless we are doing check_all, in which case the whole
1975 	 * loop is wrapped by the global lock.
1976 	 * We acquire locks only when necessary: if poll is called
1977 	 * when buffers are available, we can just return without locks.
1978 	 *
1979 	 * rxsync() is only called if we run out of buffers on a POLLIN.
1980 	 * txsync() is called if we run out of buffers on POLLOUT, or
1981 	 * there are pending packets to send. The latter can be disabled
1982 	 * passing NETMAP_NO_TX_POLL in the NIOCREG call.
1983 	 */
1984 	check_all = (priv->np_qlast == NETMAP_HW_RING) && (lim_tx > 1 || lim_rx > 1);
1985 
1986 	/*
1987 	 * core_lock indicates what to do with the core lock.
1988 	 * The core lock is used when either the card has no individual
1989 	 * locks, or it has individual locks but we are cheking all
1990 	 * rings so we need the core lock to avoid missing wakeup events.
1991 	 *
1992 	 * It has three possible states:
1993 	 * NO_CL	we don't need to use the core lock, e.g.
1994 	 *		because we are protected by individual locks.
1995 	 * NEED_CL	we need the core lock. In this case, when we
1996 	 *		call the lock routine, move to LOCKED_CL
1997 	 *		to remember to release the lock once done.
1998 	 * LOCKED_CL	core lock is set, so we need to release it.
1999 	 */
2000 	core_lock = (check_all || !na->separate_locks) ? NEED_CL : NO_CL;
2001 #ifdef NM_BRIDGE
2002 	/* the bridge uses separate locks */
2003 	if (na->nm_register == bdg_netmap_reg) {
2004 		ND("not using core lock for %s", ifp->if_xname);
2005 		core_lock = NO_CL;
2006 	}
2007 #endif /* NM_BRIDGE */
2008 	if (priv->np_qlast != NETMAP_HW_RING) {
2009 		lim_tx = lim_rx = priv->np_qlast;
2010 	}
2011 
2012 	/*
2013 	 * We start with a lock free round which is good if we have
2014 	 * data available. If this fails, then lock and call the sync
2015 	 * routines.
2016 	 */
2017 	for (i = priv->np_qfirst; want_rx && i < lim_rx; i++) {
2018 		kring = &na->rx_rings[i];
2019 		if (kring->ring->avail > 0) {
2020 			revents |= want_rx;
2021 			want_rx = 0;	/* also breaks the loop */
2022 		}
2023 	}
2024 	for (i = priv->np_qfirst; want_tx && i < lim_tx; i++) {
2025 		kring = &na->tx_rings[i];
2026 		if (kring->ring->avail > 0) {
2027 			revents |= want_tx;
2028 			want_tx = 0;	/* also breaks the loop */
2029 		}
2030 	}
2031 
2032 	/*
2033 	 * If we to push packets out (priv->np_txpoll) or want_tx is
2034 	 * still set, we do need to run the txsync calls (on all rings,
2035 	 * to avoid that the tx rings stall).
2036 	 */
2037 	if (priv->np_txpoll || want_tx) {
2038 flush_tx:
2039 		for (i = priv->np_qfirst; i < lim_tx; i++) {
2040 			kring = &na->tx_rings[i];
2041 			/*
2042 			 * Skip the current ring if want_tx == 0
2043 			 * (we have already done a successful sync on
2044 			 * a previous ring) AND kring->cur == kring->hwcur
2045 			 * (there are no pending transmissions for this ring).
2046 			 */
2047 			if (!want_tx && kring->ring->cur == kring->nr_hwcur)
2048 				continue;
2049 			if (core_lock == NEED_CL) {
2050 				na->nm_lock(ifp, NETMAP_CORE_LOCK, 0);
2051 				core_lock = LOCKED_CL;
2052 			}
2053 			if (na->separate_locks)
2054 				na->nm_lock(ifp, NETMAP_TX_LOCK, i);
2055 			if (netmap_verbose & NM_VERB_TXSYNC)
2056 				D("send %d on %s %d",
2057 					kring->ring->cur,
2058 					ifp->if_xname, i);
2059 			if (na->nm_txsync(ifp, i, 0 /* no lock */))
2060 				revents |= POLLERR;
2061 
2062 			/* Check avail/call selrecord only if called with POLLOUT */
2063 			if (want_tx) {
2064 				if (kring->ring->avail > 0) {
2065 					/* stop at the first ring. We don't risk
2066 					 * starvation.
2067 					 */
2068 					revents |= want_tx;
2069 					want_tx = 0;
2070 				} else if (!check_all)
2071 					selrecord(td, &kring->si);
2072 			}
2073 			if (na->separate_locks)
2074 				na->nm_lock(ifp, NETMAP_TX_UNLOCK, i);
2075 		}
2076 	}
2077 
2078 	/*
2079 	 * now if want_rx is still set we need to lock and rxsync.
2080 	 * Do it on all rings because otherwise we starve.
2081 	 */
2082 	if (want_rx) {
2083 		for (i = priv->np_qfirst; i < lim_rx; i++) {
2084 			kring = &na->rx_rings[i];
2085 			if (core_lock == NEED_CL) {
2086 				na->nm_lock(ifp, NETMAP_CORE_LOCK, 0);
2087 				core_lock = LOCKED_CL;
2088 			}
2089 			if (na->separate_locks)
2090 				na->nm_lock(ifp, NETMAP_RX_LOCK, i);
2091 			if (netmap_fwd ||kring->ring->flags & NR_FORWARD) {
2092 				ND(10, "forwarding some buffers up %d to %d",
2093 				    kring->nr_hwcur, kring->ring->cur);
2094 				netmap_grab_packets(kring, &q, netmap_fwd);
2095 			}
2096 
2097 			if (na->nm_rxsync(ifp, i, 0 /* no lock */))
2098 				revents |= POLLERR;
2099 			if (netmap_no_timestamp == 0 ||
2100 					kring->ring->flags & NR_TIMESTAMP) {
2101 				microtime(&kring->ring->ts);
2102 			}
2103 
2104 			if (kring->ring->avail > 0)
2105 				revents |= want_rx;
2106 			else if (!check_all)
2107 				selrecord(td, &kring->si);
2108 			if (na->separate_locks)
2109 				na->nm_lock(ifp, NETMAP_RX_UNLOCK, i);
2110 		}
2111 	}
2112 	if (check_all && revents == 0) { /* signal on the global queue */
2113 		if (want_tx)
2114 			selrecord(td, &na->tx_si);
2115 		if (want_rx)
2116 			selrecord(td, &na->rx_si);
2117 	}
2118 
2119 	/* forward host to the netmap ring */
2120 	kring = &na->rx_rings[lim_rx];
2121 	if (kring->nr_hwavail > 0)
2122 		ND("host rx %d has %d packets", lim_rx, kring->nr_hwavail);
2123 	if ( (priv->np_qlast == NETMAP_HW_RING) // XXX check_all
2124 			&& (netmap_fwd || kring->ring->flags & NR_FORWARD)
2125 			 && kring->nr_hwavail > 0 && !host_forwarded) {
2126 		if (core_lock == NEED_CL) {
2127 			na->nm_lock(ifp, NETMAP_CORE_LOCK, 0);
2128 			core_lock = LOCKED_CL;
2129 		}
2130 		netmap_sw_to_nic(na);
2131 		host_forwarded = 1; /* prevent another pass */
2132 		want_rx = 0;
2133 		goto flush_tx;
2134 	}
2135 
2136 	if (core_lock == LOCKED_CL)
2137 		na->nm_lock(ifp, NETMAP_CORE_UNLOCK, 0);
2138 	if (q.head)
2139 		netmap_send_up(na->ifp, q.head);
2140 
2141 	return (revents);
2142 }
2143 
2144 /*------- driver support routines ------*/
2145 
2146 
2147 /*
2148  * default lock wrapper.
2149  */
2150 static void
2151 netmap_lock_wrapper(struct ifnet *dev, int what, u_int queueid)
2152 {
2153 	struct netmap_adapter *na = NA(dev);
2154 
2155 	switch (what) {
2156 #ifdef linux	/* some system do not need lock on register */
2157 	case NETMAP_REG_LOCK:
2158 	case NETMAP_REG_UNLOCK:
2159 		break;
2160 #endif /* linux */
2161 
2162 	case NETMAP_CORE_LOCK:
2163 		mtx_lock(&na->core_lock);
2164 		break;
2165 
2166 	case NETMAP_CORE_UNLOCK:
2167 		mtx_unlock(&na->core_lock);
2168 		break;
2169 
2170 	case NETMAP_TX_LOCK:
2171 		mtx_lock(&na->tx_rings[queueid].q_lock);
2172 		break;
2173 
2174 	case NETMAP_TX_UNLOCK:
2175 		mtx_unlock(&na->tx_rings[queueid].q_lock);
2176 		break;
2177 
2178 	case NETMAP_RX_LOCK:
2179 		mtx_lock(&na->rx_rings[queueid].q_lock);
2180 		break;
2181 
2182 	case NETMAP_RX_UNLOCK:
2183 		mtx_unlock(&na->rx_rings[queueid].q_lock);
2184 		break;
2185 	}
2186 }
2187 
2188 
2189 /*
2190  * Initialize a ``netmap_adapter`` object created by driver on attach.
2191  * We allocate a block of memory with room for a struct netmap_adapter
2192  * plus two sets of N+2 struct netmap_kring (where N is the number
2193  * of hardware rings):
2194  * krings	0..N-1	are for the hardware queues.
2195  * kring	N	is for the host stack queue
2196  * kring	N+1	is only used for the selinfo for all queues.
2197  * Return 0 on success, ENOMEM otherwise.
2198  *
2199  * By default the receive and transmit adapter ring counts are both initialized
2200  * to num_queues.  na->num_tx_rings can be set for cards with different tx/rx
2201  * setups.
2202  */
2203 int
2204 netmap_attach(struct netmap_adapter *arg, int num_queues)
2205 {
2206 	struct netmap_adapter *na = NULL;
2207 	struct ifnet *ifp = arg ? arg->ifp : NULL;
2208 	int len;
2209 
2210 	if (arg == NULL || ifp == NULL)
2211 		goto fail;
2212 	len = nma_is_vp(arg) ? sizeof(*na) : sizeof(*na) * 2;
2213 	na = malloc(len, M_DEVBUF, M_NOWAIT | M_ZERO);
2214 	if (na == NULL)
2215 		goto fail;
2216 	WNA(ifp) = na;
2217 	*na = *arg; /* copy everything, trust the driver to not pass junk */
2218 	NETMAP_SET_CAPABLE(ifp);
2219 	if (na->num_tx_rings == 0)
2220 		na->num_tx_rings = num_queues;
2221 	na->num_rx_rings = num_queues;
2222 	na->refcount = na->na_single = na->na_multi = 0;
2223 	/* Core lock initialized here, others after netmap_if_new. */
2224 	mtx_init(&na->core_lock, "netmap core lock", MTX_NETWORK_LOCK, MTX_DEF);
2225 	if (na->nm_lock == NULL) {
2226 		ND("using default locks for %s", ifp->if_xname);
2227 		na->nm_lock = netmap_lock_wrapper;
2228 	}
2229 #ifdef linux
2230 	if (ifp->netdev_ops) {
2231 		ND("netdev_ops %p", ifp->netdev_ops);
2232 		/* prepare a clone of the netdev ops */
2233 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 28)
2234 		na->nm_ndo.ndo_start_xmit = ifp->netdev_ops;
2235 #else
2236 		na->nm_ndo = *ifp->netdev_ops;
2237 #endif
2238 	}
2239 	na->nm_ndo.ndo_start_xmit = linux_netmap_start;
2240 #endif
2241 	if (!nma_is_vp(arg))
2242 		netmap_attach_sw(ifp);
2243 	D("success for %s", ifp->if_xname);
2244 	return 0;
2245 
2246 fail:
2247 	D("fail, arg %p ifp %p na %p", arg, ifp, na);
2248 	netmap_detach(ifp);
2249 	return (na ? EINVAL : ENOMEM);
2250 }
2251 
2252 
2253 /*
2254  * Free the allocated memory linked to the given ``netmap_adapter``
2255  * object.
2256  */
2257 void
2258 netmap_detach(struct ifnet *ifp)
2259 {
2260 	struct netmap_adapter *na = NA(ifp);
2261 
2262 	if (!na)
2263 		return;
2264 
2265 	mtx_destroy(&na->core_lock);
2266 
2267 	if (na->tx_rings) { /* XXX should not happen */
2268 		D("freeing leftover tx_rings");
2269 		free(na->tx_rings, M_DEVBUF);
2270 	}
2271 	bzero(na, sizeof(*na));
2272 	WNA(ifp) = NULL;
2273 	free(na, M_DEVBUF);
2274 }
2275 
2276 
2277 int
2278 nm_bdg_flush(struct nm_bdg_fwd *ft, int n, struct netmap_adapter *na, u_int ring_nr);
2279 
2280 /* we don't need to lock myself */
2281 static int
2282 bdg_netmap_start(struct ifnet *ifp, struct mbuf *m)
2283 {
2284 	struct netmap_adapter *na = SWNA(ifp);
2285 	struct nm_bdg_fwd *ft = na->rx_rings[0].nkr_ft;
2286 	char *buf = NMB(&na->rx_rings[0].ring->slot[0]);
2287 	u_int len = MBUF_LEN(m);
2288 
2289 	if (!na->na_bdg) /* SWNA is not configured to be attached */
2290 		return EBUSY;
2291 	m_copydata(m, 0, len, buf);
2292 	ft->ft_len = len;
2293 	ft->buf = buf;
2294 	nm_bdg_flush(ft, 1, na, 0);
2295 
2296 	/* release the mbuf in either cases of success or failure. As an
2297 	 * alternative, put the mbuf in a free list and free the list
2298 	 * only when really necessary.
2299 	 */
2300 	m_freem(m);
2301 
2302 	return (0);
2303 }
2304 
2305 
2306 /*
2307  * Intercept packets from the network stack and pass them
2308  * to netmap as incoming packets on the 'software' ring.
2309  * We are not locked when called.
2310  */
2311 int
2312 netmap_start(struct ifnet *ifp, struct mbuf *m)
2313 {
2314 	struct netmap_adapter *na = NA(ifp);
2315 	struct netmap_kring *kring = &na->rx_rings[na->num_rx_rings];
2316 	u_int i, len = MBUF_LEN(m);
2317 	u_int error = EBUSY, lim = kring->nkr_num_slots - 1;
2318 	struct netmap_slot *slot;
2319 
2320 	if (netmap_verbose & NM_VERB_HOST)
2321 		D("%s packet %d len %d from the stack", ifp->if_xname,
2322 			kring->nr_hwcur + kring->nr_hwavail, len);
2323 	if (len > NETMAP_BUF_SIZE) { /* too long for us */
2324 		D("%s from_host, drop packet size %d > %d", ifp->if_xname,
2325 			len, NETMAP_BUF_SIZE);
2326 		m_freem(m);
2327 		return EINVAL;
2328 	}
2329 	if (na->na_bdg)
2330 		return bdg_netmap_start(ifp, m);
2331 
2332 	na->nm_lock(ifp, NETMAP_CORE_LOCK, 0);
2333 	if (kring->nr_hwavail >= lim) {
2334 		if (netmap_verbose)
2335 			D("stack ring %s full\n", ifp->if_xname);
2336 		goto done;	/* no space */
2337 	}
2338 
2339 	/* compute the insert position */
2340 	i = kring->nr_hwcur + kring->nr_hwavail;
2341 	if (i > lim)
2342 		i -= lim + 1;
2343 	slot = &kring->ring->slot[i];
2344 	m_copydata(m, 0, len, NMB(slot));
2345 	slot->len = len;
2346 	slot->flags = kring->nkr_slot_flags;
2347 	kring->nr_hwavail++;
2348 	if (netmap_verbose  & NM_VERB_HOST)
2349 		D("wake up host ring %s %d", na->ifp->if_xname, na->num_rx_rings);
2350 	selwakeuppri(&kring->si, PI_NET);
2351 	error = 0;
2352 done:
2353 	na->nm_lock(ifp, NETMAP_CORE_UNLOCK, 0);
2354 
2355 	/* release the mbuf in either cases of success or failure. As an
2356 	 * alternative, put the mbuf in a free list and free the list
2357 	 * only when really necessary.
2358 	 */
2359 	m_freem(m);
2360 
2361 	return (error);
2362 }
2363 
2364 
2365 /*
2366  * netmap_reset() is called by the driver routines when reinitializing
2367  * a ring. The driver is in charge of locking to protect the kring.
2368  * If netmap mode is not set just return NULL.
2369  */
2370 struct netmap_slot *
2371 netmap_reset(struct netmap_adapter *na, enum txrx tx, int n,
2372 	u_int new_cur)
2373 {
2374 	struct netmap_kring *kring;
2375 	int new_hwofs, lim;
2376 
2377 	if (na == NULL)
2378 		return NULL;	/* no netmap support here */
2379 	if (!(na->ifp->if_capenable & IFCAP_NETMAP))
2380 		return NULL;	/* nothing to reinitialize */
2381 
2382 	if (tx == NR_TX) {
2383 		if (n >= na->num_tx_rings)
2384 			return NULL;
2385 		kring = na->tx_rings + n;
2386 		new_hwofs = kring->nr_hwcur - new_cur;
2387 	} else {
2388 		if (n >= na->num_rx_rings)
2389 			return NULL;
2390 		kring = na->rx_rings + n;
2391 		new_hwofs = kring->nr_hwcur + kring->nr_hwavail - new_cur;
2392 	}
2393 	lim = kring->nkr_num_slots - 1;
2394 	if (new_hwofs > lim)
2395 		new_hwofs -= lim + 1;
2396 
2397 	/* Alwayws set the new offset value and realign the ring. */
2398 	kring->nkr_hwofs = new_hwofs;
2399 	if (tx == NR_TX)
2400 		kring->nr_hwavail = kring->nkr_num_slots - 1;
2401 	ND(10, "new hwofs %d on %s %s[%d]",
2402 			kring->nkr_hwofs, na->ifp->if_xname,
2403 			tx == NR_TX ? "TX" : "RX", n);
2404 
2405 #if 0 // def linux
2406 	/* XXX check that the mappings are correct */
2407 	/* need ring_nr, adapter->pdev, direction */
2408 	buffer_info->dma = dma_map_single(&pdev->dev, addr, adapter->rx_buffer_len, DMA_FROM_DEVICE);
2409 	if (dma_mapping_error(&adapter->pdev->dev, buffer_info->dma)) {
2410 		D("error mapping rx netmap buffer %d", i);
2411 		// XXX fix error handling
2412 	}
2413 
2414 #endif /* linux */
2415 	/*
2416 	 * Wakeup on the individual and global lock
2417 	 * We do the wakeup here, but the ring is not yet reconfigured.
2418 	 * However, we are under lock so there are no races.
2419 	 */
2420 	selwakeuppri(&kring->si, PI_NET);
2421 	selwakeuppri(tx == NR_TX ? &na->tx_si : &na->rx_si, PI_NET);
2422 	return kring->ring->slot;
2423 }
2424 
2425 
2426 /* returns the next position in the ring */
2427 static int
2428 nm_bdg_preflush(struct netmap_adapter *na, u_int ring_nr,
2429 	struct netmap_kring *kring, u_int end)
2430 {
2431 	struct netmap_ring *ring = kring->ring;
2432 	struct nm_bdg_fwd *ft = kring->nkr_ft;
2433 	u_int j = kring->nr_hwcur, lim = kring->nkr_num_slots - 1;
2434 	u_int ft_i = 0;	/* start from 0 */
2435 
2436 	for (; likely(j != end); j = unlikely(j == lim) ? 0 : j+1) {
2437 		struct netmap_slot *slot = &ring->slot[j];
2438 		int len = ft[ft_i].ft_len = slot->len;
2439 		char *buf = ft[ft_i].buf = NMB(slot);
2440 
2441 		prefetch(buf);
2442 		if (unlikely(len < 14))
2443 			continue;
2444 		if (unlikely(++ft_i == netmap_bridge))
2445 			ft_i = nm_bdg_flush(ft, ft_i, na, ring_nr);
2446 	}
2447 	if (ft_i)
2448 		ft_i = nm_bdg_flush(ft, ft_i, na, ring_nr);
2449 	return j;
2450 }
2451 
2452 
2453 /*
2454  * Pass packets from nic to the bridge. Must be called with
2455  * proper locks on the source interface.
2456  * Note, no user process can access this NIC so we can ignore
2457  * the info in the 'ring'.
2458  */
2459 static void
2460 netmap_nic_to_bdg(struct ifnet *ifp, u_int ring_nr)
2461 {
2462 	struct netmap_adapter *na = NA(ifp);
2463 	struct netmap_kring *kring = &na->rx_rings[ring_nr];
2464 	struct netmap_ring *ring = kring->ring;
2465 	int j, k, lim = kring->nkr_num_slots - 1;
2466 
2467 	/* fetch packets that have arrived */
2468 	na->nm_rxsync(ifp, ring_nr, 0);
2469 	/* XXX we don't count reserved, but it should be 0 */
2470 	j = kring->nr_hwcur;
2471 	k = j + kring->nr_hwavail;
2472 	if (k > lim)
2473 		k -= lim + 1;
2474 	if (k == j && netmap_verbose) {
2475 		D("how strange, interrupt with no packets on %s",
2476 			ifp->if_xname);
2477 		return;
2478 	}
2479 
2480 	j = nm_bdg_preflush(na, ring_nr, kring, k);
2481 
2482 	/* we consume everything, but we cannot update kring directly
2483 	 * because the nic may have destroyed the info in the NIC ring.
2484 	 * So we need to call rxsync again to restore it.
2485 	 */
2486 	ring->cur = j;
2487 	ring->avail = 0;
2488 	na->nm_rxsync(ifp, ring_nr, 0);
2489 	return;
2490 }
2491 
2492 
2493 /*
2494  * Default functions to handle rx/tx interrupts
2495  * we have 4 cases:
2496  * 1 ring, single lock:
2497  *	lock(core); wake(i=0); unlock(core)
2498  * N rings, single lock:
2499  *	lock(core); wake(i); wake(N+1) unlock(core)
2500  * 1 ring, separate locks: (i=0)
2501  *	lock(i); wake(i); unlock(i)
2502  * N rings, separate locks:
2503  *	lock(i); wake(i); unlock(i); lock(core) wake(N+1) unlock(core)
2504  * work_done is non-null on the RX path.
2505  *
2506  * The 'q' argument also includes flag to tell whether the queue is
2507  * already locked on enter, and whether it should remain locked on exit.
2508  * This helps adapting to different defaults in drivers and OSes.
2509  */
2510 int
2511 netmap_rx_irq(struct ifnet *ifp, int q, int *work_done)
2512 {
2513 	struct netmap_adapter *na;
2514 	struct netmap_kring *r;
2515 	NM_SELINFO_T *main_wq;
2516 	int locktype, unlocktype, nic_to_bridge, lock;
2517 
2518 	if (!(ifp->if_capenable & IFCAP_NETMAP))
2519 		return 0;
2520 
2521 	lock = q & (NETMAP_LOCKED_ENTER | NETMAP_LOCKED_EXIT);
2522 	q = q & NETMAP_RING_MASK;
2523 
2524 	ND(5, "received %s queue %d", work_done ? "RX" : "TX" , q);
2525 	na = NA(ifp);
2526 	if (na->na_flags & NAF_SKIP_INTR) {
2527 		ND("use regular interrupt");
2528 		return 0;
2529 	}
2530 
2531 	if (work_done) { /* RX path */
2532 		if (q >= na->num_rx_rings)
2533 			return 0;	// not a physical queue
2534 		r = na->rx_rings + q;
2535 		r->nr_kflags |= NKR_PENDINTR;
2536 		main_wq = (na->num_rx_rings > 1) ? &na->rx_si : NULL;
2537 		/* set a flag if the NIC is attached to a VALE switch */
2538 		nic_to_bridge = (na->na_bdg != NULL);
2539 		locktype = NETMAP_RX_LOCK;
2540 		unlocktype = NETMAP_RX_UNLOCK;
2541 	} else { /* TX path */
2542 		if (q >= na->num_tx_rings)
2543 			return 0;	// not a physical queue
2544 		r = na->tx_rings + q;
2545 		main_wq = (na->num_tx_rings > 1) ? &na->tx_si : NULL;
2546 		work_done = &q; /* dummy */
2547 		nic_to_bridge = 0;
2548 		locktype = NETMAP_TX_LOCK;
2549 		unlocktype = NETMAP_TX_UNLOCK;
2550 	}
2551 	if (na->separate_locks) {
2552 		if (!(lock & NETMAP_LOCKED_ENTER))
2553 			na->nm_lock(ifp, locktype, q);
2554 		/* If a NIC is attached to a bridge, flush packets
2555 		 * (and no need to wakeup anyone). Otherwise, wakeup
2556 		 * possible processes waiting for packets.
2557 		 */
2558 		if (nic_to_bridge)
2559 			netmap_nic_to_bdg(ifp, q);
2560 		else
2561 			selwakeuppri(&r->si, PI_NET);
2562 		na->nm_lock(ifp, unlocktype, q);
2563 		if (main_wq && !nic_to_bridge) {
2564 			na->nm_lock(ifp, NETMAP_CORE_LOCK, 0);
2565 			selwakeuppri(main_wq, PI_NET);
2566 			na->nm_lock(ifp, NETMAP_CORE_UNLOCK, 0);
2567 		}
2568 		/* lock the queue again if requested */
2569 		if (lock & NETMAP_LOCKED_EXIT)
2570 			na->nm_lock(ifp, locktype, q);
2571 	} else {
2572 		if (!(lock & NETMAP_LOCKED_ENTER))
2573 			na->nm_lock(ifp, NETMAP_CORE_LOCK, 0);
2574 		if (nic_to_bridge)
2575 			netmap_nic_to_bdg(ifp, q);
2576 		else {
2577 			selwakeuppri(&r->si, PI_NET);
2578 			if (main_wq)
2579 				selwakeuppri(main_wq, PI_NET);
2580 		}
2581 		if (!(lock & NETMAP_LOCKED_EXIT))
2582 			na->nm_lock(ifp, NETMAP_CORE_UNLOCK, 0);
2583 	}
2584 	*work_done = 1; /* do not fire napi again */
2585 	return 1;
2586 }
2587 
2588 
2589 #ifdef linux	/* linux-specific routines */
2590 
2591 
2592 /*
2593  * Remap linux arguments into the FreeBSD call.
2594  * - pwait is the poll table, passed as 'dev';
2595  *   If pwait == NULL someone else already woke up before. We can report
2596  *   events but they are filtered upstream.
2597  *   If pwait != NULL, then pwait->key contains the list of events.
2598  * - events is computed from pwait as above.
2599  * - file is passed as 'td';
2600  */
2601 static u_int
2602 linux_netmap_poll(struct file * file, struct poll_table_struct *pwait)
2603 {
2604 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,28)
2605 	int events = POLLIN | POLLOUT; /* XXX maybe... */
2606 #elif LINUX_VERSION_CODE < KERNEL_VERSION(3,4,0)
2607 	int events = pwait ? pwait->key : POLLIN | POLLOUT;
2608 #else /* in 3.4.0 field 'key' was renamed to '_key' */
2609 	int events = pwait ? pwait->_key : POLLIN | POLLOUT;
2610 #endif
2611 	return netmap_poll((void *)pwait, events, (void *)file);
2612 }
2613 
2614 
2615 static int
2616 linux_netmap_mmap(struct file *f, struct vm_area_struct *vma)
2617 {
2618 	int lut_skip, i, j;
2619 	int user_skip = 0;
2620 	struct lut_entry *l_entry;
2621 	int error = 0;
2622 	unsigned long off, tomap;
2623 	/*
2624 	 * vma->vm_start: start of mapping user address space
2625 	 * vma->vm_end: end of the mapping user address space
2626 	 * vma->vm_pfoff: offset of first page in the device
2627 	 */
2628 
2629 	// XXX security checks
2630 
2631 	error = netmap_get_memory(f->private_data);
2632 	ND("get_memory returned %d", error);
2633 	if (error)
2634 	    return -error;
2635 
2636 	off = vma->vm_pgoff << PAGE_SHIFT; /* offset in bytes */
2637 	tomap = vma->vm_end - vma->vm_start;
2638 	for (i = 0; i < NETMAP_POOLS_NR; i++) {  /* loop through obj_pools */
2639 		const struct netmap_obj_pool *p = &nm_mem.pools[i];
2640 		/*
2641 		 * In each pool memory is allocated in clusters
2642 		 * of size _clustsize, each containing clustentries
2643 		 * entries. For each object k we already store the
2644 		 * vtophys mapping in lut[k] so we use that, scanning
2645 		 * the lut[] array in steps of clustentries,
2646 		 * and we map each cluster (not individual pages,
2647 		 * it would be overkill -- XXX slow ? 20130415).
2648 		 */
2649 
2650 		/*
2651 		 * We interpret vm_pgoff as an offset into the whole
2652 		 * netmap memory, as if all clusters where contiguous.
2653 		 */
2654 		for (lut_skip = 0, j = 0; j < p->_numclusters; j++, lut_skip += p->clustentries) {
2655 			unsigned long paddr, mapsize;
2656 			if (p->_clustsize <= off) {
2657 				off -= p->_clustsize;
2658 				continue;
2659 			}
2660 			l_entry = &p->lut[lut_skip]; /* first obj in the cluster */
2661 			paddr = l_entry->paddr + off;
2662 			mapsize = p->_clustsize - off;
2663 			off = 0;
2664 			if (mapsize > tomap)
2665 				mapsize = tomap;
2666 			ND("remap_pfn_range(%lx, %lx, %lx)",
2667 				vma->vm_start + user_skip,
2668 				paddr >> PAGE_SHIFT, mapsize);
2669 			if (remap_pfn_range(vma, vma->vm_start + user_skip,
2670 					paddr >> PAGE_SHIFT, mapsize,
2671 					vma->vm_page_prot))
2672 				return -EAGAIN; // XXX check return value
2673 			user_skip += mapsize;
2674 			tomap -= mapsize;
2675 			if (tomap == 0)
2676 				goto done;
2677 		}
2678 	}
2679 done:
2680 
2681 	return 0;
2682 }
2683 
2684 
2685 static netdev_tx_t
2686 linux_netmap_start(struct sk_buff *skb, struct net_device *dev)
2687 {
2688 	netmap_start(dev, skb);
2689 	return (NETDEV_TX_OK);
2690 }
2691 
2692 
2693 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,37)	// XXX was 38
2694 #define LIN_IOCTL_NAME	.ioctl
2695 int
2696 linux_netmap_ioctl(struct inode *inode, struct file *file, u_int cmd, u_long data /* arg */)
2697 #else
2698 #define LIN_IOCTL_NAME	.unlocked_ioctl
2699 long
2700 linux_netmap_ioctl(struct file *file, u_int cmd, u_long data /* arg */)
2701 #endif
2702 {
2703 	int ret;
2704 	struct nmreq nmr;
2705 	bzero(&nmr, sizeof(nmr));
2706 
2707 	if (data && copy_from_user(&nmr, (void *)data, sizeof(nmr) ) != 0)
2708 		return -EFAULT;
2709 	ret = netmap_ioctl(NULL, cmd, (caddr_t)&nmr, 0, (void *)file);
2710 	if (data && copy_to_user((void*)data, &nmr, sizeof(nmr) ) != 0)
2711 		return -EFAULT;
2712 	return -ret;
2713 }
2714 
2715 
2716 static int
2717 netmap_release(struct inode *inode, struct file *file)
2718 {
2719 	(void)inode;	/* UNUSED */
2720 	if (file->private_data)
2721 		netmap_dtor(file->private_data);
2722 	return (0);
2723 }
2724 
2725 
2726 static int
2727 linux_netmap_open(struct inode *inode, struct file *file)
2728 {
2729 	struct netmap_priv_d *priv;
2730 	(void)inode;	/* UNUSED */
2731 
2732 	priv = malloc(sizeof(struct netmap_priv_d), M_DEVBUF,
2733 			      M_NOWAIT | M_ZERO);
2734 	if (priv == NULL)
2735 		return -ENOMEM;
2736 
2737 	file->private_data = priv;
2738 
2739 	return (0);
2740 }
2741 
2742 
2743 static struct file_operations netmap_fops = {
2744     .owner = THIS_MODULE,
2745     .open = linux_netmap_open,
2746     .mmap = linux_netmap_mmap,
2747     LIN_IOCTL_NAME = linux_netmap_ioctl,
2748     .poll = linux_netmap_poll,
2749     .release = netmap_release,
2750 };
2751 
2752 
2753 static struct miscdevice netmap_cdevsw = {	/* same name as FreeBSD */
2754 	MISC_DYNAMIC_MINOR,
2755 	"netmap",
2756 	&netmap_fops,
2757 };
2758 
2759 static int netmap_init(void);
2760 static void netmap_fini(void);
2761 
2762 
2763 /* Errors have negative values on linux */
2764 static int linux_netmap_init(void)
2765 {
2766 	return -netmap_init();
2767 }
2768 
2769 module_init(linux_netmap_init);
2770 module_exit(netmap_fini);
2771 /* export certain symbols to other modules */
2772 EXPORT_SYMBOL(netmap_attach);		// driver attach routines
2773 EXPORT_SYMBOL(netmap_detach);		// driver detach routines
2774 EXPORT_SYMBOL(netmap_ring_reinit);	// ring init on error
2775 EXPORT_SYMBOL(netmap_buffer_lut);
2776 EXPORT_SYMBOL(netmap_total_buffers);	// index check
2777 EXPORT_SYMBOL(netmap_buffer_base);
2778 EXPORT_SYMBOL(netmap_reset);		// ring init routines
2779 EXPORT_SYMBOL(netmap_buf_size);
2780 EXPORT_SYMBOL(netmap_rx_irq);		// default irq handler
2781 EXPORT_SYMBOL(netmap_no_pendintr);	// XXX mitigation - should go away
2782 EXPORT_SYMBOL(netmap_bdg_ctl);		// bridge configuration routine
2783 EXPORT_SYMBOL(netmap_bdg_learning);	// the default lookup function
2784 
2785 
2786 MODULE_AUTHOR("http://info.iet.unipi.it/~luigi/netmap/");
2787 MODULE_DESCRIPTION("The netmap packet I/O framework");
2788 MODULE_LICENSE("Dual BSD/GPL"); /* the code here is all BSD. */
2789 
2790 #else /* __FreeBSD__ */
2791 
2792 
2793 static struct cdevsw netmap_cdevsw = {
2794 	.d_version = D_VERSION,
2795 	.d_name = "netmap",
2796 	.d_open = netmap_open,
2797 	.d_mmap = netmap_mmap,
2798 	.d_mmap_single = netmap_mmap_single,
2799 	.d_ioctl = netmap_ioctl,
2800 	.d_poll = netmap_poll,
2801 	.d_close = netmap_close,
2802 };
2803 #endif /* __FreeBSD__ */
2804 
2805 #ifdef NM_BRIDGE
2806 /*
2807  *---- support for virtual bridge -----
2808  */
2809 
2810 /* ----- FreeBSD if_bridge hash function ------- */
2811 
2812 /*
2813  * The following hash function is adapted from "Hash Functions" by Bob Jenkins
2814  * ("Algorithm Alley", Dr. Dobbs Journal, September 1997).
2815  *
2816  * http://www.burtleburtle.net/bob/hash/spooky.html
2817  */
2818 #define mix(a, b, c)                                                    \
2819 do {                                                                    \
2820         a -= b; a -= c; a ^= (c >> 13);                                 \
2821         b -= c; b -= a; b ^= (a << 8);                                  \
2822         c -= a; c -= b; c ^= (b >> 13);                                 \
2823         a -= b; a -= c; a ^= (c >> 12);                                 \
2824         b -= c; b -= a; b ^= (a << 16);                                 \
2825         c -= a; c -= b; c ^= (b >> 5);                                  \
2826         a -= b; a -= c; a ^= (c >> 3);                                  \
2827         b -= c; b -= a; b ^= (a << 10);                                 \
2828         c -= a; c -= b; c ^= (b >> 15);                                 \
2829 } while (/*CONSTCOND*/0)
2830 
2831 static __inline uint32_t
2832 nm_bridge_rthash(const uint8_t *addr)
2833 {
2834         uint32_t a = 0x9e3779b9, b = 0x9e3779b9, c = 0; // hask key
2835 
2836         b += addr[5] << 8;
2837         b += addr[4];
2838         a += addr[3] << 24;
2839         a += addr[2] << 16;
2840         a += addr[1] << 8;
2841         a += addr[0];
2842 
2843         mix(a, b, c);
2844 #define BRIDGE_RTHASH_MASK	(NM_BDG_HASH-1)
2845         return (c & BRIDGE_RTHASH_MASK);
2846 }
2847 
2848 #undef mix
2849 
2850 
2851 static int
2852 bdg_netmap_reg(struct ifnet *ifp, int onoff)
2853 {
2854 	// struct nm_bridge *b = NA(ifp)->na_bdg;
2855 
2856 	/* the interface is already attached to the bridge,
2857 	 * so we only need to toggle IFCAP_NETMAP.
2858 	 * Locking is not necessary (we are already under
2859 	 * NMA_LOCK, and the port is not in use during this call).
2860 	 */
2861 	/* BDG_WLOCK(b); */
2862 	if (onoff) {
2863 		ifp->if_capenable |= IFCAP_NETMAP;
2864 	} else {
2865 		ifp->if_capenable &= ~IFCAP_NETMAP;
2866 	}
2867 	/* BDG_WUNLOCK(b); */
2868 	return 0;
2869 }
2870 
2871 
2872 /*
2873  * Lookup function for a learning bridge.
2874  * Update the hash table with the source address,
2875  * and then returns the destination port index, and the
2876  * ring in *dst_ring (at the moment, always use ring 0)
2877  */
2878 u_int
2879 netmap_bdg_learning(char *buf, u_int len, uint8_t *dst_ring,
2880 		struct netmap_adapter *na)
2881 {
2882 	struct nm_hash_ent *ht = na->na_bdg->ht;
2883 	uint32_t sh, dh;
2884 	u_int dst, mysrc = na->bdg_port;
2885 	uint64_t smac, dmac;
2886 
2887 	dmac = le64toh(*(uint64_t *)(buf)) & 0xffffffffffff;
2888 	smac = le64toh(*(uint64_t *)(buf + 4));
2889 	smac >>= 16;
2890 
2891 	/*
2892 	 * The hash is somewhat expensive, there might be some
2893 	 * worthwhile optimizations here.
2894 	 */
2895 	if ((buf[6] & 1) == 0) { /* valid src */
2896 		uint8_t *s = buf+6;
2897 		sh = nm_bridge_rthash(buf+6); // XXX hash of source
2898 		/* update source port forwarding entry */
2899 		ht[sh].mac = smac;	/* XXX expire ? */
2900 		ht[sh].ports = mysrc;
2901 		if (netmap_verbose)
2902 		    D("src %02x:%02x:%02x:%02x:%02x:%02x on port %d",
2903 			s[0], s[1], s[2], s[3], s[4], s[5], mysrc);
2904 	}
2905 	dst = NM_BDG_BROADCAST;
2906 	if ((buf[0] & 1) == 0) { /* unicast */
2907 		dh = nm_bridge_rthash(buf); // XXX hash of dst
2908 		if (ht[dh].mac == dmac) {	/* found dst */
2909 			dst = ht[dh].ports;
2910 		}
2911 		/* XXX otherwise return NM_BDG_UNKNOWN ? */
2912 	}
2913 	*dst_ring = 0;
2914 	return dst;
2915 }
2916 
2917 
2918 /*
2919  * This flush routine supports only unicast and broadcast but a large
2920  * number of ports, and lets us replace the learn and dispatch functions.
2921  */
2922 int
2923 nm_bdg_flush(struct nm_bdg_fwd *ft, int n, struct netmap_adapter *na,
2924 		u_int ring_nr)
2925 {
2926 	struct nm_bdg_q *dst_ents, *brddst;
2927 	uint16_t num_dsts = 0, *dsts;
2928 	struct nm_bridge *b = na->na_bdg;
2929 	u_int i, me = na->bdg_port;
2930 
2931 	dst_ents = (struct nm_bdg_q *)(ft + NM_BDG_BATCH);
2932 	dsts = (uint16_t *)(dst_ents + NM_BDG_MAXPORTS * NM_BDG_MAXRINGS + 1);
2933 
2934 	BDG_RLOCK(b);
2935 
2936 	/* first pass: find a destination */
2937 	for (i = 0; likely(i < n); i++) {
2938 		uint8_t *buf = ft[i].buf;
2939 		uint8_t dst_ring = ring_nr;
2940 		uint16_t dst_port, d_i;
2941 		struct nm_bdg_q *d;
2942 
2943 		dst_port = b->nm_bdg_lookup(buf, ft[i].ft_len, &dst_ring, na);
2944 		if (dst_port == NM_BDG_NOPORT) {
2945 			continue; /* this packet is identified to be dropped */
2946 		} else if (unlikely(dst_port > NM_BDG_MAXPORTS)) {
2947 			continue;
2948 		} else if (dst_port == NM_BDG_BROADCAST) {
2949 			dst_ring = 0; /* broadcasts always go to ring 0 */
2950 		} else if (unlikely(dst_port == me ||
2951 		    !BDG_GET_VAR(b->bdg_ports[dst_port]))) {
2952 			continue;
2953 		}
2954 
2955 		/* get a position in the scratch pad */
2956 		d_i = dst_port * NM_BDG_MAXRINGS + dst_ring;
2957 		d = dst_ents + d_i;
2958 		if (d->bq_head == NM_BDG_BATCH) { /* new destination */
2959 			d->bq_head = d->bq_tail = i;
2960 			/* remember this position to be scanned later */
2961 			if (dst_port != NM_BDG_BROADCAST)
2962 				dsts[num_dsts++] = d_i;
2963 		}
2964 		ft[d->bq_tail].ft_next = i;
2965 		d->bq_tail = i;
2966 	}
2967 
2968 	/* if there is a broadcast, set ring 0 of all ports to be scanned
2969 	 * XXX This would be optimized by recording the highest index of active
2970 	 * ports.
2971 	 */
2972 	brddst = dst_ents + NM_BDG_BROADCAST * NM_BDG_MAXRINGS;
2973 	if (brddst->bq_head != NM_BDG_BATCH) {
2974 		for (i = 0; likely(i < NM_BDG_MAXPORTS); i++) {
2975 			uint16_t d_i = i * NM_BDG_MAXRINGS;
2976 			if (unlikely(i == me) || !BDG_GET_VAR(b->bdg_ports[i]))
2977 				continue;
2978 			else if (dst_ents[d_i].bq_head == NM_BDG_BATCH)
2979 				dsts[num_dsts++] = d_i;
2980 		}
2981 	}
2982 
2983 	/* second pass: scan destinations (XXX will be modular somehow) */
2984 	for (i = 0; i < num_dsts; i++) {
2985 		struct ifnet *dst_ifp;
2986 		struct netmap_adapter *dst_na;
2987 		struct netmap_kring *kring;
2988 		struct netmap_ring *ring;
2989 		u_int dst_nr, is_vp, lim, j, sent = 0, d_i, next, brd_next;
2990 		int howmany, retry = netmap_txsync_retry;
2991 		struct nm_bdg_q *d;
2992 
2993 		d_i = dsts[i];
2994 		d = dst_ents + d_i;
2995 		dst_na = BDG_GET_VAR(b->bdg_ports[d_i/NM_BDG_MAXRINGS]);
2996 		/* protect from the lookup function returning an inactive
2997 		 * destination port
2998 		 */
2999 		if (unlikely(dst_na == NULL))
3000 			continue;
3001 		else if (dst_na->na_flags & NAF_SW_ONLY)
3002 			continue;
3003 		dst_ifp = dst_na->ifp;
3004 		/*
3005 		 * The interface may be in !netmap mode in two cases:
3006 		 * - when na is attached but not activated yet;
3007 		 * - when na is being deactivated but is still attached.
3008 		 */
3009 		if (unlikely(!(dst_ifp->if_capenable & IFCAP_NETMAP)))
3010 			continue;
3011 
3012 		/* there is at least one either unicast or broadcast packet */
3013 		brd_next = brddst->bq_head;
3014 		next = d->bq_head;
3015 
3016 		is_vp = nma_is_vp(dst_na);
3017 		dst_nr = d_i & (NM_BDG_MAXRINGS-1);
3018 		if (is_vp) { /* virtual port */
3019 			if (dst_nr >= dst_na->num_rx_rings)
3020 				dst_nr = dst_nr % dst_na->num_rx_rings;
3021 			kring = &dst_na->rx_rings[dst_nr];
3022 			ring = kring->ring;
3023 			lim = kring->nkr_num_slots - 1;
3024 			dst_na->nm_lock(dst_ifp, NETMAP_RX_LOCK, dst_nr);
3025 			j = kring->nr_hwcur + kring->nr_hwavail;
3026 			if (j > lim)
3027 				j -= kring->nkr_num_slots;
3028 			howmany = lim - kring->nr_hwavail;
3029 		} else { /* hw or sw adapter */
3030 			if (dst_nr >= dst_na->num_tx_rings)
3031 				dst_nr = dst_nr % dst_na->num_tx_rings;
3032 			kring = &dst_na->tx_rings[dst_nr];
3033 			ring = kring->ring;
3034 			lim = kring->nkr_num_slots - 1;
3035 			dst_na->nm_lock(dst_ifp, NETMAP_TX_LOCK, dst_nr);
3036 retry:
3037 			dst_na->nm_txsync(dst_ifp, dst_nr, 0);
3038 			/* see nm_bdg_flush() */
3039 			j = kring->nr_hwcur;
3040 			howmany = kring->nr_hwavail;
3041 		}
3042 		while (howmany-- > 0) {
3043 			struct netmap_slot *slot;
3044 			struct nm_bdg_fwd *ft_p;
3045 
3046 			if (next < brd_next) {
3047 				ft_p = ft + next;
3048 				next = ft_p->ft_next;
3049 			} else { /* insert broadcast */
3050 				ft_p = ft + brd_next;
3051 				brd_next = ft_p->ft_next;
3052 			}
3053 			slot = &ring->slot[j];
3054 			ND("send %d %d bytes at %s:%d", i, ft_p->ft_len, dst_ifp->if_xname, j);
3055 			pkt_copy(ft_p->buf, NMB(slot), ft_p->ft_len);
3056 			slot->len = ft_p->ft_len;
3057 			j = (j == lim) ? 0: j + 1; /* XXX to be macro-ed */
3058 			sent++;
3059 			if (next == d->bq_tail && brd_next == brddst->bq_tail)
3060 				break;
3061 		}
3062 		if (netmap_verbose && (howmany < 0))
3063 			D("rx ring full on %s", dst_ifp->if_xname);
3064 		if (is_vp) {
3065 			if (sent) {
3066 				kring->nr_hwavail += sent;
3067 				selwakeuppri(&kring->si, PI_NET);
3068 			}
3069 			dst_na->nm_lock(dst_ifp, NETMAP_RX_UNLOCK, dst_nr);
3070 		} else {
3071 			if (sent) {
3072 				ring->avail -= sent;
3073 				ring->cur = j;
3074 				dst_na->nm_txsync(dst_ifp, dst_nr, 0);
3075 			}
3076 			/* retry to send more packets */
3077 			if (nma_is_hw(dst_na) && howmany < 0 && retry--)
3078 				goto retry;
3079 			dst_na->nm_lock(dst_ifp, NETMAP_TX_UNLOCK, dst_nr);
3080 		}
3081 		d->bq_head = d->bq_tail = NM_BDG_BATCH; /* cleanup */
3082 	}
3083 	brddst->bq_head = brddst->bq_tail = NM_BDG_BATCH; /* cleanup */
3084 	BDG_RUNLOCK(b);
3085 	return 0;
3086 }
3087 
3088 
3089 /*
3090  * main dispatch routine
3091  */
3092 static int
3093 bdg_netmap_txsync(struct ifnet *ifp, u_int ring_nr, int do_lock)
3094 {
3095 	struct netmap_adapter *na = NA(ifp);
3096 	struct netmap_kring *kring = &na->tx_rings[ring_nr];
3097 	struct netmap_ring *ring = kring->ring;
3098 	int i, j, k, lim = kring->nkr_num_slots - 1;
3099 
3100 	k = ring->cur;
3101 	if (k > lim)
3102 		return netmap_ring_reinit(kring);
3103 	if (do_lock)
3104 		na->nm_lock(ifp, NETMAP_TX_LOCK, ring_nr);
3105 
3106 	if (netmap_bridge <= 0) { /* testing only */
3107 		j = k; // used all
3108 		goto done;
3109 	}
3110 	if (netmap_bridge > NM_BDG_BATCH)
3111 		netmap_bridge = NM_BDG_BATCH;
3112 
3113 	j = nm_bdg_preflush(na, ring_nr, kring, k);
3114 	i = k - j;
3115 	if (i < 0)
3116 		i += kring->nkr_num_slots;
3117 	kring->nr_hwavail = kring->nkr_num_slots - 1 - i;
3118 	if (j != k)
3119 		D("early break at %d/ %d, avail %d", j, k, kring->nr_hwavail);
3120 
3121 done:
3122 	kring->nr_hwcur = j;
3123 	ring->avail = kring->nr_hwavail;
3124 	if (do_lock)
3125 		na->nm_lock(ifp, NETMAP_TX_UNLOCK, ring_nr);
3126 
3127 	if (netmap_verbose)
3128 		D("%s ring %d lock %d", ifp->if_xname, ring_nr, do_lock);
3129 	return 0;
3130 }
3131 
3132 
3133 static int
3134 bdg_netmap_rxsync(struct ifnet *ifp, u_int ring_nr, int do_lock)
3135 {
3136 	struct netmap_adapter *na = NA(ifp);
3137 	struct netmap_kring *kring = &na->rx_rings[ring_nr];
3138 	struct netmap_ring *ring = kring->ring;
3139 	u_int j, lim = kring->nkr_num_slots - 1;
3140 	u_int k = ring->cur, resvd = ring->reserved;
3141 	int n;
3142 
3143 	ND("%s ring %d lock %d avail %d",
3144 		ifp->if_xname, ring_nr, do_lock, kring->nr_hwavail);
3145 
3146 	if (k > lim)
3147 		return netmap_ring_reinit(kring);
3148 	if (do_lock)
3149 		na->nm_lock(ifp, NETMAP_RX_LOCK, ring_nr);
3150 
3151 	/* skip past packets that userspace has released */
3152 	j = kring->nr_hwcur;    /* netmap ring index */
3153 	if (resvd > 0) {
3154 		if (resvd + ring->avail >= lim + 1) {
3155 			D("XXX invalid reserve/avail %d %d", resvd, ring->avail);
3156 			ring->reserved = resvd = 0; // XXX panic...
3157 		}
3158 		k = (k >= resvd) ? k - resvd : k + lim + 1 - resvd;
3159 	}
3160 
3161 	if (j != k) { /* userspace has released some packets. */
3162 		n = k - j;
3163 		if (n < 0)
3164 			n += kring->nkr_num_slots;
3165 		ND("userspace releases %d packets", n);
3166                 for (n = 0; likely(j != k); n++) {
3167                         struct netmap_slot *slot = &ring->slot[j];
3168                         void *addr = NMB(slot);
3169 
3170                         if (addr == netmap_buffer_base) { /* bad buf */
3171                                 if (do_lock)
3172                                         na->nm_lock(ifp, NETMAP_RX_UNLOCK, ring_nr);
3173                                 return netmap_ring_reinit(kring);
3174                         }
3175 			/* decrease refcount for buffer */
3176 
3177 			slot->flags &= ~NS_BUF_CHANGED;
3178                         j = unlikely(j == lim) ? 0 : j + 1;
3179                 }
3180                 kring->nr_hwavail -= n;
3181                 kring->nr_hwcur = k;
3182         }
3183         /* tell userspace that there are new packets */
3184         ring->avail = kring->nr_hwavail - resvd;
3185 
3186 	if (do_lock)
3187 		na->nm_lock(ifp, NETMAP_RX_UNLOCK, ring_nr);
3188 	return 0;
3189 }
3190 
3191 
3192 static void
3193 bdg_netmap_attach(struct netmap_adapter *arg)
3194 {
3195 	struct netmap_adapter na;
3196 
3197 	ND("attaching virtual bridge");
3198 	bzero(&na, sizeof(na));
3199 
3200 	na.ifp = arg->ifp;
3201 	na.separate_locks = 1;
3202 	na.num_tx_rings = arg->num_tx_rings;
3203 	na.num_rx_rings = arg->num_rx_rings;
3204 	na.num_tx_desc = NM_BRIDGE_RINGSIZE;
3205 	na.num_rx_desc = NM_BRIDGE_RINGSIZE;
3206 	na.nm_txsync = bdg_netmap_txsync;
3207 	na.nm_rxsync = bdg_netmap_rxsync;
3208 	na.nm_register = bdg_netmap_reg;
3209 	netmap_attach(&na, na.num_tx_rings);
3210 }
3211 
3212 #endif /* NM_BRIDGE */
3213 
3214 static struct cdev *netmap_dev; /* /dev/netmap character device. */
3215 
3216 
3217 /*
3218  * Module loader.
3219  *
3220  * Create the /dev/netmap device and initialize all global
3221  * variables.
3222  *
3223  * Return 0 on success, errno on failure.
3224  */
3225 static int
3226 netmap_init(void)
3227 {
3228 	int error;
3229 
3230 	error = netmap_memory_init();
3231 	if (error != 0) {
3232 		printf("netmap: unable to initialize the memory allocator.\n");
3233 		return (error);
3234 	}
3235 	printf("netmap: loaded module\n");
3236 	netmap_dev = make_dev(&netmap_cdevsw, 0, UID_ROOT, GID_WHEEL, 0660,
3237 			      "netmap");
3238 
3239 #ifdef NM_BRIDGE
3240 	{
3241 	int i;
3242 	mtx_init(&netmap_bridge_mutex, "netmap_bridge_mutex",
3243 		MTX_NETWORK_LOCK, MTX_DEF);
3244 	bzero(nm_bridges, sizeof(struct nm_bridge) * NM_BRIDGES); /* safety */
3245 	for (i = 0; i < NM_BRIDGES; i++)
3246 		rw_init(&nm_bridges[i].bdg_lock, "bdg lock");
3247 	}
3248 #endif
3249 	return (error);
3250 }
3251 
3252 
3253 /*
3254  * Module unloader.
3255  *
3256  * Free all the memory, and destroy the ``/dev/netmap`` device.
3257  */
3258 static void
3259 netmap_fini(void)
3260 {
3261 	destroy_dev(netmap_dev);
3262 	netmap_memory_fini();
3263 	printf("netmap: unloaded module.\n");
3264 }
3265 
3266 
3267 #ifdef __FreeBSD__
3268 /*
3269  * Kernel entry point.
3270  *
3271  * Initialize/finalize the module and return.
3272  *
3273  * Return 0 on success, errno on failure.
3274  */
3275 static int
3276 netmap_loader(__unused struct module *module, int event, __unused void *arg)
3277 {
3278 	int error = 0;
3279 
3280 	switch (event) {
3281 	case MOD_LOAD:
3282 		error = netmap_init();
3283 		break;
3284 
3285 	case MOD_UNLOAD:
3286 		netmap_fini();
3287 		break;
3288 
3289 	default:
3290 		error = EOPNOTSUPP;
3291 		break;
3292 	}
3293 
3294 	return (error);
3295 }
3296 
3297 
3298 DEV_MODULE(netmap, netmap_loader, NULL);
3299 #endif /* __FreeBSD__ */
3300