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