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