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