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/param.h>
31 #include <sys/module.h>
32 #include <sys/errno.h>
33 #include <sys/jail.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,
648 		      void **nm_addr)
649 {
650 	uint32_t mem_size;
651 	int rid;
652 
653 	D("ptn_memdev_driver iomap");
654 
655 	rid = PCIR_BAR(PTNETMAP_MEM_PCI_BAR);
656 	mem_size = ptn_ioread32(ptn_dev, PTNETMAP_IO_PCI_MEMSIZE);
657 
658 	/* map memory allocator */
659 	ptn_dev->pci_mem = bus_alloc_resource(ptn_dev->dev, SYS_RES_MEMORY,
660 			&rid, 0, ~0, mem_size, RF_ACTIVE);
661 	if (ptn_dev->pci_mem == NULL) {
662 		*nm_paddr = 0;
663 		*nm_addr = 0;
664 		return ENOMEM;
665 	}
666 
667 	*nm_paddr = rman_get_start(ptn_dev->pci_mem);
668 	*nm_addr = rman_get_virtual(ptn_dev->pci_mem);
669 
670 	D("=== BAR %d start %lx len %lx mem_size %x ===",
671 			PTNETMAP_MEM_PCI_BAR,
672 			(unsigned long)(*nm_paddr),
673 			(unsigned long)rman_get_size(ptn_dev->pci_mem),
674 			mem_size);
675 	return (0);
676 }
677 
678 /* Unmap host netmap memory. */
679 void
680 nm_os_pt_memdev_iounmap(struct ptnetmap_memdev *ptn_dev)
681 {
682 	D("ptn_memdev_driver iounmap");
683 
684 	if (ptn_dev->pci_mem) {
685 		bus_release_resource(ptn_dev->dev, SYS_RES_MEMORY,
686 			PCIR_BAR(PTNETMAP_MEM_PCI_BAR), ptn_dev->pci_mem);
687 		ptn_dev->pci_mem = NULL;
688 	}
689 }
690 
691 /* Device identification routine, return BUS_PROBE_DEFAULT on success,
692  * positive on failure */
693 static int
694 ptn_memdev_probe(device_t dev)
695 {
696 	char desc[256];
697 
698 	if (pci_get_vendor(dev) != PTNETMAP_PCI_VENDOR_ID)
699 		return (ENXIO);
700 	if (pci_get_device(dev) != PTNETMAP_PCI_DEVICE_ID)
701 		return (ENXIO);
702 
703 	snprintf(desc, sizeof(desc), "%s PCI adapter",
704 			PTNETMAP_MEMDEV_NAME);
705 	device_set_desc_copy(dev, desc);
706 
707 	return (BUS_PROBE_DEFAULT);
708 }
709 
710 /* Device initialization routine. */
711 static int
712 ptn_memdev_attach(device_t dev)
713 {
714 	struct ptnetmap_memdev *ptn_dev;
715 	int rid;
716 	uint16_t mem_id;
717 
718 	D("ptn_memdev_driver attach");
719 
720 	ptn_dev = device_get_softc(dev);
721 	ptn_dev->dev = dev;
722 
723 	pci_enable_busmaster(dev);
724 
725 	rid = PCIR_BAR(PTNETMAP_IO_PCI_BAR);
726 	ptn_dev->pci_io = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
727 						 RF_ACTIVE);
728 	if (ptn_dev->pci_io == NULL) {
729 	        device_printf(dev, "cannot map I/O space\n");
730 	        return (ENXIO);
731 	}
732 
733 	mem_id = ptn_ioread16(ptn_dev, PTNETMAP_IO_PCI_HOSTID);
734 
735 	/* create guest allocator */
736 	ptn_dev->nm_mem = netmap_mem_pt_guest_attach(ptn_dev, mem_id);
737 	if (ptn_dev->nm_mem == NULL) {
738 		ptn_memdev_detach(dev);
739 	        return (ENOMEM);
740 	}
741 	netmap_mem_get(ptn_dev->nm_mem);
742 
743 	D("ptn_memdev_driver probe OK - host_id: %d", mem_id);
744 
745 	return (0);
746 }
747 
748 /* Device removal routine. */
749 static int
750 ptn_memdev_detach(device_t dev)
751 {
752 	struct ptnetmap_memdev *ptn_dev;
753 
754 	D("ptn_memdev_driver detach");
755 	ptn_dev = device_get_softc(dev);
756 
757 	if (ptn_dev->nm_mem) {
758 		netmap_mem_put(ptn_dev->nm_mem);
759 		ptn_dev->nm_mem = NULL;
760 	}
761 	if (ptn_dev->pci_mem) {
762 		bus_release_resource(dev, SYS_RES_MEMORY,
763 			PCIR_BAR(PTNETMAP_MEM_PCI_BAR), ptn_dev->pci_mem);
764 		ptn_dev->pci_mem = NULL;
765 	}
766 	if (ptn_dev->pci_io) {
767 		bus_release_resource(dev, SYS_RES_IOPORT,
768 			PCIR_BAR(PTNETMAP_IO_PCI_BAR), ptn_dev->pci_io);
769 		ptn_dev->pci_io = NULL;
770 	}
771 
772 	return (0);
773 }
774 
775 static int
776 ptn_memdev_shutdown(device_t dev)
777 {
778 	D("ptn_memdev_driver shutdown");
779 	return bus_generic_shutdown(dev);
780 }
781 
782 #endif /* WITH_PTNETMAP_GUEST */
783 
784 /*
785  * In order to track whether pages are still mapped, we hook into
786  * the standard cdev_pager and intercept the constructor and
787  * destructor.
788  */
789 
790 struct netmap_vm_handle_t {
791 	struct cdev 		*dev;
792 	struct netmap_priv_d	*priv;
793 };
794 
795 
796 static int
797 netmap_dev_pager_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot,
798     vm_ooffset_t foff, struct ucred *cred, u_short *color)
799 {
800 	struct netmap_vm_handle_t *vmh = handle;
801 
802 	if (netmap_verbose)
803 		D("handle %p size %jd prot %d foff %jd",
804 			handle, (intmax_t)size, prot, (intmax_t)foff);
805 	if (color)
806 		*color = 0;
807 	dev_ref(vmh->dev);
808 	return 0;
809 }
810 
811 
812 static void
813 netmap_dev_pager_dtor(void *handle)
814 {
815 	struct netmap_vm_handle_t *vmh = handle;
816 	struct cdev *dev = vmh->dev;
817 	struct netmap_priv_d *priv = vmh->priv;
818 
819 	if (netmap_verbose)
820 		D("handle %p", handle);
821 	netmap_dtor(priv);
822 	free(vmh, M_DEVBUF);
823 	dev_rel(dev);
824 }
825 
826 
827 static int
828 netmap_dev_pager_fault(vm_object_t object, vm_ooffset_t offset,
829 	int prot, vm_page_t *mres)
830 {
831 	struct netmap_vm_handle_t *vmh = object->handle;
832 	struct netmap_priv_d *priv = vmh->priv;
833 	struct netmap_adapter *na = priv->np_na;
834 	vm_paddr_t paddr;
835 	vm_page_t page;
836 	vm_memattr_t memattr;
837 	vm_pindex_t pidx;
838 
839 	ND("object %p offset %jd prot %d mres %p",
840 			object, (intmax_t)offset, prot, mres);
841 	memattr = object->memattr;
842 	pidx = OFF_TO_IDX(offset);
843 	paddr = netmap_mem_ofstophys(na->nm_mem, offset);
844 	if (paddr == 0)
845 		return VM_PAGER_FAIL;
846 
847 	if (((*mres)->flags & PG_FICTITIOUS) != 0) {
848 		/*
849 		 * If the passed in result page is a fake page, update it with
850 		 * the new physical address.
851 		 */
852 		page = *mres;
853 		vm_page_updatefake(page, paddr, memattr);
854 	} else {
855 		/*
856 		 * Replace the passed in reqpage page with our own fake page and
857 		 * free up the all of the original pages.
858 		 */
859 #ifndef VM_OBJECT_WUNLOCK	/* FreeBSD < 10.x */
860 #define VM_OBJECT_WUNLOCK VM_OBJECT_UNLOCK
861 #define VM_OBJECT_WLOCK	VM_OBJECT_LOCK
862 #endif /* VM_OBJECT_WUNLOCK */
863 
864 		VM_OBJECT_WUNLOCK(object);
865 		page = vm_page_getfake(paddr, memattr);
866 		VM_OBJECT_WLOCK(object);
867 		vm_page_lock(*mres);
868 		vm_page_free(*mres);
869 		vm_page_unlock(*mres);
870 		*mres = page;
871 		vm_page_insert(page, object, pidx);
872 	}
873 	page->valid = VM_PAGE_BITS_ALL;
874 	return (VM_PAGER_OK);
875 }
876 
877 
878 static struct cdev_pager_ops netmap_cdev_pager_ops = {
879 	.cdev_pg_ctor = netmap_dev_pager_ctor,
880 	.cdev_pg_dtor = netmap_dev_pager_dtor,
881 	.cdev_pg_fault = netmap_dev_pager_fault,
882 };
883 
884 
885 static int
886 netmap_mmap_single(struct cdev *cdev, vm_ooffset_t *foff,
887 	vm_size_t objsize,  vm_object_t *objp, int prot)
888 {
889 	int error;
890 	struct netmap_vm_handle_t *vmh;
891 	struct netmap_priv_d *priv;
892 	vm_object_t obj;
893 
894 	if (netmap_verbose)
895 		D("cdev %p foff %jd size %jd objp %p prot %d", cdev,
896 		    (intmax_t )*foff, (intmax_t )objsize, objp, prot);
897 
898 	vmh = malloc(sizeof(struct netmap_vm_handle_t), M_DEVBUF,
899 			      M_NOWAIT | M_ZERO);
900 	if (vmh == NULL)
901 		return ENOMEM;
902 	vmh->dev = cdev;
903 
904 	NMG_LOCK();
905 	error = devfs_get_cdevpriv((void**)&priv);
906 	if (error)
907 		goto err_unlock;
908 	if (priv->np_nifp == NULL) {
909 		error = EINVAL;
910 		goto err_unlock;
911 	}
912 	vmh->priv = priv;
913 	priv->np_refs++;
914 	NMG_UNLOCK();
915 
916 	obj = cdev_pager_allocate(vmh, OBJT_DEVICE,
917 		&netmap_cdev_pager_ops, objsize, prot,
918 		*foff, NULL);
919 	if (obj == NULL) {
920 		D("cdev_pager_allocate failed");
921 		error = EINVAL;
922 		goto err_deref;
923 	}
924 
925 	*objp = obj;
926 	return 0;
927 
928 err_deref:
929 	NMG_LOCK();
930 	priv->np_refs--;
931 err_unlock:
932 	NMG_UNLOCK();
933 // err:
934 	free(vmh, M_DEVBUF);
935 	return error;
936 }
937 
938 /*
939  * On FreeBSD the close routine is only called on the last close on
940  * the device (/dev/netmap) so we cannot do anything useful.
941  * To track close() on individual file descriptors we pass netmap_dtor() to
942  * devfs_set_cdevpriv() on open(). The FreeBSD kernel will call the destructor
943  * when the last fd pointing to the device is closed.
944  *
945  * Note that FreeBSD does not even munmap() on close() so we also have
946  * to track mmap() ourselves, and postpone the call to
947  * netmap_dtor() is called when the process has no open fds and no active
948  * memory maps on /dev/netmap, as in linux.
949  */
950 static int
951 netmap_close(struct cdev *dev, int fflag, int devtype, struct thread *td)
952 {
953 	if (netmap_verbose)
954 		D("dev %p fflag 0x%x devtype %d td %p",
955 			dev, fflag, devtype, td);
956 	return 0;
957 }
958 
959 
960 static int
961 netmap_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
962 {
963 	struct netmap_priv_d *priv;
964 	int error;
965 
966 	(void)dev;
967 	(void)oflags;
968 	(void)devtype;
969 	(void)td;
970 
971 	NMG_LOCK();
972 	priv = netmap_priv_new();
973 	if (priv == NULL) {
974 		error = ENOMEM;
975 		goto out;
976 	}
977 	error = devfs_set_cdevpriv(priv, netmap_dtor);
978 	if (error) {
979 		netmap_priv_delete(priv);
980 	}
981 out:
982 	NMG_UNLOCK();
983 	return error;
984 }
985 
986 /******************** kthread wrapper ****************/
987 #include <sys/sysproto.h>
988 u_int
989 nm_os_ncpus(void)
990 {
991 	return mp_maxid + 1;
992 }
993 
994 struct nm_kthread_ctx {
995 	struct thread *user_td;		/* thread user-space (kthread creator) to send ioctl */
996 	/* notification to guest (interrupt) */
997 	int irq_fd;		/* ioctl fd */
998 	struct nm_kth_ioctl irq_ioctl;	/* ioctl arguments */
999 
1000 	/* notification from guest */
1001 	void *ioevent_file; 		/* tsleep() argument */
1002 
1003 	/* worker function and parameter */
1004 	nm_kthread_worker_fn_t worker_fn;
1005 	void *worker_private;
1006 
1007 	struct nm_kthread *nmk;
1008 
1009 	/* integer to manage multiple worker contexts (e.g., RX or TX on ptnetmap) */
1010 	long type;
1011 };
1012 
1013 struct nm_kthread {
1014 	struct thread *worker;
1015 	struct mtx worker_lock;
1016 	uint64_t scheduled; 		/* pending wake_up request */
1017 	struct nm_kthread_ctx worker_ctx;
1018 	int run;			/* used to stop kthread */
1019 	int attach_user;		/* kthread attached to user_process */
1020 	int affinity;
1021 };
1022 
1023 void inline
1024 nm_os_kthread_wakeup_worker(struct nm_kthread *nmk)
1025 {
1026 	/*
1027 	 * There may be a race between FE and BE,
1028 	 * which call both this function, and worker kthread,
1029 	 * that reads nmk->scheduled.
1030 	 *
1031 	 * For us it is not important the counter value,
1032 	 * but simply that it has changed since the last
1033 	 * time the kthread saw it.
1034 	 */
1035 	mtx_lock(&nmk->worker_lock);
1036 	nmk->scheduled++;
1037 	if (nmk->worker_ctx.ioevent_file) {
1038 		wakeup(nmk->worker_ctx.ioevent_file);
1039 	}
1040 	mtx_unlock(&nmk->worker_lock);
1041 }
1042 
1043 void inline
1044 nm_os_kthread_send_irq(struct nm_kthread *nmk)
1045 {
1046 	struct nm_kthread_ctx *ctx = &nmk->worker_ctx;
1047 	int err;
1048 
1049 	if (ctx->user_td && ctx->irq_fd > 0) {
1050 		err = kern_ioctl(ctx->user_td, ctx->irq_fd, ctx->irq_ioctl.com, (caddr_t)&ctx->irq_ioctl.data.msix);
1051 		if (err) {
1052 			D("kern_ioctl error: %d ioctl parameters: fd %d com %ju data %p",
1053 				err, ctx->irq_fd, (uintmax_t)ctx->irq_ioctl.com, &ctx->irq_ioctl.data);
1054 		}
1055 	}
1056 }
1057 
1058 static void
1059 nm_kthread_worker(void *data)
1060 {
1061 	struct nm_kthread *nmk = data;
1062 	struct nm_kthread_ctx *ctx = &nmk->worker_ctx;
1063 	uint64_t old_scheduled = nmk->scheduled;
1064 
1065 	if (nmk->affinity >= 0) {
1066 		thread_lock(curthread);
1067 		sched_bind(curthread, nmk->affinity);
1068 		thread_unlock(curthread);
1069 	}
1070 
1071 	while (nmk->run) {
1072 		/*
1073 		 * check if the parent process dies
1074 		 * (when kthread is attached to user process)
1075 		 */
1076 		if (ctx->user_td) {
1077 			PROC_LOCK(curproc);
1078 			thread_suspend_check(0);
1079 			PROC_UNLOCK(curproc);
1080 		} else {
1081 			kthread_suspend_check();
1082 		}
1083 
1084 		/*
1085 		 * if ioevent_file is not defined, we don't have notification
1086 		 * mechanism and we continually execute worker_fn()
1087 		 */
1088 		if (!ctx->ioevent_file) {
1089 			ctx->worker_fn(ctx->worker_private); /* worker body */
1090 		} else {
1091 			/* checks if there is a pending notification */
1092 			mtx_lock(&nmk->worker_lock);
1093 			if (likely(nmk->scheduled != old_scheduled)) {
1094 				old_scheduled = nmk->scheduled;
1095 				mtx_unlock(&nmk->worker_lock);
1096 
1097 				ctx->worker_fn(ctx->worker_private); /* worker body */
1098 
1099 				continue;
1100 			} else if (nmk->run) {
1101 				/* wait on event with one second timeout */
1102 				msleep_spin(ctx->ioevent_file, &nmk->worker_lock,
1103 					    "nmk_ev", hz);
1104 				nmk->scheduled++;
1105 			}
1106 			mtx_unlock(&nmk->worker_lock);
1107 		}
1108 	}
1109 
1110 	kthread_exit();
1111 }
1112 
1113 static int
1114 nm_kthread_open_files(struct nm_kthread *nmk, struct nm_kthread_cfg *cfg)
1115 {
1116 	/* send irq through ioctl to bhyve (vmm.ko) */
1117 	if (cfg->event.irqfd) {
1118 		nmk->worker_ctx.irq_fd = cfg->event.irqfd;
1119 		nmk->worker_ctx.irq_ioctl = cfg->event.ioctl;
1120 	}
1121 	/* ring.ioeventfd contains the chan where do tsleep to wait events */
1122 	if (cfg->event.ioeventfd) {
1123 		nmk->worker_ctx.ioevent_file = (void *)cfg->event.ioeventfd;
1124 	}
1125 
1126 	return 0;
1127 }
1128 
1129 static void
1130 nm_kthread_close_files(struct nm_kthread *nmk)
1131 {
1132 	nmk->worker_ctx.irq_fd = 0;
1133 	nmk->worker_ctx.ioevent_file = NULL;
1134 }
1135 
1136 void
1137 nm_os_kthread_set_affinity(struct nm_kthread *nmk, int affinity)
1138 {
1139 	nmk->affinity = affinity;
1140 }
1141 
1142 struct nm_kthread *
1143 nm_os_kthread_create(struct nm_kthread_cfg *cfg)
1144 {
1145 	struct nm_kthread *nmk = NULL;
1146 	int error;
1147 
1148 	nmk = malloc(sizeof(*nmk),  M_DEVBUF, M_NOWAIT | M_ZERO);
1149 	if (!nmk)
1150 		return NULL;
1151 
1152 	mtx_init(&nmk->worker_lock, "nm_kthread lock", NULL, MTX_SPIN);
1153 	nmk->worker_ctx.worker_fn = cfg->worker_fn;
1154 	nmk->worker_ctx.worker_private = cfg->worker_private;
1155 	nmk->worker_ctx.type = cfg->type;
1156 	nmk->affinity = -1;
1157 
1158 	/* attach kthread to user process (ptnetmap) */
1159 	nmk->attach_user = cfg->attach_user;
1160 
1161 	/* open event fd */
1162 	error = nm_kthread_open_files(nmk, cfg);
1163 	if (error)
1164 		goto err;
1165 
1166 	return nmk;
1167 err:
1168 	free(nmk, M_DEVBUF);
1169 	return NULL;
1170 }
1171 
1172 int
1173 nm_os_kthread_start(struct nm_kthread *nmk)
1174 {
1175 	struct proc *p = NULL;
1176 	int error = 0;
1177 
1178 	if (nmk->worker) {
1179 		return EBUSY;
1180 	}
1181 
1182 	/* check if we want to attach kthread to user process */
1183 	if (nmk->attach_user) {
1184 		nmk->worker_ctx.user_td = curthread;
1185 		p = curthread->td_proc;
1186 	}
1187 
1188 	/* enable kthread main loop */
1189 	nmk->run = 1;
1190 	/* create kthread */
1191 	if((error = kthread_add(nm_kthread_worker, nmk, p,
1192 			&nmk->worker, RFNOWAIT /* to be checked */, 0, "nm-kthread-%ld",
1193 			nmk->worker_ctx.type))) {
1194 		goto err;
1195 	}
1196 
1197 	D("nm_kthread started td 0x%p", nmk->worker);
1198 
1199 	return 0;
1200 err:
1201 	D("nm_kthread start failed err %d", error);
1202 	nmk->worker = NULL;
1203 	return error;
1204 }
1205 
1206 void
1207 nm_os_kthread_stop(struct nm_kthread *nmk)
1208 {
1209 	if (!nmk->worker) {
1210 		return;
1211 	}
1212 	/* tell to kthread to exit from main loop */
1213 	nmk->run = 0;
1214 
1215 	/* wake up kthread if it sleeps */
1216 	kthread_resume(nmk->worker);
1217 	nm_os_kthread_wakeup_worker(nmk);
1218 
1219 	nmk->worker = NULL;
1220 }
1221 
1222 void
1223 nm_os_kthread_delete(struct nm_kthread *nmk)
1224 {
1225 	if (!nmk)
1226 		return;
1227 	if (nmk->worker) {
1228 		nm_os_kthread_stop(nmk);
1229 	}
1230 
1231 	nm_kthread_close_files(nmk);
1232 
1233 	free(nmk, M_DEVBUF);
1234 }
1235 
1236 /******************** kqueue support ****************/
1237 
1238 /*
1239  * nm_os_selwakeup also needs to issue a KNOTE_UNLOCKED.
1240  * We use a non-zero argument to distinguish the call from the one
1241  * in kevent_scan() which instead also needs to run netmap_poll().
1242  * The knote uses a global mutex for the time being. We might
1243  * try to reuse the one in the si, but it is not allocated
1244  * permanently so it might be a bit tricky.
1245  *
1246  * The *kqfilter function registers one or another f_event
1247  * depending on read or write mode.
1248  * In the call to f_event() td_fpop is NULL so any child function
1249  * calling devfs_get_cdevpriv() would fail - and we need it in
1250  * netmap_poll(). As a workaround we store priv into kn->kn_hook
1251  * and pass it as first argument to netmap_poll(), which then
1252  * uses the failure to tell that we are called from f_event()
1253  * and do not need the selrecord().
1254  */
1255 
1256 
1257 void
1258 nm_os_selwakeup(struct nm_selinfo *si)
1259 {
1260 	if (netmap_verbose)
1261 		D("on knote %p", &si->si.si_note);
1262 	selwakeuppri(&si->si, PI_NET);
1263 	/* use a non-zero hint to tell the notification from the
1264 	 * call done in kqueue_scan() which uses 0
1265 	 */
1266 	KNOTE_UNLOCKED(&si->si.si_note, 0x100 /* notification */);
1267 }
1268 
1269 void
1270 nm_os_selrecord(struct thread *td, struct nm_selinfo *si)
1271 {
1272 	selrecord(td, &si->si);
1273 }
1274 
1275 static void
1276 netmap_knrdetach(struct knote *kn)
1277 {
1278 	struct netmap_priv_d *priv = (struct netmap_priv_d *)kn->kn_hook;
1279 	struct selinfo *si = &priv->np_si[NR_RX]->si;
1280 
1281 	D("remove selinfo %p", si);
1282 	knlist_remove(&si->si_note, kn, 0);
1283 }
1284 
1285 static void
1286 netmap_knwdetach(struct knote *kn)
1287 {
1288 	struct netmap_priv_d *priv = (struct netmap_priv_d *)kn->kn_hook;
1289 	struct selinfo *si = &priv->np_si[NR_TX]->si;
1290 
1291 	D("remove selinfo %p", si);
1292 	knlist_remove(&si->si_note, kn, 0);
1293 }
1294 
1295 /*
1296  * callback from notifies (generated externally) and our
1297  * calls to kevent(). The former we just return 1 (ready)
1298  * since we do not know better.
1299  * In the latter we call netmap_poll and return 0/1 accordingly.
1300  */
1301 static int
1302 netmap_knrw(struct knote *kn, long hint, int events)
1303 {
1304 	struct netmap_priv_d *priv;
1305 	int revents;
1306 
1307 	if (hint != 0) {
1308 		ND(5, "call from notify");
1309 		return 1; /* assume we are ready */
1310 	}
1311 	priv = kn->kn_hook;
1312 	/* the notification may come from an external thread,
1313 	 * in which case we do not want to run the netmap_poll
1314 	 * This should be filtered above, but check just in case.
1315 	 */
1316 	if (curthread != priv->np_td) { /* should not happen */
1317 		RD(5, "curthread changed %p %p", curthread, priv->np_td);
1318 		return 1;
1319 	} else {
1320 		revents = netmap_poll(priv, events, NULL);
1321 		return (events & revents) ? 1 : 0;
1322 	}
1323 }
1324 
1325 static int
1326 netmap_knread(struct knote *kn, long hint)
1327 {
1328 	return netmap_knrw(kn, hint, POLLIN);
1329 }
1330 
1331 static int
1332 netmap_knwrite(struct knote *kn, long hint)
1333 {
1334 	return netmap_knrw(kn, hint, POLLOUT);
1335 }
1336 
1337 static struct filterops netmap_rfiltops = {
1338 	.f_isfd = 1,
1339 	.f_detach = netmap_knrdetach,
1340 	.f_event = netmap_knread,
1341 };
1342 
1343 static struct filterops netmap_wfiltops = {
1344 	.f_isfd = 1,
1345 	.f_detach = netmap_knwdetach,
1346 	.f_event = netmap_knwrite,
1347 };
1348 
1349 
1350 /*
1351  * This is called when a thread invokes kevent() to record
1352  * a change in the configuration of the kqueue().
1353  * The 'priv' should be the same as in the netmap device.
1354  */
1355 static int
1356 netmap_kqfilter(struct cdev *dev, struct knote *kn)
1357 {
1358 	struct netmap_priv_d *priv;
1359 	int error;
1360 	struct netmap_adapter *na;
1361 	struct nm_selinfo *si;
1362 	int ev = kn->kn_filter;
1363 
1364 	if (ev != EVFILT_READ && ev != EVFILT_WRITE) {
1365 		D("bad filter request %d", ev);
1366 		return 1;
1367 	}
1368 	error = devfs_get_cdevpriv((void**)&priv);
1369 	if (error) {
1370 		D("device not yet setup");
1371 		return 1;
1372 	}
1373 	na = priv->np_na;
1374 	if (na == NULL) {
1375 		D("no netmap adapter for this file descriptor");
1376 		return 1;
1377 	}
1378 	/* the si is indicated in the priv */
1379 	si = priv->np_si[(ev == EVFILT_WRITE) ? NR_TX : NR_RX];
1380 	// XXX lock(priv) ?
1381 	kn->kn_fop = (ev == EVFILT_WRITE) ?
1382 		&netmap_wfiltops : &netmap_rfiltops;
1383 	kn->kn_hook = priv;
1384 	knlist_add(&si->si.si_note, kn, 1);
1385 	// XXX unlock(priv)
1386 	ND("register %p %s td %p priv %p kn %p np_nifp %p kn_fp/fpop %s",
1387 		na, na->ifp->if_xname, curthread, priv, kn,
1388 		priv->np_nifp,
1389 		kn->kn_fp == curthread->td_fpop ? "match" : "MISMATCH");
1390 	return 0;
1391 }
1392 
1393 static int
1394 freebsd_netmap_poll(struct cdev *cdevi __unused, int events, struct thread *td)
1395 {
1396 	struct netmap_priv_d *priv;
1397 	if (devfs_get_cdevpriv((void **)&priv)) {
1398 		return POLLERR;
1399 	}
1400 	return netmap_poll(priv, events, td);
1401 }
1402 
1403 static int
1404 freebsd_netmap_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data,
1405         int ffla __unused, struct thread *td)
1406 {
1407 	int error;
1408 	struct netmap_priv_d *priv;
1409 
1410 	CURVNET_SET(TD_TO_VNET(td));
1411 	error = devfs_get_cdevpriv((void **)&priv);
1412 	if (error) {
1413 		/* XXX ENOENT should be impossible, since the priv
1414 		 * is now created in the open */
1415 		if (error == ENOENT)
1416 			error = ENXIO;
1417 		goto out;
1418 	}
1419 	error = netmap_ioctl(priv, cmd, data, td);
1420 out:
1421 	CURVNET_RESTORE();
1422 
1423 	return error;
1424 }
1425 
1426 extern struct cdevsw netmap_cdevsw; /* XXX used in netmap.c, should go elsewhere */
1427 struct cdevsw netmap_cdevsw = {
1428 	.d_version = D_VERSION,
1429 	.d_name = "netmap",
1430 	.d_open = netmap_open,
1431 	.d_mmap_single = netmap_mmap_single,
1432 	.d_ioctl = freebsd_netmap_ioctl,
1433 	.d_poll = freebsd_netmap_poll,
1434 	.d_kqfilter = netmap_kqfilter,
1435 	.d_close = netmap_close,
1436 };
1437 /*--- end of kqueue support ----*/
1438 
1439 /*
1440  * Kernel entry point.
1441  *
1442  * Initialize/finalize the module and return.
1443  *
1444  * Return 0 on success, errno on failure.
1445  */
1446 static int
1447 netmap_loader(__unused struct module *module, int event, __unused void *arg)
1448 {
1449 	int error = 0;
1450 
1451 	switch (event) {
1452 	case MOD_LOAD:
1453 		error = netmap_init();
1454 		break;
1455 
1456 	case MOD_UNLOAD:
1457 		/*
1458 		 * if some one is still using netmap,
1459 		 * then the module can not be unloaded.
1460 		 */
1461 		if (netmap_use_count) {
1462 			D("netmap module can not be unloaded - netmap_use_count: %d",
1463 					netmap_use_count);
1464 			error = EBUSY;
1465 			break;
1466 		}
1467 		netmap_fini();
1468 		break;
1469 
1470 	default:
1471 		error = EOPNOTSUPP;
1472 		break;
1473 	}
1474 
1475 	return (error);
1476 }
1477 
1478 #ifdef DEV_MODULE_ORDERED
1479 /*
1480  * The netmap module contains three drivers: (i) the netmap character device
1481  * driver; (ii) the ptnetmap memdev PCI device driver, (iii) the ptnet PCI
1482  * device driver. The attach() routines of both (ii) and (iii) need the
1483  * lock of the global allocator, and such lock is initialized in netmap_init(),
1484  * which is part of (i).
1485  * Therefore, we make sure that (i) is loaded before (ii) and (iii), using
1486  * the 'order' parameter of driver declaration macros. For (i), we specify
1487  * SI_ORDER_MIDDLE, while higher orders are used with the DRIVER_MODULE_ORDERED
1488  * macros for (ii) and (iii).
1489  */
1490 DEV_MODULE_ORDERED(netmap, netmap_loader, NULL, SI_ORDER_MIDDLE);
1491 #else /* !DEV_MODULE_ORDERED */
1492 DEV_MODULE(netmap, netmap_loader, NULL);
1493 #endif /* DEV_MODULE_ORDERED  */
1494 MODULE_DEPEND(netmap, pci, 1, 1, 1);
1495 MODULE_VERSION(netmap, 1);
1496 /* reduce conditional code */
1497 // linux API, use for the knlist in FreeBSD
1498 /* use a private mutex for the knlist */
1499