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