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