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