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