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