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