xref: /freebsd/sys/dev/netmap/netmap.c (revision bb15ca603fa442c72dde3f3cb8b46db6970e3950)
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 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 	int core_lock = (check_all || !na->separate_locks) ?
1120 			NEED_CL:NO_CL;
1121 	/*
1122 	 * We start with a lock free round which is good if we have
1123 	 * data available. If this fails, then lock and call the sync
1124 	 * routines.
1125 	 */
1126 		for (i = priv->np_qfirst; want_rx && i < priv->np_qlast; i++) {
1127 			kring = &na->rx_rings[i];
1128 			if (kring->ring->avail > 0) {
1129 				revents |= want_rx;
1130 				want_rx = 0;	/* also breaks the loop */
1131 			}
1132 		}
1133 		for (i = priv->np_qfirst; want_tx && i < priv->np_qlast; i++) {
1134 			kring = &na->tx_rings[i];
1135 			if (kring->ring->avail > 0) {
1136 				revents |= want_tx;
1137 				want_tx = 0;	/* also breaks the loop */
1138 			}
1139 		}
1140 
1141 	/*
1142 	 * If we to push packets out (priv->np_txpoll) or want_tx is
1143 	 * still set, we do need to run the txsync calls (on all rings,
1144 	 * to avoid that the tx rings stall).
1145 	 */
1146 	if (priv->np_txpoll || want_tx) {
1147 		for (i = priv->np_qfirst; i < priv->np_qlast; i++) {
1148 			kring = &na->tx_rings[i];
1149 			if (!want_tx && kring->ring->cur == kring->nr_hwcur)
1150 				continue;
1151 			if (core_lock == NEED_CL) {
1152 				na->nm_lock(adapter, NETMAP_CORE_LOCK, 0);
1153 				core_lock = LOCKED_CL;
1154 			}
1155 			if (na->separate_locks)
1156 				na->nm_lock(adapter, NETMAP_TX_LOCK, i);
1157 			if (netmap_verbose & NM_VERB_TXSYNC)
1158 				D("send %d on %s %d",
1159 					kring->ring->cur,
1160 					ifp->if_xname, i);
1161 			if (na->nm_txsync(adapter, i, 0 /* no lock */))
1162 				revents |= POLLERR;
1163 
1164 			if (want_tx) {
1165 				if (kring->ring->avail > 0) {
1166 					/* stop at the first ring. We don't risk
1167 					 * starvation.
1168 					 */
1169 					revents |= want_tx;
1170 					want_tx = 0;
1171 				} else if (!check_all)
1172 					selrecord(td, &kring->si);
1173 			}
1174 			if (na->separate_locks)
1175 				na->nm_lock(adapter, NETMAP_TX_UNLOCK, i);
1176 		}
1177 	}
1178 
1179 	/*
1180 	 * now if want_rx is still set we need to lock and rxsync.
1181 	 * Do it on all rings because otherwise we starve.
1182 	 */
1183 	if (want_rx) {
1184 		for (i = priv->np_qfirst; i < priv->np_qlast; i++) {
1185 			kring = &na->rx_rings[i];
1186 			if (core_lock == NEED_CL) {
1187 				na->nm_lock(adapter, NETMAP_CORE_LOCK, 0);
1188 				core_lock = LOCKED_CL;
1189 			}
1190 			if (na->separate_locks)
1191 				na->nm_lock(adapter, NETMAP_RX_LOCK, i);
1192 
1193 			if (na->nm_rxsync(adapter, i, 0 /* no lock */))
1194 				revents |= POLLERR;
1195 			if (no_timestamp == 0 ||
1196 					kring->ring->flags & NR_TIMESTAMP)
1197 				microtime(&kring->ring->ts);
1198 
1199 			if (kring->ring->avail > 0)
1200 				revents |= want_rx;
1201 			else if (!check_all)
1202 				selrecord(td, &kring->si);
1203 			if (na->separate_locks)
1204 				na->nm_lock(adapter, NETMAP_RX_UNLOCK, i);
1205 		}
1206 	}
1207 	if (check_all && revents == 0) {
1208 		i = na->num_queues + 1; /* the global queue */
1209 		if (want_tx)
1210 			selrecord(td, &na->tx_rings[i].si);
1211 		if (want_rx)
1212 			selrecord(td, &na->rx_rings[i].si);
1213 	}
1214 	if (core_lock == LOCKED_CL)
1215 		na->nm_lock(adapter, NETMAP_CORE_UNLOCK, 0);
1216 
1217 	return (revents);
1218 }
1219 
1220 /*------- driver support routines ------*/
1221 
1222 /*
1223  * Initialize a ``netmap_adapter`` object created by driver on attach.
1224  * We allocate a block of memory with room for a struct netmap_adapter
1225  * plus two sets of N+2 struct netmap_kring (where N is the number
1226  * of hardware rings):
1227  * krings	0..N-1	are for the hardware queues.
1228  * kring	N	is for the host stack queue
1229  * kring	N+1	is only used for the selinfo for all queues.
1230  * Return 0 on success, ENOMEM otherwise.
1231  */
1232 int
1233 netmap_attach(struct netmap_adapter *na, int num_queues)
1234 {
1235 	int n = num_queues + 2;
1236 	int size = sizeof(*na) + 2 * n * sizeof(struct netmap_kring);
1237 	void *buf;
1238 	struct ifnet *ifp = na->ifp;
1239 
1240 	if (ifp == NULL) {
1241 		D("ifp not set, giving up");
1242 		return EINVAL;
1243 	}
1244 	na->refcount = 0;
1245 	na->num_queues = num_queues;
1246 
1247 	buf = malloc(size, M_DEVBUF, M_NOWAIT | M_ZERO);
1248 	if (buf) {
1249 		ifp->if_pspare[0] = buf;
1250 		na->tx_rings = (void *)((char *)buf + sizeof(*na));
1251 		na->rx_rings = na->tx_rings + n;
1252 		bcopy(na, buf, sizeof(*na));
1253 		ifp->if_capabilities |= IFCAP_NETMAP;
1254 	}
1255 	D("%s for %s", buf ? "ok" : "failed", ifp->if_xname);
1256 
1257 	return (buf ? 0 : ENOMEM);
1258 }
1259 
1260 
1261 /*
1262  * Free the allocated memory linked to the given ``netmap_adapter``
1263  * object.
1264  */
1265 void
1266 netmap_detach(struct ifnet *ifp)
1267 {
1268 	u_int i;
1269 	struct netmap_adapter *na = NA(ifp);
1270 
1271 	if (!na)
1272 		return;
1273 
1274 	for (i = 0; i < na->num_queues + 2; i++) {
1275 		knlist_destroy(&na->tx_rings[i].si.si_note);
1276 		knlist_destroy(&na->rx_rings[i].si.si_note);
1277 	}
1278 	bzero(na, sizeof(*na));
1279 	ifp->if_pspare[0] = NULL;
1280 	free(na, M_DEVBUF);
1281 }
1282 
1283 
1284 /*
1285  * Intercept packets from the network stack and pass them
1286  * to netmap as incoming packets on the 'software' ring.
1287  * We are not locked when called.
1288  */
1289 int
1290 netmap_start(struct ifnet *ifp, struct mbuf *m)
1291 {
1292 	struct netmap_adapter *na = NA(ifp);
1293 	struct netmap_kring *kring = &na->rx_rings[na->num_queues];
1294 	u_int i, len = m->m_pkthdr.len;
1295 	int error = EBUSY, lim = kring->nkr_num_slots - 1;
1296 	struct netmap_slot *slot;
1297 
1298 	if (netmap_verbose & NM_VERB_HOST)
1299 		D("%s packet %d len %d from the stack", ifp->if_xname,
1300 			kring->nr_hwcur + kring->nr_hwavail, len);
1301 	na->nm_lock(ifp->if_softc, NETMAP_CORE_LOCK, 0);
1302 	if (kring->nr_hwavail >= lim) {
1303 		D("stack ring %s full\n", ifp->if_xname);
1304 		goto done;	/* no space */
1305 	}
1306 	if (len > na->buff_size) {
1307 		D("drop packet size %d > %d", len, na->buff_size);
1308 		goto done;	/* too long for us */
1309 	}
1310 
1311 	/* compute the insert position */
1312 	i = kring->nr_hwcur + kring->nr_hwavail;
1313 	if (i > lim)
1314 		i -= lim + 1;
1315 	slot = &kring->ring->slot[i];
1316 	m_copydata(m, 0, len, NMB(slot));
1317 	slot->len = len;
1318 	kring->nr_hwavail++;
1319 	if (netmap_verbose  & NM_VERB_HOST)
1320 		D("wake up host ring %s %d", na->ifp->if_xname, na->num_queues);
1321 	selwakeuppri(&kring->si, PI_NET);
1322 	error = 0;
1323 done:
1324 	na->nm_lock(ifp->if_softc, NETMAP_CORE_UNLOCK, 0);
1325 
1326 	/* release the mbuf in either cases of success or failure. As an
1327 	 * alternative, put the mbuf in a free list and free the list
1328 	 * only when really necessary.
1329 	 */
1330 	m_freem(m);
1331 
1332 	return (error);
1333 }
1334 
1335 
1336 /*
1337  * netmap_reset() is called by the driver routines when reinitializing
1338  * a ring. The driver is in charge of locking to protect the kring.
1339  * If netmap mode is not set just return NULL.
1340  */
1341 struct netmap_slot *
1342 netmap_reset(struct netmap_adapter *na, enum txrx tx, int n,
1343 	u_int new_cur)
1344 {
1345 	struct netmap_kring *kring;
1346 	struct netmap_ring *ring;
1347 	int new_hwofs, lim;
1348 
1349 	if (na == NULL)
1350 		return NULL;	/* no netmap support here */
1351 	if (!(na->ifp->if_capenable & IFCAP_NETMAP))
1352 		return NULL;	/* nothing to reinitialize */
1353 	kring = tx == NR_TX ?  na->tx_rings + n : na->rx_rings + n;
1354 	ring = kring->ring;
1355 	lim = kring->nkr_num_slots - 1;
1356 
1357 	if (tx == NR_TX)
1358 		new_hwofs = kring->nr_hwcur - new_cur;
1359 	else
1360 		new_hwofs = kring->nr_hwcur + kring->nr_hwavail - new_cur;
1361 	if (new_hwofs > lim)
1362 		new_hwofs -= lim + 1;
1363 
1364 	/* Alwayws set the new offset value and realign the ring. */
1365 	kring->nkr_hwofs = new_hwofs;
1366 	if (tx == NR_TX)
1367 		kring->nr_hwavail = kring->nkr_num_slots - 1;
1368 	D("new hwofs %d on %s %s[%d]",
1369 			kring->nkr_hwofs, na->ifp->if_xname,
1370 			tx == NR_TX ? "TX" : "RX", n);
1371 
1372 	/*
1373 	 * We do the wakeup here, but the ring is not yet reconfigured.
1374 	 * However, we are under lock so there are no races.
1375 	 */
1376 	selwakeuppri(&kring->si, PI_NET);
1377 	selwakeuppri(&kring[na->num_queues + 1 - n].si, PI_NET);
1378 	return kring->ring->slot;
1379 }
1380 
1381 static void
1382 ns_dmamap_cb(__unused void *arg, __unused bus_dma_segment_t * segs,
1383 	__unused int nseg, __unused int error)
1384 {
1385 }
1386 
1387 /* unload a bus_dmamap and create a new one. Used when the
1388  * buffer in the slot is changed.
1389  * XXX buflen is probably not needed, buffers have constant size.
1390  */
1391 void
1392 netmap_reload_map(bus_dma_tag_t tag, bus_dmamap_t map,
1393 	void *buf, bus_size_t buflen)
1394 {
1395 	bus_addr_t paddr;
1396 	bus_dmamap_unload(tag, map);
1397 	bus_dmamap_load(tag, map, buf, buflen, ns_dmamap_cb, &paddr,
1398 				BUS_DMA_NOWAIT);
1399 }
1400 
1401 void
1402 netmap_load_map(bus_dma_tag_t tag, bus_dmamap_t map,
1403 	void *buf, bus_size_t buflen)
1404 {
1405 	bus_addr_t paddr;
1406 	bus_dmamap_load(tag, map, buf, buflen, ns_dmamap_cb, &paddr,
1407 				BUS_DMA_NOWAIT);
1408 }
1409 
1410 /*------ netmap memory allocator -------*/
1411 /*
1412  * Request for a chunk of memory.
1413  *
1414  * Memory objects are arranged into a list, hence we need to walk this
1415  * list until we find an object with the needed amount of data free.
1416  * This sounds like a completely inefficient implementation, but given
1417  * the fact that data allocation is done once, we can handle it
1418  * flawlessly.
1419  *
1420  * Return NULL on failure.
1421  */
1422 static void *
1423 netmap_malloc(size_t size, __unused const char *msg)
1424 {
1425 	struct netmap_mem_obj *mem_obj, *new_mem_obj;
1426 	void *ret = NULL;
1427 
1428 	NMA_LOCK();
1429 	TAILQ_FOREACH(mem_obj, &netmap_mem_d->nm_molist, nmo_next) {
1430 		if (mem_obj->nmo_used != 0 || mem_obj->nmo_size < size)
1431 			continue;
1432 
1433 		new_mem_obj = malloc(sizeof(struct netmap_mem_obj), M_NETMAP,
1434 				     M_WAITOK | M_ZERO);
1435 		TAILQ_INSERT_BEFORE(mem_obj, new_mem_obj, nmo_next);
1436 
1437 		new_mem_obj->nmo_used = 1;
1438 		new_mem_obj->nmo_size = size;
1439 		new_mem_obj->nmo_data = mem_obj->nmo_data;
1440 		memset(new_mem_obj->nmo_data, 0, new_mem_obj->nmo_size);
1441 
1442 		mem_obj->nmo_size -= size;
1443 		mem_obj->nmo_data = (char *) mem_obj->nmo_data + size;
1444 		if (mem_obj->nmo_size == 0) {
1445 			TAILQ_REMOVE(&netmap_mem_d->nm_molist, mem_obj,
1446 				     nmo_next);
1447 			free(mem_obj, M_NETMAP);
1448 		}
1449 
1450 		ret = new_mem_obj->nmo_data;
1451 
1452 		break;
1453 	}
1454 	NMA_UNLOCK();
1455 	ND("%s: %d bytes at %p", msg, size, ret);
1456 
1457 	return (ret);
1458 }
1459 
1460 /*
1461  * Return the memory to the allocator.
1462  *
1463  * While freeing a memory object, we try to merge adjacent chunks in
1464  * order to reduce memory fragmentation.
1465  */
1466 static void
1467 netmap_free(void *addr, const char *msg)
1468 {
1469 	size_t size;
1470 	struct netmap_mem_obj *cur, *prev, *next;
1471 
1472 	if (addr == NULL) {
1473 		D("NULL addr for %s", msg);
1474 		return;
1475 	}
1476 
1477 	NMA_LOCK();
1478 	TAILQ_FOREACH(cur, &netmap_mem_d->nm_molist, nmo_next) {
1479 		if (cur->nmo_data == addr && cur->nmo_used)
1480 			break;
1481 	}
1482 	if (cur == NULL) {
1483 		NMA_UNLOCK();
1484 		D("invalid addr %s %p", msg, addr);
1485 		return;
1486 	}
1487 
1488 	size = cur->nmo_size;
1489 	cur->nmo_used = 0;
1490 
1491 	/* merge current chunk of memory with the previous one,
1492 	   if present. */
1493 	prev = TAILQ_PREV(cur, netmap_mem_obj_h, nmo_next);
1494 	if (prev && prev->nmo_used == 0) {
1495 		TAILQ_REMOVE(&netmap_mem_d->nm_molist, cur, nmo_next);
1496 		prev->nmo_size += cur->nmo_size;
1497 		free(cur, M_NETMAP);
1498 		cur = prev;
1499 	}
1500 
1501 	/* merge with the next one */
1502 	next = TAILQ_NEXT(cur, nmo_next);
1503 	if (next && next->nmo_used == 0) {
1504 		TAILQ_REMOVE(&netmap_mem_d->nm_molist, next, nmo_next);
1505 		cur->nmo_size += next->nmo_size;
1506 		free(next, M_NETMAP);
1507 	}
1508 	NMA_UNLOCK();
1509 	ND("freed %s %d bytes at %p", msg, size, addr);
1510 }
1511 
1512 
1513 /*
1514  * Initialize the memory allocator.
1515  *
1516  * Create the descriptor for the memory , allocate the pool of memory
1517  * and initialize the list of memory objects with a single chunk
1518  * containing the whole pre-allocated memory marked as free.
1519  *
1520  * Start with a large size, then halve as needed if we fail to
1521  * allocate the block. While halving, always add one extra page
1522  * because buffers 0 and 1 are used for special purposes.
1523  * Return 0 on success, errno otherwise.
1524  */
1525 static int
1526 netmap_memory_init(void)
1527 {
1528 	struct netmap_mem_obj *mem_obj;
1529 	void *buf = NULL;
1530 	int i, n, sz = NETMAP_MEMORY_SIZE;
1531 	int extra_sz = 0; // space for rings and two spare buffers
1532 
1533 	for (; !buf && sz >= 1<<20; sz >>=1) {
1534 		extra_sz = sz/200;
1535 		extra_sz = (extra_sz + 2*PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
1536 	        buf = contigmalloc(sz + extra_sz,
1537 			     M_NETMAP,
1538 			     M_WAITOK | M_ZERO,
1539 			     0, /* low address */
1540 			     -1UL, /* high address */
1541 			     PAGE_SIZE, /* alignment */
1542 			     0 /* boundary */
1543 			    );
1544 	}
1545 	if (buf == NULL)
1546 		return (ENOMEM);
1547 	sz += extra_sz;
1548 	netmap_mem_d = malloc(sizeof(struct netmap_mem_d), M_NETMAP,
1549 			      M_WAITOK | M_ZERO);
1550 	mtx_init(&netmap_mem_d->nm_mtx, "netmap memory allocator lock", NULL,
1551 		 MTX_DEF);
1552 	TAILQ_INIT(&netmap_mem_d->nm_molist);
1553 	netmap_mem_d->nm_buffer = buf;
1554 	netmap_mem_d->nm_totalsize = sz;
1555 
1556 	/*
1557 	 * A buffer takes 2k, a slot takes 8 bytes + ring overhead,
1558 	 * so the ratio is 200:1. In other words, we can use 1/200 of
1559 	 * the memory for the rings, and the rest for the buffers,
1560 	 * and be sure we never run out.
1561 	 */
1562 	netmap_mem_d->nm_size = sz/200;
1563 	netmap_mem_d->nm_buf_start =
1564 		(netmap_mem_d->nm_size + PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
1565 	netmap_mem_d->nm_buf_len = sz - netmap_mem_d->nm_buf_start;
1566 
1567 	nm_buf_pool.base = netmap_mem_d->nm_buffer;
1568 	nm_buf_pool.base += netmap_mem_d->nm_buf_start;
1569 	netmap_buffer_base = nm_buf_pool.base;
1570 	D("netmap_buffer_base %p (offset %d)",
1571 		netmap_buffer_base, (int)netmap_mem_d->nm_buf_start);
1572 	/* number of buffers, they all start as free */
1573 
1574 	netmap_total_buffers = nm_buf_pool.total_buffers =
1575 		netmap_mem_d->nm_buf_len / NETMAP_BUF_SIZE;
1576 	nm_buf_pool.bufsize = NETMAP_BUF_SIZE;
1577 
1578 	D("Have %d MB, use %dKB for rings, %d buffers at %p",
1579 		(sz >> 20), (int)(netmap_mem_d->nm_size >> 10),
1580 		nm_buf_pool.total_buffers, nm_buf_pool.base);
1581 
1582 	/* allocate and initialize the bitmap. Entry 0 is considered
1583 	 * always busy (used as default when there are no buffers left).
1584 	 */
1585 	n = (nm_buf_pool.total_buffers + 31) / 32;
1586 	nm_buf_pool.bitmap = malloc(sizeof(uint32_t) * n, M_NETMAP,
1587 			 M_WAITOK | M_ZERO);
1588 	nm_buf_pool.bitmap[0] = ~3; /* slot 0 and 1 always busy */
1589 	for (i = 1; i < n; i++)
1590 		nm_buf_pool.bitmap[i] = ~0;
1591 	nm_buf_pool.free = nm_buf_pool.total_buffers - 2;
1592 
1593 	mem_obj = malloc(sizeof(struct netmap_mem_obj), M_NETMAP,
1594 			 M_WAITOK | M_ZERO);
1595 	TAILQ_INSERT_HEAD(&netmap_mem_d->nm_molist, mem_obj, nmo_next);
1596 	mem_obj->nmo_used = 0;
1597 	mem_obj->nmo_size = netmap_mem_d->nm_size;
1598 	mem_obj->nmo_data = netmap_mem_d->nm_buffer;
1599 
1600 	return (0);
1601 }
1602 
1603 
1604 /*
1605  * Finalize the memory allocator.
1606  *
1607  * Free all the memory objects contained inside the list, and deallocate
1608  * the pool of memory; finally free the memory allocator descriptor.
1609  */
1610 static void
1611 netmap_memory_fini(void)
1612 {
1613 	struct netmap_mem_obj *mem_obj;
1614 
1615 	while (!TAILQ_EMPTY(&netmap_mem_d->nm_molist)) {
1616 		mem_obj = TAILQ_FIRST(&netmap_mem_d->nm_molist);
1617 		TAILQ_REMOVE(&netmap_mem_d->nm_molist, mem_obj, nmo_next);
1618 		if (mem_obj->nmo_used == 1) {
1619 			printf("netmap: leaked %d bytes at %p\n",
1620 			       (int)mem_obj->nmo_size,
1621 			       mem_obj->nmo_data);
1622 		}
1623 		free(mem_obj, M_NETMAP);
1624 	}
1625 	contigfree(netmap_mem_d->nm_buffer, netmap_mem_d->nm_totalsize, M_NETMAP);
1626 	// XXX mutex_destroy(nm_mtx);
1627 	free(netmap_mem_d, M_NETMAP);
1628 }
1629 
1630 
1631 /*
1632  * Module loader.
1633  *
1634  * Create the /dev/netmap device and initialize all global
1635  * variables.
1636  *
1637  * Return 0 on success, errno on failure.
1638  */
1639 static int
1640 netmap_init(void)
1641 {
1642 	int error;
1643 
1644 
1645 	error = netmap_memory_init();
1646 	if (error != 0) {
1647 		printf("netmap: unable to initialize the memory allocator.");
1648 		return (error);
1649 	}
1650 	printf("netmap: loaded module with %d Mbytes\n",
1651 		(int)(netmap_mem_d->nm_totalsize >> 20));
1652 
1653 	netmap_dev = make_dev(&netmap_cdevsw, 0, UID_ROOT, GID_WHEEL, 0660,
1654 			      "netmap");
1655 
1656 	return (0);
1657 }
1658 
1659 
1660 /*
1661  * Module unloader.
1662  *
1663  * Free all the memory, and destroy the ``/dev/netmap`` device.
1664  */
1665 static void
1666 netmap_fini(void)
1667 {
1668 	destroy_dev(netmap_dev);
1669 
1670 	netmap_memory_fini();
1671 
1672 	printf("netmap: unloaded module.\n");
1673 }
1674 
1675 
1676 /*
1677  * Kernel entry point.
1678  *
1679  * Initialize/finalize the module and return.
1680  *
1681  * Return 0 on success, errno on failure.
1682  */
1683 static int
1684 netmap_loader(__unused struct module *module, int event, __unused void *arg)
1685 {
1686 	int error = 0;
1687 
1688 	switch (event) {
1689 	case MOD_LOAD:
1690 		error = netmap_init();
1691 		break;
1692 
1693 	case MOD_UNLOAD:
1694 		netmap_fini();
1695 		break;
1696 
1697 	default:
1698 		error = EOPNOTSUPP;
1699 		break;
1700 	}
1701 
1702 	return (error);
1703 }
1704 
1705 
1706 DEV_MODULE(netmap, netmap_loader, NULL);
1707