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