xref: /freebsd/sys/dev/netmap/netmap_freebsd.c (revision 4ac8f4067096a9d4a00e41cd53bd5c4fa295fd15)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (C) 2013-2014 Universita` di Pisa. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *   1. Redistributions of source code must retain the above copyright
10  *      notice, this list of conditions and the following disclaimer.
11  *   2. Redistributions in binary form must reproduce the above copyright
12  *      notice, this list of conditions and the following disclaimer in the
13  *      documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 /* $FreeBSD$ */
29 #include "opt_inet.h"
30 #include "opt_inet6.h"
31 
32 #include <sys/param.h>
33 #include <sys/module.h>
34 #include <sys/errno.h>
35 #include <sys/eventhandler.h>
36 #include <sys/jail.h>
37 #include <sys/poll.h>  /* POLLIN, POLLOUT */
38 #include <sys/kernel.h> /* types used in module initialization */
39 #include <sys/conf.h>	/* DEV_MODULE_ORDERED */
40 #include <sys/endian.h>
41 #include <sys/syscallsubr.h> /* kern_ioctl() */
42 
43 #include <sys/rwlock.h>
44 
45 #include <vm/vm.h>      /* vtophys */
46 #include <vm/pmap.h>    /* vtophys */
47 #include <vm/vm_param.h>
48 #include <vm/vm_object.h>
49 #include <vm/vm_page.h>
50 #include <vm/vm_pager.h>
51 #include <vm/uma.h>
52 
53 
54 #include <sys/malloc.h>
55 #include <sys/socket.h> /* sockaddrs */
56 #include <sys/selinfo.h>
57 #include <sys/kthread.h> /* kthread_add() */
58 #include <sys/proc.h> /* PROC_LOCK() */
59 #include <sys/unistd.h> /* RFNOWAIT */
60 #include <sys/sched.h> /* sched_bind() */
61 #include <sys/smp.h> /* mp_maxid */
62 #include <sys/taskqueue.h> /* taskqueue_enqueue(), taskqueue_create(), ... */
63 #include <net/if.h>
64 #include <net/if_var.h>
65 #include <net/if_types.h> /* IFT_ETHER */
66 #include <net/ethernet.h> /* ether_ifdetach */
67 #include <net/if_dl.h> /* LLADDR */
68 #include <machine/bus.h>        /* bus_dmamap_* */
69 #include <netinet/in.h>		/* in6_cksum_pseudo() */
70 #include <machine/in_cksum.h>  /* in_pseudo(), in_cksum_hdr() */
71 
72 #include <net/netmap.h>
73 #include <dev/netmap/netmap_kern.h>
74 #include <net/netmap_virt.h>
75 #include <dev/netmap/netmap_mem2.h>
76 
77 
78 /* ======================== FREEBSD-SPECIFIC ROUTINES ================== */
79 
80 static void
81 nm_kqueue_notify(void *opaque, int pending)
82 {
83 	struct nm_selinfo *si = opaque;
84 
85 	/* We use a non-zero hint to distinguish this notification call
86 	 * from the call done in kqueue_scan(), which uses hint=0.
87 	 */
88 	KNOTE_UNLOCKED(&si->si.si_note, /*hint=*/0x100);
89 }
90 
91 int nm_os_selinfo_init(NM_SELINFO_T *si, const char *name) {
92 	int err;
93 
94 	TASK_INIT(&si->ntfytask, 0, nm_kqueue_notify, si);
95 	si->ntfytq = taskqueue_create(name, M_NOWAIT,
96 	    taskqueue_thread_enqueue, &si->ntfytq);
97 	if (si->ntfytq == NULL)
98 		return -ENOMEM;
99 	err = taskqueue_start_threads(&si->ntfytq, 1, PI_NET, "tq %s", name);
100 	if (err) {
101 		taskqueue_free(si->ntfytq);
102 		si->ntfytq = NULL;
103 		return err;
104 	}
105 
106 	snprintf(si->mtxname, sizeof(si->mtxname), "nmkl%s", name);
107 	mtx_init(&si->m, si->mtxname, NULL, MTX_DEF);
108 	knlist_init_mtx(&si->si.si_note, &si->m);
109 	si->kqueue_users = 0;
110 
111 	return (0);
112 }
113 
114 void
115 nm_os_selinfo_uninit(NM_SELINFO_T *si)
116 {
117 	if (si->ntfytq == NULL) {
118 		return;	/* si was not initialized */
119 	}
120 	taskqueue_drain(si->ntfytq, &si->ntfytask);
121 	taskqueue_free(si->ntfytq);
122 	si->ntfytq = NULL;
123 	knlist_delete(&si->si.si_note, curthread, /*islocked=*/0);
124 	knlist_destroy(&si->si.si_note);
125 	/* now we don't need the mutex anymore */
126 	mtx_destroy(&si->m);
127 }
128 
129 void *
130 nm_os_malloc(size_t size)
131 {
132 	return malloc(size, M_DEVBUF, M_NOWAIT | M_ZERO);
133 }
134 
135 void *
136 nm_os_realloc(void *addr, size_t new_size, size_t old_size __unused)
137 {
138 	return realloc(addr, new_size, M_DEVBUF, M_NOWAIT | M_ZERO);
139 }
140 
141 void
142 nm_os_free(void *addr)
143 {
144 	free(addr, M_DEVBUF);
145 }
146 
147 void
148 nm_os_ifnet_lock(void)
149 {
150 	IFNET_RLOCK();
151 }
152 
153 void
154 nm_os_ifnet_unlock(void)
155 {
156 	IFNET_RUNLOCK();
157 }
158 
159 static int netmap_use_count = 0;
160 
161 void
162 nm_os_get_module(void)
163 {
164 	netmap_use_count++;
165 }
166 
167 void
168 nm_os_put_module(void)
169 {
170 	netmap_use_count--;
171 }
172 
173 static void
174 netmap_ifnet_arrival_handler(void *arg __unused, struct ifnet *ifp)
175 {
176 	netmap_undo_zombie(ifp);
177 }
178 
179 static void
180 netmap_ifnet_departure_handler(void *arg __unused, struct ifnet *ifp)
181 {
182 	netmap_make_zombie(ifp);
183 }
184 
185 static eventhandler_tag nm_ifnet_ah_tag;
186 static eventhandler_tag nm_ifnet_dh_tag;
187 
188 int
189 nm_os_ifnet_init(void)
190 {
191 	nm_ifnet_ah_tag =
192 		EVENTHANDLER_REGISTER(ifnet_arrival_event,
193 				netmap_ifnet_arrival_handler,
194 				NULL, EVENTHANDLER_PRI_ANY);
195 	nm_ifnet_dh_tag =
196 		EVENTHANDLER_REGISTER(ifnet_departure_event,
197 				netmap_ifnet_departure_handler,
198 				NULL, EVENTHANDLER_PRI_ANY);
199 	return 0;
200 }
201 
202 void
203 nm_os_ifnet_fini(void)
204 {
205 	EVENTHANDLER_DEREGISTER(ifnet_arrival_event,
206 			nm_ifnet_ah_tag);
207 	EVENTHANDLER_DEREGISTER(ifnet_departure_event,
208 			nm_ifnet_dh_tag);
209 }
210 
211 unsigned
212 nm_os_ifnet_mtu(struct ifnet *ifp)
213 {
214 	return ifp->if_mtu;
215 }
216 
217 rawsum_t
218 nm_os_csum_raw(uint8_t *data, size_t len, rawsum_t cur_sum)
219 {
220 	/* TODO XXX please use the FreeBSD implementation for this. */
221 	uint16_t *words = (uint16_t *)data;
222 	int nw = len / 2;
223 	int i;
224 
225 	for (i = 0; i < nw; i++)
226 		cur_sum += be16toh(words[i]);
227 
228 	if (len & 1)
229 		cur_sum += (data[len-1] << 8);
230 
231 	return cur_sum;
232 }
233 
234 /* Fold a raw checksum: 'cur_sum' is in host byte order, while the
235  * return value is in network byte order.
236  */
237 uint16_t
238 nm_os_csum_fold(rawsum_t cur_sum)
239 {
240 	/* TODO XXX please use the FreeBSD implementation for this. */
241 	while (cur_sum >> 16)
242 		cur_sum = (cur_sum & 0xFFFF) + (cur_sum >> 16);
243 
244 	return htobe16((~cur_sum) & 0xFFFF);
245 }
246 
247 uint16_t nm_os_csum_ipv4(struct nm_iphdr *iph)
248 {
249 #if 0
250 	return in_cksum_hdr((void *)iph);
251 #else
252 	return nm_os_csum_fold(nm_os_csum_raw((uint8_t*)iph, sizeof(struct nm_iphdr), 0));
253 #endif
254 }
255 
256 void
257 nm_os_csum_tcpudp_ipv4(struct nm_iphdr *iph, void *data,
258 					size_t datalen, uint16_t *check)
259 {
260 #ifdef INET
261 	uint16_t pseudolen = datalen + iph->protocol;
262 
263 	/* Compute and insert the pseudo-header checksum. */
264 	*check = in_pseudo(iph->saddr, iph->daddr,
265 				 htobe16(pseudolen));
266 	/* Compute the checksum on TCP/UDP header + payload
267 	 * (includes the pseudo-header).
268 	 */
269 	*check = nm_os_csum_fold(nm_os_csum_raw(data, datalen, 0));
270 #else
271 	static int notsupported = 0;
272 	if (!notsupported) {
273 		notsupported = 1;
274 		nm_prerr("inet4 segmentation not supported");
275 	}
276 #endif
277 }
278 
279 void
280 nm_os_csum_tcpudp_ipv6(struct nm_ipv6hdr *ip6h, void *data,
281 					size_t datalen, uint16_t *check)
282 {
283 #ifdef INET6
284 	*check = in6_cksum_pseudo((void*)ip6h, datalen, ip6h->nexthdr, 0);
285 	*check = nm_os_csum_fold(nm_os_csum_raw(data, datalen, 0));
286 #else
287 	static int notsupported = 0;
288 	if (!notsupported) {
289 		notsupported = 1;
290 		nm_prerr("inet6 segmentation not supported");
291 	}
292 #endif
293 }
294 
295 /* on FreeBSD we send up one packet at a time */
296 void *
297 nm_os_send_up(struct ifnet *ifp, struct mbuf *m, struct mbuf *prev)
298 {
299 	NA(ifp)->if_input(ifp, m);
300 	return NULL;
301 }
302 
303 int
304 nm_os_mbuf_has_csum_offld(struct mbuf *m)
305 {
306 	return m->m_pkthdr.csum_flags & (CSUM_TCP | CSUM_UDP | CSUM_SCTP |
307 					 CSUM_TCP_IPV6 | CSUM_UDP_IPV6 |
308 					 CSUM_SCTP_IPV6);
309 }
310 
311 int
312 nm_os_mbuf_has_seg_offld(struct mbuf *m)
313 {
314 	return m->m_pkthdr.csum_flags & CSUM_TSO;
315 }
316 
317 static void
318 freebsd_generic_rx_handler(struct ifnet *ifp, struct mbuf *m)
319 {
320 	int stolen;
321 
322 	if (unlikely(!NM_NA_VALID(ifp))) {
323 		nm_prlim(1, "Warning: RX packet intercepted, but no"
324 				" emulated adapter");
325 		return;
326 	}
327 
328 	stolen = generic_rx_handler(ifp, m);
329 	if (!stolen) {
330 		struct netmap_generic_adapter *gna =
331 				(struct netmap_generic_adapter *)NA(ifp);
332 		gna->save_if_input(ifp, m);
333 	}
334 }
335 
336 /*
337  * Intercept the rx routine in the standard device driver.
338  * Second argument is non-zero to intercept, 0 to restore
339  */
340 int
341 nm_os_catch_rx(struct netmap_generic_adapter *gna, int intercept)
342 {
343 	struct netmap_adapter *na = &gna->up.up;
344 	struct ifnet *ifp = na->ifp;
345 	int ret = 0;
346 
347 	nm_os_ifnet_lock();
348 	if (intercept) {
349 		if (gna->save_if_input) {
350 			nm_prerr("RX on %s already intercepted", na->name);
351 			ret = EBUSY; /* already set */
352 			goto out;
353 		}
354 		gna->save_if_input = ifp->if_input;
355 		ifp->if_input = freebsd_generic_rx_handler;
356 	} else {
357 		if (!gna->save_if_input) {
358 			nm_prerr("Failed to undo RX intercept on %s",
359 				na->name);
360 			ret = EINVAL;  /* not saved */
361 			goto out;
362 		}
363 		ifp->if_input = gna->save_if_input;
364 		gna->save_if_input = NULL;
365 	}
366 out:
367 	nm_os_ifnet_unlock();
368 
369 	return ret;
370 }
371 
372 
373 /*
374  * Intercept the packet steering routine in the tx path,
375  * so that we can decide which queue is used for an mbuf.
376  * Second argument is non-zero to intercept, 0 to restore.
377  * On freebsd we just intercept if_transmit.
378  */
379 int
380 nm_os_catch_tx(struct netmap_generic_adapter *gna, int intercept)
381 {
382 	struct netmap_adapter *na = &gna->up.up;
383 	struct ifnet *ifp = netmap_generic_getifp(gna);
384 
385 	nm_os_ifnet_lock();
386 	if (intercept) {
387 		na->if_transmit = ifp->if_transmit;
388 		ifp->if_transmit = netmap_transmit;
389 	} else {
390 		ifp->if_transmit = na->if_transmit;
391 	}
392 	nm_os_ifnet_unlock();
393 
394 	return 0;
395 }
396 
397 
398 /*
399  * Transmit routine used by generic_netmap_txsync(). Returns 0 on success
400  * and non-zero on error (which may be packet drops or other errors).
401  * addr and len identify the netmap buffer, m is the (preallocated)
402  * mbuf to use for transmissions.
403  *
404  * We should add a reference to the mbuf so the m_freem() at the end
405  * of the transmission does not consume resources.
406  *
407  * On FreeBSD, and on multiqueue cards, we can force the queue using
408  *      if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
409  *              i = m->m_pkthdr.flowid % adapter->num_queues;
410  *      else
411  *              i = curcpu % adapter->num_queues;
412  *
413  */
414 int
415 nm_os_generic_xmit_frame(struct nm_os_gen_arg *a)
416 {
417 	int ret;
418 	u_int len = a->len;
419 	struct ifnet *ifp = a->ifp;
420 	struct mbuf *m = a->m;
421 
422 	/* Link the external storage to
423 	 * the netmap buffer, so that no copy is necessary. */
424 	m->m_ext.ext_buf = m->m_data = a->addr;
425 	m->m_ext.ext_size = len;
426 
427 	m->m_flags |= M_PKTHDR;
428 	m->m_len = m->m_pkthdr.len = len;
429 
430 	/* mbuf refcnt is not contended, no need to use atomic
431 	 * (a memory barrier is enough). */
432 	SET_MBUF_REFCNT(m, 2);
433 	M_HASHTYPE_SET(m, M_HASHTYPE_OPAQUE);
434 	m->m_pkthdr.flowid = a->ring_nr;
435 	m->m_pkthdr.rcvif = ifp; /* used for tx notification */
436 	CURVNET_SET(ifp->if_vnet);
437 	ret = NA(ifp)->if_transmit(ifp, m);
438 	CURVNET_RESTORE();
439 	return ret ? -1 : 0;
440 }
441 
442 
443 struct netmap_adapter *
444 netmap_getna(if_t ifp)
445 {
446 	return (NA((struct ifnet *)ifp));
447 }
448 
449 /*
450  * The following two functions are empty until we have a generic
451  * way to extract the info from the ifp
452  */
453 int
454 nm_os_generic_find_num_desc(struct ifnet *ifp, unsigned int *tx, unsigned int *rx)
455 {
456 	return 0;
457 }
458 
459 
460 void
461 nm_os_generic_find_num_queues(struct ifnet *ifp, u_int *txq, u_int *rxq)
462 {
463 	unsigned num_rings = netmap_generic_rings ? netmap_generic_rings : 1;
464 
465 	*txq = num_rings;
466 	*rxq = num_rings;
467 }
468 
469 void
470 nm_os_generic_set_features(struct netmap_generic_adapter *gna)
471 {
472 
473 	gna->rxsg = 1; /* Supported through m_copydata. */
474 	gna->txqdisc = 0; /* Not supported. */
475 }
476 
477 void
478 nm_os_mitigation_init(struct nm_generic_mit *mit, int idx, struct netmap_adapter *na)
479 {
480 	mit->mit_pending = 0;
481 	mit->mit_ring_idx = idx;
482 	mit->mit_na = na;
483 }
484 
485 
486 void
487 nm_os_mitigation_start(struct nm_generic_mit *mit)
488 {
489 }
490 
491 
492 void
493 nm_os_mitigation_restart(struct nm_generic_mit *mit)
494 {
495 }
496 
497 
498 int
499 nm_os_mitigation_active(struct nm_generic_mit *mit)
500 {
501 
502 	return 0;
503 }
504 
505 
506 void
507 nm_os_mitigation_cleanup(struct nm_generic_mit *mit)
508 {
509 }
510 
511 static int
512 nm_vi_dummy(struct ifnet *ifp, u_long cmd, caddr_t addr)
513 {
514 
515 	return EINVAL;
516 }
517 
518 static void
519 nm_vi_start(struct ifnet *ifp)
520 {
521 	panic("nm_vi_start() must not be called");
522 }
523 
524 /*
525  * Index manager of persistent virtual interfaces.
526  * It is used to decide the lowest byte of the MAC address.
527  * We use the same algorithm with management of bridge port index.
528  */
529 #define NM_VI_MAX	255
530 static struct {
531 	uint8_t index[NM_VI_MAX]; /* XXX just for a reasonable number */
532 	uint8_t active;
533 	struct mtx lock;
534 } nm_vi_indices;
535 
536 void
537 nm_os_vi_init_index(void)
538 {
539 	int i;
540 	for (i = 0; i < NM_VI_MAX; i++)
541 		nm_vi_indices.index[i] = i;
542 	nm_vi_indices.active = 0;
543 	mtx_init(&nm_vi_indices.lock, "nm_vi_indices_lock", NULL, MTX_DEF);
544 }
545 
546 /* return -1 if no index available */
547 static int
548 nm_vi_get_index(void)
549 {
550 	int ret;
551 
552 	mtx_lock(&nm_vi_indices.lock);
553 	ret = nm_vi_indices.active == NM_VI_MAX ? -1 :
554 		nm_vi_indices.index[nm_vi_indices.active++];
555 	mtx_unlock(&nm_vi_indices.lock);
556 	return ret;
557 }
558 
559 static void
560 nm_vi_free_index(uint8_t val)
561 {
562 	int i, lim;
563 
564 	mtx_lock(&nm_vi_indices.lock);
565 	lim = nm_vi_indices.active;
566 	for (i = 0; i < lim; i++) {
567 		if (nm_vi_indices.index[i] == val) {
568 			/* swap index[lim-1] and j */
569 			int tmp = nm_vi_indices.index[lim-1];
570 			nm_vi_indices.index[lim-1] = val;
571 			nm_vi_indices.index[i] = tmp;
572 			nm_vi_indices.active--;
573 			break;
574 		}
575 	}
576 	if (lim == nm_vi_indices.active)
577 		nm_prerr("Index %u not found", val);
578 	mtx_unlock(&nm_vi_indices.lock);
579 }
580 #undef NM_VI_MAX
581 
582 /*
583  * Implementation of a netmap-capable virtual interface that
584  * registered to the system.
585  * It is based on if_tap.c and ip_fw_log.c in FreeBSD 9.
586  *
587  * Note: Linux sets refcount to 0 on allocation of net_device,
588  * then increments it on registration to the system.
589  * FreeBSD sets refcount to 1 on if_alloc(), and does not
590  * increment this refcount on if_attach().
591  */
592 int
593 nm_os_vi_persist(const char *name, struct ifnet **ret)
594 {
595 	struct ifnet *ifp;
596 	u_short macaddr_hi;
597 	uint32_t macaddr_mid;
598 	u_char eaddr[6];
599 	int unit = nm_vi_get_index(); /* just to decide MAC address */
600 
601 	if (unit < 0)
602 		return EBUSY;
603 	/*
604 	 * We use the same MAC address generation method with tap
605 	 * except for the highest octet is 00:be instead of 00:bd
606 	 */
607 	macaddr_hi = htons(0x00be); /* XXX tap + 1 */
608 	macaddr_mid = (uint32_t) ticks;
609 	bcopy(&macaddr_hi, eaddr, sizeof(short));
610 	bcopy(&macaddr_mid, &eaddr[2], sizeof(uint32_t));
611 	eaddr[5] = (uint8_t)unit;
612 
613 	ifp = if_alloc(IFT_ETHER);
614 	if (ifp == NULL) {
615 		nm_prerr("if_alloc failed");
616 		return ENOMEM;
617 	}
618 	if_initname(ifp, name, IF_DUNIT_NONE);
619 	ifp->if_mtu = 65536;
620 	ifp->if_flags = IFF_UP | IFF_SIMPLEX | IFF_MULTICAST;
621 	ifp->if_init = (void *)nm_vi_dummy;
622 	ifp->if_ioctl = nm_vi_dummy;
623 	ifp->if_start = nm_vi_start;
624 	ifp->if_mtu = ETHERMTU;
625 	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
626 	ifp->if_capabilities |= IFCAP_LINKSTATE;
627 	ifp->if_capenable |= IFCAP_LINKSTATE;
628 
629 	ether_ifattach(ifp, eaddr);
630 	*ret = ifp;
631 	return 0;
632 }
633 
634 /* unregister from the system and drop the final refcount */
635 void
636 nm_os_vi_detach(struct ifnet *ifp)
637 {
638 	nm_vi_free_index(((char *)IF_LLADDR(ifp))[5]);
639 	ether_ifdetach(ifp);
640 	if_free(ifp);
641 }
642 
643 #ifdef WITH_EXTMEM
644 #include <vm/vm_map.h>
645 #include <vm/vm_extern.h>
646 #include <vm/vm_kern.h>
647 struct nm_os_extmem {
648 	vm_object_t obj;
649 	vm_offset_t kva;
650 	vm_offset_t size;
651 	uintptr_t scan;
652 };
653 
654 void
655 nm_os_extmem_delete(struct nm_os_extmem *e)
656 {
657 	nm_prinf("freeing %zx bytes", (size_t)e->size);
658 	vm_map_remove(kernel_map, e->kva, e->kva + e->size);
659 	nm_os_free(e);
660 }
661 
662 char *
663 nm_os_extmem_nextpage(struct nm_os_extmem *e)
664 {
665 	char *rv = NULL;
666 	if (e->scan < e->kva + e->size) {
667 		rv = (char *)e->scan;
668 		e->scan += PAGE_SIZE;
669 	}
670 	return rv;
671 }
672 
673 int
674 nm_os_extmem_isequal(struct nm_os_extmem *e1, struct nm_os_extmem *e2)
675 {
676 	return (e1->obj == e2->obj);
677 }
678 
679 int
680 nm_os_extmem_nr_pages(struct nm_os_extmem *e)
681 {
682 	return e->size >> PAGE_SHIFT;
683 }
684 
685 struct nm_os_extmem *
686 nm_os_extmem_create(unsigned long p, struct nmreq_pools_info *pi, int *perror)
687 {
688 	vm_map_t map;
689 	vm_map_entry_t entry;
690 	vm_object_t obj;
691 	vm_prot_t prot;
692 	vm_pindex_t index;
693 	boolean_t wired;
694 	struct nm_os_extmem *e = NULL;
695 	int rv, error = 0;
696 
697 	e = nm_os_malloc(sizeof(*e));
698 	if (e == NULL) {
699 		error = ENOMEM;
700 		goto out;
701 	}
702 
703 	map = &curthread->td_proc->p_vmspace->vm_map;
704 	rv = vm_map_lookup(&map, p, VM_PROT_RW, &entry,
705 			&obj, &index, &prot, &wired);
706 	if (rv != KERN_SUCCESS) {
707 		nm_prerr("address %lx not found", p);
708 		error = vm_mmap_to_errno(rv);
709 		goto out_free;
710 	}
711 	vm_object_reference(obj);
712 
713 	/* check that we are given the whole vm_object ? */
714 	vm_map_lookup_done(map, entry);
715 
716 	e->obj = obj;
717 	/* Wire the memory and add the vm_object to the kernel map,
718 	 * to make sure that it is not freed even if all the processes
719 	 * that are mmap()ing should munmap() it.
720 	 */
721 	e->kva = vm_map_min(kernel_map);
722 	e->size = obj->size << PAGE_SHIFT;
723 	rv = vm_map_find(kernel_map, obj, 0, &e->kva, e->size, 0,
724 			VMFS_OPTIMAL_SPACE, VM_PROT_READ | VM_PROT_WRITE,
725 			VM_PROT_READ | VM_PROT_WRITE, 0);
726 	if (rv != KERN_SUCCESS) {
727 		nm_prerr("vm_map_find(%zx) failed", (size_t)e->size);
728 		error = vm_mmap_to_errno(rv);
729 		goto out_rel;
730 	}
731 	rv = vm_map_wire(kernel_map, e->kva, e->kva + e->size,
732 			VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
733 	if (rv != KERN_SUCCESS) {
734 		nm_prerr("vm_map_wire failed");
735 		error = vm_mmap_to_errno(rv);
736 		goto out_rem;
737 	}
738 
739 	e->scan = e->kva;
740 
741 	return e;
742 
743 out_rem:
744 	vm_map_remove(kernel_map, e->kva, e->kva + e->size);
745 out_rel:
746 	vm_object_deallocate(e->obj);
747 	e->obj = NULL;
748 out_free:
749 	nm_os_free(e);
750 out:
751 	if (perror)
752 		*perror = error;
753 	return NULL;
754 }
755 #endif /* WITH_EXTMEM */
756 
757 /* ================== PTNETMAP GUEST SUPPORT ==================== */
758 
759 #ifdef WITH_PTNETMAP
760 #include <sys/bus.h>
761 #include <sys/rman.h>
762 #include <machine/bus.h>        /* bus_dmamap_* */
763 #include <machine/resource.h>
764 #include <dev/pci/pcivar.h>
765 #include <dev/pci/pcireg.h>
766 /*
767  * ptnetmap memory device (memdev) for freebsd guest,
768  * ssed to expose host netmap memory to the guest through a PCI BAR.
769  */
770 
771 /*
772  * ptnetmap memdev private data structure
773  */
774 struct ptnetmap_memdev {
775 	device_t dev;
776 	struct resource *pci_io;
777 	struct resource *pci_mem;
778 	struct netmap_mem_d *nm_mem;
779 };
780 
781 static int	ptn_memdev_probe(device_t);
782 static int	ptn_memdev_attach(device_t);
783 static int	ptn_memdev_detach(device_t);
784 static int	ptn_memdev_shutdown(device_t);
785 
786 static device_method_t ptn_memdev_methods[] = {
787 	DEVMETHOD(device_probe, ptn_memdev_probe),
788 	DEVMETHOD(device_attach, ptn_memdev_attach),
789 	DEVMETHOD(device_detach, ptn_memdev_detach),
790 	DEVMETHOD(device_shutdown, ptn_memdev_shutdown),
791 	DEVMETHOD_END
792 };
793 
794 static driver_t ptn_memdev_driver = {
795 	PTNETMAP_MEMDEV_NAME,
796 	ptn_memdev_methods,
797 	sizeof(struct ptnetmap_memdev),
798 };
799 
800 /* We use (SI_ORDER_MIDDLE+1) here, see DEV_MODULE_ORDERED() invocation
801  * below. */
802 DRIVER_MODULE_ORDERED(ptn_memdev, pci, ptn_memdev_driver, NULL, NULL,
803 		      SI_ORDER_MIDDLE + 1);
804 
805 /*
806  * Map host netmap memory through PCI-BAR in the guest OS,
807  * returning physical (nm_paddr) and virtual (nm_addr) addresses
808  * of the netmap memory mapped in the guest.
809  */
810 int
811 nm_os_pt_memdev_iomap(struct ptnetmap_memdev *ptn_dev, vm_paddr_t *nm_paddr,
812 		      void **nm_addr, uint64_t *mem_size)
813 {
814 	int rid;
815 
816 	nm_prinf("ptn_memdev_driver iomap");
817 
818 	rid = PCIR_BAR(PTNETMAP_MEM_PCI_BAR);
819 	*mem_size = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMSIZE_HI);
820 	*mem_size = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMSIZE_LO) |
821 			(*mem_size << 32);
822 
823 	/* map memory allocator */
824 	ptn_dev->pci_mem = bus_alloc_resource(ptn_dev->dev, SYS_RES_MEMORY,
825 			&rid, 0, ~0, *mem_size, RF_ACTIVE);
826 	if (ptn_dev->pci_mem == NULL) {
827 		*nm_paddr = 0;
828 		*nm_addr = NULL;
829 		return ENOMEM;
830 	}
831 
832 	*nm_paddr = rman_get_start(ptn_dev->pci_mem);
833 	*nm_addr = rman_get_virtual(ptn_dev->pci_mem);
834 
835 	nm_prinf("=== BAR %d start %lx len %lx mem_size %lx ===",
836 			PTNETMAP_MEM_PCI_BAR,
837 			(unsigned long)(*nm_paddr),
838 			(unsigned long)rman_get_size(ptn_dev->pci_mem),
839 			(unsigned long)*mem_size);
840 	return (0);
841 }
842 
843 uint32_t
844 nm_os_pt_memdev_ioread(struct ptnetmap_memdev *ptn_dev, unsigned int reg)
845 {
846 	return bus_read_4(ptn_dev->pci_io, reg);
847 }
848 
849 /* Unmap host netmap memory. */
850 void
851 nm_os_pt_memdev_iounmap(struct ptnetmap_memdev *ptn_dev)
852 {
853 	nm_prinf("ptn_memdev_driver iounmap");
854 
855 	if (ptn_dev->pci_mem) {
856 		bus_release_resource(ptn_dev->dev, SYS_RES_MEMORY,
857 			PCIR_BAR(PTNETMAP_MEM_PCI_BAR), ptn_dev->pci_mem);
858 		ptn_dev->pci_mem = NULL;
859 	}
860 }
861 
862 /* Device identification routine, return BUS_PROBE_DEFAULT on success,
863  * positive on failure */
864 static int
865 ptn_memdev_probe(device_t dev)
866 {
867 	char desc[256];
868 
869 	if (pci_get_vendor(dev) != PTNETMAP_PCI_VENDOR_ID)
870 		return (ENXIO);
871 	if (pci_get_device(dev) != PTNETMAP_PCI_DEVICE_ID)
872 		return (ENXIO);
873 
874 	snprintf(desc, sizeof(desc), "%s PCI adapter",
875 			PTNETMAP_MEMDEV_NAME);
876 	device_set_desc_copy(dev, desc);
877 
878 	return (BUS_PROBE_DEFAULT);
879 }
880 
881 /* Device initialization routine. */
882 static int
883 ptn_memdev_attach(device_t dev)
884 {
885 	struct ptnetmap_memdev *ptn_dev;
886 	int rid;
887 	uint16_t mem_id;
888 
889 	ptn_dev = device_get_softc(dev);
890 	ptn_dev->dev = dev;
891 
892 	pci_enable_busmaster(dev);
893 
894 	rid = PCIR_BAR(PTNETMAP_IO_PCI_BAR);
895 	ptn_dev->pci_io = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
896 						 RF_ACTIVE);
897 	if (ptn_dev->pci_io == NULL) {
898 	        device_printf(dev, "cannot map I/O space\n");
899 	        return (ENXIO);
900 	}
901 
902 	mem_id = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMID);
903 
904 	/* create guest allocator */
905 	ptn_dev->nm_mem = netmap_mem_pt_guest_attach(ptn_dev, mem_id);
906 	if (ptn_dev->nm_mem == NULL) {
907 		ptn_memdev_detach(dev);
908 	        return (ENOMEM);
909 	}
910 	netmap_mem_get(ptn_dev->nm_mem);
911 
912 	nm_prinf("ptnetmap memdev attached, host memid: %u", mem_id);
913 
914 	return (0);
915 }
916 
917 /* Device removal routine. */
918 static int
919 ptn_memdev_detach(device_t dev)
920 {
921 	struct ptnetmap_memdev *ptn_dev;
922 
923 	ptn_dev = device_get_softc(dev);
924 
925 	if (ptn_dev->nm_mem) {
926 		nm_prinf("ptnetmap memdev detached, host memid %u",
927 			netmap_mem_get_id(ptn_dev->nm_mem));
928 		netmap_mem_put(ptn_dev->nm_mem);
929 		ptn_dev->nm_mem = NULL;
930 	}
931 	if (ptn_dev->pci_mem) {
932 		bus_release_resource(dev, SYS_RES_MEMORY,
933 			PCIR_BAR(PTNETMAP_MEM_PCI_BAR), ptn_dev->pci_mem);
934 		ptn_dev->pci_mem = NULL;
935 	}
936 	if (ptn_dev->pci_io) {
937 		bus_release_resource(dev, SYS_RES_IOPORT,
938 			PCIR_BAR(PTNETMAP_IO_PCI_BAR), ptn_dev->pci_io);
939 		ptn_dev->pci_io = NULL;
940 	}
941 
942 	return (0);
943 }
944 
945 static int
946 ptn_memdev_shutdown(device_t dev)
947 {
948 	return bus_generic_shutdown(dev);
949 }
950 
951 #endif /* WITH_PTNETMAP */
952 
953 /*
954  * In order to track whether pages are still mapped, we hook into
955  * the standard cdev_pager and intercept the constructor and
956  * destructor.
957  */
958 
959 struct netmap_vm_handle_t {
960 	struct cdev 		*dev;
961 	struct netmap_priv_d	*priv;
962 };
963 
964 
965 static int
966 netmap_dev_pager_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot,
967 		vm_ooffset_t foff, struct ucred *cred, u_short *color)
968 {
969 	struct netmap_vm_handle_t *vmh = handle;
970 
971 	if (netmap_verbose)
972 		nm_prinf("handle %p size %jd prot %d foff %jd",
973 			handle, (intmax_t)size, prot, (intmax_t)foff);
974 	if (color)
975 		*color = 0;
976 	dev_ref(vmh->dev);
977 	return 0;
978 }
979 
980 
981 static void
982 netmap_dev_pager_dtor(void *handle)
983 {
984 	struct netmap_vm_handle_t *vmh = handle;
985 	struct cdev *dev = vmh->dev;
986 	struct netmap_priv_d *priv = vmh->priv;
987 
988 	if (netmap_verbose)
989 		nm_prinf("handle %p", handle);
990 	netmap_dtor(priv);
991 	free(vmh, M_DEVBUF);
992 	dev_rel(dev);
993 }
994 
995 
996 static int
997 netmap_dev_pager_fault(vm_object_t object, vm_ooffset_t offset,
998 	int prot, vm_page_t *mres)
999 {
1000 	struct netmap_vm_handle_t *vmh = object->handle;
1001 	struct netmap_priv_d *priv = vmh->priv;
1002 	struct netmap_adapter *na = priv->np_na;
1003 	vm_paddr_t paddr;
1004 	vm_page_t page;
1005 	vm_memattr_t memattr;
1006 
1007 	nm_prdis("object %p offset %jd prot %d mres %p",
1008 			object, (intmax_t)offset, prot, mres);
1009 	memattr = object->memattr;
1010 	paddr = netmap_mem_ofstophys(na->nm_mem, offset);
1011 	if (paddr == 0)
1012 		return VM_PAGER_FAIL;
1013 
1014 	if (((*mres)->flags & PG_FICTITIOUS) != 0) {
1015 		/*
1016 		 * If the passed in result page is a fake page, update it with
1017 		 * the new physical address.
1018 		 */
1019 		page = *mres;
1020 		vm_page_updatefake(page, paddr, memattr);
1021 	} else {
1022 		/*
1023 		 * Replace the passed in reqpage page with our own fake page and
1024 		 * free up the all of the original pages.
1025 		 */
1026 #ifndef VM_OBJECT_WUNLOCK	/* FreeBSD < 10.x */
1027 #define VM_OBJECT_WUNLOCK VM_OBJECT_UNLOCK
1028 #define VM_OBJECT_WLOCK	VM_OBJECT_LOCK
1029 #endif /* VM_OBJECT_WUNLOCK */
1030 
1031 		VM_OBJECT_WUNLOCK(object);
1032 		page = vm_page_getfake(paddr, memattr);
1033 		VM_OBJECT_WLOCK(object);
1034 		vm_page_replace(page, object, (*mres)->pindex, *mres);
1035 		*mres = page;
1036 	}
1037 	page->valid = VM_PAGE_BITS_ALL;
1038 	return (VM_PAGER_OK);
1039 }
1040 
1041 
1042 static struct cdev_pager_ops netmap_cdev_pager_ops = {
1043 	.cdev_pg_ctor = netmap_dev_pager_ctor,
1044 	.cdev_pg_dtor = netmap_dev_pager_dtor,
1045 	.cdev_pg_fault = netmap_dev_pager_fault,
1046 };
1047 
1048 
1049 static int
1050 netmap_mmap_single(struct cdev *cdev, vm_ooffset_t *foff,
1051 	vm_size_t objsize,  vm_object_t *objp, int prot)
1052 {
1053 	int error;
1054 	struct netmap_vm_handle_t *vmh;
1055 	struct netmap_priv_d *priv;
1056 	vm_object_t obj;
1057 
1058 	if (netmap_verbose)
1059 		nm_prinf("cdev %p foff %jd size %jd objp %p prot %d", cdev,
1060 		    (intmax_t )*foff, (intmax_t )objsize, objp, prot);
1061 
1062 	vmh = malloc(sizeof(struct netmap_vm_handle_t), M_DEVBUF,
1063 			      M_NOWAIT | M_ZERO);
1064 	if (vmh == NULL)
1065 		return ENOMEM;
1066 	vmh->dev = cdev;
1067 
1068 	NMG_LOCK();
1069 	error = devfs_get_cdevpriv((void**)&priv);
1070 	if (error)
1071 		goto err_unlock;
1072 	if (priv->np_nifp == NULL) {
1073 		error = EINVAL;
1074 		goto err_unlock;
1075 	}
1076 	vmh->priv = priv;
1077 	priv->np_refs++;
1078 	NMG_UNLOCK();
1079 
1080 	obj = cdev_pager_allocate(vmh, OBJT_DEVICE,
1081 		&netmap_cdev_pager_ops, objsize, prot,
1082 		*foff, NULL);
1083 	if (obj == NULL) {
1084 		nm_prerr("cdev_pager_allocate failed");
1085 		error = EINVAL;
1086 		goto err_deref;
1087 	}
1088 
1089 	*objp = obj;
1090 	return 0;
1091 
1092 err_deref:
1093 	NMG_LOCK();
1094 	priv->np_refs--;
1095 err_unlock:
1096 	NMG_UNLOCK();
1097 // err:
1098 	free(vmh, M_DEVBUF);
1099 	return error;
1100 }
1101 
1102 /*
1103  * On FreeBSD the close routine is only called on the last close on
1104  * the device (/dev/netmap) so we cannot do anything useful.
1105  * To track close() on individual file descriptors we pass netmap_dtor() to
1106  * devfs_set_cdevpriv() on open(). The FreeBSD kernel will call the destructor
1107  * when the last fd pointing to the device is closed.
1108  *
1109  * Note that FreeBSD does not even munmap() on close() so we also have
1110  * to track mmap() ourselves, and postpone the call to
1111  * netmap_dtor() is called when the process has no open fds and no active
1112  * memory maps on /dev/netmap, as in linux.
1113  */
1114 static int
1115 netmap_close(struct cdev *dev, int fflag, int devtype, struct thread *td)
1116 {
1117 	if (netmap_verbose)
1118 		nm_prinf("dev %p fflag 0x%x devtype %d td %p",
1119 			dev, fflag, devtype, td);
1120 	return 0;
1121 }
1122 
1123 
1124 static int
1125 netmap_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
1126 {
1127 	struct netmap_priv_d *priv;
1128 	int error;
1129 
1130 	(void)dev;
1131 	(void)oflags;
1132 	(void)devtype;
1133 	(void)td;
1134 
1135 	NMG_LOCK();
1136 	priv = netmap_priv_new();
1137 	if (priv == NULL) {
1138 		error = ENOMEM;
1139 		goto out;
1140 	}
1141 	error = devfs_set_cdevpriv(priv, netmap_dtor);
1142 	if (error) {
1143 		netmap_priv_delete(priv);
1144 	}
1145 out:
1146 	NMG_UNLOCK();
1147 	return error;
1148 }
1149 
1150 /******************** kthread wrapper ****************/
1151 #include <sys/sysproto.h>
1152 u_int
1153 nm_os_ncpus(void)
1154 {
1155 	return mp_maxid + 1;
1156 }
1157 
1158 struct nm_kctx_ctx {
1159 	/* Userspace thread (kthread creator). */
1160 	struct thread *user_td;
1161 
1162 	/* worker function and parameter */
1163 	nm_kctx_worker_fn_t worker_fn;
1164 	void *worker_private;
1165 
1166 	struct nm_kctx *nmk;
1167 
1168 	/* integer to manage multiple worker contexts (e.g., RX or TX on ptnetmap) */
1169 	long type;
1170 };
1171 
1172 struct nm_kctx {
1173 	struct thread *worker;
1174 	struct mtx worker_lock;
1175 	struct nm_kctx_ctx worker_ctx;
1176 	int run;			/* used to stop kthread */
1177 	int attach_user;		/* kthread attached to user_process */
1178 	int affinity;
1179 };
1180 
1181 static void
1182 nm_kctx_worker(void *data)
1183 {
1184 	struct nm_kctx *nmk = data;
1185 	struct nm_kctx_ctx *ctx = &nmk->worker_ctx;
1186 
1187 	if (nmk->affinity >= 0) {
1188 		thread_lock(curthread);
1189 		sched_bind(curthread, nmk->affinity);
1190 		thread_unlock(curthread);
1191 	}
1192 
1193 	while (nmk->run) {
1194 		/*
1195 		 * check if the parent process dies
1196 		 * (when kthread is attached to user process)
1197 		 */
1198 		if (ctx->user_td) {
1199 			PROC_LOCK(curproc);
1200 			thread_suspend_check(0);
1201 			PROC_UNLOCK(curproc);
1202 		} else {
1203 			kthread_suspend_check();
1204 		}
1205 
1206 		/* Continuously execute worker process. */
1207 		ctx->worker_fn(ctx->worker_private); /* worker body */
1208 	}
1209 
1210 	kthread_exit();
1211 }
1212 
1213 void
1214 nm_os_kctx_worker_setaff(struct nm_kctx *nmk, int affinity)
1215 {
1216 	nmk->affinity = affinity;
1217 }
1218 
1219 struct nm_kctx *
1220 nm_os_kctx_create(struct nm_kctx_cfg *cfg, void *opaque)
1221 {
1222 	struct nm_kctx *nmk = NULL;
1223 
1224 	nmk = malloc(sizeof(*nmk),  M_DEVBUF, M_NOWAIT | M_ZERO);
1225 	if (!nmk)
1226 		return NULL;
1227 
1228 	mtx_init(&nmk->worker_lock, "nm_kthread lock", NULL, MTX_DEF);
1229 	nmk->worker_ctx.worker_fn = cfg->worker_fn;
1230 	nmk->worker_ctx.worker_private = cfg->worker_private;
1231 	nmk->worker_ctx.type = cfg->type;
1232 	nmk->affinity = -1;
1233 
1234 	/* attach kthread to user process (ptnetmap) */
1235 	nmk->attach_user = cfg->attach_user;
1236 
1237 	return nmk;
1238 }
1239 
1240 int
1241 nm_os_kctx_worker_start(struct nm_kctx *nmk)
1242 {
1243 	struct proc *p = NULL;
1244 	int error = 0;
1245 
1246 	/* Temporarily disable this function as it is currently broken
1247 	 * and causes kernel crashes. The failure can be triggered by
1248 	 * the "vale_polling_enable_disable" test in ctrl-api-test.c. */
1249 	return EOPNOTSUPP;
1250 
1251 	if (nmk->worker)
1252 		return EBUSY;
1253 
1254 	/* check if we want to attach kthread to user process */
1255 	if (nmk->attach_user) {
1256 		nmk->worker_ctx.user_td = curthread;
1257 		p = curthread->td_proc;
1258 	}
1259 
1260 	/* enable kthread main loop */
1261 	nmk->run = 1;
1262 	/* create kthread */
1263 	if((error = kthread_add(nm_kctx_worker, nmk, p,
1264 			&nmk->worker, RFNOWAIT /* to be checked */, 0, "nm-kthread-%ld",
1265 			nmk->worker_ctx.type))) {
1266 		goto err;
1267 	}
1268 
1269 	nm_prinf("nm_kthread started td %p", nmk->worker);
1270 
1271 	return 0;
1272 err:
1273 	nm_prerr("nm_kthread start failed err %d", error);
1274 	nmk->worker = NULL;
1275 	return error;
1276 }
1277 
1278 void
1279 nm_os_kctx_worker_stop(struct nm_kctx *nmk)
1280 {
1281 	if (!nmk->worker)
1282 		return;
1283 
1284 	/* tell to kthread to exit from main loop */
1285 	nmk->run = 0;
1286 
1287 	/* wake up kthread if it sleeps */
1288 	kthread_resume(nmk->worker);
1289 
1290 	nmk->worker = NULL;
1291 }
1292 
1293 void
1294 nm_os_kctx_destroy(struct nm_kctx *nmk)
1295 {
1296 	if (!nmk)
1297 		return;
1298 
1299 	if (nmk->worker)
1300 		nm_os_kctx_worker_stop(nmk);
1301 
1302 	free(nmk, M_DEVBUF);
1303 }
1304 
1305 /******************** kqueue support ****************/
1306 
1307 /*
1308  * In addition to calling selwakeuppri(), nm_os_selwakeup() also
1309  * needs to call knote() to wake up kqueue listeners.
1310  * This operation is deferred to a taskqueue in order to avoid possible
1311  * lock order reversals; these may happen because knote() grabs a
1312  * private lock associated to the 'si' (see struct selinfo,
1313  * struct nm_selinfo, and nm_os_selinfo_init), and nm_os_selwakeup()
1314  * can be called while holding the lock associated to a different
1315  * 'si'.
1316  * When calling knote() we use a non-zero 'hint' argument to inform
1317  * the netmap_knrw() function that it is being called from
1318  * 'nm_os_selwakeup'; this is necessary because when netmap_knrw() is
1319  * called by the kevent subsystem (i.e. kevent_scan()) we also need to
1320  * call netmap_poll().
1321  *
1322  * The netmap_kqfilter() function registers one or another f_event
1323  * depending on read or write mode. A pointer to the struct
1324  * 'netmap_priv_d' is stored into kn->kn_hook, so that it can later
1325  * be passed to netmap_poll(). We pass NULL as a third argument to
1326  * netmap_poll(), so that the latter only runs the txsync/rxsync
1327  * (if necessary), and skips the nm_os_selrecord() calls.
1328  */
1329 
1330 
1331 void
1332 nm_os_selwakeup(struct nm_selinfo *si)
1333 {
1334 	selwakeuppri(&si->si, PI_NET);
1335 	if (si->kqueue_users > 0) {
1336 		taskqueue_enqueue(si->ntfytq, &si->ntfytask);
1337 	}
1338 }
1339 
1340 void
1341 nm_os_selrecord(struct thread *td, struct nm_selinfo *si)
1342 {
1343 	selrecord(td, &si->si);
1344 }
1345 
1346 static void
1347 netmap_knrdetach(struct knote *kn)
1348 {
1349 	struct netmap_priv_d *priv = (struct netmap_priv_d *)kn->kn_hook;
1350 	struct nm_selinfo *si = priv->np_si[NR_RX];
1351 
1352 	knlist_remove(&si->si.si_note, kn, /*islocked=*/0);
1353 	NMG_LOCK();
1354 	KASSERT(si->kqueue_users > 0, ("kqueue_user underflow on %s",
1355 	    si->mtxname));
1356 	si->kqueue_users--;
1357 	nm_prinf("kqueue users for %s: %d", si->mtxname, si->kqueue_users);
1358 	NMG_UNLOCK();
1359 }
1360 
1361 static void
1362 netmap_knwdetach(struct knote *kn)
1363 {
1364 	struct netmap_priv_d *priv = (struct netmap_priv_d *)kn->kn_hook;
1365 	struct nm_selinfo *si = priv->np_si[NR_TX];
1366 
1367 	knlist_remove(&si->si.si_note, kn, /*islocked=*/0);
1368 	NMG_LOCK();
1369 	si->kqueue_users--;
1370 	nm_prinf("kqueue users for %s: %d", si->mtxname, si->kqueue_users);
1371 	NMG_UNLOCK();
1372 }
1373 
1374 /*
1375  * Callback triggered by netmap notifications (see netmap_notify()),
1376  * and by the application calling kevent(). In the former case we
1377  * just return 1 (events ready), since we are not able to do better.
1378  * In the latter case we use netmap_poll() to see which events are
1379  * ready.
1380  */
1381 static int
1382 netmap_knrw(struct knote *kn, long hint, int events)
1383 {
1384 	struct netmap_priv_d *priv;
1385 	int revents;
1386 
1387 	if (hint != 0) {
1388 		/* Called from netmap_notify(), typically from a
1389 		 * thread different from the one issuing kevent().
1390 		 * Assume we are ready. */
1391 		return 1;
1392 	}
1393 
1394 	/* Called from kevent(). */
1395 	priv = kn->kn_hook;
1396 	revents = netmap_poll(priv, events, /*thread=*/NULL);
1397 
1398 	return (events & revents) ? 1 : 0;
1399 }
1400 
1401 static int
1402 netmap_knread(struct knote *kn, long hint)
1403 {
1404 	return netmap_knrw(kn, hint, POLLIN);
1405 }
1406 
1407 static int
1408 netmap_knwrite(struct knote *kn, long hint)
1409 {
1410 	return netmap_knrw(kn, hint, POLLOUT);
1411 }
1412 
1413 static struct filterops netmap_rfiltops = {
1414 	.f_isfd = 1,
1415 	.f_detach = netmap_knrdetach,
1416 	.f_event = netmap_knread,
1417 };
1418 
1419 static struct filterops netmap_wfiltops = {
1420 	.f_isfd = 1,
1421 	.f_detach = netmap_knwdetach,
1422 	.f_event = netmap_knwrite,
1423 };
1424 
1425 
1426 /*
1427  * This is called when a thread invokes kevent() to record
1428  * a change in the configuration of the kqueue().
1429  * The 'priv' is the one associated to the open netmap device.
1430  */
1431 static int
1432 netmap_kqfilter(struct cdev *dev, struct knote *kn)
1433 {
1434 	struct netmap_priv_d *priv;
1435 	int error;
1436 	struct netmap_adapter *na;
1437 	struct nm_selinfo *si;
1438 	int ev = kn->kn_filter;
1439 
1440 	if (ev != EVFILT_READ && ev != EVFILT_WRITE) {
1441 		nm_prerr("bad filter request %d", ev);
1442 		return 1;
1443 	}
1444 	error = devfs_get_cdevpriv((void**)&priv);
1445 	if (error) {
1446 		nm_prerr("device not yet setup");
1447 		return 1;
1448 	}
1449 	na = priv->np_na;
1450 	if (na == NULL) {
1451 		nm_prerr("no netmap adapter for this file descriptor");
1452 		return 1;
1453 	}
1454 	/* the si is indicated in the priv */
1455 	si = priv->np_si[(ev == EVFILT_WRITE) ? NR_TX : NR_RX];
1456 	kn->kn_fop = (ev == EVFILT_WRITE) ?
1457 		&netmap_wfiltops : &netmap_rfiltops;
1458 	kn->kn_hook = priv;
1459 	NMG_LOCK();
1460 	si->kqueue_users++;
1461 	nm_prinf("kqueue users for %s: %d", si->mtxname, si->kqueue_users);
1462 	NMG_UNLOCK();
1463 	knlist_add(&si->si.si_note, kn, /*islocked=*/0);
1464 
1465 	return 0;
1466 }
1467 
1468 static int
1469 freebsd_netmap_poll(struct cdev *cdevi __unused, int events, struct thread *td)
1470 {
1471 	struct netmap_priv_d *priv;
1472 	if (devfs_get_cdevpriv((void **)&priv)) {
1473 		return POLLERR;
1474 	}
1475 	return netmap_poll(priv, events, td);
1476 }
1477 
1478 static int
1479 freebsd_netmap_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data,
1480 		int ffla __unused, struct thread *td)
1481 {
1482 	int error;
1483 	struct netmap_priv_d *priv;
1484 
1485 	CURVNET_SET(TD_TO_VNET(td));
1486 	error = devfs_get_cdevpriv((void **)&priv);
1487 	if (error) {
1488 		/* XXX ENOENT should be impossible, since the priv
1489 		 * is now created in the open */
1490 		if (error == ENOENT)
1491 			error = ENXIO;
1492 		goto out;
1493 	}
1494 	error = netmap_ioctl(priv, cmd, data, td, /*nr_body_is_user=*/1);
1495 out:
1496 	CURVNET_RESTORE();
1497 
1498 	return error;
1499 }
1500 
1501 void
1502 nm_os_onattach(struct ifnet *ifp)
1503 {
1504 	ifp->if_capabilities |= IFCAP_NETMAP;
1505 }
1506 
1507 void
1508 nm_os_onenter(struct ifnet *ifp)
1509 {
1510 	struct netmap_adapter *na = NA(ifp);
1511 
1512 	na->if_transmit = ifp->if_transmit;
1513 	ifp->if_transmit = netmap_transmit;
1514 	ifp->if_capenable |= IFCAP_NETMAP;
1515 }
1516 
1517 void
1518 nm_os_onexit(struct ifnet *ifp)
1519 {
1520 	struct netmap_adapter *na = NA(ifp);
1521 
1522 	ifp->if_transmit = na->if_transmit;
1523 	ifp->if_capenable &= ~IFCAP_NETMAP;
1524 }
1525 
1526 extern struct cdevsw netmap_cdevsw; /* XXX used in netmap.c, should go elsewhere */
1527 struct cdevsw netmap_cdevsw = {
1528 	.d_version = D_VERSION,
1529 	.d_name = "netmap",
1530 	.d_open = netmap_open,
1531 	.d_mmap_single = netmap_mmap_single,
1532 	.d_ioctl = freebsd_netmap_ioctl,
1533 	.d_poll = freebsd_netmap_poll,
1534 	.d_kqfilter = netmap_kqfilter,
1535 	.d_close = netmap_close,
1536 };
1537 /*--- end of kqueue support ----*/
1538 
1539 /*
1540  * Kernel entry point.
1541  *
1542  * Initialize/finalize the module and return.
1543  *
1544  * Return 0 on success, errno on failure.
1545  */
1546 static int
1547 netmap_loader(__unused struct module *module, int event, __unused void *arg)
1548 {
1549 	int error = 0;
1550 
1551 	switch (event) {
1552 	case MOD_LOAD:
1553 		error = netmap_init();
1554 		break;
1555 
1556 	case MOD_UNLOAD:
1557 		/*
1558 		 * if some one is still using netmap,
1559 		 * then the module can not be unloaded.
1560 		 */
1561 		if (netmap_use_count) {
1562 			nm_prerr("netmap module can not be unloaded - netmap_use_count: %d",
1563 					netmap_use_count);
1564 			error = EBUSY;
1565 			break;
1566 		}
1567 		netmap_fini();
1568 		break;
1569 
1570 	default:
1571 		error = EOPNOTSUPP;
1572 		break;
1573 	}
1574 
1575 	return (error);
1576 }
1577 
1578 #ifdef DEV_MODULE_ORDERED
1579 /*
1580  * The netmap module contains three drivers: (i) the netmap character device
1581  * driver; (ii) the ptnetmap memdev PCI device driver, (iii) the ptnet PCI
1582  * device driver. The attach() routines of both (ii) and (iii) need the
1583  * lock of the global allocator, and such lock is initialized in netmap_init(),
1584  * which is part of (i).
1585  * Therefore, we make sure that (i) is loaded before (ii) and (iii), using
1586  * the 'order' parameter of driver declaration macros. For (i), we specify
1587  * SI_ORDER_MIDDLE, while higher orders are used with the DRIVER_MODULE_ORDERED
1588  * macros for (ii) and (iii).
1589  */
1590 DEV_MODULE_ORDERED(netmap, netmap_loader, NULL, SI_ORDER_MIDDLE);
1591 #else /* !DEV_MODULE_ORDERED */
1592 DEV_MODULE(netmap, netmap_loader, NULL);
1593 #endif /* DEV_MODULE_ORDERED  */
1594 MODULE_DEPEND(netmap, pci, 1, 1, 1);
1595 MODULE_VERSION(netmap, 1);
1596 /* reduce conditional code */
1597 // linux API, use for the knlist in FreeBSD
1598 /* use a private mutex for the knlist */
1599