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