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