xref: /freebsd/sys/dev/netmap/netmap.c (revision 9a14aa017b21c292740c00ee098195cd46642730)
1 /*
2  * Copyright (C) 2011 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 /*
27  * $FreeBSD$
28  * $Id: netmap.c 9795 2011-12-02 11:39:08Z luigi $
29  *
30  * This module supports memory mapped access to network devices,
31  * see netmap(4).
32  *
33  * The module uses a large, memory pool allocated by the kernel
34  * and accessible as mmapped memory by multiple userspace threads/processes.
35  * The memory pool contains packet buffers and "netmap rings",
36  * i.e. user-accessible copies of the interface's queues.
37  *
38  * Access to the network card works like this:
39  * 1. a process/thread issues one or more open() on /dev/netmap, to create
40  *    select()able file descriptor on which events are reported.
41  * 2. on each descriptor, the process issues an ioctl() to identify
42  *    the interface that should report events to the file descriptor.
43  * 3. on each descriptor, the process issues an mmap() request to
44  *    map the shared memory region within the process' address space.
45  *    The list of interesting queues is indicated by a location in
46  *    the shared memory region.
47  * 4. using the functions in the netmap(4) userspace API, a process
48  *    can look up the occupation state of a queue, access memory buffers,
49  *    and retrieve received packets or enqueue packets to transmit.
50  * 5. using some ioctl()s the process can synchronize the userspace view
51  *    of the queue with the actual status in the kernel. This includes both
52  *    receiving the notification of new packets, and transmitting new
53  *    packets on the output interface.
54  * 6. select() or poll() can be used to wait for events on individual
55  *    transmit or receive queues (or all queues for a given interface).
56  */
57 
58 #include <sys/cdefs.h> /* prerequisite */
59 __FBSDID("$FreeBSD$");
60 
61 #include <sys/types.h>
62 #include <sys/module.h>
63 #include <sys/errno.h>
64 #include <sys/param.h>	/* defines used in kernel.h */
65 #include <sys/jail.h>
66 #include <sys/kernel.h>	/* types used in module initialization */
67 #include <sys/conf.h>	/* cdevsw struct */
68 #include <sys/uio.h>	/* uio struct */
69 #include <sys/sockio.h>
70 #include <sys/socketvar.h>	/* struct socket */
71 #include <sys/malloc.h>
72 #include <sys/mman.h>	/* PROT_EXEC */
73 #include <sys/poll.h>
74 #include <sys/proc.h>
75 #include <vm/vm.h>	/* vtophys */
76 #include <vm/pmap.h>	/* vtophys */
77 #include <sys/socket.h> /* sockaddrs */
78 #include <machine/bus.h>
79 #include <sys/selinfo.h>
80 #include <sys/sysctl.h>
81 #include <net/if.h>
82 #include <net/bpf.h>		/* BIOCIMMEDIATE */
83 #include <net/vnet.h>
84 #include <net/netmap.h>
85 #include <dev/netmap/netmap_kern.h>
86 #include <machine/bus.h>	/* bus_dmamap_* */
87 
88 MALLOC_DEFINE(M_NETMAP, "netmap", "Network memory map");
89 
90 /*
91  * lock and unlock for the netmap memory allocator
92  */
93 #define NMA_LOCK()	mtx_lock(&netmap_mem_d->nm_mtx);
94 #define NMA_UNLOCK()	mtx_unlock(&netmap_mem_d->nm_mtx);
95 
96 /*
97  * Default amount of memory pre-allocated by the module.
98  * We start with a large size and then shrink our demand
99  * according to what is avalable when the module is loaded.
100  * At the moment the block is contiguous, but we can easily
101  * restrict our demand to smaller units (16..64k)
102  */
103 #define NETMAP_MEMORY_SIZE (64 * 1024 * PAGE_SIZE)
104 static void * netmap_malloc(size_t size, const char *msg);
105 static void netmap_free(void *addr, const char *msg);
106 
107 #define netmap_if_malloc(len)   netmap_malloc(len, "nifp")
108 #define netmap_if_free(v)	netmap_free((v), "nifp")
109 
110 #define netmap_ring_malloc(len) netmap_malloc(len, "ring")
111 #define netmap_free_rings(na)		\
112 	netmap_free((na)->tx_rings[0].ring, "shadow rings");
113 
114 /*
115  * Allocator for a pool of packet buffers. For each buffer we have
116  * one entry in the bitmap to signal the state. Allocation scans
117  * the bitmap, but since this is done only on attach, we are not
118  * too worried about performance
119  * XXX if we need to allocate small blocks, a translation
120  * table is used both for kernel virtual address and physical
121  * addresses.
122  */
123 struct netmap_buf_pool {
124 	u_int total_buffers;	/* total buffers. */
125 	u_int free;
126 	u_int bufsize;
127 	char *base;		/* buffer base address */
128 	uint32_t *bitmap;	/* one bit per buffer, 1 means free */
129 };
130 struct netmap_buf_pool nm_buf_pool;
131 /* XXX move these two vars back into netmap_buf_pool */
132 u_int netmap_total_buffers;
133 char *netmap_buffer_base;	/* address of an invalid buffer */
134 
135 /* user-controlled variables */
136 int netmap_verbose;
137 
138 static int no_timestamp; /* don't timestamp on rxsync */
139 
140 SYSCTL_NODE(_dev, OID_AUTO, netmap, CTLFLAG_RW, 0, "Netmap args");
141 SYSCTL_INT(_dev_netmap, OID_AUTO, verbose,
142     CTLFLAG_RW, &netmap_verbose, 0, "Verbose mode");
143 SYSCTL_INT(_dev_netmap, OID_AUTO, no_timestamp,
144     CTLFLAG_RW, &no_timestamp, 0, "no_timestamp");
145 SYSCTL_INT(_dev_netmap, OID_AUTO, total_buffers,
146     CTLFLAG_RD, &nm_buf_pool.total_buffers, 0, "total_buffers");
147 SYSCTL_INT(_dev_netmap, OID_AUTO, free_buffers,
148     CTLFLAG_RD, &nm_buf_pool.free, 0, "free_buffers");
149 
150 /*
151  * Allocate n buffers from the ring, and fill the slot.
152  * Buffer 0 is the 'junk' buffer.
153  */
154 static void
155 netmap_new_bufs(struct netmap_if *nifp __unused,
156 		struct netmap_slot *slot, u_int n)
157 {
158 	struct netmap_buf_pool *p = &nm_buf_pool;
159 	uint32_t bi = 0;		/* index in the bitmap */
160 	uint32_t mask, j, i = 0;	/* slot counter */
161 
162 	if (n > p->free) {
163 		D("only %d out of %d buffers available", i, n);
164 		return;
165 	}
166 	/* termination is guaranteed by p->free */
167 	while (i < n && p->free > 0) {
168 		uint32_t cur = p->bitmap[bi];
169 		if (cur == 0) { /* bitmask is fully used */
170 			bi++;
171 			continue;
172 		}
173 		/* locate a slot */
174 		for (j = 0, mask = 1; (cur & mask) == 0; j++, mask <<= 1) ;
175 		p->bitmap[bi] &= ~mask;		/* slot in use */
176 		p->free--;
177 		slot[i].buf_idx = bi*32+j;
178 		slot[i].len = p->bufsize;
179 		slot[i].flags = NS_BUF_CHANGED;
180 		i++;
181 	}
182 	ND("allocated %d buffers, %d available", n, p->free);
183 }
184 
185 
186 static void
187 netmap_free_buf(struct netmap_if *nifp __unused, uint32_t i)
188 {
189 	struct netmap_buf_pool *p = &nm_buf_pool;
190 
191 	uint32_t pos, mask;
192 	if (i >= p->total_buffers) {
193 		D("invalid free index %d", i);
194 		return;
195 	}
196 	pos = i / 32;
197 	mask = 1 << (i % 32);
198 	if (p->bitmap[pos] & mask) {
199 		D("slot %d already free", i);
200 		return;
201 	}
202 	p->bitmap[pos] |= mask;
203 	p->free++;
204 }
205 
206 
207 /* Descriptor of the memory objects handled by our memory allocator. */
208 struct netmap_mem_obj {
209 	TAILQ_ENTRY(netmap_mem_obj) nmo_next; /* next object in the
210 						 chain. */
211 	int nmo_used; /* flag set on used memory objects. */
212 	size_t nmo_size; /* size of the memory area reserved for the
213 			    object. */
214 	void *nmo_data; /* pointer to the memory area. */
215 };
216 
217 /* Wrap our memory objects to make them ``chainable``. */
218 TAILQ_HEAD(netmap_mem_obj_h, netmap_mem_obj);
219 
220 
221 /* Descriptor of our custom memory allocator. */
222 struct netmap_mem_d {
223 	struct mtx nm_mtx; /* lock used to handle the chain of memory
224 			      objects. */
225 	struct netmap_mem_obj_h nm_molist; /* list of memory objects */
226 	size_t nm_size; /* total amount of memory used for rings etc. */
227 	size_t nm_totalsize; /* total amount of allocated memory
228 		(the difference is used for buffers) */
229 	size_t nm_buf_start; /* offset of packet buffers.
230 			This is page-aligned. */
231 	size_t nm_buf_len; /* total memory for buffers */
232 	void *nm_buffer; /* pointer to the whole pre-allocated memory
233 			    area. */
234 };
235 
236 
237 /* Structure associated to each thread which registered an interface. */
238 struct netmap_priv_d {
239 	struct netmap_if *np_nifp;	/* netmap interface descriptor. */
240 
241 	struct ifnet	*np_ifp;	/* device for which we hold a reference */
242 	int		np_ringid;	/* from the ioctl */
243 	u_int		np_qfirst, np_qlast;	/* range of rings to scan */
244 	uint16_t	np_txpoll;
245 };
246 
247 /* Shorthand to compute a netmap interface offset. */
248 #define netmap_if_offset(v)                                     \
249     ((char *) (v) - (char *) netmap_mem_d->nm_buffer)
250 /* .. and get a physical address given a memory offset */
251 #define netmap_ofstophys(o)                                     \
252     (vtophys(netmap_mem_d->nm_buffer) + (o))
253 
254 static struct cdev *netmap_dev; /* /dev/netmap character device. */
255 static struct netmap_mem_d *netmap_mem_d; /* Our memory allocator. */
256 
257 
258 static d_mmap_t netmap_mmap;
259 static d_ioctl_t netmap_ioctl;
260 static d_poll_t netmap_poll;
261 
262 #ifdef NETMAP_KEVENT
263 static d_kqfilter_t netmap_kqfilter;
264 #endif
265 
266 static struct cdevsw netmap_cdevsw = {
267 	.d_version = D_VERSION,
268 	.d_name = "netmap",
269 	.d_mmap = netmap_mmap,
270 	.d_ioctl = netmap_ioctl,
271 	.d_poll = netmap_poll,
272 #ifdef NETMAP_KEVENT
273 	.d_kqfilter = netmap_kqfilter,
274 #endif
275 };
276 
277 #ifdef NETMAP_KEVENT
278 static int              netmap_kqread(struct knote *, long);
279 static int              netmap_kqwrite(struct knote *, long);
280 static void             netmap_kqdetach(struct knote *);
281 
282 static struct filterops netmap_read_filterops = {
283 	.f_isfd =       1,
284 	.f_attach =     NULL,
285 	.f_detach =     netmap_kqdetach,
286 	.f_event =      netmap_kqread,
287 };
288 
289 static struct filterops netmap_write_filterops = {
290 	.f_isfd =       1,
291 	.f_attach =     NULL,
292 	.f_detach =     netmap_kqdetach,
293 	.f_event =      netmap_kqwrite,
294 };
295 
296 /*
297  * support for the kevent() system call.
298  *
299  * This is the kevent filter, and is executed each time a new event
300  * is triggered on the device. This function execute some operation
301  * depending on the received filter.
302  *
303  * The implementation should test the filters and should implement
304  * filter operations we are interested on (a full list in /sys/event.h).
305  *
306  * On a match we should:
307  * - set kn->kn_fop
308  * - set kn->kn_hook
309  * - call knlist_add() to deliver the event to the application.
310  *
311  * Return 0 if the event should be delivered to the application.
312  */
313 static int
314 netmap_kqfilter(struct cdev *dev, struct knote *kn)
315 {
316 	/* declare variables needed to read/write */
317 
318 	switch(kn->kn_filter) {
319 	case EVFILT_READ:
320 		if (netmap_verbose)
321 			D("%s kqfilter: EVFILT_READ" ifp->if_xname);
322 
323 		/* read operations */
324 		kn->kn_fop = &netmap_read_filterops;
325 		break;
326 
327 	case EVFILT_WRITE:
328 		if (netmap_verbose)
329 			D("%s kqfilter: EVFILT_WRITE" ifp->if_xname);
330 
331 		/* write operations */
332 		kn->kn_fop = &netmap_write_filterops;
333 		break;
334 
335 	default:
336 		if (netmap_verbose)
337 			D("%s kqfilter: invalid filter" ifp->if_xname);
338 		return(EINVAL);
339 	}
340 
341 	kn->kn_hook = 0;//
342 	knlist_add(&netmap_sc->tun_rsel.si_note, kn, 0);
343 
344 	return (0);
345 }
346 #endif /* NETMAP_KEVENT */
347 
348 /*
349  * File descriptor's private data destructor.
350  *
351  * Call nm_register(ifp,0) to stop netmap mode on the interface and
352  * revert to normal operation. We expect that np_ifp has not gone.
353  */
354 static void
355 netmap_dtor(void *data)
356 {
357 	struct netmap_priv_d *priv = data;
358 	struct ifnet *ifp = priv->np_ifp;
359 	struct netmap_adapter *na = NA(ifp);
360 	struct netmap_if *nifp = priv->np_nifp;
361 
362 	if (0)
363 	    printf("%s starting for %p ifp %p\n", __FUNCTION__, priv,
364 		priv ? priv->np_ifp : NULL);
365 
366 	na->nm_lock(ifp->if_softc, NETMAP_CORE_LOCK, 0);
367 
368 	na->refcount--;
369 	if (na->refcount <= 0) {	/* last instance */
370 		u_int i;
371 
372 		D("deleting last netmap instance for %s", ifp->if_xname);
373 		/*
374 		 * there is a race here with *_netmap_task() and
375 		 * netmap_poll(), which don't run under NETMAP_CORE_LOCK.
376 		 * na->refcount == 0 && na->ifp->if_capenable & IFCAP_NETMAP
377 		 * (aka NETMAP_DELETING(na)) are a unique marker that the
378 		 * device is dying.
379 		 * Before destroying stuff we sleep a bit, and then complete
380 		 * the job. NIOCREG should realize the condition and
381 		 * loop until they can continue; the other routines
382 		 * should check the condition at entry and quit if
383 		 * they cannot run.
384 		 */
385 		na->nm_lock(ifp->if_softc, NETMAP_CORE_UNLOCK, 0);
386 		tsleep(na, 0, "NIOCUNREG", 4);
387 		na->nm_lock(ifp->if_softc, NETMAP_CORE_LOCK, 0);
388 		na->nm_register(ifp, 0); /* off, clear IFCAP_NETMAP */
389 		/* Wake up any sleeping threads. netmap_poll will
390 		 * then return POLLERR
391 		 */
392 		for (i = 0; i < na->num_queues + 2; i++) {
393 			selwakeuppri(&na->tx_rings[i].si, PI_NET);
394 			selwakeuppri(&na->rx_rings[i].si, PI_NET);
395 		}
396 		/* release all buffers */
397 		NMA_LOCK();
398 		for (i = 0; i < na->num_queues + 1; i++) {
399 			int j, lim;
400 			struct netmap_ring *ring;
401 
402 			ND("tx queue %d", i);
403 			ring = na->tx_rings[i].ring;
404 			lim = na->tx_rings[i].nkr_num_slots;
405 			for (j = 0; j < lim; j++)
406 				netmap_free_buf(nifp, ring->slot[j].buf_idx);
407 
408 			ND("rx queue %d", i);
409 			ring = na->rx_rings[i].ring;
410 			lim = na->rx_rings[i].nkr_num_slots;
411 			for (j = 0; j < lim; j++)
412 				netmap_free_buf(nifp, ring->slot[j].buf_idx);
413 		}
414 		NMA_UNLOCK();
415 		netmap_free_rings(na);
416 		wakeup(na);
417 	}
418 	netmap_if_free(nifp);
419 
420 	na->nm_lock(ifp->if_softc, NETMAP_CORE_UNLOCK, 0);
421 
422 	if_rele(ifp);
423 
424 	bzero(priv, sizeof(*priv));	/* XXX for safety */
425 	free(priv, M_DEVBUF);
426 }
427 
428 
429 /*
430  * Create and return a new ``netmap_if`` object, and possibly also
431  * rings and packet buffors.
432  *
433  * Return NULL on failure.
434  */
435 static void *
436 netmap_if_new(const char *ifname, struct netmap_adapter *na)
437 {
438 	struct netmap_if *nifp;
439 	struct netmap_ring *ring;
440 	char *buff;
441 	u_int i, len, ofs;
442 	u_int n = na->num_queues + 1; /* shorthand, include stack queue */
443 
444 	/*
445 	 * the descriptor is followed inline by an array of offsets
446 	 * to the tx and rx rings in the shared memory region.
447 	 */
448 	len = sizeof(struct netmap_if) + 2 * n * sizeof(ssize_t);
449 	nifp = netmap_if_malloc(len);
450 	if (nifp == NULL)
451 		return (NULL);
452 
453 	/* initialize base fields */
454 	*(int *)(uintptr_t)&nifp->ni_num_queues = na->num_queues;
455 	strncpy(nifp->ni_name, ifname, IFNAMSIZ);
456 
457 	(na->refcount)++;	/* XXX atomic ? we are under lock */
458 	if (na->refcount > 1)
459 		goto final;
460 
461 	/*
462 	 * If this is the first instance, allocate the shadow rings and
463 	 * buffers for this card (one for each hw queue, one for the host).
464 	 * The rings are contiguous, but have variable size.
465 	 * The entire block is reachable at
466 	 *	na->tx_rings[0].ring
467 	 */
468 
469 	len = n * (2 * sizeof(struct netmap_ring) +
470 		  (na->num_tx_desc + na->num_rx_desc) *
471 		   sizeof(struct netmap_slot) );
472 	buff = netmap_ring_malloc(len);
473 	if (buff == NULL) {
474 		D("failed to allocate %d bytes for %s shadow ring",
475 			len, ifname);
476 error:
477 		(na->refcount)--;
478 		netmap_if_free(nifp);
479 		return (NULL);
480 	}
481 	/* do we have the bufers ? we are in need of num_tx_desc buffers for
482 	 * each tx ring and num_tx_desc buffers for each rx ring. */
483 	len = n * (na->num_tx_desc + na->num_rx_desc);
484 	NMA_LOCK();
485 	if (nm_buf_pool.free < len) {
486 		NMA_UNLOCK();
487 		netmap_free(buff, "not enough bufs");
488 		goto error;
489 	}
490 	/*
491 	 * in the kring, store the pointers to the shared rings
492 	 * and initialize the rings. We are under NMA_LOCK().
493 	 */
494 	ofs = 0;
495 	for (i = 0; i < n; i++) {
496 		struct netmap_kring *kring;
497 		int numdesc;
498 
499 		/* Transmit rings */
500 		kring = &na->tx_rings[i];
501 		numdesc = na->num_tx_desc;
502 		bzero(kring, sizeof(*kring));
503 		kring->na = na;
504 
505 		ring = kring->ring = (struct netmap_ring *)(buff + ofs);
506 		*(ssize_t *)(uintptr_t)&ring->buf_ofs =
507 			nm_buf_pool.base - (char *)ring;
508 		ND("txring[%d] at %p ofs %d", i, ring, ring->buf_ofs);
509 		*(int *)(int *)(uintptr_t)&ring->num_slots =
510 			kring->nkr_num_slots = numdesc;
511 
512 		/*
513 		 * IMPORTANT:
514 		 * Always keep one slot empty, so we can detect new
515 		 * transmissions comparing cur and nr_hwcur (they are
516 		 * the same only if there are no new transmissions).
517 		 */
518 		ring->avail = kring->nr_hwavail = numdesc - 1;
519 		ring->cur = kring->nr_hwcur = 0;
520 		netmap_new_bufs(nifp, ring->slot, numdesc);
521 
522 		ofs += sizeof(struct netmap_ring) +
523 			numdesc * sizeof(struct netmap_slot);
524 
525 		/* Receive rings */
526 		kring = &na->rx_rings[i];
527 		numdesc = na->num_rx_desc;
528 		bzero(kring, sizeof(*kring));
529 		kring->na = na;
530 
531 		ring = kring->ring = (struct netmap_ring *)(buff + ofs);
532 		*(ssize_t *)(uintptr_t)&ring->buf_ofs =
533 			nm_buf_pool.base - (char *)ring;
534 		ND("rxring[%d] at %p offset %d", i, ring, ring->buf_ofs);
535 		*(int *)(int *)(uintptr_t)&ring->num_slots =
536 			kring->nkr_num_slots = numdesc;
537 		ring->cur = kring->nr_hwcur = 0;
538 		ring->avail = kring->nr_hwavail = 0; /* empty */
539 		netmap_new_bufs(nifp, ring->slot, numdesc);
540 		ofs += sizeof(struct netmap_ring) +
541 			numdesc * sizeof(struct netmap_slot);
542 	}
543 	NMA_UNLOCK();
544 	for (i = 0; i < n+1; i++) {
545 		// XXX initialize the selrecord structs.
546 	}
547 final:
548 	/*
549 	 * fill the slots for the rx and tx queues. They contain the offset
550 	 * between the ring and nifp, so the information is usable in
551 	 * userspace to reach the ring from the nifp.
552 	 */
553 	for (i = 0; i < n; i++) {
554 		char *base = (char *)nifp;
555 		*(ssize_t *)(uintptr_t)&nifp->ring_ofs[i] =
556 			(char *)na->tx_rings[i].ring - base;
557 		*(ssize_t *)(uintptr_t)&nifp->ring_ofs[i+n] =
558 			(char *)na->rx_rings[i].ring - base;
559 	}
560 	return (nifp);
561 }
562 
563 
564 /*
565  * mmap(2) support for the "netmap" device.
566  *
567  * Expose all the memory previously allocated by our custom memory
568  * allocator: this way the user has only to issue a single mmap(2), and
569  * can work on all the data structures flawlessly.
570  *
571  * Return 0 on success, -1 otherwise.
572  */
573 static int
574 #if __FreeBSD_version < 900000
575 netmap_mmap(__unused struct cdev *dev, vm_offset_t offset, vm_paddr_t *paddr,
576 	    int nprot)
577 #else
578 netmap_mmap(__unused struct cdev *dev, vm_ooffset_t offset, vm_paddr_t *paddr,
579 	    int nprot, __unused vm_memattr_t *memattr)
580 #endif
581 {
582 	if (nprot & PROT_EXEC)
583 		return (-1);	// XXX -1 or EINVAL ?
584 
585 	ND("request for offset 0x%x", (uint32_t)offset);
586 	*paddr = netmap_ofstophys(offset);
587 
588 	return (0);
589 }
590 
591 
592 /*
593  * Handlers for synchronization of the queues from/to the host.
594  *
595  * netmap_sync_to_host() passes packets up. We are called from a
596  * system call in user process context, and the only contention
597  * can be among multiple user threads erroneously calling
598  * this routine concurrently. In principle we should not even
599  * need to lock.
600  */
601 static void
602 netmap_sync_to_host(struct netmap_adapter *na)
603 {
604 	struct netmap_kring *kring = &na->tx_rings[na->num_queues];
605 	struct netmap_ring *ring = kring->ring;
606 	struct mbuf *head = NULL, *tail = NULL, *m;
607 	u_int k, n, lim = kring->nkr_num_slots - 1;
608 
609 	k = ring->cur;
610 	if (k > lim) {
611 		netmap_ring_reinit(kring);
612 		return;
613 	}
614 	// na->nm_lock(na->ifp->if_softc, NETMAP_CORE_LOCK, 0);
615 
616 	/* Take packets from hwcur to cur and pass them up.
617 	 * In case of no buffers we give up. At the end of the loop,
618 	 * the queue is drained in all cases.
619 	 */
620 	for (n = kring->nr_hwcur; n != k;) {
621 		struct netmap_slot *slot = &ring->slot[n];
622 
623 		n = (n == lim) ? 0 : n + 1;
624 		if (slot->len < 14 || slot->len > NETMAP_BUF_SIZE) {
625 			D("bad pkt at %d len %d", n, slot->len);
626 			continue;
627 		}
628 		m = m_devget(NMB(slot), slot->len, 0, na->ifp, NULL);
629 
630 		if (m == NULL)
631 			break;
632 		if (tail)
633 			tail->m_nextpkt = m;
634 		else
635 			head = m;
636 		tail = m;
637 		m->m_nextpkt = NULL;
638 	}
639 	kring->nr_hwcur = k;
640 	kring->nr_hwavail = ring->avail = lim;
641 	// na->nm_lock(na->ifp->if_softc, NETMAP_CORE_UNLOCK, 0);
642 
643 	/* send packets up, outside the lock */
644 	while ((m = head) != NULL) {
645 		head = head->m_nextpkt;
646 		m->m_nextpkt = NULL;
647 		m->m_pkthdr.rcvif = na->ifp;
648 		if (netmap_verbose & NM_VERB_HOST)
649 			D("sending up pkt %p size %d", m, m->m_pkthdr.len);
650 		(na->ifp->if_input)(na->ifp, m);
651 	}
652 }
653 
654 /*
655  * rxsync backend for packets coming from the host stack.
656  * They have been put in the queue by netmap_start() so we
657  * need to protect access to the kring using a lock.
658  *
659  * This routine also does the selrecord if called from the poll handler
660  * (we know because td != NULL).
661  */
662 static void
663 netmap_sync_from_host(struct netmap_adapter *na, struct thread *td)
664 {
665 	struct netmap_kring *kring = &na->rx_rings[na->num_queues];
666 	struct netmap_ring *ring = kring->ring;
667 	int error = 1, delta;
668 	u_int k = ring->cur, lim = kring->nkr_num_slots;
669 
670 	na->nm_lock(na->ifp->if_softc, NETMAP_CORE_LOCK, 0);
671 	if (k >= lim) /* bad value */
672 		goto done;
673 	delta = k - kring->nr_hwcur;
674 	if (delta < 0)
675 		delta += lim;
676 	kring->nr_hwavail -= delta;
677 	if (kring->nr_hwavail < 0)	/* error */
678 		goto done;
679 	kring->nr_hwcur = k;
680 	error = 0;
681 	k = ring->avail = kring->nr_hwavail;
682 	if (k == 0 && td)
683 		selrecord(td, &kring->si);
684 	if (k && (netmap_verbose & NM_VERB_HOST))
685 		D("%d pkts from stack", k);
686 done:
687 	na->nm_lock(na->ifp->if_softc, NETMAP_CORE_UNLOCK, 0);
688 	if (error)
689 		netmap_ring_reinit(kring);
690 }
691 
692 
693 /*
694  * get a refcounted reference to an interface.
695  * Return ENXIO if the interface does not exist, EINVAL if netmap
696  * is not supported by the interface.
697  * If successful, hold a reference.
698  */
699 static int
700 get_ifp(const char *name, struct ifnet **ifp)
701 {
702 	*ifp = ifunit_ref(name);
703 	if (*ifp == NULL)
704 		return (ENXIO);
705 	/* can do this if the capability exists and if_pspare[0]
706 	 * points to the netmap descriptor.
707 	 */
708 	if ((*ifp)->if_capabilities & IFCAP_NETMAP && NA(*ifp))
709 		return 0;	/* valid pointer, we hold the refcount */
710 	if_rele(*ifp);
711 	return EINVAL;	// not NETMAP capable
712 }
713 
714 
715 /*
716  * Error routine called when txsync/rxsync detects an error.
717  * Can't do much more than resetting cur = hwcur, avail = hwavail.
718  * Return 1 on reinit.
719  *
720  * This routine is only called by the upper half of the kernel.
721  * It only reads hwcur (which is changed only by the upper half, too)
722  * and hwavail (which may be changed by the lower half, but only on
723  * a tx ring and only to increase it, so any error will be recovered
724  * on the next call). For the above, we don't strictly need to call
725  * it under lock.
726  */
727 int
728 netmap_ring_reinit(struct netmap_kring *kring)
729 {
730 	struct netmap_ring *ring = kring->ring;
731 	u_int i, lim = kring->nkr_num_slots - 1;
732 	int errors = 0;
733 
734 	D("called for %s", kring->na->ifp->if_xname);
735 	if (ring->cur > lim)
736 		errors++;
737 	for (i = 0; i <= lim; i++) {
738 		u_int idx = ring->slot[i].buf_idx;
739 		u_int len = ring->slot[i].len;
740 		if (idx < 2 || idx >= netmap_total_buffers) {
741 			if (!errors++)
742 				D("bad buffer at slot %d idx %d len %d ", i, idx, len);
743 			ring->slot[i].buf_idx = 0;
744 			ring->slot[i].len = 0;
745 		} else if (len > NETMAP_BUF_SIZE) {
746 			ring->slot[i].len = 0;
747 			if (!errors++)
748 				D("bad len %d at slot %d idx %d",
749 					len, i, idx);
750 		}
751 	}
752 	if (errors) {
753 		int pos = kring - kring->na->tx_rings;
754 		int n = kring->na->num_queues + 2;
755 
756 		D("total %d errors", errors);
757 		errors++;
758 		D("%s %s[%d] reinit, cur %d -> %d avail %d -> %d",
759 			kring->na->ifp->if_xname,
760 			pos < n ?  "TX" : "RX", pos < n ? pos : pos - n,
761 			ring->cur, kring->nr_hwcur,
762 			ring->avail, kring->nr_hwavail);
763 		ring->cur = kring->nr_hwcur;
764 		ring->avail = kring->nr_hwavail;
765 	}
766 	return (errors ? 1 : 0);
767 }
768 
769 
770 /*
771  * Set the ring ID. For devices with a single queue, a request
772  * for all rings is the same as a single ring.
773  */
774 static int
775 netmap_set_ringid(struct netmap_priv_d *priv, u_int ringid)
776 {
777 	struct ifnet *ifp = priv->np_ifp;
778 	struct netmap_adapter *na = NA(ifp);
779 	void *adapter = na->ifp->if_softc;	/* shorthand */
780 	u_int i = ringid & NETMAP_RING_MASK;
781 	/* first time we don't lock */
782 	int need_lock = (priv->np_qfirst != priv->np_qlast);
783 
784 	if ( (ringid & NETMAP_HW_RING) && i >= na->num_queues) {
785 		D("invalid ring id %d", i);
786 		return (EINVAL);
787 	}
788 	if (need_lock)
789 		na->nm_lock(adapter, NETMAP_CORE_LOCK, 0);
790 	priv->np_ringid = ringid;
791 	if (ringid & NETMAP_SW_RING) {
792 		priv->np_qfirst = na->num_queues;
793 		priv->np_qlast = na->num_queues + 1;
794 	} else if (ringid & NETMAP_HW_RING) {
795 		priv->np_qfirst = i;
796 		priv->np_qlast = i + 1;
797 	} else {
798 		priv->np_qfirst = 0;
799 		priv->np_qlast = na->num_queues;
800 	}
801 	priv->np_txpoll = (ringid & NETMAP_NO_TX_POLL) ? 0 : 1;
802 	if (need_lock)
803 		na->nm_lock(adapter, NETMAP_CORE_UNLOCK, 0);
804 	if (ringid & NETMAP_SW_RING)
805 		D("ringid %s set to SW RING", ifp->if_xname);
806 	else if (ringid & NETMAP_HW_RING)
807 		D("ringid %s set to HW RING %d", ifp->if_xname,
808 			priv->np_qfirst);
809 	else
810 		D("ringid %s set to all %d HW RINGS", ifp->if_xname,
811 			priv->np_qlast);
812 	return 0;
813 }
814 
815 /*
816  * ioctl(2) support for the "netmap" device.
817  *
818  * Following a list of accepted commands:
819  * - NIOCGINFO
820  * - SIOCGIFADDR	just for convenience
821  * - NIOCREGIF
822  * - NIOCUNREGIF
823  * - NIOCTXSYNC
824  * - NIOCRXSYNC
825  *
826  * Return 0 on success, errno otherwise.
827  */
828 static int
829 netmap_ioctl(__unused struct cdev *dev, u_long cmd, caddr_t data,
830 	__unused int fflag, struct thread *td)
831 {
832 	struct netmap_priv_d *priv = NULL;
833 	struct ifnet *ifp;
834 	struct nmreq *nmr = (struct nmreq *) data;
835 	struct netmap_adapter *na;
836 	void *adapter;
837 	int error;
838 	u_int i;
839 	struct netmap_if *nifp;
840 
841 	CURVNET_SET(TD_TO_VNET(td));
842 
843 	error = devfs_get_cdevpriv((void **)&priv);
844 	if (error != ENOENT && error != 0) {
845 		CURVNET_RESTORE();
846 		return (error);
847 	}
848 
849 	error = 0;	/* Could be ENOENT */
850 	switch (cmd) {
851 	case NIOCGINFO:		/* return capabilities etc */
852 		/* memsize is always valid */
853 		nmr->nr_memsize = netmap_mem_d->nm_totalsize;
854 		nmr->nr_offset = 0;
855 		nmr->nr_numrings = 0;
856 		nmr->nr_numslots = 0;
857 		if (nmr->nr_name[0] == '\0')	/* just get memory info */
858 			break;
859 		error = get_ifp(nmr->nr_name, &ifp); /* get a refcount */
860 		if (error)
861 			break;
862 		na = NA(ifp); /* retrieve netmap_adapter */
863 		nmr->nr_numrings = na->num_queues;
864 		nmr->nr_numslots = na->num_tx_desc;
865 		if_rele(ifp);	/* return the refcount */
866 		break;
867 
868 	case NIOCREGIF:
869 		if (priv != NULL) {	/* thread already registered */
870 			error = netmap_set_ringid(priv, nmr->nr_ringid);
871 			break;
872 		}
873 		/* find the interface and a reference */
874 		error = get_ifp(nmr->nr_name, &ifp); /* keep reference */
875 		if (error)
876 			break;
877 		na = NA(ifp); /* retrieve netmap adapter */
878 		adapter = na->ifp->if_softc;	/* shorthand */
879 		/*
880 		 * Allocate the private per-thread structure.
881 		 * XXX perhaps we can use a blocking malloc ?
882 		 */
883 		priv = malloc(sizeof(struct netmap_priv_d), M_DEVBUF,
884 			      M_NOWAIT | M_ZERO);
885 		if (priv == NULL) {
886 			error = ENOMEM;
887 			if_rele(ifp);   /* return the refcount */
888 			break;
889 		}
890 
891 
892 		for (i = 10; i > 0; i--) {
893 			na->nm_lock(adapter, NETMAP_CORE_LOCK, 0);
894 			if (!NETMAP_DELETING(na))
895 				break;
896 			na->nm_lock(adapter, NETMAP_CORE_UNLOCK, 0);
897 			tsleep(na, 0, "NIOCREGIF", hz/10);
898 		}
899 		if (i == 0) {
900 			D("too many NIOCREGIF attempts, give up");
901 			error = EINVAL;
902 			free(priv, M_DEVBUF);
903 			if_rele(ifp);	/* return the refcount */
904 			break;
905 		}
906 
907 		priv->np_ifp = ifp;	/* store the reference */
908 		error = netmap_set_ringid(priv, nmr->nr_ringid);
909 		if (error)
910 			goto error;
911 		priv->np_nifp = nifp = netmap_if_new(nmr->nr_name, na);
912 		if (nifp == NULL) { /* allocation failed */
913 			error = ENOMEM;
914 		} else if (ifp->if_capenable & IFCAP_NETMAP) {
915 			/* was already set */
916 		} else {
917 			/* Otherwise set the card in netmap mode
918 			 * and make it use the shared buffers.
919 			 */
920 			error = na->nm_register(ifp, 1); /* mode on */
921 			if (error) {
922 				/*
923 				 * do something similar to netmap_dtor().
924 				 */
925 				netmap_free_rings(na);
926 				// XXX tx_rings is inline, must not be freed.
927 				// free(na->tx_rings, M_DEVBUF); // XXX wrong ?
928 				na->tx_rings = na->rx_rings = NULL;
929 				na->refcount--;
930 				netmap_if_free(nifp);
931 				nifp = NULL;
932 			}
933 		}
934 
935 		if (error) {	/* reg. failed, release priv and ref */
936 error:
937 			na->nm_lock(adapter, NETMAP_CORE_UNLOCK, 0);
938 			free(priv, M_DEVBUF);
939 			if_rele(ifp);	/* return the refcount */
940 			break;
941 		}
942 
943 		na->nm_lock(adapter, NETMAP_CORE_UNLOCK, 0);
944 		error = devfs_set_cdevpriv(priv, netmap_dtor);
945 
946 		if (error != 0) {
947 			/* could not assign the private storage for the
948 			 * thread, call the destructor explicitly.
949 			 */
950 			netmap_dtor(priv);
951 			break;
952 		}
953 
954 		/* return the offset of the netmap_if object */
955 		nmr->nr_numrings = na->num_queues;
956 		nmr->nr_numslots = na->num_tx_desc;
957 		nmr->nr_memsize = netmap_mem_d->nm_totalsize;
958 		nmr->nr_offset = netmap_if_offset(nifp);
959 		break;
960 
961 	case NIOCUNREGIF:
962 		if (priv == NULL) {
963 			error = ENXIO;
964 			break;
965 		}
966 
967 		/* the interface is unregistered inside the
968 		   destructor of the private data. */
969 		devfs_clear_cdevpriv();
970 		break;
971 
972 	case NIOCTXSYNC:
973         case NIOCRXSYNC:
974 		if (priv == NULL) {
975 			error = ENXIO;
976 			break;
977 		}
978 		ifp = priv->np_ifp;	/* we have a reference */
979 		na = NA(ifp); /* retrieve netmap adapter */
980 		adapter = ifp->if_softc;	/* shorthand */
981 
982 		if (priv->np_qfirst == na->num_queues) {
983 			/* queues to/from host */
984 			if (cmd == NIOCTXSYNC)
985 				netmap_sync_to_host(na);
986 			else
987 				netmap_sync_from_host(na, NULL);
988 			break;
989 		}
990 
991 		for (i = priv->np_qfirst; i < priv->np_qlast; i++) {
992 		    if (cmd == NIOCTXSYNC) {
993 			struct netmap_kring *kring = &na->tx_rings[i];
994 			if (netmap_verbose & NM_VERB_TXSYNC)
995 				D("sync tx ring %d cur %d hwcur %d",
996 					i, kring->ring->cur,
997 					kring->nr_hwcur);
998                         na->nm_txsync(adapter, i, 1 /* do lock */);
999 			if (netmap_verbose & NM_VERB_TXSYNC)
1000 				D("after sync tx ring %d cur %d hwcur %d",
1001 					i, kring->ring->cur,
1002 					kring->nr_hwcur);
1003 		    } else {
1004 			na->nm_rxsync(adapter, i, 1 /* do lock */);
1005 			microtime(&na->rx_rings[i].ring->ts);
1006 		    }
1007 		}
1008 
1009                 break;
1010 
1011 	case BIOCIMMEDIATE:
1012 	case BIOCGHDRCMPLT:
1013 	case BIOCSHDRCMPLT:
1014 	case BIOCSSEESENT:
1015 		D("ignore BIOCIMMEDIATE/BIOCSHDRCMPLT/BIOCSHDRCMPLT/BIOCSSEESENT");
1016 		break;
1017 
1018 	default:
1019 	    {
1020 		/*
1021 		 * allow device calls
1022 		 */
1023 		struct socket so;
1024 		bzero(&so, sizeof(so));
1025 		error = get_ifp(nmr->nr_name, &ifp); /* keep reference */
1026 		if (error)
1027 			break;
1028 		so.so_vnet = ifp->if_vnet;
1029 		// so->so_proto not null.
1030 		error = ifioctl(&so, cmd, data, td);
1031 		if_rele(ifp);
1032 	    }
1033 	}
1034 
1035 	CURVNET_RESTORE();
1036 	return (error);
1037 }
1038 
1039 
1040 /*
1041  * select(2) and poll(2) handlers for the "netmap" device.
1042  *
1043  * Can be called for one or more queues.
1044  * Return true the event mask corresponding to ready events.
1045  * If there are no ready events, do a selrecord on either individual
1046  * selfd or on the global one.
1047  * Device-dependent parts (locking and sync of tx/rx rings)
1048  * are done through callbacks.
1049  */
1050 static int
1051 netmap_poll(__unused struct cdev *dev, int events, struct thread *td)
1052 {
1053 	struct netmap_priv_d *priv = NULL;
1054 	struct netmap_adapter *na;
1055 	struct ifnet *ifp;
1056 	struct netmap_kring *kring;
1057 	u_int core_lock, i, check_all, want_tx, want_rx, revents = 0;
1058 	void *adapter;
1059 	enum {NO_CL, NEED_CL, LOCKED_CL }; /* see below */
1060 
1061 	if (devfs_get_cdevpriv((void **)&priv) != 0 || priv == NULL)
1062 		return POLLERR;
1063 
1064 	ifp = priv->np_ifp;
1065 	// XXX check for deleting() ?
1066 	if ( (ifp->if_capenable & IFCAP_NETMAP) == 0)
1067 		return POLLERR;
1068 
1069 	if (netmap_verbose & 0x8000)
1070 		D("device %s events 0x%x", ifp->if_xname, events);
1071 	want_tx = events & (POLLOUT | POLLWRNORM);
1072 	want_rx = events & (POLLIN | POLLRDNORM);
1073 
1074 	adapter = ifp->if_softc;
1075 	na = NA(ifp); /* retrieve netmap adapter */
1076 
1077 	/* how many queues we are scanning */
1078 	i = priv->np_qfirst;
1079 	if (i == na->num_queues) { /* from/to host */
1080 		if (priv->np_txpoll || want_tx) {
1081 			/* push any packets up, then we are always ready */
1082 			kring = &na->tx_rings[i];
1083 			netmap_sync_to_host(na);
1084 			revents |= want_tx;
1085 		}
1086 		if (want_rx) {
1087 			kring = &na->rx_rings[i];
1088 			if (kring->ring->avail == 0)
1089 				netmap_sync_from_host(na, td);
1090 			if (kring->ring->avail > 0) {
1091 				revents |= want_rx;
1092 			}
1093 		}
1094 		return (revents);
1095 	}
1096 
1097 	/*
1098 	 * check_all is set if the card has more than one queue and
1099 	 * the client is polling all of them. If true, we sleep on
1100 	 * the "global" selfd, otherwise we sleep on individual selfd
1101 	 * (we can only sleep on one of them per direction).
1102 	 * The interrupt routine in the driver should always wake on
1103 	 * the individual selfd, and also on the global one if the card
1104 	 * has more than one ring.
1105 	 *
1106 	 * If the card has only one lock, we just use that.
1107 	 * If the card has separate ring locks, we just use those
1108 	 * unless we are doing check_all, in which case the whole
1109 	 * loop is wrapped by the global lock.
1110 	 * We acquire locks only when necessary: if poll is called
1111 	 * when buffers are available, we can just return without locks.
1112 	 *
1113 	 * rxsync() is only called if we run out of buffers on a POLLIN.
1114 	 * txsync() is called if we run out of buffers on POLLOUT, or
1115 	 * there are pending packets to send. The latter can be disabled
1116 	 * passing NETMAP_NO_TX_POLL in the NIOCREG call.
1117 	 */
1118 	check_all = (i + 1 != priv->np_qlast);
1119 
1120 	/*
1121 	 * core_lock indicates what to do with the core lock.
1122 	 * The core lock is used when either the card has no individual
1123 	 * locks, or it has individual locks but we are cheking all
1124 	 * rings so we need the core lock to avoid missing wakeup events.
1125 	 *
1126 	 * It has three possible states:
1127 	 * NO_CL	we don't need to use the core lock, e.g.
1128 	 *		because we are protected by individual locks.
1129 	 * NEED_CL	we need the core lock. In this case, when we
1130 	 *		call the lock routine, move to LOCKED_CL
1131 	 *		to remember to release the lock once done.
1132 	 * LOCKED_CL	core lock is set, so we need to release it.
1133 	 */
1134 	core_lock = (check_all || !na->separate_locks) ? NEED_CL : NO_CL;
1135 	/*
1136 	 * We start with a lock free round which is good if we have
1137 	 * data available. If this fails, then lock and call the sync
1138 	 * routines.
1139 	 */
1140 		for (i = priv->np_qfirst; want_rx && i < priv->np_qlast; i++) {
1141 			kring = &na->rx_rings[i];
1142 			if (kring->ring->avail > 0) {
1143 				revents |= want_rx;
1144 				want_rx = 0;	/* also breaks the loop */
1145 			}
1146 		}
1147 		for (i = priv->np_qfirst; want_tx && i < priv->np_qlast; i++) {
1148 			kring = &na->tx_rings[i];
1149 			if (kring->ring->avail > 0) {
1150 				revents |= want_tx;
1151 				want_tx = 0;	/* also breaks the loop */
1152 			}
1153 		}
1154 
1155 	/*
1156 	 * If we to push packets out (priv->np_txpoll) or want_tx is
1157 	 * still set, we do need to run the txsync calls (on all rings,
1158 	 * to avoid that the tx rings stall).
1159 	 */
1160 	if (priv->np_txpoll || want_tx) {
1161 		for (i = priv->np_qfirst; i < priv->np_qlast; i++) {
1162 			kring = &na->tx_rings[i];
1163 			if (!want_tx && kring->ring->cur == kring->nr_hwcur)
1164 				continue;
1165 			if (core_lock == NEED_CL) {
1166 				na->nm_lock(adapter, NETMAP_CORE_LOCK, 0);
1167 				core_lock = LOCKED_CL;
1168 			}
1169 			if (na->separate_locks)
1170 				na->nm_lock(adapter, NETMAP_TX_LOCK, i);
1171 			if (netmap_verbose & NM_VERB_TXSYNC)
1172 				D("send %d on %s %d",
1173 					kring->ring->cur,
1174 					ifp->if_xname, i);
1175 			if (na->nm_txsync(adapter, i, 0 /* no lock */))
1176 				revents |= POLLERR;
1177 
1178 			if (want_tx) {
1179 				if (kring->ring->avail > 0) {
1180 					/* stop at the first ring. We don't risk
1181 					 * starvation.
1182 					 */
1183 					revents |= want_tx;
1184 					want_tx = 0;
1185 				} else if (!check_all)
1186 					selrecord(td, &kring->si);
1187 			}
1188 			if (na->separate_locks)
1189 				na->nm_lock(adapter, NETMAP_TX_UNLOCK, i);
1190 		}
1191 	}
1192 
1193 	/*
1194 	 * now if want_rx is still set we need to lock and rxsync.
1195 	 * Do it on all rings because otherwise we starve.
1196 	 */
1197 	if (want_rx) {
1198 		for (i = priv->np_qfirst; i < priv->np_qlast; i++) {
1199 			kring = &na->rx_rings[i];
1200 			if (core_lock == NEED_CL) {
1201 				na->nm_lock(adapter, NETMAP_CORE_LOCK, 0);
1202 				core_lock = LOCKED_CL;
1203 			}
1204 			if (na->separate_locks)
1205 				na->nm_lock(adapter, NETMAP_RX_LOCK, i);
1206 
1207 			if (na->nm_rxsync(adapter, i, 0 /* no lock */))
1208 				revents |= POLLERR;
1209 			if (no_timestamp == 0 ||
1210 					kring->ring->flags & NR_TIMESTAMP)
1211 				microtime(&kring->ring->ts);
1212 
1213 			if (kring->ring->avail > 0)
1214 				revents |= want_rx;
1215 			else if (!check_all)
1216 				selrecord(td, &kring->si);
1217 			if (na->separate_locks)
1218 				na->nm_lock(adapter, NETMAP_RX_UNLOCK, i);
1219 		}
1220 	}
1221 	if (check_all && revents == 0) {
1222 		i = na->num_queues + 1; /* the global queue */
1223 		if (want_tx)
1224 			selrecord(td, &na->tx_rings[i].si);
1225 		if (want_rx)
1226 			selrecord(td, &na->rx_rings[i].si);
1227 	}
1228 	if (core_lock == LOCKED_CL)
1229 		na->nm_lock(adapter, NETMAP_CORE_UNLOCK, 0);
1230 
1231 	return (revents);
1232 }
1233 
1234 /*------- driver support routines ------*/
1235 
1236 /*
1237  * Initialize a ``netmap_adapter`` object created by driver on attach.
1238  * We allocate a block of memory with room for a struct netmap_adapter
1239  * plus two sets of N+2 struct netmap_kring (where N is the number
1240  * of hardware rings):
1241  * krings	0..N-1	are for the hardware queues.
1242  * kring	N	is for the host stack queue
1243  * kring	N+1	is only used for the selinfo for all queues.
1244  * Return 0 on success, ENOMEM otherwise.
1245  */
1246 int
1247 netmap_attach(struct netmap_adapter *na, int num_queues)
1248 {
1249 	int n = num_queues + 2;
1250 	int size = sizeof(*na) + 2 * n * sizeof(struct netmap_kring);
1251 	void *buf;
1252 	struct ifnet *ifp = na->ifp;
1253 
1254 	if (ifp == NULL) {
1255 		D("ifp not set, giving up");
1256 		return EINVAL;
1257 	}
1258 	na->refcount = 0;
1259 	na->num_queues = num_queues;
1260 
1261 	buf = malloc(size, M_DEVBUF, M_NOWAIT | M_ZERO);
1262 	if (buf) {
1263 		WNA(ifp) = buf;
1264 		na->tx_rings = (void *)((char *)buf + sizeof(*na));
1265 		na->rx_rings = na->tx_rings + n;
1266 		bcopy(na, buf, sizeof(*na));
1267 		ifp->if_capabilities |= IFCAP_NETMAP;
1268 	}
1269 	D("%s for %s", buf ? "ok" : "failed", ifp->if_xname);
1270 
1271 	return (buf ? 0 : ENOMEM);
1272 }
1273 
1274 
1275 /*
1276  * Free the allocated memory linked to the given ``netmap_adapter``
1277  * object.
1278  */
1279 void
1280 netmap_detach(struct ifnet *ifp)
1281 {
1282 	u_int i;
1283 	struct netmap_adapter *na = NA(ifp);
1284 
1285 	if (!na)
1286 		return;
1287 
1288 	for (i = 0; i < na->num_queues + 2; i++) {
1289 		knlist_destroy(&na->tx_rings[i].si.si_note);
1290 		knlist_destroy(&na->rx_rings[i].si.si_note);
1291 	}
1292 	bzero(na, sizeof(*na));
1293 	WNA(ifp) = NULL;
1294 	free(na, M_DEVBUF);
1295 }
1296 
1297 
1298 /*
1299  * Intercept packets from the network stack and pass them
1300  * to netmap as incoming packets on the 'software' ring.
1301  * We are not locked when called.
1302  */
1303 int
1304 netmap_start(struct ifnet *ifp, struct mbuf *m)
1305 {
1306 	struct netmap_adapter *na = NA(ifp);
1307 	struct netmap_kring *kring = &na->rx_rings[na->num_queues];
1308 	u_int i, len = m->m_pkthdr.len;
1309 	int error = EBUSY, lim = kring->nkr_num_slots - 1;
1310 	struct netmap_slot *slot;
1311 
1312 	if (netmap_verbose & NM_VERB_HOST)
1313 		D("%s packet %d len %d from the stack", ifp->if_xname,
1314 			kring->nr_hwcur + kring->nr_hwavail, len);
1315 	na->nm_lock(ifp->if_softc, NETMAP_CORE_LOCK, 0);
1316 	if (kring->nr_hwavail >= lim) {
1317 		D("stack ring %s full\n", ifp->if_xname);
1318 		goto done;	/* no space */
1319 	}
1320 	if (len > na->buff_size) {
1321 		D("drop packet size %d > %d", len, na->buff_size);
1322 		goto done;	/* too long for us */
1323 	}
1324 
1325 	/* compute the insert position */
1326 	i = kring->nr_hwcur + kring->nr_hwavail;
1327 	if (i > lim)
1328 		i -= lim + 1;
1329 	slot = &kring->ring->slot[i];
1330 	m_copydata(m, 0, len, NMB(slot));
1331 	slot->len = len;
1332 	kring->nr_hwavail++;
1333 	if (netmap_verbose  & NM_VERB_HOST)
1334 		D("wake up host ring %s %d", na->ifp->if_xname, na->num_queues);
1335 	selwakeuppri(&kring->si, PI_NET);
1336 	error = 0;
1337 done:
1338 	na->nm_lock(ifp->if_softc, NETMAP_CORE_UNLOCK, 0);
1339 
1340 	/* release the mbuf in either cases of success or failure. As an
1341 	 * alternative, put the mbuf in a free list and free the list
1342 	 * only when really necessary.
1343 	 */
1344 	m_freem(m);
1345 
1346 	return (error);
1347 }
1348 
1349 
1350 /*
1351  * netmap_reset() is called by the driver routines when reinitializing
1352  * a ring. The driver is in charge of locking to protect the kring.
1353  * If netmap mode is not set just return NULL.
1354  */
1355 struct netmap_slot *
1356 netmap_reset(struct netmap_adapter *na, enum txrx tx, int n,
1357 	u_int new_cur)
1358 {
1359 	struct netmap_kring *kring;
1360 	struct netmap_ring *ring;
1361 	int new_hwofs, lim;
1362 
1363 	if (na == NULL)
1364 		return NULL;	/* no netmap support here */
1365 	if (!(na->ifp->if_capenable & IFCAP_NETMAP))
1366 		return NULL;	/* nothing to reinitialize */
1367 	kring = tx == NR_TX ?  na->tx_rings + n : na->rx_rings + n;
1368 	ring = kring->ring;
1369 	lim = kring->nkr_num_slots - 1;
1370 
1371 	if (tx == NR_TX)
1372 		new_hwofs = kring->nr_hwcur - new_cur;
1373 	else
1374 		new_hwofs = kring->nr_hwcur + kring->nr_hwavail - new_cur;
1375 	if (new_hwofs > lim)
1376 		new_hwofs -= lim + 1;
1377 
1378 	/* Alwayws set the new offset value and realign the ring. */
1379 	kring->nkr_hwofs = new_hwofs;
1380 	if (tx == NR_TX)
1381 		kring->nr_hwavail = kring->nkr_num_slots - 1;
1382 	D("new hwofs %d on %s %s[%d]",
1383 			kring->nkr_hwofs, na->ifp->if_xname,
1384 			tx == NR_TX ? "TX" : "RX", n);
1385 
1386 	/*
1387 	 * We do the wakeup here, but the ring is not yet reconfigured.
1388 	 * However, we are under lock so there are no races.
1389 	 */
1390 	selwakeuppri(&kring->si, PI_NET);
1391 	selwakeuppri(&kring[na->num_queues + 1 - n].si, PI_NET);
1392 	return kring->ring->slot;
1393 }
1394 
1395 
1396 /*------ netmap memory allocator -------*/
1397 /*
1398  * Request for a chunk of memory.
1399  *
1400  * Memory objects are arranged into a list, hence we need to walk this
1401  * list until we find an object with the needed amount of data free.
1402  * This sounds like a completely inefficient implementation, but given
1403  * the fact that data allocation is done once, we can handle it
1404  * flawlessly.
1405  *
1406  * Return NULL on failure.
1407  */
1408 static void *
1409 netmap_malloc(size_t size, __unused const char *msg)
1410 {
1411 	struct netmap_mem_obj *mem_obj, *new_mem_obj;
1412 	void *ret = NULL;
1413 
1414 	NMA_LOCK();
1415 	TAILQ_FOREACH(mem_obj, &netmap_mem_d->nm_molist, nmo_next) {
1416 		if (mem_obj->nmo_used != 0 || mem_obj->nmo_size < size)
1417 			continue;
1418 
1419 		new_mem_obj = malloc(sizeof(struct netmap_mem_obj), M_NETMAP,
1420 				     M_WAITOK | M_ZERO);
1421 		TAILQ_INSERT_BEFORE(mem_obj, new_mem_obj, nmo_next);
1422 
1423 		new_mem_obj->nmo_used = 1;
1424 		new_mem_obj->nmo_size = size;
1425 		new_mem_obj->nmo_data = mem_obj->nmo_data;
1426 		memset(new_mem_obj->nmo_data, 0, new_mem_obj->nmo_size);
1427 
1428 		mem_obj->nmo_size -= size;
1429 		mem_obj->nmo_data = (char *) mem_obj->nmo_data + size;
1430 		if (mem_obj->nmo_size == 0) {
1431 			TAILQ_REMOVE(&netmap_mem_d->nm_molist, mem_obj,
1432 				     nmo_next);
1433 			free(mem_obj, M_NETMAP);
1434 		}
1435 
1436 		ret = new_mem_obj->nmo_data;
1437 
1438 		break;
1439 	}
1440 	NMA_UNLOCK();
1441 	ND("%s: %d bytes at %p", msg, size, ret);
1442 
1443 	return (ret);
1444 }
1445 
1446 /*
1447  * Return the memory to the allocator.
1448  *
1449  * While freeing a memory object, we try to merge adjacent chunks in
1450  * order to reduce memory fragmentation.
1451  */
1452 static void
1453 netmap_free(void *addr, const char *msg)
1454 {
1455 	size_t size;
1456 	struct netmap_mem_obj *cur, *prev, *next;
1457 
1458 	if (addr == NULL) {
1459 		D("NULL addr for %s", msg);
1460 		return;
1461 	}
1462 
1463 	NMA_LOCK();
1464 	TAILQ_FOREACH(cur, &netmap_mem_d->nm_molist, nmo_next) {
1465 		if (cur->nmo_data == addr && cur->nmo_used)
1466 			break;
1467 	}
1468 	if (cur == NULL) {
1469 		NMA_UNLOCK();
1470 		D("invalid addr %s %p", msg, addr);
1471 		return;
1472 	}
1473 
1474 	size = cur->nmo_size;
1475 	cur->nmo_used = 0;
1476 
1477 	/* merge current chunk of memory with the previous one,
1478 	   if present. */
1479 	prev = TAILQ_PREV(cur, netmap_mem_obj_h, nmo_next);
1480 	if (prev && prev->nmo_used == 0) {
1481 		TAILQ_REMOVE(&netmap_mem_d->nm_molist, cur, nmo_next);
1482 		prev->nmo_size += cur->nmo_size;
1483 		free(cur, M_NETMAP);
1484 		cur = prev;
1485 	}
1486 
1487 	/* merge with the next one */
1488 	next = TAILQ_NEXT(cur, nmo_next);
1489 	if (next && next->nmo_used == 0) {
1490 		TAILQ_REMOVE(&netmap_mem_d->nm_molist, next, nmo_next);
1491 		cur->nmo_size += next->nmo_size;
1492 		free(next, M_NETMAP);
1493 	}
1494 	NMA_UNLOCK();
1495 	ND("freed %s %d bytes at %p", msg, size, addr);
1496 }
1497 
1498 
1499 /*
1500  * Initialize the memory allocator.
1501  *
1502  * Create the descriptor for the memory , allocate the pool of memory
1503  * and initialize the list of memory objects with a single chunk
1504  * containing the whole pre-allocated memory marked as free.
1505  *
1506  * Start with a large size, then halve as needed if we fail to
1507  * allocate the block. While halving, always add one extra page
1508  * because buffers 0 and 1 are used for special purposes.
1509  * Return 0 on success, errno otherwise.
1510  */
1511 static int
1512 netmap_memory_init(void)
1513 {
1514 	struct netmap_mem_obj *mem_obj;
1515 	void *buf = NULL;
1516 	int i, n, sz = NETMAP_MEMORY_SIZE;
1517 	int extra_sz = 0; // space for rings and two spare buffers
1518 
1519 	for (; sz >= 1<<20; sz >>=1) {
1520 		extra_sz = sz/200;
1521 		extra_sz = (extra_sz + 2*PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
1522 	        buf = contigmalloc(sz + extra_sz,
1523 			     M_NETMAP,
1524 			     M_WAITOK | M_ZERO,
1525 			     0, /* low address */
1526 			     -1UL, /* high address */
1527 			     PAGE_SIZE, /* alignment */
1528 			     0 /* boundary */
1529 			    );
1530 		if (buf)
1531 			break;
1532 	}
1533 	if (buf == NULL)
1534 		return (ENOMEM);
1535 	sz += extra_sz;
1536 	netmap_mem_d = malloc(sizeof(struct netmap_mem_d), M_NETMAP,
1537 			      M_WAITOK | M_ZERO);
1538 	mtx_init(&netmap_mem_d->nm_mtx, "netmap memory allocator lock", NULL,
1539 		 MTX_DEF);
1540 	TAILQ_INIT(&netmap_mem_d->nm_molist);
1541 	netmap_mem_d->nm_buffer = buf;
1542 	netmap_mem_d->nm_totalsize = sz;
1543 
1544 	/*
1545 	 * A buffer takes 2k, a slot takes 8 bytes + ring overhead,
1546 	 * so the ratio is 200:1. In other words, we can use 1/200 of
1547 	 * the memory for the rings, and the rest for the buffers,
1548 	 * and be sure we never run out.
1549 	 */
1550 	netmap_mem_d->nm_size = sz/200;
1551 	netmap_mem_d->nm_buf_start =
1552 		(netmap_mem_d->nm_size + PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
1553 	netmap_mem_d->nm_buf_len = sz - netmap_mem_d->nm_buf_start;
1554 
1555 	nm_buf_pool.base = netmap_mem_d->nm_buffer;
1556 	nm_buf_pool.base += netmap_mem_d->nm_buf_start;
1557 	netmap_buffer_base = nm_buf_pool.base;
1558 	D("netmap_buffer_base %p (offset %d)",
1559 		netmap_buffer_base, (int)netmap_mem_d->nm_buf_start);
1560 	/* number of buffers, they all start as free */
1561 
1562 	netmap_total_buffers = nm_buf_pool.total_buffers =
1563 		netmap_mem_d->nm_buf_len / NETMAP_BUF_SIZE;
1564 	nm_buf_pool.bufsize = NETMAP_BUF_SIZE;
1565 
1566 	D("Have %d MB, use %dKB for rings, %d buffers at %p",
1567 		(sz >> 20), (int)(netmap_mem_d->nm_size >> 10),
1568 		nm_buf_pool.total_buffers, nm_buf_pool.base);
1569 
1570 	/* allocate and initialize the bitmap. Entry 0 is considered
1571 	 * always busy (used as default when there are no buffers left).
1572 	 */
1573 	n = (nm_buf_pool.total_buffers + 31) / 32;
1574 	nm_buf_pool.bitmap = malloc(sizeof(uint32_t) * n, M_NETMAP,
1575 			 M_WAITOK | M_ZERO);
1576 	nm_buf_pool.bitmap[0] = ~3; /* slot 0 and 1 always busy */
1577 	for (i = 1; i < n; i++)
1578 		nm_buf_pool.bitmap[i] = ~0;
1579 	nm_buf_pool.free = nm_buf_pool.total_buffers - 2;
1580 
1581 	mem_obj = malloc(sizeof(struct netmap_mem_obj), M_NETMAP,
1582 			 M_WAITOK | M_ZERO);
1583 	TAILQ_INSERT_HEAD(&netmap_mem_d->nm_molist, mem_obj, nmo_next);
1584 	mem_obj->nmo_used = 0;
1585 	mem_obj->nmo_size = netmap_mem_d->nm_size;
1586 	mem_obj->nmo_data = netmap_mem_d->nm_buffer;
1587 
1588 	return (0);
1589 }
1590 
1591 
1592 /*
1593  * Finalize the memory allocator.
1594  *
1595  * Free all the memory objects contained inside the list, and deallocate
1596  * the pool of memory; finally free the memory allocator descriptor.
1597  */
1598 static void
1599 netmap_memory_fini(void)
1600 {
1601 	struct netmap_mem_obj *mem_obj;
1602 
1603 	while (!TAILQ_EMPTY(&netmap_mem_d->nm_molist)) {
1604 		mem_obj = TAILQ_FIRST(&netmap_mem_d->nm_molist);
1605 		TAILQ_REMOVE(&netmap_mem_d->nm_molist, mem_obj, nmo_next);
1606 		if (mem_obj->nmo_used == 1) {
1607 			printf("netmap: leaked %d bytes at %p\n",
1608 			       (int)mem_obj->nmo_size,
1609 			       mem_obj->nmo_data);
1610 		}
1611 		free(mem_obj, M_NETMAP);
1612 	}
1613 	contigfree(netmap_mem_d->nm_buffer, netmap_mem_d->nm_totalsize, M_NETMAP);
1614 	// XXX mutex_destroy(nm_mtx);
1615 	free(netmap_mem_d, M_NETMAP);
1616 }
1617 
1618 
1619 /*
1620  * Module loader.
1621  *
1622  * Create the /dev/netmap device and initialize all global
1623  * variables.
1624  *
1625  * Return 0 on success, errno on failure.
1626  */
1627 static int
1628 netmap_init(void)
1629 {
1630 	int error;
1631 
1632 
1633 	error = netmap_memory_init();
1634 	if (error != 0) {
1635 		printf("netmap: unable to initialize the memory allocator.");
1636 		return (error);
1637 	}
1638 	printf("netmap: loaded module with %d Mbytes\n",
1639 		(int)(netmap_mem_d->nm_totalsize >> 20));
1640 
1641 	netmap_dev = make_dev(&netmap_cdevsw, 0, UID_ROOT, GID_WHEEL, 0660,
1642 			      "netmap");
1643 
1644 	return (0);
1645 }
1646 
1647 
1648 /*
1649  * Module unloader.
1650  *
1651  * Free all the memory, and destroy the ``/dev/netmap`` device.
1652  */
1653 static void
1654 netmap_fini(void)
1655 {
1656 	destroy_dev(netmap_dev);
1657 
1658 	netmap_memory_fini();
1659 
1660 	printf("netmap: unloaded module.\n");
1661 }
1662 
1663 
1664 /*
1665  * Kernel entry point.
1666  *
1667  * Initialize/finalize the module and return.
1668  *
1669  * Return 0 on success, errno on failure.
1670  */
1671 static int
1672 netmap_loader(__unused struct module *module, int event, __unused void *arg)
1673 {
1674 	int error = 0;
1675 
1676 	switch (event) {
1677 	case MOD_LOAD:
1678 		error = netmap_init();
1679 		break;
1680 
1681 	case MOD_UNLOAD:
1682 		netmap_fini();
1683 		break;
1684 
1685 	default:
1686 		error = EOPNOTSUPP;
1687 		break;
1688 	}
1689 
1690 	return (error);
1691 }
1692 
1693 
1694 DEV_MODULE(netmap, netmap_loader, NULL);
1695