xref: /freebsd-14.2/sys/dev/netmap/netmap.c (revision f196ce38)
1 /*
2  * Copyright (C) 2011-2012 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 netmap_start_linux(struct sk_buff *skb, struct net_device *dev);
60 #endif /* linux */
61 #ifdef __APPLE__
62 #include "osx_glue.h"
63 #endif
64 #ifdef __FreeBSD__
65 #include <sys/cdefs.h> /* prerequisite */
66 __FBSDID("$FreeBSD$");
67 
68 #include <sys/types.h>
69 #include <sys/module.h>
70 #include <sys/errno.h>
71 #include <sys/param.h>	/* defines used in kernel.h */
72 #include <sys/jail.h>
73 #include <sys/kernel.h>	/* types used in module initialization */
74 #include <sys/conf.h>	/* cdevsw struct */
75 #include <sys/uio.h>	/* uio struct */
76 #include <sys/sockio.h>
77 #include <sys/socketvar.h>	/* struct socket */
78 #include <sys/malloc.h>
79 #include <sys/mman.h>	/* PROT_EXEC */
80 #include <sys/poll.h>
81 #include <sys/proc.h>
82 #include <vm/vm.h>	/* vtophys */
83 #include <vm/pmap.h>	/* vtophys */
84 #include <sys/socket.h> /* sockaddrs */
85 #include <machine/bus.h>
86 #include <sys/selinfo.h>
87 #include <sys/sysctl.h>
88 #include <net/if.h>
89 #include <net/bpf.h>		/* BIOCIMMEDIATE */
90 #include <net/vnet.h>
91 #include <net/netmap.h>
92 #include <dev/netmap/netmap_kern.h>
93 #include <machine/bus.h>	/* bus_dmamap_* */
94 
95 MALLOC_DEFINE(M_NETMAP, "netmap", "Network memory map");
96 #endif /* __FreeBSD__ */
97 
98 /*
99  * lock and unlock for the netmap memory allocator
100  */
101 #define NMA_LOCK()	mtx_lock(&nm_mem->nm_mtx);
102 #define NMA_UNLOCK()	mtx_unlock(&nm_mem->nm_mtx);
103 struct netmap_mem_d;
104 static struct netmap_mem_d *nm_mem;	/* Our memory allocator. */
105 
106 u_int netmap_total_buffers;
107 char *netmap_buffer_base;	/* address of an invalid buffer */
108 
109 /* user-controlled variables */
110 int netmap_verbose;
111 
112 static int netmap_no_timestamp; /* don't timestamp on rxsync */
113 
114 SYSCTL_NODE(_dev, OID_AUTO, netmap, CTLFLAG_RW, 0, "Netmap args");
115 SYSCTL_INT(_dev_netmap, OID_AUTO, verbose,
116     CTLFLAG_RW, &netmap_verbose, 0, "Verbose mode");
117 SYSCTL_INT(_dev_netmap, OID_AUTO, no_timestamp,
118     CTLFLAG_RW, &netmap_no_timestamp, 0, "no_timestamp");
119 int netmap_buf_size = 2048;
120 TUNABLE_INT("hw.netmap.buf_size", &netmap_buf_size);
121 SYSCTL_INT(_dev_netmap, OID_AUTO, buf_size,
122     CTLFLAG_RD, &netmap_buf_size, 0, "Size of packet buffers");
123 int netmap_mitigate = 1;
124 SYSCTL_INT(_dev_netmap, OID_AUTO, mitigate, CTLFLAG_RW, &netmap_mitigate, 0, "");
125 int netmap_no_pendintr = 1;
126 SYSCTL_INT(_dev_netmap, OID_AUTO, no_pendintr,
127     CTLFLAG_RW, &netmap_no_pendintr, 0, "Always look for new received packets.");
128 
129 int netmap_drop = 0;	/* debugging */
130 int netmap_flags = 0;	/* debug flags */
131 int netmap_copy = 0;	/* debugging, copy content */
132 
133 SYSCTL_INT(_dev_netmap, OID_AUTO, drop, CTLFLAG_RW, &netmap_drop, 0 , "");
134 SYSCTL_INT(_dev_netmap, OID_AUTO, flags, CTLFLAG_RW, &netmap_flags, 0 , "");
135 SYSCTL_INT(_dev_netmap, OID_AUTO, copy, CTLFLAG_RW, &netmap_copy, 0 , "");
136 
137 #ifdef NM_BRIDGE /* support for netmap bridge */
138 
139 /*
140  * system parameters.
141  *
142  * All switched ports have prefix NM_NAME.
143  * The switch has a max of NM_BDG_MAXPORTS ports (often stored in a bitmap,
144  * so a practical upper bound is 64).
145  * Each tx ring is read-write, whereas rx rings are readonly (XXX not done yet).
146  * The virtual interfaces use per-queue lock instead of core lock.
147  * In the tx loop, we aggregate traffic in batches to make all operations
148  * faster. The batch size is NM_BDG_BATCH
149  */
150 #define	NM_NAME			"vale"	/* prefix for the interface */
151 #define NM_BDG_MAXPORTS		16	/* up to 64 ? */
152 #define NM_BRIDGE_RINGSIZE	1024	/* in the device */
153 #define NM_BDG_HASH		1024	/* forwarding table entries */
154 #define NM_BDG_BATCH		1024	/* entries in the forwarding buffer */
155 #define	NM_BRIDGES		4	/* number of bridges */
156 int netmap_bridge = NM_BDG_BATCH; /* bridge batch size */
157 SYSCTL_INT(_dev_netmap, OID_AUTO, bridge, CTLFLAG_RW, &netmap_bridge, 0 , "");
158 #ifdef linux
159 #define	ADD_BDG_REF(ifp)	(NA(ifp)->if_refcount++)
160 #define	DROP_BDG_REF(ifp)	(NA(ifp)->if_refcount-- <= 1)
161 #else /* !linux */
162 #define	ADD_BDG_REF(ifp)	(ifp)->if_refcount++
163 #define	DROP_BDG_REF(ifp)	refcount_release(&(ifp)->if_refcount)
164 #ifdef __FreeBSD__
165 #include <sys/endian.h>
166 #include <sys/refcount.h>
167 #endif /* __FreeBSD__ */
168 #endif /* !linux */
169 
170 static void bdg_netmap_attach(struct ifnet *ifp);
171 static int bdg_netmap_reg(struct ifnet *ifp, int onoff);
172 /* per-tx-queue entry */
173 struct nm_bdg_fwd {	/* forwarding entry for a bridge */
174 	void *buf;
175 	uint64_t dst;	/* dst mask */
176 	uint32_t src;	/* src index ? */
177 	uint16_t len;	/* src len */
178 #if 0
179 	uint64_t src_mac;	/* ignore 2 MSBytes */
180 	uint64_t dst_mac;	/* ignore 2 MSBytes */
181 	uint32_t dst_idx;	/* dst index in fwd table */
182 	uint32_t dst_buf;	/* where we copy to */
183 #endif
184 };
185 
186 struct nm_hash_ent {
187 	uint64_t	mac;	/* the top 2 bytes are the epoch */
188 	uint64_t	ports;
189 };
190 
191 /*
192  * Interfaces for a bridge are all in ports[].
193  * The array has fixed size, an empty entry does not terminate
194  * the search.
195  */
196 struct nm_bridge {
197 	struct ifnet *bdg_ports[NM_BDG_MAXPORTS];
198 	int n_ports;
199 	uint64_t act_ports;
200 	int freelist;	/* first buffer index */
201 	NM_SELINFO_T si;	/* poll/select wait queue */
202 	NM_LOCK_T bdg_lock;	/* protect the selinfo ? */
203 
204 	/* the forwarding table, MAC+ports */
205 	struct nm_hash_ent ht[NM_BDG_HASH];
206 
207 	int namelen;	/* 0 means free */
208 	char basename[IFNAMSIZ];
209 };
210 
211 struct nm_bridge nm_bridges[NM_BRIDGES];
212 
213 #define BDG_LOCK(b)	mtx_lock(&(b)->bdg_lock)
214 #define BDG_UNLOCK(b)	mtx_unlock(&(b)->bdg_lock)
215 
216 /*
217  * NA(ifp)->bdg_port	port index
218  */
219 
220 #ifndef linux
221 static inline void prefetch (const void *x)
222 {
223         __asm volatile("prefetcht0 %0" :: "m" (*(const unsigned long *)x));
224 }
225 #endif /* !linux */
226 
227 // XXX only for multiples of 64 bytes, non overlapped.
228 static inline void
229 pkt_copy(void *_src, void *_dst, int l)
230 {
231         uint64_t *src = _src;
232         uint64_t *dst = _dst;
233         if (unlikely(l >= 1024)) {
234                 bcopy(src, dst, l);
235                 return;
236         }
237         for (; likely(l > 0); l-=64) {
238                 *dst++ = *src++;
239                 *dst++ = *src++;
240                 *dst++ = *src++;
241                 *dst++ = *src++;
242                 *dst++ = *src++;
243                 *dst++ = *src++;
244                 *dst++ = *src++;
245                 *dst++ = *src++;
246         }
247 }
248 
249 /*
250  * locate a bridge among the existing ones.
251  * a ':' in the name terminates the bridge name. Otherwise, just NM_NAME.
252  * We assume that this is called with a name of at least NM_NAME chars.
253  */
254 static struct nm_bridge *
255 nm_find_bridge(const char *name)
256 {
257 	int i, l, namelen, e;
258 	struct nm_bridge *b = NULL;
259 
260 	namelen = strlen(NM_NAME);	/* base length */
261 	l = strlen(name);		/* actual length */
262 	for (i = namelen + 1; i < l; i++) {
263 		if (name[i] == ':') {
264 			namelen = i;
265 			break;
266 		}
267 	}
268 	if (namelen >= IFNAMSIZ)
269 		namelen = IFNAMSIZ;
270 	ND("--- prefix is '%.*s' ---", namelen, name);
271 
272 	/* use the first entry for locking */
273 	BDG_LOCK(nm_bridges); // XXX do better
274 	for (e = -1, i = 1; i < NM_BRIDGES; i++) {
275 		b = nm_bridges + i;
276 		if (b->namelen == 0)
277 			e = i;	/* record empty slot */
278 		else if (strncmp(name, b->basename, namelen) == 0) {
279 			ND("found '%.*s' at %d", namelen, name, i);
280 			break;
281 		}
282 	}
283 	if (i == NM_BRIDGES) { /* all full */
284 		if (e == -1) { /* no empty slot */
285 			b = NULL;
286 		} else {
287 			b = nm_bridges + e;
288 			strncpy(b->basename, name, namelen);
289 			b->namelen = namelen;
290 		}
291 	}
292 	BDG_UNLOCK(nm_bridges);
293 	return b;
294 }
295 #endif /* NM_BRIDGE */
296 
297 /*------------- memory allocator -----------------*/
298 #ifdef NETMAP_MEM2
299 #include "netmap_mem2.c"
300 #else /* !NETMAP_MEM2 */
301 #include "netmap_mem1.c"
302 #endif /* !NETMAP_MEM2 */
303 /*------------ end of memory allocator ----------*/
304 
305 /* Structure associated to each thread which registered an interface. */
306 struct netmap_priv_d {
307 	struct netmap_if *np_nifp;	/* netmap interface descriptor. */
308 
309 	struct ifnet	*np_ifp;	/* device for which we hold a reference */
310 	int		np_ringid;	/* from the ioctl */
311 	u_int		np_qfirst, np_qlast;	/* range of rings to scan */
312 	uint16_t	np_txpoll;
313 };
314 
315 
316 /*
317  * File descriptor's private data destructor.
318  *
319  * Call nm_register(ifp,0) to stop netmap mode on the interface and
320  * revert to normal operation. We expect that np_ifp has not gone.
321  */
322 static void
323 netmap_dtor_locked(void *data)
324 {
325 	struct netmap_priv_d *priv = data;
326 	struct ifnet *ifp = priv->np_ifp;
327 	struct netmap_adapter *na = NA(ifp);
328 	struct netmap_if *nifp = priv->np_nifp;
329 
330 	na->refcount--;
331 	if (na->refcount <= 0) {	/* last instance */
332 		u_int i, j, lim;
333 
334 		D("deleting last netmap instance for %s", ifp->if_xname);
335 		/*
336 		 * there is a race here with *_netmap_task() and
337 		 * netmap_poll(), which don't run under NETMAP_REG_LOCK.
338 		 * na->refcount == 0 && na->ifp->if_capenable & IFCAP_NETMAP
339 		 * (aka NETMAP_DELETING(na)) are a unique marker that the
340 		 * device is dying.
341 		 * Before destroying stuff we sleep a bit, and then complete
342 		 * the job. NIOCREG should realize the condition and
343 		 * loop until they can continue; the other routines
344 		 * should check the condition at entry and quit if
345 		 * they cannot run.
346 		 */
347 		na->nm_lock(ifp, NETMAP_REG_UNLOCK, 0);
348 		tsleep(na, 0, "NIOCUNREG", 4);
349 		na->nm_lock(ifp, NETMAP_REG_LOCK, 0);
350 		na->nm_register(ifp, 0); /* off, clear IFCAP_NETMAP */
351 		/* Wake up any sleeping threads. netmap_poll will
352 		 * then return POLLERR
353 		 */
354 		for (i = 0; i < na->num_tx_rings + 1; i++)
355 			selwakeuppri(&na->tx_rings[i].si, PI_NET);
356 		for (i = 0; i < na->num_rx_rings + 1; i++)
357 			selwakeuppri(&na->rx_rings[i].si, PI_NET);
358 		selwakeuppri(&na->tx_si, PI_NET);
359 		selwakeuppri(&na->rx_si, PI_NET);
360 		/* release all buffers */
361 		NMA_LOCK();
362 		for (i = 0; i < na->num_tx_rings + 1; i++) {
363 			struct netmap_ring *ring = na->tx_rings[i].ring;
364 			lim = na->tx_rings[i].nkr_num_slots;
365 			for (j = 0; j < lim; j++)
366 				netmap_free_buf(nifp, ring->slot[j].buf_idx);
367 		}
368 		for (i = 0; i < na->num_rx_rings + 1; i++) {
369 			struct netmap_ring *ring = na->rx_rings[i].ring;
370 			lim = na->rx_rings[i].nkr_num_slots;
371 			for (j = 0; j < lim; j++)
372 				netmap_free_buf(nifp, ring->slot[j].buf_idx);
373 		}
374 		NMA_UNLOCK();
375 		netmap_free_rings(na);
376 		wakeup(na);
377 	}
378 	netmap_if_free(nifp);
379 }
380 
381 static void
382 nm_if_rele(struct ifnet *ifp)
383 {
384 #ifndef NM_BRIDGE
385 	if_rele(ifp);
386 #else /* NM_BRIDGE */
387 	int i, full;
388 	struct nm_bridge *b;
389 
390 	if (strncmp(ifp->if_xname, NM_NAME, sizeof(NM_NAME) - 1)) {
391 		if_rele(ifp);
392 		return;
393 	}
394 	if (!DROP_BDG_REF(ifp))
395 		return;
396 	b = ifp->if_bridge;
397 	BDG_LOCK(nm_bridges);
398 	BDG_LOCK(b);
399 	ND("want to disconnect %s from the bridge", ifp->if_xname);
400 	full = 0;
401 	for (i = 0; i < NM_BDG_MAXPORTS; i++) {
402 		if (b->bdg_ports[i] == ifp) {
403 			b->bdg_ports[i] = NULL;
404 			bzero(ifp, sizeof(*ifp));
405 			free(ifp, M_DEVBUF);
406 			break;
407 		}
408 		else if (b->bdg_ports[i] != NULL)
409 			full = 1;
410 	}
411 	BDG_UNLOCK(b);
412 	if (full == 0) {
413 		ND("freeing bridge %d", b - nm_bridges);
414 		b->namelen = 0;
415 	}
416 	BDG_UNLOCK(nm_bridges);
417 	if (i == NM_BDG_MAXPORTS)
418 		D("ouch, cannot find ifp to remove");
419 #endif /* NM_BRIDGE */
420 }
421 
422 static void
423 netmap_dtor(void *data)
424 {
425 	struct netmap_priv_d *priv = data;
426 	struct ifnet *ifp = priv->np_ifp;
427 	struct netmap_adapter *na = NA(ifp);
428 
429 	na->nm_lock(ifp, NETMAP_REG_LOCK, 0);
430 	netmap_dtor_locked(data);
431 	na->nm_lock(ifp, NETMAP_REG_UNLOCK, 0);
432 
433 	nm_if_rele(ifp);
434 	bzero(priv, sizeof(*priv));	/* XXX for safety */
435 	free(priv, M_DEVBUF);
436 }
437 
438 
439 /*
440  * mmap(2) support for the "netmap" device.
441  *
442  * Expose all the memory previously allocated by our custom memory
443  * allocator: this way the user has only to issue a single mmap(2), and
444  * can work on all the data structures flawlessly.
445  *
446  * Return 0 on success, -1 otherwise.
447  */
448 
449 #ifdef __FreeBSD__
450 static int
451 netmap_mmap(__unused struct cdev *dev,
452 #if __FreeBSD_version < 900000
453 		vm_offset_t offset, vm_paddr_t *paddr, int nprot
454 #else
455 		vm_ooffset_t offset, vm_paddr_t *paddr, int nprot,
456 		__unused vm_memattr_t *memattr
457 #endif
458 	)
459 {
460 	if (nprot & PROT_EXEC)
461 		return (-1);	// XXX -1 or EINVAL ?
462 
463 	ND("request for offset 0x%x", (uint32_t)offset);
464 	*paddr = netmap_ofstophys(offset);
465 
466 	return (0);
467 }
468 #endif /* __FreeBSD__ */
469 
470 
471 /*
472  * Handlers for synchronization of the queues from/to the host.
473  *
474  * netmap_sync_to_host() passes packets up. We are called from a
475  * system call in user process context, and the only contention
476  * can be among multiple user threads erroneously calling
477  * this routine concurrently. In principle we should not even
478  * need to lock.
479  */
480 static void
481 netmap_sync_to_host(struct netmap_adapter *na)
482 {
483 	struct netmap_kring *kring = &na->tx_rings[na->num_tx_rings];
484 	struct netmap_ring *ring = kring->ring;
485 	struct mbuf *head = NULL, *tail = NULL, *m;
486 	u_int k, n, lim = kring->nkr_num_slots - 1;
487 
488 	k = ring->cur;
489 	if (k > lim) {
490 		netmap_ring_reinit(kring);
491 		return;
492 	}
493 	// na->nm_lock(na->ifp, NETMAP_CORE_LOCK, 0);
494 
495 	/* Take packets from hwcur to cur and pass them up.
496 	 * In case of no buffers we give up. At the end of the loop,
497 	 * the queue is drained in all cases.
498 	 */
499 	for (n = kring->nr_hwcur; n != k;) {
500 		struct netmap_slot *slot = &ring->slot[n];
501 
502 		n = (n == lim) ? 0 : n + 1;
503 		if (slot->len < 14 || slot->len > NETMAP_BUF_SIZE) {
504 			D("bad pkt at %d len %d", n, slot->len);
505 			continue;
506 		}
507 		m = m_devget(NMB(slot), slot->len, 0, na->ifp, NULL);
508 
509 		if (m == NULL)
510 			break;
511 		if (tail)
512 			tail->m_nextpkt = m;
513 		else
514 			head = m;
515 		tail = m;
516 		m->m_nextpkt = NULL;
517 	}
518 	kring->nr_hwcur = k;
519 	kring->nr_hwavail = ring->avail = lim;
520 	// na->nm_lock(na->ifp, NETMAP_CORE_UNLOCK, 0);
521 
522 	/* send packets up, outside the lock */
523 	while ((m = head) != NULL) {
524 		head = head->m_nextpkt;
525 		m->m_nextpkt = NULL;
526 		if (netmap_verbose & NM_VERB_HOST)
527 			D("sending up pkt %p size %d", m, MBUF_LEN(m));
528 		NM_SEND_UP(na->ifp, m);
529 	}
530 }
531 
532 /*
533  * rxsync backend for packets coming from the host stack.
534  * They have been put in the queue by netmap_start() so we
535  * need to protect access to the kring using a lock.
536  *
537  * This routine also does the selrecord if called from the poll handler
538  * (we know because td != NULL).
539  */
540 static void
541 netmap_sync_from_host(struct netmap_adapter *na, struct thread *td)
542 {
543 	struct netmap_kring *kring = &na->rx_rings[na->num_rx_rings];
544 	struct netmap_ring *ring = kring->ring;
545 	u_int j, n, lim = kring->nkr_num_slots;
546 	u_int k = ring->cur, resvd = ring->reserved;
547 
548 	na->nm_lock(na->ifp, NETMAP_CORE_LOCK, 0);
549 	if (k >= lim) {
550 		netmap_ring_reinit(kring);
551 		return;
552 	}
553 	/* new packets are already set in nr_hwavail */
554 	/* skip past packets that userspace has released */
555 	j = kring->nr_hwcur;
556 	if (resvd > 0) {
557 		if (resvd + ring->avail >= lim + 1) {
558 			D("XXX invalid reserve/avail %d %d", resvd, ring->avail);
559 			ring->reserved = resvd = 0; // XXX panic...
560 		}
561 		k = (k >= resvd) ? k - resvd : k + lim - resvd;
562         }
563 	if (j != k) {
564 		n = k >= j ? k - j : k + lim - j;
565 		kring->nr_hwavail -= n;
566 		kring->nr_hwcur = k;
567 	}
568 	k = ring->avail = kring->nr_hwavail - resvd;
569 	if (k == 0 && td)
570 		selrecord(td, &kring->si);
571 	if (k && (netmap_verbose & NM_VERB_HOST))
572 		D("%d pkts from stack", k);
573 	na->nm_lock(na->ifp, NETMAP_CORE_UNLOCK, 0);
574 }
575 
576 
577 /*
578  * get a refcounted reference to an interface.
579  * Return ENXIO if the interface does not exist, EINVAL if netmap
580  * is not supported by the interface.
581  * If successful, hold a reference.
582  */
583 static int
584 get_ifp(const char *name, struct ifnet **ifp)
585 {
586 #ifdef NM_BRIDGE
587 	struct ifnet *iter = NULL;
588 
589 	do {
590 		struct nm_bridge *b;
591 		int i, l, cand = -1;
592 
593 		if (strncmp(name, NM_NAME, sizeof(NM_NAME) - 1))
594 			break;
595 		b = nm_find_bridge(name);
596 		if (b == NULL) {
597 			D("no bridges available for '%s'", name);
598 			return (ENXIO);
599 		}
600 		/* XXX locking */
601 		BDG_LOCK(b);
602 		/* lookup in the local list of ports */
603 		for (i = 0; i < NM_BDG_MAXPORTS; i++) {
604 			iter = b->bdg_ports[i];
605 			if (iter == NULL) {
606 				if (cand == -1)
607 					cand = i; /* potential insert point */
608 				continue;
609 			}
610 			if (!strcmp(iter->if_xname, name)) {
611 				ADD_BDG_REF(iter);
612 				ND("found existing interface");
613 				BDG_UNLOCK(b);
614 				break;
615 			}
616 		}
617 		if (i < NM_BDG_MAXPORTS) /* already unlocked */
618 			break;
619 		if (cand == -1) {
620 			D("bridge full, cannot create new port");
621 no_port:
622 			BDG_UNLOCK(b);
623 			*ifp = NULL;
624 			return EINVAL;
625 		}
626 		ND("create new bridge port %s", name);
627 		/* space for forwarding list after the ifnet */
628 		l = sizeof(*iter) +
629 			 sizeof(struct nm_bdg_fwd)*NM_BDG_BATCH ;
630 		iter = malloc(l, M_DEVBUF, M_NOWAIT | M_ZERO);
631 		if (!iter)
632 			goto no_port;
633 		strcpy(iter->if_xname, name);
634 		bdg_netmap_attach(iter);
635 		b->bdg_ports[cand] = iter;
636 		iter->if_bridge = b;
637 		ADD_BDG_REF(iter);
638 		BDG_UNLOCK(b);
639 		ND("attaching virtual bridge %p", b);
640 	} while (0);
641 	*ifp = iter;
642 	if (! *ifp)
643 #endif /* NM_BRIDGE */
644 	*ifp = ifunit_ref(name);
645 	if (*ifp == NULL)
646 		return (ENXIO);
647 	/* can do this if the capability exists and if_pspare[0]
648 	 * points to the netmap descriptor.
649 	 */
650 	if ((*ifp)->if_capabilities & IFCAP_NETMAP && NA(*ifp))
651 		return 0;	/* valid pointer, we hold the refcount */
652 	nm_if_rele(*ifp);
653 	return EINVAL;	// not NETMAP capable
654 }
655 
656 
657 /*
658  * Error routine called when txsync/rxsync detects an error.
659  * Can't do much more than resetting cur = hwcur, avail = hwavail.
660  * Return 1 on reinit.
661  *
662  * This routine is only called by the upper half of the kernel.
663  * It only reads hwcur (which is changed only by the upper half, too)
664  * and hwavail (which may be changed by the lower half, but only on
665  * a tx ring and only to increase it, so any error will be recovered
666  * on the next call). For the above, we don't strictly need to call
667  * it under lock.
668  */
669 int
670 netmap_ring_reinit(struct netmap_kring *kring)
671 {
672 	struct netmap_ring *ring = kring->ring;
673 	u_int i, lim = kring->nkr_num_slots - 1;
674 	int errors = 0;
675 
676 	D("called for %s", kring->na->ifp->if_xname);
677 	if (ring->cur > lim)
678 		errors++;
679 	for (i = 0; i <= lim; i++) {
680 		u_int idx = ring->slot[i].buf_idx;
681 		u_int len = ring->slot[i].len;
682 		if (idx < 2 || idx >= netmap_total_buffers) {
683 			if (!errors++)
684 				D("bad buffer at slot %d idx %d len %d ", i, idx, len);
685 			ring->slot[i].buf_idx = 0;
686 			ring->slot[i].len = 0;
687 		} else if (len > NETMAP_BUF_SIZE) {
688 			ring->slot[i].len = 0;
689 			if (!errors++)
690 				D("bad len %d at slot %d idx %d",
691 					len, i, idx);
692 		}
693 	}
694 	if (errors) {
695 		int pos = kring - kring->na->tx_rings;
696 		int n = kring->na->num_tx_rings + 1;
697 
698 		D("total %d errors", errors);
699 		errors++;
700 		D("%s %s[%d] reinit, cur %d -> %d avail %d -> %d",
701 			kring->na->ifp->if_xname,
702 			pos < n ?  "TX" : "RX", pos < n ? pos : pos - n,
703 			ring->cur, kring->nr_hwcur,
704 			ring->avail, kring->nr_hwavail);
705 		ring->cur = kring->nr_hwcur;
706 		ring->avail = kring->nr_hwavail;
707 	}
708 	return (errors ? 1 : 0);
709 }
710 
711 
712 /*
713  * Set the ring ID. For devices with a single queue, a request
714  * for all rings is the same as a single ring.
715  */
716 static int
717 netmap_set_ringid(struct netmap_priv_d *priv, u_int ringid)
718 {
719 	struct ifnet *ifp = priv->np_ifp;
720 	struct netmap_adapter *na = NA(ifp);
721 	u_int i = ringid & NETMAP_RING_MASK;
722 	/* initially (np_qfirst == np_qlast) we don't want to lock */
723 	int need_lock = (priv->np_qfirst != priv->np_qlast);
724 	int lim = na->num_rx_rings;
725 
726 	if (na->num_tx_rings > lim)
727 		lim = na->num_tx_rings;
728 	if ( (ringid & NETMAP_HW_RING) && i >= lim) {
729 		D("invalid ring id %d", i);
730 		return (EINVAL);
731 	}
732 	if (need_lock)
733 		na->nm_lock(ifp, NETMAP_CORE_LOCK, 0);
734 	priv->np_ringid = ringid;
735 	if (ringid & NETMAP_SW_RING) {
736 		priv->np_qfirst = NETMAP_SW_RING;
737 		priv->np_qlast = 0;
738 	} else if (ringid & NETMAP_HW_RING) {
739 		priv->np_qfirst = i;
740 		priv->np_qlast = i + 1;
741 	} else {
742 		priv->np_qfirst = 0;
743 		priv->np_qlast = NETMAP_HW_RING ;
744 	}
745 	priv->np_txpoll = (ringid & NETMAP_NO_TX_POLL) ? 0 : 1;
746 	if (need_lock)
747 		na->nm_lock(ifp, NETMAP_CORE_UNLOCK, 0);
748 	if (ringid & NETMAP_SW_RING)
749 		D("ringid %s set to SW RING", ifp->if_xname);
750 	else if (ringid & NETMAP_HW_RING)
751 		D("ringid %s set to HW RING %d", ifp->if_xname,
752 			priv->np_qfirst);
753 	else
754 		D("ringid %s set to all %d HW RINGS", ifp->if_xname, lim);
755 	return 0;
756 }
757 
758 /*
759  * ioctl(2) support for the "netmap" device.
760  *
761  * Following a list of accepted commands:
762  * - NIOCGINFO
763  * - SIOCGIFADDR	just for convenience
764  * - NIOCREGIF
765  * - NIOCUNREGIF
766  * - NIOCTXSYNC
767  * - NIOCRXSYNC
768  *
769  * Return 0 on success, errno otherwise.
770  */
771 static int
772 netmap_ioctl(__unused struct cdev *dev, u_long cmd, caddr_t data,
773 	__unused int fflag, struct thread *td)
774 {
775 	struct netmap_priv_d *priv = NULL;
776 	struct ifnet *ifp;
777 	struct nmreq *nmr = (struct nmreq *) data;
778 	struct netmap_adapter *na;
779 	int error;
780 	u_int i, lim;
781 	struct netmap_if *nifp;
782 
783 #ifdef linux
784 #define devfs_get_cdevpriv(pp)				\
785 	({ *(struct netmap_priv_d **)pp = ((struct file *)td)->private_data; 	\
786 		(*pp ? 0 : ENOENT); })
787 
788 /* devfs_set_cdevpriv cannot fail on linux */
789 #define devfs_set_cdevpriv(p, fn)				\
790 	({ ((struct file *)td)->private_data = p; (p ? 0 : EINVAL); })
791 
792 
793 #define devfs_clear_cdevpriv()	do {				\
794 		netmap_dtor(priv); ((struct file *)td)->private_data = 0;	\
795 	} while (0)
796 #endif /* linux */
797 
798 	CURVNET_SET(TD_TO_VNET(td));
799 
800 	error = devfs_get_cdevpriv((void **)&priv);
801 	if (error != ENOENT && error != 0) {
802 		CURVNET_RESTORE();
803 		return (error);
804 	}
805 
806 	error = 0;	/* Could be ENOENT */
807 	nmr->nr_name[sizeof(nmr->nr_name) - 1] = '\0';	/* truncate name */
808 	switch (cmd) {
809 	case NIOCGINFO:		/* return capabilities etc */
810 		/* memsize is always valid */
811 		nmr->nr_memsize = nm_mem->nm_totalsize;
812 		nmr->nr_offset = 0;
813 		nmr->nr_rx_rings = nmr->nr_tx_rings = 0;
814 		nmr->nr_rx_slots = nmr->nr_tx_slots = 0;
815 		if (nmr->nr_version != NETMAP_API) {
816 			D("API mismatch got %d have %d",
817 				nmr->nr_version, NETMAP_API);
818 			nmr->nr_version = NETMAP_API;
819 			error = EINVAL;
820 			break;
821 		}
822 		if (nmr->nr_name[0] == '\0')	/* just get memory info */
823 			break;
824 		error = get_ifp(nmr->nr_name, &ifp); /* get a refcount */
825 		if (error)
826 			break;
827 		na = NA(ifp); /* retrieve netmap_adapter */
828 		nmr->nr_rx_rings = na->num_rx_rings;
829 		nmr->nr_tx_rings = na->num_tx_rings;
830 		nmr->nr_rx_slots = na->num_rx_desc;
831 		nmr->nr_tx_slots = na->num_tx_desc;
832 		nm_if_rele(ifp);	/* return the refcount */
833 		break;
834 
835 	case NIOCREGIF:
836 		if (nmr->nr_version != NETMAP_API) {
837 			nmr->nr_version = NETMAP_API;
838 			error = EINVAL;
839 			break;
840 		}
841 		if (priv != NULL) {	/* thread already registered */
842 			error = netmap_set_ringid(priv, nmr->nr_ringid);
843 			break;
844 		}
845 		/* find the interface and a reference */
846 		error = get_ifp(nmr->nr_name, &ifp); /* keep reference */
847 		if (error)
848 			break;
849 		na = NA(ifp); /* retrieve netmap adapter */
850 		/*
851 		 * Allocate the private per-thread structure.
852 		 * XXX perhaps we can use a blocking malloc ?
853 		 */
854 		priv = malloc(sizeof(struct netmap_priv_d), M_DEVBUF,
855 			      M_NOWAIT | M_ZERO);
856 		if (priv == NULL) {
857 			error = ENOMEM;
858 			nm_if_rele(ifp);   /* return the refcount */
859 			break;
860 		}
861 
862 		for (i = 10; i > 0; i--) {
863 			na->nm_lock(ifp, NETMAP_REG_LOCK, 0);
864 			if (!NETMAP_DELETING(na))
865 				break;
866 			na->nm_lock(ifp, NETMAP_REG_UNLOCK, 0);
867 			tsleep(na, 0, "NIOCREGIF", hz/10);
868 		}
869 		if (i == 0) {
870 			D("too many NIOCREGIF attempts, give up");
871 			error = EINVAL;
872 			free(priv, M_DEVBUF);
873 			nm_if_rele(ifp);	/* return the refcount */
874 			break;
875 		}
876 
877 		priv->np_ifp = ifp;	/* store the reference */
878 		error = netmap_set_ringid(priv, nmr->nr_ringid);
879 		if (error)
880 			goto error;
881 		priv->np_nifp = nifp = netmap_if_new(nmr->nr_name, na);
882 		if (nifp == NULL) { /* allocation failed */
883 			error = ENOMEM;
884 		} else if (ifp->if_capenable & IFCAP_NETMAP) {
885 			/* was already set */
886 		} else {
887 			/* Otherwise set the card in netmap mode
888 			 * and make it use the shared buffers.
889 			 */
890 			for (i = 0 ; i < na->num_tx_rings + 1; i++)
891 				mtx_init(&na->tx_rings[i].q_lock, "nm_txq_lock", MTX_NETWORK_LOCK, MTX_DEF);
892 			for (i = 0 ; i < na->num_rx_rings + 1; i++) {
893 				mtx_init(&na->rx_rings[i].q_lock, "nm_rxq_lock", MTX_NETWORK_LOCK, MTX_DEF);
894 			}
895 			error = na->nm_register(ifp, 1); /* mode on */
896 			if (error)
897 				netmap_dtor_locked(priv);
898 		}
899 
900 		if (error) {	/* reg. failed, release priv and ref */
901 error:
902 			na->nm_lock(ifp, NETMAP_REG_UNLOCK, 0);
903 			nm_if_rele(ifp);	/* return the refcount */
904 			bzero(priv, sizeof(*priv));
905 			free(priv, M_DEVBUF);
906 			break;
907 		}
908 
909 		na->nm_lock(ifp, NETMAP_REG_UNLOCK, 0);
910 		error = devfs_set_cdevpriv(priv, netmap_dtor);
911 
912 		if (error != 0) {
913 			/* could not assign the private storage for the
914 			 * thread, call the destructor explicitly.
915 			 */
916 			netmap_dtor(priv);
917 			break;
918 		}
919 
920 		/* return the offset of the netmap_if object */
921 		nmr->nr_rx_rings = na->num_rx_rings;
922 		nmr->nr_tx_rings = na->num_tx_rings;
923 		nmr->nr_rx_slots = na->num_rx_desc;
924 		nmr->nr_tx_slots = na->num_tx_desc;
925 		nmr->nr_memsize = nm_mem->nm_totalsize;
926 		nmr->nr_offset = netmap_if_offset(nifp);
927 		break;
928 
929 	case NIOCUNREGIF:
930 		if (priv == NULL) {
931 			error = ENXIO;
932 			break;
933 		}
934 
935 		/* the interface is unregistered inside the
936 		   destructor of the private data. */
937 		devfs_clear_cdevpriv();
938 		break;
939 
940 	case NIOCTXSYNC:
941         case NIOCRXSYNC:
942 		if (priv == NULL) {
943 			error = ENXIO;
944 			break;
945 		}
946 		ifp = priv->np_ifp;	/* we have a reference */
947 		na = NA(ifp); /* retrieve netmap adapter */
948 		if (priv->np_qfirst == NETMAP_SW_RING) { /* host rings */
949 			if (cmd == NIOCTXSYNC)
950 				netmap_sync_to_host(na);
951 			else
952 				netmap_sync_from_host(na, NULL);
953 			break;
954 		}
955 		/* find the last ring to scan */
956 		lim = priv->np_qlast;
957 		if (lim == NETMAP_HW_RING)
958 			lim = (cmd == NIOCTXSYNC) ?
959 			    na->num_tx_rings : na->num_rx_rings;
960 
961 		for (i = priv->np_qfirst; i < lim; i++) {
962 			if (cmd == NIOCTXSYNC) {
963 				struct netmap_kring *kring = &na->tx_rings[i];
964 				if (netmap_verbose & NM_VERB_TXSYNC)
965 					D("pre txsync ring %d cur %d hwcur %d",
966 					    i, kring->ring->cur,
967 					    kring->nr_hwcur);
968 				na->nm_txsync(ifp, i, 1 /* do lock */);
969 				if (netmap_verbose & NM_VERB_TXSYNC)
970 					D("post txsync ring %d cur %d hwcur %d",
971 					    i, kring->ring->cur,
972 					    kring->nr_hwcur);
973 			} else {
974 				na->nm_rxsync(ifp, i, 1 /* do lock */);
975 				microtime(&na->rx_rings[i].ring->ts);
976 			}
977 		}
978 
979 		break;
980 
981 #ifdef __FreeBSD__
982 	case BIOCIMMEDIATE:
983 	case BIOCGHDRCMPLT:
984 	case BIOCSHDRCMPLT:
985 	case BIOCSSEESENT:
986 		D("ignore BIOCIMMEDIATE/BIOCSHDRCMPLT/BIOCSHDRCMPLT/BIOCSSEESENT");
987 		break;
988 
989 	default:	/* allow device-specific ioctls */
990 	    {
991 		struct socket so;
992 		bzero(&so, sizeof(so));
993 		error = get_ifp(nmr->nr_name, &ifp); /* keep reference */
994 		if (error)
995 			break;
996 		so.so_vnet = ifp->if_vnet;
997 		// so->so_proto not null.
998 		error = ifioctl(&so, cmd, data, td);
999 		nm_if_rele(ifp);
1000 		break;
1001 	    }
1002 
1003 #else /* linux */
1004 	default:
1005 		error = EOPNOTSUPP;
1006 #endif /* linux */
1007 	}
1008 
1009 	CURVNET_RESTORE();
1010 	return (error);
1011 }
1012 
1013 
1014 /*
1015  * select(2) and poll(2) handlers for the "netmap" device.
1016  *
1017  * Can be called for one or more queues.
1018  * Return true the event mask corresponding to ready events.
1019  * If there are no ready events, do a selrecord on either individual
1020  * selfd or on the global one.
1021  * Device-dependent parts (locking and sync of tx/rx rings)
1022  * are done through callbacks.
1023  *
1024  * On linux, pwait is the poll table.
1025  * If pwait == NULL someone else already woke up before. We can report
1026  * events but they are filtered upstream.
1027  * If pwait != NULL, then pwait->key contains the list of events.
1028  */
1029 static int
1030 netmap_poll(__unused struct cdev *dev, int events, struct thread *td)
1031 {
1032 	struct netmap_priv_d *priv = NULL;
1033 	struct netmap_adapter *na;
1034 	struct ifnet *ifp;
1035 	struct netmap_kring *kring;
1036 	u_int core_lock, i, check_all, want_tx, want_rx, revents = 0;
1037 	u_int lim_tx, lim_rx;
1038 	enum {NO_CL, NEED_CL, LOCKED_CL }; /* see below */
1039 
1040 	if (devfs_get_cdevpriv((void **)&priv) != 0 || priv == NULL)
1041 		return POLLERR;
1042 
1043 	ifp = priv->np_ifp;
1044 	// XXX check for deleting() ?
1045 	if ( (ifp->if_capenable & IFCAP_NETMAP) == 0)
1046 		return POLLERR;
1047 
1048 	if (netmap_verbose & 0x8000)
1049 		D("device %s events 0x%x", ifp->if_xname, events);
1050 	want_tx = events & (POLLOUT | POLLWRNORM);
1051 	want_rx = events & (POLLIN | POLLRDNORM);
1052 
1053 	na = NA(ifp); /* retrieve netmap adapter */
1054 
1055 	lim_tx = na->num_tx_rings;
1056 	lim_rx = na->num_rx_rings;
1057 	/* how many queues we are scanning */
1058 	if (priv->np_qfirst == NETMAP_SW_RING) {
1059 		if (priv->np_txpoll || want_tx) {
1060 			/* push any packets up, then we are always ready */
1061 			kring = &na->tx_rings[lim_tx];
1062 			netmap_sync_to_host(na);
1063 			revents |= want_tx;
1064 		}
1065 		if (want_rx) {
1066 			kring = &na->rx_rings[lim_rx];
1067 			if (kring->ring->avail == 0)
1068 				netmap_sync_from_host(na, td);
1069 			if (kring->ring->avail > 0) {
1070 				revents |= want_rx;
1071 			}
1072 		}
1073 		return (revents);
1074 	}
1075 
1076 	/*
1077 	 * check_all is set if the card has more than one queue and
1078 	 * the client is polling all of them. If true, we sleep on
1079 	 * the "global" selfd, otherwise we sleep on individual selfd
1080 	 * (we can only sleep on one of them per direction).
1081 	 * The interrupt routine in the driver should always wake on
1082 	 * the individual selfd, and also on the global one if the card
1083 	 * has more than one ring.
1084 	 *
1085 	 * If the card has only one lock, we just use that.
1086 	 * If the card has separate ring locks, we just use those
1087 	 * unless we are doing check_all, in which case the whole
1088 	 * loop is wrapped by the global lock.
1089 	 * We acquire locks only when necessary: if poll is called
1090 	 * when buffers are available, we can just return without locks.
1091 	 *
1092 	 * rxsync() is only called if we run out of buffers on a POLLIN.
1093 	 * txsync() is called if we run out of buffers on POLLOUT, or
1094 	 * there are pending packets to send. The latter can be disabled
1095 	 * passing NETMAP_NO_TX_POLL in the NIOCREG call.
1096 	 */
1097 	check_all = (priv->np_qlast == NETMAP_HW_RING) && (lim_tx > 1 || lim_rx > 1);
1098 
1099 	/*
1100 	 * core_lock indicates what to do with the core lock.
1101 	 * The core lock is used when either the card has no individual
1102 	 * locks, or it has individual locks but we are cheking all
1103 	 * rings so we need the core lock to avoid missing wakeup events.
1104 	 *
1105 	 * It has three possible states:
1106 	 * NO_CL	we don't need to use the core lock, e.g.
1107 	 *		because we are protected by individual locks.
1108 	 * NEED_CL	we need the core lock. In this case, when we
1109 	 *		call the lock routine, move to LOCKED_CL
1110 	 *		to remember to release the lock once done.
1111 	 * LOCKED_CL	core lock is set, so we need to release it.
1112 	 */
1113 	core_lock = (check_all || !na->separate_locks) ? NEED_CL : NO_CL;
1114 #ifdef NM_BRIDGE
1115 	/* the bridge uses separate locks */
1116 	if (na->nm_register == bdg_netmap_reg) {
1117 		ND("not using core lock for %s", ifp->if_xname);
1118 		core_lock = NO_CL;
1119 	}
1120 #endif /* NM_BRIDGE */
1121 	if (priv->np_qlast != NETMAP_HW_RING) {
1122 		lim_tx = lim_rx = priv->np_qlast;
1123 	}
1124 
1125 	/*
1126 	 * We start with a lock free round which is good if we have
1127 	 * data available. If this fails, then lock and call the sync
1128 	 * routines.
1129 	 */
1130 	for (i = priv->np_qfirst; want_rx && i < lim_rx; i++) {
1131 		kring = &na->rx_rings[i];
1132 		if (kring->ring->avail > 0) {
1133 			revents |= want_rx;
1134 			want_rx = 0;	/* also breaks the loop */
1135 		}
1136 	}
1137 	for (i = priv->np_qfirst; want_tx && i < lim_tx; i++) {
1138 		kring = &na->tx_rings[i];
1139 		if (kring->ring->avail > 0) {
1140 			revents |= want_tx;
1141 			want_tx = 0;	/* also breaks the loop */
1142 		}
1143 	}
1144 
1145 	/*
1146 	 * If we to push packets out (priv->np_txpoll) or want_tx is
1147 	 * still set, we do need to run the txsync calls (on all rings,
1148 	 * to avoid that the tx rings stall).
1149 	 */
1150 	if (priv->np_txpoll || want_tx) {
1151 		for (i = priv->np_qfirst; i < lim_tx; i++) {
1152 			kring = &na->tx_rings[i];
1153 			/*
1154 			 * Skip the current ring if want_tx == 0
1155 			 * (we have already done a successful sync on
1156 			 * a previous ring) AND kring->cur == kring->hwcur
1157 			 * (there are no pending transmissions for this ring).
1158 			 */
1159 			if (!want_tx && kring->ring->cur == kring->nr_hwcur)
1160 				continue;
1161 			if (core_lock == NEED_CL) {
1162 				na->nm_lock(ifp, NETMAP_CORE_LOCK, 0);
1163 				core_lock = LOCKED_CL;
1164 			}
1165 			if (na->separate_locks)
1166 				na->nm_lock(ifp, NETMAP_TX_LOCK, i);
1167 			if (netmap_verbose & NM_VERB_TXSYNC)
1168 				D("send %d on %s %d",
1169 					kring->ring->cur,
1170 					ifp->if_xname, i);
1171 			if (na->nm_txsync(ifp, i, 0 /* no lock */))
1172 				revents |= POLLERR;
1173 
1174 			/* Check avail/call selrecord only if called with POLLOUT */
1175 			if (want_tx) {
1176 				if (kring->ring->avail > 0) {
1177 					/* stop at the first ring. We don't risk
1178 					 * starvation.
1179 					 */
1180 					revents |= want_tx;
1181 					want_tx = 0;
1182 				} else if (!check_all)
1183 					selrecord(td, &kring->si);
1184 			}
1185 			if (na->separate_locks)
1186 				na->nm_lock(ifp, NETMAP_TX_UNLOCK, i);
1187 		}
1188 	}
1189 
1190 	/*
1191 	 * now if want_rx is still set we need to lock and rxsync.
1192 	 * Do it on all rings because otherwise we starve.
1193 	 */
1194 	if (want_rx) {
1195 		for (i = priv->np_qfirst; i < lim_rx; i++) {
1196 			kring = &na->rx_rings[i];
1197 			if (core_lock == NEED_CL) {
1198 				na->nm_lock(ifp, NETMAP_CORE_LOCK, 0);
1199 				core_lock = LOCKED_CL;
1200 			}
1201 			if (na->separate_locks)
1202 				na->nm_lock(ifp, NETMAP_RX_LOCK, i);
1203 
1204 			if (na->nm_rxsync(ifp, i, 0 /* no lock */))
1205 				revents |= POLLERR;
1206 			if (netmap_no_timestamp == 0 ||
1207 					kring->ring->flags & NR_TIMESTAMP) {
1208 				microtime(&kring->ring->ts);
1209 			}
1210 
1211 			if (kring->ring->avail > 0)
1212 				revents |= want_rx;
1213 			else if (!check_all)
1214 				selrecord(td, &kring->si);
1215 			if (na->separate_locks)
1216 				na->nm_lock(ifp, NETMAP_RX_UNLOCK, i);
1217 		}
1218 	}
1219 	if (check_all && revents == 0) { /* signal on the global queue */
1220 		if (want_tx)
1221 			selrecord(td, &na->tx_si);
1222 		if (want_rx)
1223 			selrecord(td, &na->rx_si);
1224 	}
1225 	if (core_lock == LOCKED_CL)
1226 		na->nm_lock(ifp, NETMAP_CORE_UNLOCK, 0);
1227 
1228 	return (revents);
1229 }
1230 
1231 /*------- driver support routines ------*/
1232 
1233 /*
1234  * default lock wrapper.
1235  */
1236 static void
1237 netmap_lock_wrapper(struct ifnet *dev, int what, u_int queueid)
1238 {
1239 	struct netmap_adapter *na = NA(dev);
1240 
1241 	switch (what) {
1242 #ifdef linux	/* some system do not need lock on register */
1243 	case NETMAP_REG_LOCK:
1244 	case NETMAP_REG_UNLOCK:
1245 		break;
1246 #endif /* linux */
1247 
1248 	case NETMAP_CORE_LOCK:
1249 		mtx_lock(&na->core_lock);
1250 		break;
1251 
1252 	case NETMAP_CORE_UNLOCK:
1253 		mtx_unlock(&na->core_lock);
1254 		break;
1255 
1256 	case NETMAP_TX_LOCK:
1257 		mtx_lock(&na->tx_rings[queueid].q_lock);
1258 		break;
1259 
1260 	case NETMAP_TX_UNLOCK:
1261 		mtx_unlock(&na->tx_rings[queueid].q_lock);
1262 		break;
1263 
1264 	case NETMAP_RX_LOCK:
1265 		mtx_lock(&na->rx_rings[queueid].q_lock);
1266 		break;
1267 
1268 	case NETMAP_RX_UNLOCK:
1269 		mtx_unlock(&na->rx_rings[queueid].q_lock);
1270 		break;
1271 	}
1272 }
1273 
1274 
1275 /*
1276  * Initialize a ``netmap_adapter`` object created by driver on attach.
1277  * We allocate a block of memory with room for a struct netmap_adapter
1278  * plus two sets of N+2 struct netmap_kring (where N is the number
1279  * of hardware rings):
1280  * krings	0..N-1	are for the hardware queues.
1281  * kring	N	is for the host stack queue
1282  * kring	N+1	is only used for the selinfo for all queues.
1283  * Return 0 on success, ENOMEM otherwise.
1284  *
1285  * na->num_tx_rings can be set for cards with different tx/rx setups
1286  */
1287 int
1288 netmap_attach(struct netmap_adapter *na, int num_queues)
1289 {
1290 	int n, size;
1291 	void *buf;
1292 	struct ifnet *ifp = na->ifp;
1293 
1294 	if (ifp == NULL) {
1295 		D("ifp not set, giving up");
1296 		return EINVAL;
1297 	}
1298 	/* clear other fields ? */
1299 	na->refcount = 0;
1300 	if (na->num_tx_rings == 0)
1301 		na->num_tx_rings = num_queues;
1302 	na->num_rx_rings = num_queues;
1303 	/* on each direction we have N+1 resources
1304 	 * 0..n-1	are the hardware rings
1305 	 * n		is the ring attached to the stack.
1306 	 */
1307 	n = na->num_rx_rings + na->num_tx_rings + 2;
1308 	size = sizeof(*na) + n * sizeof(struct netmap_kring);
1309 
1310 	buf = malloc(size, M_DEVBUF, M_NOWAIT | M_ZERO);
1311 	if (buf) {
1312 		WNA(ifp) = buf;
1313 		na->tx_rings = (void *)((char *)buf + sizeof(*na));
1314 		na->rx_rings = na->tx_rings + na->num_tx_rings + 1;
1315 		bcopy(na, buf, sizeof(*na));
1316 		ifp->if_capabilities |= IFCAP_NETMAP;
1317 
1318 		na = buf;
1319 		if (na->nm_lock == NULL) {
1320 			ND("using default locks for %s", ifp->if_xname);
1321 			na->nm_lock = netmap_lock_wrapper;
1322 			/* core lock initialized here.
1323 			 * others initialized after netmap_if_new
1324 			 */
1325 			mtx_init(&na->core_lock, "netmap core lock", MTX_NETWORK_LOCK, MTX_DEF);
1326 		}
1327 	}
1328 #ifdef linux
1329 	if (ifp->netdev_ops) {
1330 		D("netdev_ops %p", ifp->netdev_ops);
1331 		/* prepare a clone of the netdev ops */
1332 		na->nm_ndo = *ifp->netdev_ops;
1333 	}
1334 	na->nm_ndo.ndo_start_xmit = netmap_start_linux;
1335 #endif
1336 	D("%s for %s", buf ? "ok" : "failed", ifp->if_xname);
1337 
1338 	return (buf ? 0 : ENOMEM);
1339 }
1340 
1341 
1342 /*
1343  * Free the allocated memory linked to the given ``netmap_adapter``
1344  * object.
1345  */
1346 void
1347 netmap_detach(struct ifnet *ifp)
1348 {
1349 	u_int i;
1350 	struct netmap_adapter *na = NA(ifp);
1351 
1352 	if (!na)
1353 		return;
1354 
1355 	for (i = 0; i < na->num_tx_rings + 1; i++) {
1356 		knlist_destroy(&na->tx_rings[i].si.si_note);
1357 		mtx_destroy(&na->tx_rings[i].q_lock);
1358 	}
1359 	for (i = 0; i < na->num_rx_rings + 1; i++) {
1360 		knlist_destroy(&na->rx_rings[i].si.si_note);
1361 		mtx_destroy(&na->rx_rings[i].q_lock);
1362 	}
1363 	knlist_destroy(&na->tx_si.si_note);
1364 	knlist_destroy(&na->rx_si.si_note);
1365 	bzero(na, sizeof(*na));
1366 	WNA(ifp) = NULL;
1367 	free(na, M_DEVBUF);
1368 }
1369 
1370 
1371 /*
1372  * Intercept packets from the network stack and pass them
1373  * to netmap as incoming packets on the 'software' ring.
1374  * We are not locked when called.
1375  */
1376 int
1377 netmap_start(struct ifnet *ifp, struct mbuf *m)
1378 {
1379 	struct netmap_adapter *na = NA(ifp);
1380 	struct netmap_kring *kring = &na->rx_rings[na->num_rx_rings];
1381 	u_int i, len = MBUF_LEN(m);
1382 	int error = EBUSY, lim = kring->nkr_num_slots - 1;
1383 	struct netmap_slot *slot;
1384 
1385 	if (netmap_verbose & NM_VERB_HOST)
1386 		D("%s packet %d len %d from the stack", ifp->if_xname,
1387 			kring->nr_hwcur + kring->nr_hwavail, len);
1388 	na->nm_lock(ifp, NETMAP_CORE_LOCK, 0);
1389 	if (kring->nr_hwavail >= lim) {
1390 		if (netmap_verbose)
1391 			D("stack ring %s full\n", ifp->if_xname);
1392 		goto done;	/* no space */
1393 	}
1394 	if (len > NETMAP_BUF_SIZE) {
1395 		D("drop packet size %d > %d", len, NETMAP_BUF_SIZE);
1396 		goto done;	/* too long for us */
1397 	}
1398 
1399 	/* compute the insert position */
1400 	i = kring->nr_hwcur + kring->nr_hwavail;
1401 	if (i > lim)
1402 		i -= lim + 1;
1403 	slot = &kring->ring->slot[i];
1404 	m_copydata(m, 0, len, NMB(slot));
1405 	slot->len = len;
1406 	kring->nr_hwavail++;
1407 	if (netmap_verbose  & NM_VERB_HOST)
1408 		D("wake up host ring %s %d", na->ifp->if_xname, na->num_rx_rings);
1409 	selwakeuppri(&kring->si, PI_NET);
1410 	error = 0;
1411 done:
1412 	na->nm_lock(ifp, NETMAP_CORE_UNLOCK, 0);
1413 
1414 	/* release the mbuf in either cases of success or failure. As an
1415 	 * alternative, put the mbuf in a free list and free the list
1416 	 * only when really necessary.
1417 	 */
1418 	m_freem(m);
1419 
1420 	return (error);
1421 }
1422 
1423 
1424 /*
1425  * netmap_reset() is called by the driver routines when reinitializing
1426  * a ring. The driver is in charge of locking to protect the kring.
1427  * If netmap mode is not set just return NULL.
1428  */
1429 struct netmap_slot *
1430 netmap_reset(struct netmap_adapter *na, enum txrx tx, int n,
1431 	u_int new_cur)
1432 {
1433 	struct netmap_kring *kring;
1434 	int new_hwofs, lim;
1435 
1436 	if (na == NULL)
1437 		return NULL;	/* no netmap support here */
1438 	if (!(na->ifp->if_capenable & IFCAP_NETMAP))
1439 		return NULL;	/* nothing to reinitialize */
1440 
1441 	if (tx == NR_TX) {
1442 		kring = na->tx_rings + n;
1443 		new_hwofs = kring->nr_hwcur - new_cur;
1444 	} else {
1445 		kring = na->rx_rings + n;
1446 		new_hwofs = kring->nr_hwcur + kring->nr_hwavail - new_cur;
1447 	}
1448 	lim = kring->nkr_num_slots - 1;
1449 	if (new_hwofs > lim)
1450 		new_hwofs -= lim + 1;
1451 
1452 	/* Alwayws set the new offset value and realign the ring. */
1453 	kring->nkr_hwofs = new_hwofs;
1454 	if (tx == NR_TX)
1455 		kring->nr_hwavail = kring->nkr_num_slots - 1;
1456 	D("new hwofs %d on %s %s[%d]",
1457 			kring->nkr_hwofs, na->ifp->if_xname,
1458 			tx == NR_TX ? "TX" : "RX", n);
1459 
1460 #if 0 // def linux
1461 	/* XXX check that the mappings are correct */
1462 	/* need ring_nr, adapter->pdev, direction */
1463 	buffer_info->dma = dma_map_single(&pdev->dev, addr, adapter->rx_buffer_len, DMA_FROM_DEVICE);
1464 	if (dma_mapping_error(&adapter->pdev->dev, buffer_info->dma)) {
1465 		D("error mapping rx netmap buffer %d", i);
1466 		// XXX fix error handling
1467 	}
1468 
1469 #endif /* linux */
1470 	/*
1471 	 * Wakeup on the individual and global lock
1472 	 * We do the wakeup here, but the ring is not yet reconfigured.
1473 	 * However, we are under lock so there are no races.
1474 	 */
1475 	selwakeuppri(&kring->si, PI_NET);
1476 	selwakeuppri(tx == NR_TX ? &na->tx_si : &na->rx_si, PI_NET);
1477 	return kring->ring->slot;
1478 }
1479 
1480 
1481 /*
1482  * Default functions to handle rx/tx interrupts
1483  * we have 4 cases:
1484  * 1 ring, single lock:
1485  *	lock(core); wake(i=0); unlock(core)
1486  * N rings, single lock:
1487  *	lock(core); wake(i); wake(N+1) unlock(core)
1488  * 1 ring, separate locks: (i=0)
1489  *	lock(i); wake(i); unlock(i)
1490  * N rings, separate locks:
1491  *	lock(i); wake(i); unlock(i); lock(core) wake(N+1) unlock(core)
1492  * work_done is non-null on the RX path.
1493  */
1494 int
1495 netmap_rx_irq(struct ifnet *ifp, int q, int *work_done)
1496 {
1497 	struct netmap_adapter *na;
1498 	struct netmap_kring *r;
1499 	NM_SELINFO_T *main_wq;
1500 
1501 	if (!(ifp->if_capenable & IFCAP_NETMAP))
1502 		return 0;
1503 	na = NA(ifp);
1504 	if (work_done) { /* RX path */
1505 		r = na->rx_rings + q;
1506 		r->nr_kflags |= NKR_PENDINTR;
1507 		main_wq = (na->num_rx_rings > 1) ? &na->rx_si : NULL;
1508 	} else { /* tx path */
1509 		r = na->tx_rings + q;
1510 		main_wq = (na->num_tx_rings > 1) ? &na->tx_si : NULL;
1511 		work_done = &q; /* dummy */
1512 	}
1513 	if (na->separate_locks) {
1514 		mtx_lock(&r->q_lock);
1515 		selwakeuppri(&r->si, PI_NET);
1516 		mtx_unlock(&r->q_lock);
1517 		if (main_wq) {
1518 			mtx_lock(&na->core_lock);
1519 			selwakeuppri(main_wq, PI_NET);
1520 			mtx_unlock(&na->core_lock);
1521 		}
1522 	} else {
1523 		mtx_lock(&na->core_lock);
1524 		selwakeuppri(&r->si, PI_NET);
1525 		if (main_wq)
1526 			selwakeuppri(main_wq, PI_NET);
1527 		mtx_unlock(&na->core_lock);
1528 	}
1529 	*work_done = 1; /* do not fire napi again */
1530 	return 1;
1531 }
1532 
1533 
1534 static struct cdevsw netmap_cdevsw = {
1535 	.d_version = D_VERSION,
1536 	.d_name = "netmap",
1537 	.d_mmap = netmap_mmap,
1538 	.d_ioctl = netmap_ioctl,
1539 	.d_poll = netmap_poll,
1540 };
1541 
1542 #ifdef NM_BRIDGE
1543 /*
1544  *---- support for virtual bridge -----
1545  */
1546 
1547 /* ----- FreeBSD if_bridge hash function ------- */
1548 
1549 /*
1550  * The following hash function is adapted from "Hash Functions" by Bob Jenkins
1551  * ("Algorithm Alley", Dr. Dobbs Journal, September 1997).
1552  *
1553  * http://www.burtleburtle.net/bob/hash/spooky.html
1554  */
1555 #define mix(a, b, c)                                                    \
1556 do {                                                                    \
1557         a -= b; a -= c; a ^= (c >> 13);                                 \
1558         b -= c; b -= a; b ^= (a << 8);                                  \
1559         c -= a; c -= b; c ^= (b >> 13);                                 \
1560         a -= b; a -= c; a ^= (c >> 12);                                 \
1561         b -= c; b -= a; b ^= (a << 16);                                 \
1562         c -= a; c -= b; c ^= (b >> 5);                                  \
1563         a -= b; a -= c; a ^= (c >> 3);                                  \
1564         b -= c; b -= a; b ^= (a << 10);                                 \
1565         c -= a; c -= b; c ^= (b >> 15);                                 \
1566 } while (/*CONSTCOND*/0)
1567 
1568 static __inline uint32_t
1569 nm_bridge_rthash(const uint8_t *addr)
1570 {
1571         uint32_t a = 0x9e3779b9, b = 0x9e3779b9, c = 0; // hask key
1572 
1573         b += addr[5] << 8;
1574         b += addr[4];
1575         a += addr[3] << 24;
1576         a += addr[2] << 16;
1577         a += addr[1] << 8;
1578         a += addr[0];
1579 
1580         mix(a, b, c);
1581 #define BRIDGE_RTHASH_MASK	(NM_BDG_HASH-1)
1582         return (c & BRIDGE_RTHASH_MASK);
1583 }
1584 
1585 #undef mix
1586 
1587 
1588 static int
1589 bdg_netmap_reg(struct ifnet *ifp, int onoff)
1590 {
1591 	int i, err = 0;
1592 	struct nm_bridge *b = ifp->if_bridge;
1593 
1594 	BDG_LOCK(b);
1595 	if (onoff) {
1596 		/* the interface must be already in the list.
1597 		 * only need to mark the port as active
1598 		 */
1599 		ND("should attach %s to the bridge", ifp->if_xname);
1600 		for (i=0; i < NM_BDG_MAXPORTS; i++)
1601 			if (b->bdg_ports[i] == ifp)
1602 				break;
1603 		if (i == NM_BDG_MAXPORTS) {
1604 			D("no more ports available");
1605 			err = EINVAL;
1606 			goto done;
1607 		}
1608 		ND("setting %s in netmap mode", ifp->if_xname);
1609 		ifp->if_capenable |= IFCAP_NETMAP;
1610 		NA(ifp)->bdg_port = i;
1611 		b->act_ports |= (1<<i);
1612 		b->bdg_ports[i] = ifp;
1613 	} else {
1614 		/* should be in the list, too -- remove from the mask */
1615 		ND("removing %s from netmap mode", ifp->if_xname);
1616 		ifp->if_capenable &= ~IFCAP_NETMAP;
1617 		i = NA(ifp)->bdg_port;
1618 		b->act_ports &= ~(1<<i);
1619 	}
1620 done:
1621 	BDG_UNLOCK(b);
1622 	return err;
1623 }
1624 
1625 
1626 static int
1627 nm_bdg_flush(struct nm_bdg_fwd *ft, int n, struct ifnet *ifp)
1628 {
1629 	int i, ifn;
1630 	uint64_t all_dst, dst;
1631 	uint32_t sh, dh;
1632 	uint64_t mysrc = 1 << NA(ifp)->bdg_port;
1633 	uint64_t smac, dmac;
1634 	struct netmap_slot *slot;
1635 	struct nm_bridge *b = ifp->if_bridge;
1636 
1637 	ND("prepare to send %d packets, act_ports 0x%x", n, b->act_ports);
1638 	/* only consider valid destinations */
1639 	all_dst = (b->act_ports & ~mysrc);
1640 	/* first pass: hash and find destinations */
1641 	for (i = 0; likely(i < n); i++) {
1642 		uint8_t *buf = ft[i].buf;
1643 		dmac = le64toh(*(uint64_t *)(buf)) & 0xffffffffffff;
1644 		smac = le64toh(*(uint64_t *)(buf + 4));
1645 		smac >>= 16;
1646 		if (unlikely(netmap_verbose)) {
1647 		    uint8_t *s = buf+6, *d = buf;
1648 		    D("%d len %4d %02x:%02x:%02x:%02x:%02x:%02x -> %02x:%02x:%02x:%02x:%02x:%02x",
1649 			i,
1650 			ft[i].len,
1651 			s[0], s[1], s[2], s[3], s[4], s[5],
1652 			d[0], d[1], d[2], d[3], d[4], d[5]);
1653 		}
1654 		/*
1655 		 * The hash is somewhat expensive, there might be some
1656 		 * worthwhile optimizations here.
1657 		 */
1658 		if ((buf[6] & 1) == 0) { /* valid src */
1659 		    	uint8_t *s = buf+6;
1660 			sh = nm_bridge_rthash(buf+6); // XXX hash of source
1661 			/* update source port forwarding entry */
1662 			b->ht[sh].mac = smac;	/* XXX expire ? */
1663 			b->ht[sh].ports = mysrc;
1664 			if (netmap_verbose)
1665 			    D("src %02x:%02x:%02x:%02x:%02x:%02x on port %d",
1666 				s[0], s[1], s[2], s[3], s[4], s[5], NA(ifp)->bdg_port);
1667 		}
1668 		dst = 0;
1669 		if ( (buf[0] & 1) == 0) { /* unicast */
1670 		    	uint8_t *d = buf;
1671 			dh = nm_bridge_rthash(buf); // XXX hash of dst
1672 			if (b->ht[dh].mac == dmac) {	/* found dst */
1673 				dst = b->ht[dh].ports;
1674 				if (netmap_verbose)
1675 				    D("dst %02x:%02x:%02x:%02x:%02x:%02x to port %x",
1676 					d[0], d[1], d[2], d[3], d[4], d[5], (uint32_t)(dst >> 16));
1677 			}
1678 		}
1679 		if (dst == 0)
1680 			dst = all_dst;
1681 		dst &= all_dst; /* only consider valid ports */
1682 		if (unlikely(netmap_verbose))
1683 			D("pkt goes to ports 0x%x", (uint32_t)dst);
1684 		ft[i].dst = dst;
1685 	}
1686 
1687 	/* second pass, scan interfaces and forward */
1688 	all_dst = (b->act_ports & ~mysrc);
1689 	for (ifn = 0; all_dst; ifn++) {
1690 		struct ifnet *dst_ifp = b->bdg_ports[ifn];
1691 		struct netmap_adapter *na;
1692 		struct netmap_kring *kring;
1693 		struct netmap_ring *ring;
1694 		int j, lim, sent, locked;
1695 
1696 		if (!dst_ifp)
1697 			continue;
1698 		ND("scan port %d %s", ifn, dst_ifp->if_xname);
1699 		dst = 1 << ifn;
1700 		if ((dst & all_dst) == 0)	/* skip if not set */
1701 			continue;
1702 		all_dst &= ~dst;	/* clear current node */
1703 		na = NA(dst_ifp);
1704 
1705 		ring = NULL;
1706 		kring = NULL;
1707 		lim = sent = locked = 0;
1708 		/* inside, scan slots */
1709 		for (i = 0; likely(i < n); i++) {
1710 			if ((ft[i].dst & dst) == 0)
1711 				continue;	/* not here */
1712 			if (!locked) {
1713 				kring = &na->rx_rings[0];
1714 				ring = kring->ring;
1715 				lim = kring->nkr_num_slots - 1;
1716 				na->nm_lock(dst_ifp, NETMAP_RX_LOCK, 0);
1717 				locked = 1;
1718 			}
1719 			if (unlikely(kring->nr_hwavail >= lim)) {
1720 				if (netmap_verbose)
1721 					D("rx ring full on %s", ifp->if_xname);
1722 				break;
1723 			}
1724 			j = kring->nr_hwcur + kring->nr_hwavail;
1725 			if (j > lim)
1726 				j -= kring->nkr_num_slots;
1727 			slot = &ring->slot[j];
1728 			ND("send %d %d bytes at %s:%d", i, ft[i].len, dst_ifp->if_xname, j);
1729 			pkt_copy(ft[i].buf, NMB(slot), ft[i].len);
1730 			slot->len = ft[i].len;
1731 			kring->nr_hwavail++;
1732 			sent++;
1733 		}
1734 		if (locked) {
1735 			ND("sent %d on %s", sent, dst_ifp->if_xname);
1736 			if (sent)
1737 				selwakeuppri(&kring->si, PI_NET);
1738 			na->nm_lock(dst_ifp, NETMAP_RX_UNLOCK, 0);
1739 		}
1740 	}
1741 	return 0;
1742 }
1743 
1744 /*
1745  * main dispatch routine
1746  */
1747 static int
1748 bdg_netmap_txsync(struct ifnet *ifp, u_int ring_nr, int do_lock)
1749 {
1750 	struct netmap_adapter *na = NA(ifp);
1751 	struct netmap_kring *kring = &na->tx_rings[ring_nr];
1752 	struct netmap_ring *ring = kring->ring;
1753 	int i, j, k, lim = kring->nkr_num_slots - 1;
1754 	struct nm_bdg_fwd *ft = (struct nm_bdg_fwd *)(ifp + 1);
1755 	int ft_i;	/* position in the forwarding table */
1756 
1757 	k = ring->cur;
1758 	if (k > lim)
1759 		return netmap_ring_reinit(kring);
1760 	if (do_lock)
1761 		na->nm_lock(ifp, NETMAP_TX_LOCK, ring_nr);
1762 
1763 	if (netmap_bridge <= 0) { /* testing only */
1764 		j = k; // used all
1765 		goto done;
1766 	}
1767 	if (netmap_bridge > NM_BDG_BATCH)
1768 		netmap_bridge = NM_BDG_BATCH;
1769 
1770 	ft_i = 0;	/* start from 0 */
1771 	for (j = kring->nr_hwcur; likely(j != k); j = unlikely(j == lim) ? 0 : j+1) {
1772 		struct netmap_slot *slot = &ring->slot[j];
1773 		int len = ft[ft_i].len = slot->len;
1774 		char *buf = ft[ft_i].buf = NMB(slot);
1775 
1776 		prefetch(buf);
1777 		if (unlikely(len < 14))
1778 			continue;
1779 		if (unlikely(++ft_i == netmap_bridge))
1780 			ft_i = nm_bdg_flush(ft, ft_i, ifp);
1781 	}
1782 	if (ft_i)
1783 		ft_i = nm_bdg_flush(ft, ft_i, ifp);
1784 	/* count how many packets we sent */
1785 	i = k - j;
1786 	if (i < 0)
1787 		i += kring->nkr_num_slots;
1788 	kring->nr_hwavail = kring->nkr_num_slots - 1 - i;
1789 	if (j != k)
1790 		D("early break at %d/ %d, avail %d", j, k, kring->nr_hwavail);
1791 
1792 done:
1793 	kring->nr_hwcur = j;
1794 	ring->avail = kring->nr_hwavail;
1795 	if (do_lock)
1796 		na->nm_lock(ifp, NETMAP_TX_UNLOCK, ring_nr);
1797 
1798 	if (netmap_verbose)
1799 		D("%s ring %d lock %d", ifp->if_xname, ring_nr, do_lock);
1800 	return 0;
1801 }
1802 
1803 static int
1804 bdg_netmap_rxsync(struct ifnet *ifp, u_int ring_nr, int do_lock)
1805 {
1806 	struct netmap_adapter *na = NA(ifp);
1807 	struct netmap_kring *kring = &na->rx_rings[ring_nr];
1808 	struct netmap_ring *ring = kring->ring;
1809 	int j, n, lim = kring->nkr_num_slots - 1;
1810 	u_int k = ring->cur, resvd = ring->reserved;
1811 
1812 	ND("%s ring %d lock %d avail %d",
1813 		ifp->if_xname, ring_nr, do_lock, kring->nr_hwavail);
1814 
1815 	if (k > lim)
1816 		return netmap_ring_reinit(kring);
1817 	if (do_lock)
1818 		na->nm_lock(ifp, NETMAP_RX_LOCK, ring_nr);
1819 
1820 	/* skip past packets that userspace has released */
1821 	j = kring->nr_hwcur;    /* netmap ring index */
1822 	if (resvd > 0) {
1823 		if (resvd + ring->avail >= lim + 1) {
1824 			D("XXX invalid reserve/avail %d %d", resvd, ring->avail);
1825 			ring->reserved = resvd = 0; // XXX panic...
1826 		}
1827 		k = (k >= resvd) ? k - resvd : k + lim + 1 - resvd;
1828 	}
1829 
1830 	if (j != k) { /* userspace has released some packets. */
1831 		n = k - j;
1832 		if (n < 0)
1833 			n += kring->nkr_num_slots;
1834 		ND("userspace releases %d packets", n);
1835                 for (n = 0; likely(j != k); n++) {
1836                         struct netmap_slot *slot = &ring->slot[j];
1837                         void *addr = NMB(slot);
1838 
1839                         if (addr == netmap_buffer_base) { /* bad buf */
1840                                 if (do_lock)
1841                                         na->nm_lock(ifp, NETMAP_RX_UNLOCK, ring_nr);
1842                                 return netmap_ring_reinit(kring);
1843                         }
1844 			/* decrease refcount for buffer */
1845 
1846 			slot->flags &= ~NS_BUF_CHANGED;
1847                         j = unlikely(j == lim) ? 0 : j + 1;
1848                 }
1849                 kring->nr_hwavail -= n;
1850                 kring->nr_hwcur = k;
1851         }
1852         /* tell userspace that there are new packets */
1853         ring->avail = kring->nr_hwavail - resvd;
1854 
1855 	if (do_lock)
1856 		na->nm_lock(ifp, NETMAP_RX_UNLOCK, ring_nr);
1857 	return 0;
1858 }
1859 
1860 static void
1861 bdg_netmap_attach(struct ifnet *ifp)
1862 {
1863 	struct netmap_adapter na;
1864 
1865 	ND("attaching virtual bridge");
1866 	bzero(&na, sizeof(na));
1867 
1868 	na.ifp = ifp;
1869 	na.separate_locks = 1;
1870 	na.num_tx_desc = NM_BRIDGE_RINGSIZE;
1871 	na.num_rx_desc = NM_BRIDGE_RINGSIZE;
1872 	na.nm_txsync = bdg_netmap_txsync;
1873 	na.nm_rxsync = bdg_netmap_rxsync;
1874 	na.nm_register = bdg_netmap_reg;
1875 	netmap_attach(&na, 1);
1876 }
1877 
1878 #endif /* NM_BRIDGE */
1879 
1880 static struct cdev *netmap_dev; /* /dev/netmap character device. */
1881 
1882 
1883 /*
1884  * Module loader.
1885  *
1886  * Create the /dev/netmap device and initialize all global
1887  * variables.
1888  *
1889  * Return 0 on success, errno on failure.
1890  */
1891 static int
1892 netmap_init(void)
1893 {
1894 	int error;
1895 
1896 	error = netmap_memory_init();
1897 	if (error != 0) {
1898 		printf("netmap: unable to initialize the memory allocator.");
1899 		return (error);
1900 	}
1901 	printf("netmap: loaded module with %d Mbytes\n",
1902 		(int)(nm_mem->nm_totalsize >> 20));
1903 	netmap_dev = make_dev(&netmap_cdevsw, 0, UID_ROOT, GID_WHEEL, 0660,
1904 			      "netmap");
1905 
1906 #ifdef NM_BRIDGE
1907 	{
1908 	int i;
1909 	for (i = 0; i < NM_BRIDGES; i++)
1910 		mtx_init(&nm_bridges[i].bdg_lock, "bdg lock", "bdg_lock", MTX_DEF);
1911 	}
1912 #endif
1913 	return (error);
1914 }
1915 
1916 
1917 /*
1918  * Module unloader.
1919  *
1920  * Free all the memory, and destroy the ``/dev/netmap`` device.
1921  */
1922 static void
1923 netmap_fini(void)
1924 {
1925 	destroy_dev(netmap_dev);
1926 	netmap_memory_fini();
1927 	printf("netmap: unloaded module.\n");
1928 }
1929 
1930 
1931 #ifdef __FreeBSD__
1932 /*
1933  * Kernel entry point.
1934  *
1935  * Initialize/finalize the module and return.
1936  *
1937  * Return 0 on success, errno on failure.
1938  */
1939 static int
1940 netmap_loader(__unused struct module *module, int event, __unused void *arg)
1941 {
1942 	int error = 0;
1943 
1944 	switch (event) {
1945 	case MOD_LOAD:
1946 		error = netmap_init();
1947 		break;
1948 
1949 	case MOD_UNLOAD:
1950 		netmap_fini();
1951 		break;
1952 
1953 	default:
1954 		error = EOPNOTSUPP;
1955 		break;
1956 	}
1957 
1958 	return (error);
1959 }
1960 
1961 
1962 DEV_MODULE(netmap, netmap_loader, NULL);
1963 #endif /* __FreeBSD__ */
1964