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