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