xref: /freebsd/sys/dev/netmap/netmap.c (revision f5f7c05209ca2c3748fd8b27c5e80ffad49120eb)
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 linux_netmap_start(struct sk_buff *skb, struct net_device *dev);
60 #endif /* linux */
61 
62 #ifdef __APPLE__
63 #include "osx_glue.h"
64 #endif /* __APPLE__ */
65 
66 #ifdef __FreeBSD__
67 #include <sys/cdefs.h> /* prerequisite */
68 __FBSDID("$FreeBSD$");
69 
70 #include <sys/types.h>
71 #include <sys/module.h>
72 #include <sys/errno.h>
73 #include <sys/param.h>	/* defines used in kernel.h */
74 #include <sys/jail.h>
75 #include <sys/kernel.h>	/* types used in module initialization */
76 #include <sys/conf.h>	/* cdevsw struct */
77 #include <sys/uio.h>	/* uio struct */
78 #include <sys/sockio.h>
79 #include <sys/socketvar.h>	/* struct socket */
80 #include <sys/malloc.h>
81 #include <sys/mman.h>	/* PROT_EXEC */
82 #include <sys/poll.h>
83 #include <sys/proc.h>
84 #include <vm/vm.h>	/* vtophys */
85 #include <vm/pmap.h>	/* vtophys */
86 #include <sys/socket.h> /* sockaddrs */
87 #include <machine/bus.h>
88 #include <sys/selinfo.h>
89 #include <sys/sysctl.h>
90 #include <net/if.h>
91 #include <net/bpf.h>		/* BIOCIMMEDIATE */
92 #include <net/vnet.h>
93 #include <machine/bus.h>	/* bus_dmamap_* */
94 
95 MALLOC_DEFINE(M_NETMAP, "netmap", "Network memory map");
96 #endif /* __FreeBSD__ */
97 
98 #include <net/netmap.h>
99 #include <dev/netmap/netmap_kern.h>
100 
101 u_int netmap_total_buffers;
102 u_int netmap_buf_size;
103 char *netmap_buffer_base;	/* address of an invalid buffer */
104 
105 /* user-controlled variables */
106 int netmap_verbose;
107 
108 static int netmap_no_timestamp; /* don't timestamp on rxsync */
109 
110 SYSCTL_NODE(_dev, OID_AUTO, netmap, CTLFLAG_RW, 0, "Netmap args");
111 SYSCTL_INT(_dev_netmap, OID_AUTO, verbose,
112     CTLFLAG_RW, &netmap_verbose, 0, "Verbose mode");
113 SYSCTL_INT(_dev_netmap, OID_AUTO, no_timestamp,
114     CTLFLAG_RW, &netmap_no_timestamp, 0, "no_timestamp");
115 int netmap_mitigate = 1;
116 SYSCTL_INT(_dev_netmap, OID_AUTO, mitigate, CTLFLAG_RW, &netmap_mitigate, 0, "");
117 int netmap_no_pendintr = 1;
118 SYSCTL_INT(_dev_netmap, OID_AUTO, no_pendintr,
119     CTLFLAG_RW, &netmap_no_pendintr, 0, "Always look for new received packets.");
120 
121 int netmap_drop = 0;	/* debugging */
122 int netmap_flags = 0;	/* debug flags */
123 int netmap_fwd = 0;	/* force transparent mode */
124 int netmap_copy = 0;	/* debugging, copy content */
125 
126 SYSCTL_INT(_dev_netmap, OID_AUTO, drop, CTLFLAG_RW, &netmap_drop, 0 , "");
127 SYSCTL_INT(_dev_netmap, OID_AUTO, flags, CTLFLAG_RW, &netmap_flags, 0 , "");
128 SYSCTL_INT(_dev_netmap, OID_AUTO, fwd, CTLFLAG_RW, &netmap_fwd, 0 , "");
129 SYSCTL_INT(_dev_netmap, OID_AUTO, copy, CTLFLAG_RW, &netmap_copy, 0 , "");
130 
131 #ifdef NM_BRIDGE /* support for netmap bridge */
132 
133 /*
134  * system parameters.
135  *
136  * All switched ports have prefix NM_NAME.
137  * The switch has a max of NM_BDG_MAXPORTS ports (often stored in a bitmap,
138  * so a practical upper bound is 64).
139  * Each tx ring is read-write, whereas rx rings are readonly (XXX not done yet).
140  * The virtual interfaces use per-queue lock instead of core lock.
141  * In the tx loop, we aggregate traffic in batches to make all operations
142  * faster. The batch size is NM_BDG_BATCH
143  */
144 #define	NM_NAME			"vale"	/* prefix for the interface */
145 #define NM_BDG_MAXPORTS		16	/* up to 64 ? */
146 #define NM_BRIDGE_RINGSIZE	1024	/* in the device */
147 #define NM_BDG_HASH		1024	/* forwarding table entries */
148 #define NM_BDG_BATCH		1024	/* entries in the forwarding buffer */
149 #define	NM_BRIDGES		4	/* number of bridges */
150 int netmap_bridge = NM_BDG_BATCH; /* bridge batch size */
151 SYSCTL_INT(_dev_netmap, OID_AUTO, bridge, CTLFLAG_RW, &netmap_bridge, 0 , "");
152 
153 #ifdef linux
154 #define	ADD_BDG_REF(ifp)	(NA(ifp)->if_refcount++)
155 #define	DROP_BDG_REF(ifp)	(NA(ifp)->if_refcount-- <= 1)
156 #else /* !linux */
157 #define	ADD_BDG_REF(ifp)	(ifp)->if_refcount++
158 #define	DROP_BDG_REF(ifp)	refcount_release(&(ifp)->if_refcount)
159 #ifdef __FreeBSD__
160 #include <sys/endian.h>
161 #include <sys/refcount.h>
162 #endif /* __FreeBSD__ */
163 #define prefetch(x)	__builtin_prefetch(x)
164 #endif /* !linux */
165 
166 static void bdg_netmap_attach(struct ifnet *ifp);
167 static int bdg_netmap_reg(struct ifnet *ifp, int onoff);
168 /* per-tx-queue entry */
169 struct nm_bdg_fwd {	/* forwarding entry for a bridge */
170 	void *buf;
171 	uint64_t dst;	/* dst mask */
172 	uint32_t src;	/* src index ? */
173 	uint16_t len;	/* src len */
174 };
175 
176 struct nm_hash_ent {
177 	uint64_t	mac;	/* the top 2 bytes are the epoch */
178 	uint64_t	ports;
179 };
180 
181 /*
182  * Interfaces for a bridge are all in ports[].
183  * The array has fixed size, an empty entry does not terminate
184  * the search.
185  */
186 struct nm_bridge {
187 	struct ifnet *bdg_ports[NM_BDG_MAXPORTS];
188 	int n_ports;
189 	uint64_t act_ports;
190 	int freelist;	/* first buffer index */
191 	NM_SELINFO_T si;	/* poll/select wait queue */
192 	NM_LOCK_T bdg_lock;	/* protect the selinfo ? */
193 
194 	/* the forwarding table, MAC+ports */
195 	struct nm_hash_ent ht[NM_BDG_HASH];
196 
197 	int namelen;	/* 0 means free */
198 	char basename[IFNAMSIZ];
199 };
200 
201 struct nm_bridge nm_bridges[NM_BRIDGES];
202 
203 #define BDG_LOCK(b)	mtx_lock(&(b)->bdg_lock)
204 #define BDG_UNLOCK(b)	mtx_unlock(&(b)->bdg_lock)
205 
206 /*
207  * NA(ifp)->bdg_port	port index
208  */
209 
210 // XXX only for multiples of 64 bytes, non overlapped.
211 static inline void
212 pkt_copy(void *_src, void *_dst, int l)
213 {
214         uint64_t *src = _src;
215         uint64_t *dst = _dst;
216         if (unlikely(l >= 1024)) {
217                 bcopy(src, dst, l);
218                 return;
219         }
220         for (; likely(l > 0); l-=64) {
221                 *dst++ = *src++;
222                 *dst++ = *src++;
223                 *dst++ = *src++;
224                 *dst++ = *src++;
225                 *dst++ = *src++;
226                 *dst++ = *src++;
227                 *dst++ = *src++;
228                 *dst++ = *src++;
229         }
230 }
231 
232 /*
233  * locate a bridge among the existing ones.
234  * a ':' in the name terminates the bridge name. Otherwise, just NM_NAME.
235  * We assume that this is called with a name of at least NM_NAME chars.
236  */
237 static struct nm_bridge *
238 nm_find_bridge(const char *name)
239 {
240 	int i, l, namelen, e;
241 	struct nm_bridge *b = NULL;
242 
243 	namelen = strlen(NM_NAME);	/* base length */
244 	l = strlen(name);		/* actual length */
245 	for (i = namelen + 1; i < l; i++) {
246 		if (name[i] == ':') {
247 			namelen = i;
248 			break;
249 		}
250 	}
251 	if (namelen >= IFNAMSIZ)
252 		namelen = IFNAMSIZ;
253 	ND("--- prefix is '%.*s' ---", namelen, name);
254 
255 	/* use the first entry for locking */
256 	BDG_LOCK(nm_bridges); // XXX do better
257 	for (e = -1, i = 1; i < NM_BRIDGES; i++) {
258 		b = nm_bridges + i;
259 		if (b->namelen == 0)
260 			e = i;	/* record empty slot */
261 		else if (strncmp(name, b->basename, namelen) == 0) {
262 			ND("found '%.*s' at %d", namelen, name, i);
263 			break;
264 		}
265 	}
266 	if (i == NM_BRIDGES) { /* all full */
267 		if (e == -1) { /* no empty slot */
268 			b = NULL;
269 		} else {
270 			b = nm_bridges + e;
271 			strncpy(b->basename, name, namelen);
272 			b->namelen = namelen;
273 		}
274 	}
275 	BDG_UNLOCK(nm_bridges);
276 	return b;
277 }
278 #endif /* NM_BRIDGE */
279 
280 
281 /*
282  * Fetch configuration from the device, to cope with dynamic
283  * reconfigurations after loading the module.
284  */
285 static int
286 netmap_update_config(struct netmap_adapter *na)
287 {
288 	struct ifnet *ifp = na->ifp;
289 	u_int txr, txd, rxr, rxd;
290 
291 	txr = txd = rxr = rxd = 0;
292 	if (na->nm_config) {
293 		na->nm_config(ifp, &txr, &txd, &rxr, &rxd);
294 	} else {
295 		/* take whatever we had at init time */
296 		txr = na->num_tx_rings;
297 		txd = na->num_tx_desc;
298 		rxr = na->num_rx_rings;
299 		rxd = na->num_rx_desc;
300 	}
301 
302 	if (na->num_tx_rings == txr && na->num_tx_desc == txd &&
303 	    na->num_rx_rings == rxr && na->num_rx_desc == rxd)
304 		return 0; /* nothing changed */
305 	if (netmap_verbose || na->refcount > 0) {
306 		D("stored config %s: txring %d x %d, rxring %d x %d",
307 			ifp->if_xname,
308 			na->num_tx_rings, na->num_tx_desc,
309 			na->num_rx_rings, na->num_rx_desc);
310 		D("new config %s: txring %d x %d, rxring %d x %d",
311 			ifp->if_xname, txr, txd, rxr, rxd);
312 	}
313 	if (na->refcount == 0) {
314 		D("configuration changed (but fine)");
315 		na->num_tx_rings = txr;
316 		na->num_tx_desc = txd;
317 		na->num_rx_rings = rxr;
318 		na->num_rx_desc = rxd;
319 		return 0;
320 	}
321 	D("configuration changed while active, this is bad...");
322 	return 1;
323 }
324 
325 /*------------- memory allocator -----------------*/
326 #ifdef NETMAP_MEM2
327 #include "netmap_mem2.c"
328 #else /* !NETMAP_MEM2 */
329 #include "netmap_mem1.c"
330 #endif /* !NETMAP_MEM2 */
331 /*------------ end of memory allocator ----------*/
332 
333 
334 /* Structure associated to each thread which registered an interface.
335  *
336  * The first 4 fields of this structure are written by NIOCREGIF and
337  * read by poll() and NIOC?XSYNC.
338  * There is low contention among writers (actually, a correct user program
339  * should have no contention among writers) and among writers and readers,
340  * so we use a single global lock to protect the structure initialization.
341  * Since initialization involves the allocation of memory, we reuse the memory
342  * allocator lock.
343  * Read access to the structure is lock free. Readers must check that
344  * np_nifp is not NULL before using the other fields.
345  * If np_nifp is NULL initialization has not been performed, so they should
346  * return an error to userlevel.
347  *
348  * The ref_done field is used to regulate access to the refcount in the
349  * memory allocator. The refcount must be incremented at most once for
350  * each open("/dev/netmap"). The increment is performed by the first
351  * function that calls netmap_get_memory() (currently called by
352  * mmap(), NIOCGINFO and NIOCREGIF).
353  * If the refcount is incremented, it is then decremented when the
354  * private structure is destroyed.
355  */
356 struct netmap_priv_d {
357 	struct netmap_if * volatile np_nifp;	/* netmap interface descriptor. */
358 
359 	struct ifnet	*np_ifp;	/* device for which we hold a reference */
360 	int		np_ringid;	/* from the ioctl */
361 	u_int		np_qfirst, np_qlast;	/* range of rings to scan */
362 	uint16_t	np_txpoll;
363 
364 	unsigned long	ref_done;	/* use with NMA_LOCK held */
365 };
366 
367 
368 static int
369 netmap_get_memory(struct netmap_priv_d* p)
370 {
371 	int error = 0;
372 	NMA_LOCK();
373 	if (!p->ref_done) {
374 		error = netmap_memory_finalize();
375 		if (!error)
376 			p->ref_done = 1;
377 	}
378 	NMA_UNLOCK();
379 	return error;
380 }
381 
382 /*
383  * File descriptor's private data destructor.
384  *
385  * Call nm_register(ifp,0) to stop netmap mode on the interface and
386  * revert to normal operation. We expect that np_ifp has not gone.
387  */
388 /* call with NMA_LOCK held */
389 static void
390 netmap_dtor_locked(void *data)
391 {
392 	struct netmap_priv_d *priv = data;
393 	struct ifnet *ifp = priv->np_ifp;
394 	struct netmap_adapter *na = NA(ifp);
395 	struct netmap_if *nifp = priv->np_nifp;
396 
397 	na->refcount--;
398 	if (na->refcount <= 0) {	/* last instance */
399 		u_int i, j, lim;
400 
401 		if (netmap_verbose)
402 			D("deleting last instance for %s", ifp->if_xname);
403 		/*
404 		 * there is a race here with *_netmap_task() and
405 		 * netmap_poll(), which don't run under NETMAP_REG_LOCK.
406 		 * na->refcount == 0 && na->ifp->if_capenable & IFCAP_NETMAP
407 		 * (aka NETMAP_DELETING(na)) are a unique marker that the
408 		 * device is dying.
409 		 * Before destroying stuff we sleep a bit, and then complete
410 		 * the job. NIOCREG should realize the condition and
411 		 * loop until they can continue; the other routines
412 		 * should check the condition at entry and quit if
413 		 * they cannot run.
414 		 */
415 		na->nm_lock(ifp, NETMAP_REG_UNLOCK, 0);
416 		tsleep(na, 0, "NIOCUNREG", 4);
417 		na->nm_lock(ifp, NETMAP_REG_LOCK, 0);
418 		na->nm_register(ifp, 0); /* off, clear IFCAP_NETMAP */
419 		/* Wake up any sleeping threads. netmap_poll will
420 		 * then return POLLERR
421 		 */
422 		for (i = 0; i < na->num_tx_rings + 1; i++)
423 			selwakeuppri(&na->tx_rings[i].si, PI_NET);
424 		for (i = 0; i < na->num_rx_rings + 1; i++)
425 			selwakeuppri(&na->rx_rings[i].si, PI_NET);
426 		selwakeuppri(&na->tx_si, PI_NET);
427 		selwakeuppri(&na->rx_si, PI_NET);
428 		/* release all buffers */
429 		for (i = 0; i < na->num_tx_rings + 1; i++) {
430 			struct netmap_ring *ring = na->tx_rings[i].ring;
431 			lim = na->tx_rings[i].nkr_num_slots;
432 			for (j = 0; j < lim; j++)
433 				netmap_free_buf(nifp, ring->slot[j].buf_idx);
434 			/* knlist_destroy(&na->tx_rings[i].si.si_note); */
435 			mtx_destroy(&na->tx_rings[i].q_lock);
436 		}
437 		for (i = 0; i < na->num_rx_rings + 1; i++) {
438 			struct netmap_ring *ring = na->rx_rings[i].ring;
439 			lim = na->rx_rings[i].nkr_num_slots;
440 			for (j = 0; j < lim; j++)
441 				netmap_free_buf(nifp, ring->slot[j].buf_idx);
442 			/* knlist_destroy(&na->rx_rings[i].si.si_note); */
443 			mtx_destroy(&na->rx_rings[i].q_lock);
444 		}
445 		/* XXX kqueue(9) needed; these will mirror knlist_init. */
446 		/* knlist_destroy(&na->tx_si.si_note); */
447 		/* knlist_destroy(&na->rx_si.si_note); */
448 		netmap_free_rings(na);
449 		wakeup(na);
450 	}
451 	netmap_if_free(nifp);
452 }
453 
454 static void
455 nm_if_rele(struct ifnet *ifp)
456 {
457 #ifndef NM_BRIDGE
458 	if_rele(ifp);
459 #else /* NM_BRIDGE */
460 	int i, full;
461 	struct nm_bridge *b;
462 
463 	if (strncmp(ifp->if_xname, NM_NAME, sizeof(NM_NAME) - 1)) {
464 		if_rele(ifp);
465 		return;
466 	}
467 	if (!DROP_BDG_REF(ifp))
468 		return;
469 	b = ifp->if_bridge;
470 	BDG_LOCK(nm_bridges);
471 	BDG_LOCK(b);
472 	ND("want to disconnect %s from the bridge", ifp->if_xname);
473 	full = 0;
474 	for (i = 0; i < NM_BDG_MAXPORTS; i++) {
475 		if (b->bdg_ports[i] == ifp) {
476 			b->bdg_ports[i] = NULL;
477 			bzero(ifp, sizeof(*ifp));
478 			free(ifp, M_DEVBUF);
479 			break;
480 		}
481 		else if (b->bdg_ports[i] != NULL)
482 			full = 1;
483 	}
484 	BDG_UNLOCK(b);
485 	if (full == 0) {
486 		ND("freeing bridge %d", b - nm_bridges);
487 		b->namelen = 0;
488 	}
489 	BDG_UNLOCK(nm_bridges);
490 	if (i == NM_BDG_MAXPORTS)
491 		D("ouch, cannot find ifp to remove");
492 #endif /* NM_BRIDGE */
493 }
494 
495 static void
496 netmap_dtor(void *data)
497 {
498 	struct netmap_priv_d *priv = data;
499 	struct ifnet *ifp = priv->np_ifp;
500 	struct netmap_adapter *na;
501 
502 	NMA_LOCK();
503 	if (ifp) {
504 		na = NA(ifp);
505 		na->nm_lock(ifp, NETMAP_REG_LOCK, 0);
506 		netmap_dtor_locked(data);
507 		na->nm_lock(ifp, NETMAP_REG_UNLOCK, 0);
508 
509 		nm_if_rele(ifp);
510 	}
511 	if (priv->ref_done) {
512 		netmap_memory_deref();
513 	}
514 	NMA_UNLOCK();
515 	bzero(priv, sizeof(*priv));	/* XXX for safety */
516 	free(priv, M_DEVBUF);
517 }
518 
519 #ifdef __FreeBSD__
520 #include <vm/vm.h>
521 #include <vm/vm_param.h>
522 #include <vm/vm_object.h>
523 #include <vm/vm_page.h>
524 #include <vm/vm_pager.h>
525 #include <vm/uma.h>
526 
527 static struct cdev_pager_ops saved_cdev_pager_ops;
528 
529 static int
530 netmap_dev_pager_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot,
531     vm_ooffset_t foff, struct ucred *cred, u_short *color)
532 {
533 	if (netmap_verbose)
534 		D("first mmap for %p", handle);
535 	return saved_cdev_pager_ops.cdev_pg_ctor(handle,
536 			size, prot, foff, cred, color);
537 }
538 
539 static void
540 netmap_dev_pager_dtor(void *handle)
541 {
542 	saved_cdev_pager_ops.cdev_pg_dtor(handle);
543 	ND("ready to release memory for %p", handle);
544 }
545 
546 
547 static struct cdev_pager_ops netmap_cdev_pager_ops = {
548         .cdev_pg_ctor = netmap_dev_pager_ctor,
549         .cdev_pg_dtor = netmap_dev_pager_dtor,
550         .cdev_pg_fault = NULL,
551 };
552 
553 static int
554 netmap_mmap_single(struct cdev *cdev, vm_ooffset_t *foff,
555 	vm_size_t objsize,  vm_object_t *objp, int prot)
556 {
557 	vm_object_t obj;
558 
559 	ND("cdev %p foff %jd size %jd objp %p prot %d", cdev,
560 	    (intmax_t )*foff, (intmax_t )objsize, objp, prot);
561 	obj = vm_pager_allocate(OBJT_DEVICE, cdev, objsize, prot, *foff,
562             curthread->td_ucred);
563 	ND("returns obj %p", obj);
564 	if (obj == NULL)
565 		return EINVAL;
566 	if (saved_cdev_pager_ops.cdev_pg_fault == NULL) {
567 		ND("initialize cdev_pager_ops");
568 		saved_cdev_pager_ops = *(obj->un_pager.devp.ops);
569 		netmap_cdev_pager_ops.cdev_pg_fault =
570 			saved_cdev_pager_ops.cdev_pg_fault;
571 	};
572 	obj->un_pager.devp.ops = &netmap_cdev_pager_ops;
573 	*objp = obj;
574 	return 0;
575 }
576 #endif /* __FreeBSD__ */
577 
578 
579 /*
580  * mmap(2) support for the "netmap" device.
581  *
582  * Expose all the memory previously allocated by our custom memory
583  * allocator: this way the user has only to issue a single mmap(2), and
584  * can work on all the data structures flawlessly.
585  *
586  * Return 0 on success, -1 otherwise.
587  */
588 
589 #ifdef __FreeBSD__
590 static int
591 netmap_mmap(__unused struct cdev *dev,
592 #if __FreeBSD_version < 900000
593 		vm_offset_t offset, vm_paddr_t *paddr, int nprot
594 #else
595 		vm_ooffset_t offset, vm_paddr_t *paddr, int nprot,
596 		__unused vm_memattr_t *memattr
597 #endif
598 	)
599 {
600 	int error = 0;
601 	struct netmap_priv_d *priv;
602 
603 	if (nprot & PROT_EXEC)
604 		return (-1);	// XXX -1 or EINVAL ?
605 
606 	error = devfs_get_cdevpriv((void **)&priv);
607 	if (error == EBADF) {	/* called on fault, memory is initialized */
608 		ND(5, "handling fault at ofs 0x%x", offset);
609 		error = 0;
610 	} else if (error == 0)	/* make sure memory is set */
611 		error = netmap_get_memory(priv);
612 	if (error)
613 		return (error);
614 
615 	ND("request for offset 0x%x", (uint32_t)offset);
616 	*paddr = netmap_ofstophys(offset);
617 
618 	return (*paddr ? 0 : ENOMEM);
619 }
620 
621 static int
622 netmap_close(struct cdev *dev, int fflag, int devtype, struct thread *td)
623 {
624 	if (netmap_verbose)
625 		D("dev %p fflag 0x%x devtype %d td %p",
626 			dev, fflag, devtype, td);
627 	return 0;
628 }
629 
630 static int
631 netmap_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
632 {
633 	struct netmap_priv_d *priv;
634 	int error;
635 
636 	priv = malloc(sizeof(struct netmap_priv_d), M_DEVBUF,
637 			      M_NOWAIT | M_ZERO);
638 	if (priv == NULL)
639 		return ENOMEM;
640 
641 	error = devfs_set_cdevpriv(priv, netmap_dtor);
642 	if (error)
643 	        return error;
644 
645 	return 0;
646 }
647 #endif /* __FreeBSD__ */
648 
649 
650 /*
651  * Handlers for synchronization of the queues from/to the host.
652  * Netmap has two operating modes:
653  * - in the default mode, the rings connected to the host stack are
654  *   just another ring pair managed by userspace;
655  * - in transparent mode (XXX to be defined) incoming packets
656  *   (from the host or the NIC) are marked as NS_FORWARD upon
657  *   arrival, and the user application has a chance to reset the
658  *   flag for packets that should be dropped.
659  *   On the RXSYNC or poll(), packets in RX rings between
660  *   kring->nr_kcur and ring->cur with NS_FORWARD still set are moved
661  *   to the other side.
662  * The transfer NIC --> host is relatively easy, just encapsulate
663  * into mbufs and we are done. The host --> NIC side is slightly
664  * harder because there might not be room in the tx ring so it
665  * might take a while before releasing the buffer.
666  */
667 
668 /*
669  * pass a chain of buffers to the host stack as coming from 'dst'
670  */
671 static void
672 netmap_send_up(struct ifnet *dst, struct mbuf *head)
673 {
674 	struct mbuf *m;
675 
676 	/* send packets up, outside the lock */
677 	while ((m = head) != NULL) {
678 		head = head->m_nextpkt;
679 		m->m_nextpkt = NULL;
680 		if (netmap_verbose & NM_VERB_HOST)
681 			D("sending up pkt %p size %d", m, MBUF_LEN(m));
682 		NM_SEND_UP(dst, m);
683 	}
684 }
685 
686 struct mbq {
687 	struct mbuf *head;
688 	struct mbuf *tail;
689 	int count;
690 };
691 
692 /*
693  * put a copy of the buffers marked NS_FORWARD into an mbuf chain.
694  * Run from hwcur to cur - reserved
695  */
696 static void
697 netmap_grab_packets(struct netmap_kring *kring, struct mbq *q, int force)
698 {
699 	/* Take packets from hwcur to cur-reserved and pass them up.
700 	 * In case of no buffers we give up. At the end of the loop,
701 	 * the queue is drained in all cases.
702 	 * XXX handle reserved
703 	 */
704 	int k = kring->ring->cur - kring->ring->reserved;
705 	u_int n, lim = kring->nkr_num_slots - 1;
706 	struct mbuf *m, *tail = q->tail;
707 
708 	if (k < 0)
709 		k = k + kring->nkr_num_slots;
710 	for (n = kring->nr_hwcur; n != k;) {
711 		struct netmap_slot *slot = &kring->ring->slot[n];
712 
713 		n = (n == lim) ? 0 : n + 1;
714 		if ((slot->flags & NS_FORWARD) == 0 && !force)
715 			continue;
716 		if (slot->len < 14 || slot->len > NETMAP_BUF_SIZE) {
717 			D("bad pkt at %d len %d", n, slot->len);
718 			continue;
719 		}
720 		slot->flags &= ~NS_FORWARD; // XXX needed ?
721 		m = m_devget(NMB(slot), slot->len, 0, kring->na->ifp, NULL);
722 
723 		if (m == NULL)
724 			break;
725 		if (tail)
726 			tail->m_nextpkt = m;
727 		else
728 			q->head = m;
729 		tail = m;
730 		q->count++;
731 		m->m_nextpkt = NULL;
732 	}
733 	q->tail = tail;
734 }
735 
736 /*
737  * called under main lock to send packets from the host to the NIC
738  * The host ring has packets from nr_hwcur to (cur - reserved)
739  * to be sent down. We scan the tx rings, which have just been
740  * flushed so nr_hwcur == cur. Pushing packets down means
741  * increment cur and decrement avail.
742  * XXX to be verified
743  */
744 static void
745 netmap_sw_to_nic(struct netmap_adapter *na)
746 {
747 	struct netmap_kring *kring = &na->rx_rings[na->num_rx_rings];
748 	struct netmap_kring *k1 = &na->tx_rings[0];
749 	int i, howmany, src_lim, dst_lim;
750 
751 	howmany = kring->nr_hwavail;	/* XXX otherwise cur - reserved - nr_hwcur */
752 
753 	src_lim = kring->nkr_num_slots;
754 	for (i = 0; howmany > 0 && i < na->num_tx_rings; i++, k1++) {
755 		ND("%d packets left to ring %d (space %d)", howmany, i, k1->nr_hwavail);
756 		dst_lim = k1->nkr_num_slots;
757 		while (howmany > 0 && k1->ring->avail > 0) {
758 			struct netmap_slot *src, *dst, tmp;
759 			src = &kring->ring->slot[kring->nr_hwcur];
760 			dst = &k1->ring->slot[k1->ring->cur];
761 			tmp = *src;
762 			src->buf_idx = dst->buf_idx;
763 			src->flags = NS_BUF_CHANGED;
764 
765 			dst->buf_idx = tmp.buf_idx;
766 			dst->len = tmp.len;
767 			dst->flags = NS_BUF_CHANGED;
768 			ND("out len %d buf %d from %d to %d",
769 				dst->len, dst->buf_idx,
770 				kring->nr_hwcur, k1->ring->cur);
771 
772 			if (++kring->nr_hwcur >= src_lim)
773 				kring->nr_hwcur = 0;
774 			howmany--;
775 			kring->nr_hwavail--;
776 			if (++k1->ring->cur >= dst_lim)
777 				k1->ring->cur = 0;
778 			k1->ring->avail--;
779 		}
780 		kring->ring->cur = kring->nr_hwcur; // XXX
781 		k1++;
782 	}
783 }
784 
785 /*
786  * netmap_sync_to_host() passes packets up. We are called from a
787  * system call in user process context, and the only contention
788  * can be among multiple user threads erroneously calling
789  * this routine concurrently.
790  */
791 static void
792 netmap_sync_to_host(struct netmap_adapter *na)
793 {
794 	struct netmap_kring *kring = &na->tx_rings[na->num_tx_rings];
795 	struct netmap_ring *ring = kring->ring;
796 	u_int k, lim = kring->nkr_num_slots - 1;
797 	struct mbq q = { NULL, NULL };
798 
799 	k = ring->cur;
800 	if (k > lim) {
801 		netmap_ring_reinit(kring);
802 		return;
803 	}
804 	// na->nm_lock(na->ifp, NETMAP_CORE_LOCK, 0);
805 
806 	/* Take packets from hwcur to cur and pass them up.
807 	 * In case of no buffers we give up. At the end of the loop,
808 	 * the queue is drained in all cases.
809 	 */
810 	netmap_grab_packets(kring, &q, 1);
811 	kring->nr_hwcur = k;
812 	kring->nr_hwavail = ring->avail = lim;
813 	// na->nm_lock(na->ifp, NETMAP_CORE_UNLOCK, 0);
814 
815 	netmap_send_up(na->ifp, q.head);
816 }
817 
818 /*
819  * rxsync backend for packets coming from the host stack.
820  * They have been put in the queue by netmap_start() so we
821  * need to protect access to the kring using a lock.
822  *
823  * This routine also does the selrecord if called from the poll handler
824  * (we know because td != NULL).
825  *
826  * NOTE: on linux, selrecord() is defined as a macro and uses pwait
827  *     as an additional hidden argument.
828  */
829 static void
830 netmap_sync_from_host(struct netmap_adapter *na, struct thread *td, void *pwait)
831 {
832 	struct netmap_kring *kring = &na->rx_rings[na->num_rx_rings];
833 	struct netmap_ring *ring = kring->ring;
834 	u_int j, n, lim = kring->nkr_num_slots;
835 	u_int k = ring->cur, resvd = ring->reserved;
836 
837 	(void)pwait;	/* disable unused warnings */
838 	na->nm_lock(na->ifp, NETMAP_CORE_LOCK, 0);
839 	if (k >= lim) {
840 		netmap_ring_reinit(kring);
841 		return;
842 	}
843 	/* new packets are already set in nr_hwavail */
844 	/* skip past packets that userspace has released */
845 	j = kring->nr_hwcur;
846 	if (resvd > 0) {
847 		if (resvd + ring->avail >= lim + 1) {
848 			D("XXX invalid reserve/avail %d %d", resvd, ring->avail);
849 			ring->reserved = resvd = 0; // XXX panic...
850 		}
851 		k = (k >= resvd) ? k - resvd : k + lim - resvd;
852         }
853 	if (j != k) {
854 		n = k >= j ? k - j : k + lim - j;
855 		kring->nr_hwavail -= n;
856 		kring->nr_hwcur = k;
857 	}
858 	k = ring->avail = kring->nr_hwavail - resvd;
859 	if (k == 0 && td)
860 		selrecord(td, &kring->si);
861 	if (k && (netmap_verbose & NM_VERB_HOST))
862 		D("%d pkts from stack", k);
863 	na->nm_lock(na->ifp, NETMAP_CORE_UNLOCK, 0);
864 }
865 
866 
867 /*
868  * get a refcounted reference to an interface.
869  * Return ENXIO if the interface does not exist, EINVAL if netmap
870  * is not supported by the interface.
871  * If successful, hold a reference.
872  */
873 static int
874 get_ifp(const char *name, struct ifnet **ifp)
875 {
876 #ifdef NM_BRIDGE
877 	struct ifnet *iter = NULL;
878 
879 	do {
880 		struct nm_bridge *b;
881 		int i, l, cand = -1;
882 
883 		if (strncmp(name, NM_NAME, sizeof(NM_NAME) - 1))
884 			break;
885 		b = nm_find_bridge(name);
886 		if (b == NULL) {
887 			D("no bridges available for '%s'", name);
888 			return (ENXIO);
889 		}
890 		/* XXX locking */
891 		BDG_LOCK(b);
892 		/* lookup in the local list of ports */
893 		for (i = 0; i < NM_BDG_MAXPORTS; i++) {
894 			iter = b->bdg_ports[i];
895 			if (iter == NULL) {
896 				if (cand == -1)
897 					cand = i; /* potential insert point */
898 				continue;
899 			}
900 			if (!strcmp(iter->if_xname, name)) {
901 				ADD_BDG_REF(iter);
902 				ND("found existing interface");
903 				BDG_UNLOCK(b);
904 				break;
905 			}
906 		}
907 		if (i < NM_BDG_MAXPORTS) /* already unlocked */
908 			break;
909 		if (cand == -1) {
910 			D("bridge full, cannot create new port");
911 no_port:
912 			BDG_UNLOCK(b);
913 			*ifp = NULL;
914 			return EINVAL;
915 		}
916 		ND("create new bridge port %s", name);
917 		/* space for forwarding list after the ifnet */
918 		l = sizeof(*iter) +
919 			 sizeof(struct nm_bdg_fwd)*NM_BDG_BATCH ;
920 		iter = malloc(l, M_DEVBUF, M_NOWAIT | M_ZERO);
921 		if (!iter)
922 			goto no_port;
923 		strcpy(iter->if_xname, name);
924 		bdg_netmap_attach(iter);
925 		b->bdg_ports[cand] = iter;
926 		iter->if_bridge = b;
927 		ADD_BDG_REF(iter);
928 		BDG_UNLOCK(b);
929 		ND("attaching virtual bridge %p", b);
930 	} while (0);
931 	*ifp = iter;
932 	if (! *ifp)
933 #endif /* NM_BRIDGE */
934 	*ifp = ifunit_ref(name);
935 	if (*ifp == NULL)
936 		return (ENXIO);
937 	/* can do this if the capability exists and if_pspare[0]
938 	 * points to the netmap descriptor.
939 	 */
940 	if (NETMAP_CAPABLE(*ifp))
941 		return 0;	/* valid pointer, we hold the refcount */
942 	nm_if_rele(*ifp);
943 	return EINVAL;	// not NETMAP capable
944 }
945 
946 
947 /*
948  * Error routine called when txsync/rxsync detects an error.
949  * Can't do much more than resetting cur = hwcur, avail = hwavail.
950  * Return 1 on reinit.
951  *
952  * This routine is only called by the upper half of the kernel.
953  * It only reads hwcur (which is changed only by the upper half, too)
954  * and hwavail (which may be changed by the lower half, but only on
955  * a tx ring and only to increase it, so any error will be recovered
956  * on the next call). For the above, we don't strictly need to call
957  * it under lock.
958  */
959 int
960 netmap_ring_reinit(struct netmap_kring *kring)
961 {
962 	struct netmap_ring *ring = kring->ring;
963 	u_int i, lim = kring->nkr_num_slots - 1;
964 	int errors = 0;
965 
966 	RD(10, "called for %s", kring->na->ifp->if_xname);
967 	if (ring->cur > lim)
968 		errors++;
969 	for (i = 0; i <= lim; i++) {
970 		u_int idx = ring->slot[i].buf_idx;
971 		u_int len = ring->slot[i].len;
972 		if (idx < 2 || idx >= netmap_total_buffers) {
973 			if (!errors++)
974 				D("bad buffer at slot %d idx %d len %d ", i, idx, len);
975 			ring->slot[i].buf_idx = 0;
976 			ring->slot[i].len = 0;
977 		} else if (len > NETMAP_BUF_SIZE) {
978 			ring->slot[i].len = 0;
979 			if (!errors++)
980 				D("bad len %d at slot %d idx %d",
981 					len, i, idx);
982 		}
983 	}
984 	if (errors) {
985 		int pos = kring - kring->na->tx_rings;
986 		int n = kring->na->num_tx_rings + 1;
987 
988 		RD(10, "total %d errors", errors);
989 		errors++;
990 		RD(10, "%s %s[%d] reinit, cur %d -> %d avail %d -> %d",
991 			kring->na->ifp->if_xname,
992 			pos < n ?  "TX" : "RX", pos < n ? pos : pos - n,
993 			ring->cur, kring->nr_hwcur,
994 			ring->avail, kring->nr_hwavail);
995 		ring->cur = kring->nr_hwcur;
996 		ring->avail = kring->nr_hwavail;
997 	}
998 	return (errors ? 1 : 0);
999 }
1000 
1001 
1002 /*
1003  * Set the ring ID. For devices with a single queue, a request
1004  * for all rings is the same as a single ring.
1005  */
1006 static int
1007 netmap_set_ringid(struct netmap_priv_d *priv, u_int ringid)
1008 {
1009 	struct ifnet *ifp = priv->np_ifp;
1010 	struct netmap_adapter *na = NA(ifp);
1011 	u_int i = ringid & NETMAP_RING_MASK;
1012 	/* initially (np_qfirst == np_qlast) we don't want to lock */
1013 	int need_lock = (priv->np_qfirst != priv->np_qlast);
1014 	int lim = na->num_rx_rings;
1015 
1016 	if (na->num_tx_rings > lim)
1017 		lim = na->num_tx_rings;
1018 	if ( (ringid & NETMAP_HW_RING) && i >= lim) {
1019 		D("invalid ring id %d", i);
1020 		return (EINVAL);
1021 	}
1022 	if (need_lock)
1023 		na->nm_lock(ifp, NETMAP_CORE_LOCK, 0);
1024 	priv->np_ringid = ringid;
1025 	if (ringid & NETMAP_SW_RING) {
1026 		priv->np_qfirst = NETMAP_SW_RING;
1027 		priv->np_qlast = 0;
1028 	} else if (ringid & NETMAP_HW_RING) {
1029 		priv->np_qfirst = i;
1030 		priv->np_qlast = i + 1;
1031 	} else {
1032 		priv->np_qfirst = 0;
1033 		priv->np_qlast = NETMAP_HW_RING ;
1034 	}
1035 	priv->np_txpoll = (ringid & NETMAP_NO_TX_POLL) ? 0 : 1;
1036 	if (need_lock)
1037 		na->nm_lock(ifp, NETMAP_CORE_UNLOCK, 0);
1038     if (netmap_verbose) {
1039 	if (ringid & NETMAP_SW_RING)
1040 		D("ringid %s set to SW RING", ifp->if_xname);
1041 	else if (ringid & NETMAP_HW_RING)
1042 		D("ringid %s set to HW RING %d", ifp->if_xname,
1043 			priv->np_qfirst);
1044 	else
1045 		D("ringid %s set to all %d HW RINGS", ifp->if_xname, lim);
1046     }
1047 	return 0;
1048 }
1049 
1050 /*
1051  * ioctl(2) support for the "netmap" device.
1052  *
1053  * Following a list of accepted commands:
1054  * - NIOCGINFO
1055  * - SIOCGIFADDR	just for convenience
1056  * - NIOCREGIF
1057  * - NIOCUNREGIF
1058  * - NIOCTXSYNC
1059  * - NIOCRXSYNC
1060  *
1061  * Return 0 on success, errno otherwise.
1062  */
1063 static int
1064 netmap_ioctl(struct cdev *dev, u_long cmd, caddr_t data,
1065 	int fflag, struct thread *td)
1066 {
1067 	struct netmap_priv_d *priv = NULL;
1068 	struct ifnet *ifp;
1069 	struct nmreq *nmr = (struct nmreq *) data;
1070 	struct netmap_adapter *na;
1071 	int error;
1072 	u_int i, lim;
1073 	struct netmap_if *nifp;
1074 
1075 	(void)dev;	/* UNUSED */
1076 	(void)fflag;	/* UNUSED */
1077 #ifdef linux
1078 #define devfs_get_cdevpriv(pp)				\
1079 	({ *(struct netmap_priv_d **)pp = ((struct file *)td)->private_data; 	\
1080 		(*pp ? 0 : ENOENT); })
1081 
1082 /* devfs_set_cdevpriv cannot fail on linux */
1083 #define devfs_set_cdevpriv(p, fn)				\
1084 	({ ((struct file *)td)->private_data = p; (p ? 0 : EINVAL); })
1085 
1086 
1087 #define devfs_clear_cdevpriv()	do {				\
1088 		netmap_dtor(priv); ((struct file *)td)->private_data = 0;	\
1089 	} while (0)
1090 #endif /* linux */
1091 
1092 	CURVNET_SET(TD_TO_VNET(td));
1093 
1094 	error = devfs_get_cdevpriv((void **)&priv);
1095 	if (error) {
1096 		CURVNET_RESTORE();
1097 		/* XXX ENOENT should be impossible, since the priv
1098 		 * is now created in the open */
1099 		return (error == ENOENT ? ENXIO : error);
1100 	}
1101 
1102 	nmr->nr_name[sizeof(nmr->nr_name) - 1] = '\0';	/* truncate name */
1103 	switch (cmd) {
1104 	case NIOCGINFO:		/* return capabilities etc */
1105 		if (nmr->nr_version != NETMAP_API) {
1106 			D("API mismatch got %d have %d",
1107 				nmr->nr_version, NETMAP_API);
1108 			nmr->nr_version = NETMAP_API;
1109 			error = EINVAL;
1110 			break;
1111 		}
1112 		/* update configuration */
1113 		error = netmap_get_memory(priv);
1114 		ND("get_memory returned %d", error);
1115 		if (error)
1116 			break;
1117 		/* memsize is always valid */
1118 		nmr->nr_memsize = nm_mem.nm_totalsize;
1119 		nmr->nr_offset = 0;
1120 		nmr->nr_rx_rings = nmr->nr_tx_rings = 0;
1121 		nmr->nr_rx_slots = nmr->nr_tx_slots = 0;
1122 		if (nmr->nr_name[0] == '\0')	/* just get memory info */
1123 			break;
1124 		error = get_ifp(nmr->nr_name, &ifp); /* get a refcount */
1125 		if (error)
1126 			break;
1127 		na = NA(ifp); /* retrieve netmap_adapter */
1128 		netmap_update_config(na);
1129 		nmr->nr_rx_rings = na->num_rx_rings;
1130 		nmr->nr_tx_rings = na->num_tx_rings;
1131 		nmr->nr_rx_slots = na->num_rx_desc;
1132 		nmr->nr_tx_slots = na->num_tx_desc;
1133 		nm_if_rele(ifp);	/* return the refcount */
1134 		break;
1135 
1136 	case NIOCREGIF:
1137 		if (nmr->nr_version != NETMAP_API) {
1138 			nmr->nr_version = NETMAP_API;
1139 			error = EINVAL;
1140 			break;
1141 		}
1142 		/* ensure allocators are ready */
1143 		error = netmap_get_memory(priv);
1144 		ND("get_memory returned %d", error);
1145 		if (error)
1146 			break;
1147 
1148 		/* protect access to priv from concurrent NIOCREGIF */
1149 		NMA_LOCK();
1150 		if (priv->np_ifp != NULL) {	/* thread already registered */
1151 			error = netmap_set_ringid(priv, nmr->nr_ringid);
1152 			NMA_UNLOCK();
1153 			break;
1154 		}
1155 		/* find the interface and a reference */
1156 		error = get_ifp(nmr->nr_name, &ifp); /* keep reference */
1157 		if (error) {
1158 			NMA_UNLOCK();
1159 			break;
1160 		}
1161 		na = NA(ifp); /* retrieve netmap adapter */
1162 
1163 		for (i = 10; i > 0; i--) {
1164 			na->nm_lock(ifp, NETMAP_REG_LOCK, 0);
1165 			if (!NETMAP_DELETING(na))
1166 				break;
1167 			na->nm_lock(ifp, NETMAP_REG_UNLOCK, 0);
1168 			tsleep(na, 0, "NIOCREGIF", hz/10);
1169 		}
1170 		if (i == 0) {
1171 			D("too many NIOCREGIF attempts, give up");
1172 			error = EINVAL;
1173 			nm_if_rele(ifp);	/* return the refcount */
1174 			NMA_UNLOCK();
1175 			break;
1176 		}
1177 
1178 		/* ring configuration may have changed, fetch from the card */
1179 		netmap_update_config(na);
1180 		priv->np_ifp = ifp;	/* store the reference */
1181 		error = netmap_set_ringid(priv, nmr->nr_ringid);
1182 		if (error)
1183 			goto error;
1184 		nifp = netmap_if_new(nmr->nr_name, na);
1185 		if (nifp == NULL) { /* allocation failed */
1186 			error = ENOMEM;
1187 		} else if (ifp->if_capenable & IFCAP_NETMAP) {
1188 			/* was already set */
1189 		} else {
1190 			/* Otherwise set the card in netmap mode
1191 			 * and make it use the shared buffers.
1192 			 */
1193 			for (i = 0 ; i < na->num_tx_rings + 1; i++)
1194 				mtx_init(&na->tx_rings[i].q_lock, "nm_txq_lock", MTX_NETWORK_LOCK, MTX_DEF);
1195 			for (i = 0 ; i < na->num_rx_rings + 1; i++) {
1196 				mtx_init(&na->rx_rings[i].q_lock, "nm_rxq_lock", MTX_NETWORK_LOCK, MTX_DEF);
1197 			}
1198 			error = na->nm_register(ifp, 1); /* mode on */
1199 			if (error) {
1200 				netmap_dtor_locked(priv);
1201 				netmap_if_free(nifp);
1202 			}
1203 		}
1204 
1205 		if (error) {	/* reg. failed, release priv and ref */
1206 error:
1207 			na->nm_lock(ifp, NETMAP_REG_UNLOCK, 0);
1208 			nm_if_rele(ifp);	/* return the refcount */
1209 			priv->np_ifp = NULL;
1210 			priv->np_nifp = NULL;
1211 			NMA_UNLOCK();
1212 			break;
1213 		}
1214 
1215 		na->nm_lock(ifp, NETMAP_REG_UNLOCK, 0);
1216 
1217 		/* the following assignment is a commitment.
1218 		 * Readers (i.e., poll and *SYNC) check for
1219 		 * np_nifp != NULL without locking
1220 		 */
1221 		wmb(); /* make sure previous writes are visible to all CPUs */
1222 		priv->np_nifp = nifp;
1223 		NMA_UNLOCK();
1224 
1225 		/* return the offset of the netmap_if object */
1226 		nmr->nr_rx_rings = na->num_rx_rings;
1227 		nmr->nr_tx_rings = na->num_tx_rings;
1228 		nmr->nr_rx_slots = na->num_rx_desc;
1229 		nmr->nr_tx_slots = na->num_tx_desc;
1230 		nmr->nr_memsize = nm_mem.nm_totalsize;
1231 		nmr->nr_offset = netmap_if_offset(nifp);
1232 		break;
1233 
1234 	case NIOCUNREGIF:
1235 		// XXX we have no data here ?
1236 		D("deprecated, data is %p", nmr);
1237 		error = EINVAL;
1238 		break;
1239 
1240 	case NIOCTXSYNC:
1241 	case NIOCRXSYNC:
1242 		nifp = priv->np_nifp;
1243 
1244 		if (nifp == NULL) {
1245 			error = ENXIO;
1246 			break;
1247 		}
1248 		rmb(); /* make sure following reads are not from cache */
1249 
1250 
1251 		ifp = priv->np_ifp;	/* we have a reference */
1252 
1253 		if (ifp == NULL) {
1254 			D("Internal error: nifp != NULL && ifp == NULL");
1255 			error = ENXIO;
1256 			break;
1257 		}
1258 
1259 		na = NA(ifp); /* retrieve netmap adapter */
1260 		if (priv->np_qfirst == NETMAP_SW_RING) { /* host rings */
1261 			if (cmd == NIOCTXSYNC)
1262 				netmap_sync_to_host(na);
1263 			else
1264 				netmap_sync_from_host(na, NULL, NULL);
1265 			break;
1266 		}
1267 		/* find the last ring to scan */
1268 		lim = priv->np_qlast;
1269 		if (lim == NETMAP_HW_RING)
1270 			lim = (cmd == NIOCTXSYNC) ?
1271 			    na->num_tx_rings : na->num_rx_rings;
1272 
1273 		for (i = priv->np_qfirst; i < lim; i++) {
1274 			if (cmd == NIOCTXSYNC) {
1275 				struct netmap_kring *kring = &na->tx_rings[i];
1276 				if (netmap_verbose & NM_VERB_TXSYNC)
1277 					D("pre txsync ring %d cur %d hwcur %d",
1278 					    i, kring->ring->cur,
1279 					    kring->nr_hwcur);
1280 				na->nm_txsync(ifp, i, 1 /* do lock */);
1281 				if (netmap_verbose & NM_VERB_TXSYNC)
1282 					D("post txsync ring %d cur %d hwcur %d",
1283 					    i, kring->ring->cur,
1284 					    kring->nr_hwcur);
1285 			} else {
1286 				na->nm_rxsync(ifp, i, 1 /* do lock */);
1287 				microtime(&na->rx_rings[i].ring->ts);
1288 			}
1289 		}
1290 
1291 		break;
1292 
1293 #ifdef __FreeBSD__
1294 	case BIOCIMMEDIATE:
1295 	case BIOCGHDRCMPLT:
1296 	case BIOCSHDRCMPLT:
1297 	case BIOCSSEESENT:
1298 		D("ignore BIOCIMMEDIATE/BIOCSHDRCMPLT/BIOCSHDRCMPLT/BIOCSSEESENT");
1299 		break;
1300 
1301 	default:	/* allow device-specific ioctls */
1302 	    {
1303 		struct socket so;
1304 		bzero(&so, sizeof(so));
1305 		error = get_ifp(nmr->nr_name, &ifp); /* keep reference */
1306 		if (error)
1307 			break;
1308 		so.so_vnet = ifp->if_vnet;
1309 		// so->so_proto not null.
1310 		error = ifioctl(&so, cmd, data, td);
1311 		nm_if_rele(ifp);
1312 		break;
1313 	    }
1314 
1315 #else /* linux */
1316 	default:
1317 		error = EOPNOTSUPP;
1318 #endif /* linux */
1319 	}
1320 
1321 	CURVNET_RESTORE();
1322 	return (error);
1323 }
1324 
1325 
1326 /*
1327  * select(2) and poll(2) handlers for the "netmap" device.
1328  *
1329  * Can be called for one or more queues.
1330  * Return true the event mask corresponding to ready events.
1331  * If there are no ready events, do a selrecord on either individual
1332  * selfd or on the global one.
1333  * Device-dependent parts (locking and sync of tx/rx rings)
1334  * are done through callbacks.
1335  *
1336  * On linux, arguments are really pwait, the poll table, and 'td' is struct file *
1337  * The first one is remapped to pwait as selrecord() uses the name as an
1338  * hidden argument.
1339  */
1340 static int
1341 netmap_poll(struct cdev *dev, int events, struct thread *td)
1342 {
1343 	struct netmap_priv_d *priv = NULL;
1344 	struct netmap_adapter *na;
1345 	struct ifnet *ifp;
1346 	struct netmap_kring *kring;
1347 	u_int core_lock, i, check_all, want_tx, want_rx, revents = 0;
1348 	u_int lim_tx, lim_rx, host_forwarded = 0;
1349 	struct mbq q = { NULL, NULL, 0 };
1350 	enum {NO_CL, NEED_CL, LOCKED_CL }; /* see below */
1351 	void *pwait = dev;	/* linux compatibility */
1352 
1353 	(void)pwait;
1354 
1355 	if (devfs_get_cdevpriv((void **)&priv) != 0 || priv == NULL)
1356 		return POLLERR;
1357 
1358 	if (priv->np_nifp == NULL) {
1359 		D("No if registered");
1360 		return POLLERR;
1361 	}
1362 	rmb(); /* make sure following reads are not from cache */
1363 
1364 	ifp = priv->np_ifp;
1365 	// XXX check for deleting() ?
1366 	if ( (ifp->if_capenable & IFCAP_NETMAP) == 0)
1367 		return POLLERR;
1368 
1369 	if (netmap_verbose & 0x8000)
1370 		D("device %s events 0x%x", ifp->if_xname, events);
1371 	want_tx = events & (POLLOUT | POLLWRNORM);
1372 	want_rx = events & (POLLIN | POLLRDNORM);
1373 
1374 	na = NA(ifp); /* retrieve netmap adapter */
1375 
1376 	lim_tx = na->num_tx_rings;
1377 	lim_rx = na->num_rx_rings;
1378 	/* how many queues we are scanning */
1379 	if (priv->np_qfirst == NETMAP_SW_RING) {
1380 		if (priv->np_txpoll || want_tx) {
1381 			/* push any packets up, then we are always ready */
1382 			kring = &na->tx_rings[lim_tx];
1383 			netmap_sync_to_host(na);
1384 			revents |= want_tx;
1385 		}
1386 		if (want_rx) {
1387 			kring = &na->rx_rings[lim_rx];
1388 			if (kring->ring->avail == 0)
1389 				netmap_sync_from_host(na, td, dev);
1390 			if (kring->ring->avail > 0) {
1391 				revents |= want_rx;
1392 			}
1393 		}
1394 		return (revents);
1395 	}
1396 
1397 	/* if we are in transparent mode, check also the host rx ring */
1398 	kring = &na->rx_rings[lim_rx];
1399 	if ( (priv->np_qlast == NETMAP_HW_RING) // XXX check_all
1400 			&& want_rx
1401 			&& (netmap_fwd || kring->ring->flags & NR_FORWARD) ) {
1402 		if (kring->ring->avail == 0)
1403 			netmap_sync_from_host(na, td, dev);
1404 		if (kring->ring->avail > 0)
1405 			revents |= want_rx;
1406 	}
1407 
1408 	/*
1409 	 * check_all is set if the card has more than one queue and
1410 	 * the client is polling all of them. If true, we sleep on
1411 	 * the "global" selfd, otherwise we sleep on individual selfd
1412 	 * (we can only sleep on one of them per direction).
1413 	 * The interrupt routine in the driver should always wake on
1414 	 * the individual selfd, and also on the global one if the card
1415 	 * has more than one ring.
1416 	 *
1417 	 * If the card has only one lock, we just use that.
1418 	 * If the card has separate ring locks, we just use those
1419 	 * unless we are doing check_all, in which case the whole
1420 	 * loop is wrapped by the global lock.
1421 	 * We acquire locks only when necessary: if poll is called
1422 	 * when buffers are available, we can just return without locks.
1423 	 *
1424 	 * rxsync() is only called if we run out of buffers on a POLLIN.
1425 	 * txsync() is called if we run out of buffers on POLLOUT, or
1426 	 * there are pending packets to send. The latter can be disabled
1427 	 * passing NETMAP_NO_TX_POLL in the NIOCREG call.
1428 	 */
1429 	check_all = (priv->np_qlast == NETMAP_HW_RING) && (lim_tx > 1 || lim_rx > 1);
1430 
1431 	/*
1432 	 * core_lock indicates what to do with the core lock.
1433 	 * The core lock is used when either the card has no individual
1434 	 * locks, or it has individual locks but we are cheking all
1435 	 * rings so we need the core lock to avoid missing wakeup events.
1436 	 *
1437 	 * It has three possible states:
1438 	 * NO_CL	we don't need to use the core lock, e.g.
1439 	 *		because we are protected by individual locks.
1440 	 * NEED_CL	we need the core lock. In this case, when we
1441 	 *		call the lock routine, move to LOCKED_CL
1442 	 *		to remember to release the lock once done.
1443 	 * LOCKED_CL	core lock is set, so we need to release it.
1444 	 */
1445 	core_lock = (check_all || !na->separate_locks) ? NEED_CL : NO_CL;
1446 #ifdef NM_BRIDGE
1447 	/* the bridge uses separate locks */
1448 	if (na->nm_register == bdg_netmap_reg) {
1449 		ND("not using core lock for %s", ifp->if_xname);
1450 		core_lock = NO_CL;
1451 	}
1452 #endif /* NM_BRIDGE */
1453 	if (priv->np_qlast != NETMAP_HW_RING) {
1454 		lim_tx = lim_rx = priv->np_qlast;
1455 	}
1456 
1457 	/*
1458 	 * We start with a lock free round which is good if we have
1459 	 * data available. If this fails, then lock and call the sync
1460 	 * routines.
1461 	 */
1462 	for (i = priv->np_qfirst; want_rx && i < lim_rx; i++) {
1463 		kring = &na->rx_rings[i];
1464 		if (kring->ring->avail > 0) {
1465 			revents |= want_rx;
1466 			want_rx = 0;	/* also breaks the loop */
1467 		}
1468 	}
1469 	for (i = priv->np_qfirst; want_tx && i < lim_tx; i++) {
1470 		kring = &na->tx_rings[i];
1471 		if (kring->ring->avail > 0) {
1472 			revents |= want_tx;
1473 			want_tx = 0;	/* also breaks the loop */
1474 		}
1475 	}
1476 
1477 	/*
1478 	 * If we to push packets out (priv->np_txpoll) or want_tx is
1479 	 * still set, we do need to run the txsync calls (on all rings,
1480 	 * to avoid that the tx rings stall).
1481 	 */
1482 	if (priv->np_txpoll || want_tx) {
1483 flush_tx:
1484 		for (i = priv->np_qfirst; i < lim_tx; i++) {
1485 			kring = &na->tx_rings[i];
1486 			/*
1487 			 * Skip the current ring if want_tx == 0
1488 			 * (we have already done a successful sync on
1489 			 * a previous ring) AND kring->cur == kring->hwcur
1490 			 * (there are no pending transmissions for this ring).
1491 			 */
1492 			if (!want_tx && kring->ring->cur == kring->nr_hwcur)
1493 				continue;
1494 			if (core_lock == NEED_CL) {
1495 				na->nm_lock(ifp, NETMAP_CORE_LOCK, 0);
1496 				core_lock = LOCKED_CL;
1497 			}
1498 			if (na->separate_locks)
1499 				na->nm_lock(ifp, NETMAP_TX_LOCK, i);
1500 			if (netmap_verbose & NM_VERB_TXSYNC)
1501 				D("send %d on %s %d",
1502 					kring->ring->cur,
1503 					ifp->if_xname, i);
1504 			if (na->nm_txsync(ifp, i, 0 /* no lock */))
1505 				revents |= POLLERR;
1506 
1507 			/* Check avail/call selrecord only if called with POLLOUT */
1508 			if (want_tx) {
1509 				if (kring->ring->avail > 0) {
1510 					/* stop at the first ring. We don't risk
1511 					 * starvation.
1512 					 */
1513 					revents |= want_tx;
1514 					want_tx = 0;
1515 				} else if (!check_all)
1516 					selrecord(td, &kring->si);
1517 			}
1518 			if (na->separate_locks)
1519 				na->nm_lock(ifp, NETMAP_TX_UNLOCK, i);
1520 		}
1521 	}
1522 
1523 	/*
1524 	 * now if want_rx is still set we need to lock and rxsync.
1525 	 * Do it on all rings because otherwise we starve.
1526 	 */
1527 	if (want_rx) {
1528 		for (i = priv->np_qfirst; i < lim_rx; i++) {
1529 			kring = &na->rx_rings[i];
1530 			if (core_lock == NEED_CL) {
1531 				na->nm_lock(ifp, NETMAP_CORE_LOCK, 0);
1532 				core_lock = LOCKED_CL;
1533 			}
1534 			if (na->separate_locks)
1535 				na->nm_lock(ifp, NETMAP_RX_LOCK, i);
1536 			if (netmap_fwd ||kring->ring->flags & NR_FORWARD) {
1537 				ND(10, "forwarding some buffers up %d to %d",
1538 				    kring->nr_hwcur, kring->ring->cur);
1539 				netmap_grab_packets(kring, &q, netmap_fwd);
1540 			}
1541 
1542 			if (na->nm_rxsync(ifp, i, 0 /* no lock */))
1543 				revents |= POLLERR;
1544 			if (netmap_no_timestamp == 0 ||
1545 					kring->ring->flags & NR_TIMESTAMP) {
1546 				microtime(&kring->ring->ts);
1547 			}
1548 
1549 			if (kring->ring->avail > 0)
1550 				revents |= want_rx;
1551 			else if (!check_all)
1552 				selrecord(td, &kring->si);
1553 			if (na->separate_locks)
1554 				na->nm_lock(ifp, NETMAP_RX_UNLOCK, i);
1555 		}
1556 	}
1557 	if (check_all && revents == 0) { /* signal on the global queue */
1558 		if (want_tx)
1559 			selrecord(td, &na->tx_si);
1560 		if (want_rx)
1561 			selrecord(td, &na->rx_si);
1562 	}
1563 
1564 	/* forward host to the netmap ring */
1565 	kring = &na->rx_rings[lim_rx];
1566 	if (kring->nr_hwavail > 0)
1567 		ND("host rx %d has %d packets", lim_rx, kring->nr_hwavail);
1568 	if ( (priv->np_qlast == NETMAP_HW_RING) // XXX check_all
1569 			&& (netmap_fwd || kring->ring->flags & NR_FORWARD)
1570 			 && kring->nr_hwavail > 0 && !host_forwarded) {
1571 		if (core_lock == NEED_CL) {
1572 			na->nm_lock(ifp, NETMAP_CORE_LOCK, 0);
1573 			core_lock = LOCKED_CL;
1574 		}
1575 		netmap_sw_to_nic(na);
1576 		host_forwarded = 1; /* prevent another pass */
1577 		want_rx = 0;
1578 		goto flush_tx;
1579 	}
1580 
1581 	if (core_lock == LOCKED_CL)
1582 		na->nm_lock(ifp, NETMAP_CORE_UNLOCK, 0);
1583 	if (q.head)
1584 		netmap_send_up(na->ifp, q.head);
1585 
1586 	return (revents);
1587 }
1588 
1589 /*------- driver support routines ------*/
1590 
1591 /*
1592  * default lock wrapper.
1593  */
1594 static void
1595 netmap_lock_wrapper(struct ifnet *dev, int what, u_int queueid)
1596 {
1597 	struct netmap_adapter *na = NA(dev);
1598 
1599 	switch (what) {
1600 #ifdef linux	/* some system do not need lock on register */
1601 	case NETMAP_REG_LOCK:
1602 	case NETMAP_REG_UNLOCK:
1603 		break;
1604 #endif /* linux */
1605 
1606 	case NETMAP_CORE_LOCK:
1607 		mtx_lock(&na->core_lock);
1608 		break;
1609 
1610 	case NETMAP_CORE_UNLOCK:
1611 		mtx_unlock(&na->core_lock);
1612 		break;
1613 
1614 	case NETMAP_TX_LOCK:
1615 		mtx_lock(&na->tx_rings[queueid].q_lock);
1616 		break;
1617 
1618 	case NETMAP_TX_UNLOCK:
1619 		mtx_unlock(&na->tx_rings[queueid].q_lock);
1620 		break;
1621 
1622 	case NETMAP_RX_LOCK:
1623 		mtx_lock(&na->rx_rings[queueid].q_lock);
1624 		break;
1625 
1626 	case NETMAP_RX_UNLOCK:
1627 		mtx_unlock(&na->rx_rings[queueid].q_lock);
1628 		break;
1629 	}
1630 }
1631 
1632 
1633 /*
1634  * Initialize a ``netmap_adapter`` object created by driver on attach.
1635  * We allocate a block of memory with room for a struct netmap_adapter
1636  * plus two sets of N+2 struct netmap_kring (where N is the number
1637  * of hardware rings):
1638  * krings	0..N-1	are for the hardware queues.
1639  * kring	N	is for the host stack queue
1640  * kring	N+1	is only used for the selinfo for all queues.
1641  * Return 0 on success, ENOMEM otherwise.
1642  *
1643  * By default the receive and transmit adapter ring counts are both initialized
1644  * to num_queues.  na->num_tx_rings can be set for cards with different tx/rx
1645  * setups.
1646  */
1647 int
1648 netmap_attach(struct netmap_adapter *arg, int num_queues)
1649 {
1650 	struct netmap_adapter *na = NULL;
1651 	struct ifnet *ifp = arg ? arg->ifp : NULL;
1652 
1653 	if (arg == NULL || ifp == NULL)
1654 		goto fail;
1655 	na = malloc(sizeof(*na), M_DEVBUF, M_NOWAIT | M_ZERO);
1656 	if (na == NULL)
1657 		goto fail;
1658 	WNA(ifp) = na;
1659 	*na = *arg; /* copy everything, trust the driver to not pass junk */
1660 	NETMAP_SET_CAPABLE(ifp);
1661 	if (na->num_tx_rings == 0)
1662 		na->num_tx_rings = num_queues;
1663 	na->num_rx_rings = num_queues;
1664 	na->refcount = na->na_single = na->na_multi = 0;
1665 	/* Core lock initialized here, others after netmap_if_new. */
1666 	mtx_init(&na->core_lock, "netmap core lock", MTX_NETWORK_LOCK, MTX_DEF);
1667 	if (na->nm_lock == NULL) {
1668 		ND("using default locks for %s", ifp->if_xname);
1669 		na->nm_lock = netmap_lock_wrapper;
1670 	}
1671 #ifdef linux
1672 	if (ifp->netdev_ops) {
1673 		ND("netdev_ops %p", ifp->netdev_ops);
1674 		/* prepare a clone of the netdev ops */
1675 		na->nm_ndo = *ifp->netdev_ops;
1676 	}
1677 	na->nm_ndo.ndo_start_xmit = linux_netmap_start;
1678 #endif
1679 	D("success for %s", ifp->if_xname);
1680 	return 0;
1681 
1682 fail:
1683 	D("fail, arg %p ifp %p na %p", arg, ifp, na);
1684 	return (na ? EINVAL : ENOMEM);
1685 }
1686 
1687 
1688 /*
1689  * Free the allocated memory linked to the given ``netmap_adapter``
1690  * object.
1691  */
1692 void
1693 netmap_detach(struct ifnet *ifp)
1694 {
1695 	struct netmap_adapter *na = NA(ifp);
1696 
1697 	if (!na)
1698 		return;
1699 
1700 	mtx_destroy(&na->core_lock);
1701 
1702 	if (na->tx_rings) { /* XXX should not happen */
1703 		D("freeing leftover tx_rings");
1704 		free(na->tx_rings, M_DEVBUF);
1705 	}
1706 	bzero(na, sizeof(*na));
1707 	WNA(ifp) = NULL;
1708 	free(na, M_DEVBUF);
1709 }
1710 
1711 
1712 /*
1713  * Intercept packets from the network stack and pass them
1714  * to netmap as incoming packets on the 'software' ring.
1715  * We are not locked when called.
1716  */
1717 int
1718 netmap_start(struct ifnet *ifp, struct mbuf *m)
1719 {
1720 	struct netmap_adapter *na = NA(ifp);
1721 	struct netmap_kring *kring = &na->rx_rings[na->num_rx_rings];
1722 	u_int i, len = MBUF_LEN(m);
1723 	u_int error = EBUSY, lim = kring->nkr_num_slots - 1;
1724 	struct netmap_slot *slot;
1725 
1726 	if (netmap_verbose & NM_VERB_HOST)
1727 		D("%s packet %d len %d from the stack", ifp->if_xname,
1728 			kring->nr_hwcur + kring->nr_hwavail, len);
1729 	na->nm_lock(ifp, NETMAP_CORE_LOCK, 0);
1730 	if (kring->nr_hwavail >= lim) {
1731 		if (netmap_verbose)
1732 			D("stack ring %s full\n", ifp->if_xname);
1733 		goto done;	/* no space */
1734 	}
1735 	if (len > NETMAP_BUF_SIZE) {
1736 		D("%s from_host, drop packet size %d > %d", ifp->if_xname,
1737 			len, NETMAP_BUF_SIZE);
1738 		goto done;	/* too long for us */
1739 	}
1740 
1741 	/* compute the insert position */
1742 	i = kring->nr_hwcur + kring->nr_hwavail;
1743 	if (i > lim)
1744 		i -= lim + 1;
1745 	slot = &kring->ring->slot[i];
1746 	m_copydata(m, 0, len, NMB(slot));
1747 	slot->len = len;
1748 	slot->flags = kring->nkr_slot_flags;
1749 	kring->nr_hwavail++;
1750 	if (netmap_verbose  & NM_VERB_HOST)
1751 		D("wake up host ring %s %d", na->ifp->if_xname, na->num_rx_rings);
1752 	selwakeuppri(&kring->si, PI_NET);
1753 	error = 0;
1754 done:
1755 	na->nm_lock(ifp, NETMAP_CORE_UNLOCK, 0);
1756 
1757 	/* release the mbuf in either cases of success or failure. As an
1758 	 * alternative, put the mbuf in a free list and free the list
1759 	 * only when really necessary.
1760 	 */
1761 	m_freem(m);
1762 
1763 	return (error);
1764 }
1765 
1766 
1767 /*
1768  * netmap_reset() is called by the driver routines when reinitializing
1769  * a ring. The driver is in charge of locking to protect the kring.
1770  * If netmap mode is not set just return NULL.
1771  */
1772 struct netmap_slot *
1773 netmap_reset(struct netmap_adapter *na, enum txrx tx, int n,
1774 	u_int new_cur)
1775 {
1776 	struct netmap_kring *kring;
1777 	int new_hwofs, lim;
1778 
1779 	if (na == NULL)
1780 		return NULL;	/* no netmap support here */
1781 	if (!(na->ifp->if_capenable & IFCAP_NETMAP))
1782 		return NULL;	/* nothing to reinitialize */
1783 
1784 	if (tx == NR_TX) {
1785 		if (n >= na->num_tx_rings)
1786 			return NULL;
1787 		kring = na->tx_rings + n;
1788 		new_hwofs = kring->nr_hwcur - new_cur;
1789 	} else {
1790 		if (n >= na->num_rx_rings)
1791 			return NULL;
1792 		kring = na->rx_rings + n;
1793 		new_hwofs = kring->nr_hwcur + kring->nr_hwavail - new_cur;
1794 	}
1795 	lim = kring->nkr_num_slots - 1;
1796 	if (new_hwofs > lim)
1797 		new_hwofs -= lim + 1;
1798 
1799 	/* Alwayws set the new offset value and realign the ring. */
1800 	kring->nkr_hwofs = new_hwofs;
1801 	if (tx == NR_TX)
1802 		kring->nr_hwavail = kring->nkr_num_slots - 1;
1803 	ND(10, "new hwofs %d on %s %s[%d]",
1804 			kring->nkr_hwofs, na->ifp->if_xname,
1805 			tx == NR_TX ? "TX" : "RX", n);
1806 
1807 #if 0 // def linux
1808 	/* XXX check that the mappings are correct */
1809 	/* need ring_nr, adapter->pdev, direction */
1810 	buffer_info->dma = dma_map_single(&pdev->dev, addr, adapter->rx_buffer_len, DMA_FROM_DEVICE);
1811 	if (dma_mapping_error(&adapter->pdev->dev, buffer_info->dma)) {
1812 		D("error mapping rx netmap buffer %d", i);
1813 		// XXX fix error handling
1814 	}
1815 
1816 #endif /* linux */
1817 	/*
1818 	 * Wakeup on the individual and global lock
1819 	 * We do the wakeup here, but the ring is not yet reconfigured.
1820 	 * However, we are under lock so there are no races.
1821 	 */
1822 	selwakeuppri(&kring->si, PI_NET);
1823 	selwakeuppri(tx == NR_TX ? &na->tx_si : &na->rx_si, PI_NET);
1824 	return kring->ring->slot;
1825 }
1826 
1827 
1828 /*
1829  * Default functions to handle rx/tx interrupts
1830  * we have 4 cases:
1831  * 1 ring, single lock:
1832  *	lock(core); wake(i=0); unlock(core)
1833  * N rings, single lock:
1834  *	lock(core); wake(i); wake(N+1) unlock(core)
1835  * 1 ring, separate locks: (i=0)
1836  *	lock(i); wake(i); unlock(i)
1837  * N rings, separate locks:
1838  *	lock(i); wake(i); unlock(i); lock(core) wake(N+1) unlock(core)
1839  * work_done is non-null on the RX path.
1840  */
1841 int
1842 netmap_rx_irq(struct ifnet *ifp, int q, int *work_done)
1843 {
1844 	struct netmap_adapter *na;
1845 	struct netmap_kring *r;
1846 	NM_SELINFO_T *main_wq;
1847 
1848 	if (!(ifp->if_capenable & IFCAP_NETMAP))
1849 		return 0;
1850 	ND(5, "received %s queue %d", work_done ? "RX" : "TX" , q);
1851 	na = NA(ifp);
1852 	if (na->na_flags & NAF_SKIP_INTR) {
1853 		ND("use regular interrupt");
1854 		return 0;
1855 	}
1856 
1857 	if (work_done) { /* RX path */
1858 		if (q >= na->num_rx_rings)
1859 			return 0;	// regular queue
1860 		r = na->rx_rings + q;
1861 		r->nr_kflags |= NKR_PENDINTR;
1862 		main_wq = (na->num_rx_rings > 1) ? &na->rx_si : NULL;
1863 	} else { /* tx path */
1864 		if (q >= na->num_tx_rings)
1865 			return 0;	// regular queue
1866 		r = na->tx_rings + q;
1867 		main_wq = (na->num_tx_rings > 1) ? &na->tx_si : NULL;
1868 		work_done = &q; /* dummy */
1869 	}
1870 	if (na->separate_locks) {
1871 		mtx_lock(&r->q_lock);
1872 		selwakeuppri(&r->si, PI_NET);
1873 		mtx_unlock(&r->q_lock);
1874 		if (main_wq) {
1875 			mtx_lock(&na->core_lock);
1876 			selwakeuppri(main_wq, PI_NET);
1877 			mtx_unlock(&na->core_lock);
1878 		}
1879 	} else {
1880 		mtx_lock(&na->core_lock);
1881 		selwakeuppri(&r->si, PI_NET);
1882 		if (main_wq)
1883 			selwakeuppri(main_wq, PI_NET);
1884 		mtx_unlock(&na->core_lock);
1885 	}
1886 	*work_done = 1; /* do not fire napi again */
1887 	return 1;
1888 }
1889 
1890 
1891 #ifdef linux	/* linux-specific routines */
1892 
1893 /*
1894  * Remap linux arguments into the FreeBSD call.
1895  * - pwait is the poll table, passed as 'dev';
1896  *   If pwait == NULL someone else already woke up before. We can report
1897  *   events but they are filtered upstream.
1898  *   If pwait != NULL, then pwait->key contains the list of events.
1899  * - events is computed from pwait as above.
1900  * - file is passed as 'td';
1901  */
1902 static u_int
1903 linux_netmap_poll(struct file * file, struct poll_table_struct *pwait)
1904 {
1905 #if LINUX_VERSION_CODE < KERNEL_VERSION(3,4,0)
1906 	int events = pwait ? pwait->key : POLLIN | POLLOUT;
1907 #else /* in 3.4.0 field 'key' was renamed to '_key' */
1908 	int events = pwait ? pwait->_key : POLLIN | POLLOUT;
1909 #endif
1910 	return netmap_poll((void *)pwait, events, (void *)file);
1911 }
1912 
1913 static int
1914 linux_netmap_mmap(struct file *f, struct vm_area_struct *vma)
1915 {
1916 	int lut_skip, i, j;
1917 	int user_skip = 0;
1918 	struct lut_entry *l_entry;
1919 	int error = 0;
1920 	unsigned long off, tomap;
1921 	/*
1922 	 * vma->vm_start: start of mapping user address space
1923 	 * vma->vm_end: end of the mapping user address space
1924 	 * vma->vm_pfoff: offset of first page in the device
1925 	 */
1926 
1927 	// XXX security checks
1928 
1929 	error = netmap_get_memory(f->private_data);
1930 	ND("get_memory returned %d", error);
1931 	if (error)
1932 	    return -error;
1933 
1934 	off = vma->vm_pgoff << PAGE_SHIFT; /* offset in bytes */
1935 	tomap = vma->vm_end - vma->vm_start;
1936 	for (i = 0; i < NETMAP_POOLS_NR; i++) {  /* loop through obj_pools */
1937 		const struct netmap_obj_pool *p = &nm_mem.pools[i];
1938 		/*
1939 		 * In each pool memory is allocated in clusters
1940 		 * of size _clustsize, each containing clustentries
1941 		 * entries. For each object k we already store the
1942 		 * vtophys mapping in lut[k] so we use that, scanning
1943 		 * the lut[] array in steps of clustentries,
1944 		 * and we map each cluster (not individual pages,
1945 		 * it would be overkill).
1946 		 */
1947 
1948 		/*
1949 		 * We interpret vm_pgoff as an offset into the whole
1950 		 * netmap memory, as if all clusters where contiguous.
1951 		 */
1952 		for (lut_skip = 0, j = 0; j < p->_numclusters; j++, lut_skip += p->clustentries) {
1953 			unsigned long paddr, mapsize;
1954 			if (p->_clustsize <= off) {
1955 				off -= p->_clustsize;
1956 				continue;
1957 			}
1958 			l_entry = &p->lut[lut_skip]; /* first obj in the cluster */
1959 			paddr = l_entry->paddr + off;
1960 			mapsize = p->_clustsize - off;
1961 			off = 0;
1962 			if (mapsize > tomap)
1963 				mapsize = tomap;
1964 			ND("remap_pfn_range(%lx, %lx, %lx)",
1965 				vma->vm_start + user_skip,
1966 				paddr >> PAGE_SHIFT, mapsize);
1967 			if (remap_pfn_range(vma, vma->vm_start + user_skip,
1968 					paddr >> PAGE_SHIFT, mapsize,
1969 					vma->vm_page_prot))
1970 				return -EAGAIN; // XXX check return value
1971 			user_skip += mapsize;
1972 			tomap -= mapsize;
1973 			if (tomap == 0)
1974 				goto done;
1975 		}
1976 	}
1977 done:
1978 
1979 	return 0;
1980 }
1981 
1982 static netdev_tx_t
1983 linux_netmap_start(struct sk_buff *skb, struct net_device *dev)
1984 {
1985 	netmap_start(dev, skb);
1986 	return (NETDEV_TX_OK);
1987 }
1988 
1989 
1990 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,37)	// XXX was 38
1991 #define LIN_IOCTL_NAME	.ioctl
1992 int
1993 linux_netmap_ioctl(struct inode *inode, struct file *file, u_int cmd, u_long data /* arg */)
1994 #else
1995 #define LIN_IOCTL_NAME	.unlocked_ioctl
1996 long
1997 linux_netmap_ioctl(struct file *file, u_int cmd, u_long data /* arg */)
1998 #endif
1999 {
2000 	int ret;
2001 	struct nmreq nmr;
2002 	bzero(&nmr, sizeof(nmr));
2003 
2004 	if (data && copy_from_user(&nmr, (void *)data, sizeof(nmr) ) != 0)
2005 		return -EFAULT;
2006 	ret = netmap_ioctl(NULL, cmd, (caddr_t)&nmr, 0, (void *)file);
2007 	if (data && copy_to_user((void*)data, &nmr, sizeof(nmr) ) != 0)
2008 		return -EFAULT;
2009 	return -ret;
2010 }
2011 
2012 
2013 static int
2014 netmap_release(struct inode *inode, struct file *file)
2015 {
2016 	(void)inode;	/* UNUSED */
2017 	if (file->private_data)
2018 		netmap_dtor(file->private_data);
2019 	return (0);
2020 }
2021 
2022 static int
2023 linux_netmap_open(struct inode *inode, struct file *file)
2024 {
2025 	struct netmap_priv_d *priv;
2026 	(void)inode;	/* UNUSED */
2027 
2028 	priv = malloc(sizeof(struct netmap_priv_d), M_DEVBUF,
2029 			      M_NOWAIT | M_ZERO);
2030 	if (priv == NULL)
2031 		return -ENOMEM;
2032 
2033 	file->private_data = priv;
2034 
2035 	return (0);
2036 }
2037 
2038 static struct file_operations netmap_fops = {
2039     .open = linux_netmap_open,
2040     .mmap = linux_netmap_mmap,
2041     LIN_IOCTL_NAME = linux_netmap_ioctl,
2042     .poll = linux_netmap_poll,
2043     .release = netmap_release,
2044 };
2045 
2046 static struct miscdevice netmap_cdevsw = {	/* same name as FreeBSD */
2047 	MISC_DYNAMIC_MINOR,
2048 	"netmap",
2049 	&netmap_fops,
2050 };
2051 
2052 static int netmap_init(void);
2053 static void netmap_fini(void);
2054 
2055 /* Errors have negative values on linux */
2056 static int linux_netmap_init(void)
2057 {
2058 	return -netmap_init();
2059 }
2060 
2061 module_init(linux_netmap_init);
2062 module_exit(netmap_fini);
2063 /* export certain symbols to other modules */
2064 EXPORT_SYMBOL(netmap_attach);		// driver attach routines
2065 EXPORT_SYMBOL(netmap_detach);		// driver detach routines
2066 EXPORT_SYMBOL(netmap_ring_reinit);	// ring init on error
2067 EXPORT_SYMBOL(netmap_buffer_lut);
2068 EXPORT_SYMBOL(netmap_total_buffers);	// index check
2069 EXPORT_SYMBOL(netmap_buffer_base);
2070 EXPORT_SYMBOL(netmap_reset);		// ring init routines
2071 EXPORT_SYMBOL(netmap_buf_size);
2072 EXPORT_SYMBOL(netmap_rx_irq);		// default irq handler
2073 EXPORT_SYMBOL(netmap_no_pendintr);	// XXX mitigation - should go away
2074 
2075 
2076 MODULE_AUTHOR("http://info.iet.unipi.it/~luigi/netmap/");
2077 MODULE_DESCRIPTION("The netmap packet I/O framework");
2078 MODULE_LICENSE("Dual BSD/GPL"); /* the code here is all BSD. */
2079 
2080 #else /* __FreeBSD__ */
2081 
2082 static struct cdevsw netmap_cdevsw = {
2083 	.d_version = D_VERSION,
2084 	.d_name = "netmap",
2085 	.d_open = netmap_open,
2086 	.d_mmap = netmap_mmap,
2087 	.d_mmap_single = netmap_mmap_single,
2088 	.d_ioctl = netmap_ioctl,
2089 	.d_poll = netmap_poll,
2090 	.d_close = netmap_close,
2091 };
2092 #endif /* __FreeBSD__ */
2093 
2094 #ifdef NM_BRIDGE
2095 /*
2096  *---- support for virtual bridge -----
2097  */
2098 
2099 /* ----- FreeBSD if_bridge hash function ------- */
2100 
2101 /*
2102  * The following hash function is adapted from "Hash Functions" by Bob Jenkins
2103  * ("Algorithm Alley", Dr. Dobbs Journal, September 1997).
2104  *
2105  * http://www.burtleburtle.net/bob/hash/spooky.html
2106  */
2107 #define mix(a, b, c)                                                    \
2108 do {                                                                    \
2109         a -= b; a -= c; a ^= (c >> 13);                                 \
2110         b -= c; b -= a; b ^= (a << 8);                                  \
2111         c -= a; c -= b; c ^= (b >> 13);                                 \
2112         a -= b; a -= c; a ^= (c >> 12);                                 \
2113         b -= c; b -= a; b ^= (a << 16);                                 \
2114         c -= a; c -= b; c ^= (b >> 5);                                  \
2115         a -= b; a -= c; a ^= (c >> 3);                                  \
2116         b -= c; b -= a; b ^= (a << 10);                                 \
2117         c -= a; c -= b; c ^= (b >> 15);                                 \
2118 } while (/*CONSTCOND*/0)
2119 
2120 static __inline uint32_t
2121 nm_bridge_rthash(const uint8_t *addr)
2122 {
2123         uint32_t a = 0x9e3779b9, b = 0x9e3779b9, c = 0; // hask key
2124 
2125         b += addr[5] << 8;
2126         b += addr[4];
2127         a += addr[3] << 24;
2128         a += addr[2] << 16;
2129         a += addr[1] << 8;
2130         a += addr[0];
2131 
2132         mix(a, b, c);
2133 #define BRIDGE_RTHASH_MASK	(NM_BDG_HASH-1)
2134         return (c & BRIDGE_RTHASH_MASK);
2135 }
2136 
2137 #undef mix
2138 
2139 
2140 static int
2141 bdg_netmap_reg(struct ifnet *ifp, int onoff)
2142 {
2143 	int i, err = 0;
2144 	struct nm_bridge *b = ifp->if_bridge;
2145 
2146 	BDG_LOCK(b);
2147 	if (onoff) {
2148 		/* the interface must be already in the list.
2149 		 * only need to mark the port as active
2150 		 */
2151 		ND("should attach %s to the bridge", ifp->if_xname);
2152 		for (i=0; i < NM_BDG_MAXPORTS; i++)
2153 			if (b->bdg_ports[i] == ifp)
2154 				break;
2155 		if (i == NM_BDG_MAXPORTS) {
2156 			D("no more ports available");
2157 			err = EINVAL;
2158 			goto done;
2159 		}
2160 		ND("setting %s in netmap mode", ifp->if_xname);
2161 		ifp->if_capenable |= IFCAP_NETMAP;
2162 		NA(ifp)->bdg_port = i;
2163 		b->act_ports |= (1<<i);
2164 		b->bdg_ports[i] = ifp;
2165 	} else {
2166 		/* should be in the list, too -- remove from the mask */
2167 		ND("removing %s from netmap mode", ifp->if_xname);
2168 		ifp->if_capenable &= ~IFCAP_NETMAP;
2169 		i = NA(ifp)->bdg_port;
2170 		b->act_ports &= ~(1<<i);
2171 	}
2172 done:
2173 	BDG_UNLOCK(b);
2174 	return err;
2175 }
2176 
2177 
2178 static int
2179 nm_bdg_flush(struct nm_bdg_fwd *ft, int n, struct ifnet *ifp)
2180 {
2181 	int i, ifn;
2182 	uint64_t all_dst, dst;
2183 	uint32_t sh, dh;
2184 	uint64_t mysrc = 1 << NA(ifp)->bdg_port;
2185 	uint64_t smac, dmac;
2186 	struct netmap_slot *slot;
2187 	struct nm_bridge *b = ifp->if_bridge;
2188 
2189 	ND("prepare to send %d packets, act_ports 0x%x", n, b->act_ports);
2190 	/* only consider valid destinations */
2191 	all_dst = (b->act_ports & ~mysrc);
2192 	/* first pass: hash and find destinations */
2193 	for (i = 0; likely(i < n); i++) {
2194 		uint8_t *buf = ft[i].buf;
2195 		dmac = le64toh(*(uint64_t *)(buf)) & 0xffffffffffff;
2196 		smac = le64toh(*(uint64_t *)(buf + 4));
2197 		smac >>= 16;
2198 		if (unlikely(netmap_verbose)) {
2199 		    uint8_t *s = buf+6, *d = buf;
2200 		    D("%d len %4d %02x:%02x:%02x:%02x:%02x:%02x -> %02x:%02x:%02x:%02x:%02x:%02x",
2201 			i,
2202 			ft[i].len,
2203 			s[0], s[1], s[2], s[3], s[4], s[5],
2204 			d[0], d[1], d[2], d[3], d[4], d[5]);
2205 		}
2206 		/*
2207 		 * The hash is somewhat expensive, there might be some
2208 		 * worthwhile optimizations here.
2209 		 */
2210 		if ((buf[6] & 1) == 0) { /* valid src */
2211 		    	uint8_t *s = buf+6;
2212 			sh = nm_bridge_rthash(buf+6); // XXX hash of source
2213 			/* update source port forwarding entry */
2214 			b->ht[sh].mac = smac;	/* XXX expire ? */
2215 			b->ht[sh].ports = mysrc;
2216 			if (netmap_verbose)
2217 			    D("src %02x:%02x:%02x:%02x:%02x:%02x on port %d",
2218 				s[0], s[1], s[2], s[3], s[4], s[5], NA(ifp)->bdg_port);
2219 		}
2220 		dst = 0;
2221 		if ( (buf[0] & 1) == 0) { /* unicast */
2222 		    	uint8_t *d = buf;
2223 			dh = nm_bridge_rthash(buf); // XXX hash of dst
2224 			if (b->ht[dh].mac == dmac) {	/* found dst */
2225 				dst = b->ht[dh].ports;
2226 				if (netmap_verbose)
2227 				    D("dst %02x:%02x:%02x:%02x:%02x:%02x to port %x",
2228 					d[0], d[1], d[2], d[3], d[4], d[5], (uint32_t)(dst >> 16));
2229 			}
2230 		}
2231 		if (dst == 0)
2232 			dst = all_dst;
2233 		dst &= all_dst; /* only consider valid ports */
2234 		if (unlikely(netmap_verbose))
2235 			D("pkt goes to ports 0x%x", (uint32_t)dst);
2236 		ft[i].dst = dst;
2237 	}
2238 
2239 	/* second pass, scan interfaces and forward */
2240 	all_dst = (b->act_ports & ~mysrc);
2241 	for (ifn = 0; all_dst; ifn++) {
2242 		struct ifnet *dst_ifp = b->bdg_ports[ifn];
2243 		struct netmap_adapter *na;
2244 		struct netmap_kring *kring;
2245 		struct netmap_ring *ring;
2246 		int j, lim, sent, locked;
2247 
2248 		if (!dst_ifp)
2249 			continue;
2250 		ND("scan port %d %s", ifn, dst_ifp->if_xname);
2251 		dst = 1 << ifn;
2252 		if ((dst & all_dst) == 0)	/* skip if not set */
2253 			continue;
2254 		all_dst &= ~dst;	/* clear current node */
2255 		na = NA(dst_ifp);
2256 
2257 		ring = NULL;
2258 		kring = NULL;
2259 		lim = sent = locked = 0;
2260 		/* inside, scan slots */
2261 		for (i = 0; likely(i < n); i++) {
2262 			if ((ft[i].dst & dst) == 0)
2263 				continue;	/* not here */
2264 			if (!locked) {
2265 				kring = &na->rx_rings[0];
2266 				ring = kring->ring;
2267 				lim = kring->nkr_num_slots - 1;
2268 				na->nm_lock(dst_ifp, NETMAP_RX_LOCK, 0);
2269 				locked = 1;
2270 			}
2271 			if (unlikely(kring->nr_hwavail >= lim)) {
2272 				if (netmap_verbose)
2273 					D("rx ring full on %s", ifp->if_xname);
2274 				break;
2275 			}
2276 			j = kring->nr_hwcur + kring->nr_hwavail;
2277 			if (j > lim)
2278 				j -= kring->nkr_num_slots;
2279 			slot = &ring->slot[j];
2280 			ND("send %d %d bytes at %s:%d", i, ft[i].len, dst_ifp->if_xname, j);
2281 			pkt_copy(ft[i].buf, NMB(slot), ft[i].len);
2282 			slot->len = ft[i].len;
2283 			kring->nr_hwavail++;
2284 			sent++;
2285 		}
2286 		if (locked) {
2287 			ND("sent %d on %s", sent, dst_ifp->if_xname);
2288 			if (sent)
2289 				selwakeuppri(&kring->si, PI_NET);
2290 			na->nm_lock(dst_ifp, NETMAP_RX_UNLOCK, 0);
2291 		}
2292 	}
2293 	return 0;
2294 }
2295 
2296 /*
2297  * main dispatch routine
2298  */
2299 static int
2300 bdg_netmap_txsync(struct ifnet *ifp, u_int ring_nr, int do_lock)
2301 {
2302 	struct netmap_adapter *na = NA(ifp);
2303 	struct netmap_kring *kring = &na->tx_rings[ring_nr];
2304 	struct netmap_ring *ring = kring->ring;
2305 	int i, j, k, lim = kring->nkr_num_slots - 1;
2306 	struct nm_bdg_fwd *ft = (struct nm_bdg_fwd *)(ifp + 1);
2307 	int ft_i;	/* position in the forwarding table */
2308 
2309 	k = ring->cur;
2310 	if (k > lim)
2311 		return netmap_ring_reinit(kring);
2312 	if (do_lock)
2313 		na->nm_lock(ifp, NETMAP_TX_LOCK, ring_nr);
2314 
2315 	if (netmap_bridge <= 0) { /* testing only */
2316 		j = k; // used all
2317 		goto done;
2318 	}
2319 	if (netmap_bridge > NM_BDG_BATCH)
2320 		netmap_bridge = NM_BDG_BATCH;
2321 
2322 	ft_i = 0;	/* start from 0 */
2323 	for (j = kring->nr_hwcur; likely(j != k); j = unlikely(j == lim) ? 0 : j+1) {
2324 		struct netmap_slot *slot = &ring->slot[j];
2325 		int len = ft[ft_i].len = slot->len;
2326 		char *buf = ft[ft_i].buf = NMB(slot);
2327 
2328 		prefetch(buf);
2329 		if (unlikely(len < 14))
2330 			continue;
2331 		if (unlikely(++ft_i == netmap_bridge))
2332 			ft_i = nm_bdg_flush(ft, ft_i, ifp);
2333 	}
2334 	if (ft_i)
2335 		ft_i = nm_bdg_flush(ft, ft_i, ifp);
2336 	/* count how many packets we sent */
2337 	i = k - j;
2338 	if (i < 0)
2339 		i += kring->nkr_num_slots;
2340 	kring->nr_hwavail = kring->nkr_num_slots - 1 - i;
2341 	if (j != k)
2342 		D("early break at %d/ %d, avail %d", j, k, kring->nr_hwavail);
2343 
2344 done:
2345 	kring->nr_hwcur = j;
2346 	ring->avail = kring->nr_hwavail;
2347 	if (do_lock)
2348 		na->nm_lock(ifp, NETMAP_TX_UNLOCK, ring_nr);
2349 
2350 	if (netmap_verbose)
2351 		D("%s ring %d lock %d", ifp->if_xname, ring_nr, do_lock);
2352 	return 0;
2353 }
2354 
2355 static int
2356 bdg_netmap_rxsync(struct ifnet *ifp, u_int ring_nr, int do_lock)
2357 {
2358 	struct netmap_adapter *na = NA(ifp);
2359 	struct netmap_kring *kring = &na->rx_rings[ring_nr];
2360 	struct netmap_ring *ring = kring->ring;
2361 	u_int j, n, lim = kring->nkr_num_slots - 1;
2362 	u_int k = ring->cur, resvd = ring->reserved;
2363 
2364 	ND("%s ring %d lock %d avail %d",
2365 		ifp->if_xname, ring_nr, do_lock, kring->nr_hwavail);
2366 
2367 	if (k > lim)
2368 		return netmap_ring_reinit(kring);
2369 	if (do_lock)
2370 		na->nm_lock(ifp, NETMAP_RX_LOCK, ring_nr);
2371 
2372 	/* skip past packets that userspace has released */
2373 	j = kring->nr_hwcur;    /* netmap ring index */
2374 	if (resvd > 0) {
2375 		if (resvd + ring->avail >= lim + 1) {
2376 			D("XXX invalid reserve/avail %d %d", resvd, ring->avail);
2377 			ring->reserved = resvd = 0; // XXX panic...
2378 		}
2379 		k = (k >= resvd) ? k - resvd : k + lim + 1 - resvd;
2380 	}
2381 
2382 	if (j != k) { /* userspace has released some packets. */
2383 		n = k - j;
2384 		if (n < 0)
2385 			n += kring->nkr_num_slots;
2386 		ND("userspace releases %d packets", n);
2387                 for (n = 0; likely(j != k); n++) {
2388                         struct netmap_slot *slot = &ring->slot[j];
2389                         void *addr = NMB(slot);
2390 
2391                         if (addr == netmap_buffer_base) { /* bad buf */
2392                                 if (do_lock)
2393                                         na->nm_lock(ifp, NETMAP_RX_UNLOCK, ring_nr);
2394                                 return netmap_ring_reinit(kring);
2395                         }
2396 			/* decrease refcount for buffer */
2397 
2398 			slot->flags &= ~NS_BUF_CHANGED;
2399                         j = unlikely(j == lim) ? 0 : j + 1;
2400                 }
2401                 kring->nr_hwavail -= n;
2402                 kring->nr_hwcur = k;
2403         }
2404         /* tell userspace that there are new packets */
2405         ring->avail = kring->nr_hwavail - resvd;
2406 
2407 	if (do_lock)
2408 		na->nm_lock(ifp, NETMAP_RX_UNLOCK, ring_nr);
2409 	return 0;
2410 }
2411 
2412 static void
2413 bdg_netmap_attach(struct ifnet *ifp)
2414 {
2415 	struct netmap_adapter na;
2416 
2417 	ND("attaching virtual bridge");
2418 	bzero(&na, sizeof(na));
2419 
2420 	na.ifp = ifp;
2421 	na.separate_locks = 1;
2422 	na.num_tx_desc = NM_BRIDGE_RINGSIZE;
2423 	na.num_rx_desc = NM_BRIDGE_RINGSIZE;
2424 	na.nm_txsync = bdg_netmap_txsync;
2425 	na.nm_rxsync = bdg_netmap_rxsync;
2426 	na.nm_register = bdg_netmap_reg;
2427 	netmap_attach(&na, 1);
2428 }
2429 
2430 #endif /* NM_BRIDGE */
2431 
2432 static struct cdev *netmap_dev; /* /dev/netmap character device. */
2433 
2434 
2435 /*
2436  * Module loader.
2437  *
2438  * Create the /dev/netmap device and initialize all global
2439  * variables.
2440  *
2441  * Return 0 on success, errno on failure.
2442  */
2443 static int
2444 netmap_init(void)
2445 {
2446 	int error;
2447 
2448 	error = netmap_memory_init();
2449 	if (error != 0) {
2450 		printf("netmap: unable to initialize the memory allocator.\n");
2451 		return (error);
2452 	}
2453 	printf("netmap: loaded module\n");
2454 	netmap_dev = make_dev(&netmap_cdevsw, 0, UID_ROOT, GID_WHEEL, 0660,
2455 			      "netmap");
2456 
2457 #ifdef NM_BRIDGE
2458 	{
2459 	int i;
2460 	for (i = 0; i < NM_BRIDGES; i++)
2461 		mtx_init(&nm_bridges[i].bdg_lock, "bdg lock", "bdg_lock", MTX_DEF);
2462 	}
2463 #endif
2464 	return (error);
2465 }
2466 
2467 
2468 /*
2469  * Module unloader.
2470  *
2471  * Free all the memory, and destroy the ``/dev/netmap`` device.
2472  */
2473 static void
2474 netmap_fini(void)
2475 {
2476 	destroy_dev(netmap_dev);
2477 	netmap_memory_fini();
2478 	printf("netmap: unloaded module.\n");
2479 }
2480 
2481 
2482 #ifdef __FreeBSD__
2483 /*
2484  * Kernel entry point.
2485  *
2486  * Initialize/finalize the module and return.
2487  *
2488  * Return 0 on success, errno on failure.
2489  */
2490 static int
2491 netmap_loader(__unused struct module *module, int event, __unused void *arg)
2492 {
2493 	int error = 0;
2494 
2495 	switch (event) {
2496 	case MOD_LOAD:
2497 		error = netmap_init();
2498 		break;
2499 
2500 	case MOD_UNLOAD:
2501 		netmap_fini();
2502 		break;
2503 
2504 	default:
2505 		error = EOPNOTSUPP;
2506 		break;
2507 	}
2508 
2509 	return (error);
2510 }
2511 
2512 
2513 DEV_MODULE(netmap, netmap_loader, NULL);
2514 #endif /* __FreeBSD__ */
2515