2 * Copyright (C) 2013-2014 Universita` di Pisa. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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
28 #include "opt_inet6.h"
30 #include <sys/param.h>
31 #include <sys/module.h>
32 #include <sys/errno.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() */
40 #include <sys/rwlock.h>
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>
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 */
60 #include <net/if_var.h>
61 #include <net/if_types.h> /* IFT_ETHER */
62 #include <net/ethernet.h> /* ether_ifdetach */
63 #include <net/if_dl.h> /* LLADDR */
64 #include <machine/bus.h> /* bus_dmamap_* */
65 #include <netinet/in.h> /* in6_cksum_pseudo() */
66 #include <machine/in_cksum.h> /* in_pseudo(), in_cksum_hdr() */
68 #include <net/netmap.h>
69 #include <dev/netmap/netmap_kern.h>
70 #include <net/netmap_virt.h>
71 #include <dev/netmap/netmap_mem2.h>
74 /* ======================== FREEBSD-SPECIFIC ROUTINES ================== */
76 void nm_os_selinfo_init(NM_SELINFO_T *si) {
77 struct mtx *m = &si->m;
78 mtx_init(m, "nm_kn_lock", NULL, MTX_DEF);
79 knlist_init_mtx(&si->si.si_note, m);
83 nm_os_selinfo_uninit(NM_SELINFO_T *si)
85 /* XXX kqueue(9) needed; these will mirror knlist_init. */
86 knlist_delete(&si->si.si_note, curthread, 0 /* not locked */ );
87 knlist_destroy(&si->si.si_note);
88 /* now we don't need the mutex anymore */
93 nm_os_ifnet_lock(void)
99 nm_os_ifnet_unlock(void)
104 static int netmap_use_count = 0;
107 nm_os_get_module(void)
113 nm_os_put_module(void)
119 netmap_ifnet_arrival_handler(void *arg __unused, struct ifnet *ifp)
121 netmap_undo_zombie(ifp);
125 netmap_ifnet_departure_handler(void *arg __unused, struct ifnet *ifp)
127 netmap_make_zombie(ifp);
130 static eventhandler_tag nm_ifnet_ah_tag;
131 static eventhandler_tag nm_ifnet_dh_tag;
134 nm_os_ifnet_init(void)
137 EVENTHANDLER_REGISTER(ifnet_arrival_event,
138 netmap_ifnet_arrival_handler,
139 NULL, EVENTHANDLER_PRI_ANY);
141 EVENTHANDLER_REGISTER(ifnet_departure_event,
142 netmap_ifnet_departure_handler,
143 NULL, EVENTHANDLER_PRI_ANY);
148 nm_os_ifnet_fini(void)
150 EVENTHANDLER_DEREGISTER(ifnet_arrival_event,
152 EVENTHANDLER_DEREGISTER(ifnet_departure_event,
157 nm_os_csum_raw(uint8_t *data, size_t len, rawsum_t cur_sum)
159 /* TODO XXX please use the FreeBSD implementation for this. */
160 uint16_t *words = (uint16_t *)data;
164 for (i = 0; i < nw; i++)
165 cur_sum += be16toh(words[i]);
168 cur_sum += (data[len-1] << 8);
173 /* Fold a raw checksum: 'cur_sum' is in host byte order, while the
174 * return value is in network byte order.
177 nm_os_csum_fold(rawsum_t cur_sum)
179 /* TODO XXX please use the FreeBSD implementation for this. */
180 while (cur_sum >> 16)
181 cur_sum = (cur_sum & 0xFFFF) + (cur_sum >> 16);
183 return htobe16((~cur_sum) & 0xFFFF);
186 uint16_t nm_os_csum_ipv4(struct nm_iphdr *iph)
189 return in_cksum_hdr((void *)iph);
191 return nm_os_csum_fold(nm_os_csum_raw((uint8_t*)iph, sizeof(struct nm_iphdr), 0));
196 nm_os_csum_tcpudp_ipv4(struct nm_iphdr *iph, void *data,
197 size_t datalen, uint16_t *check)
200 uint16_t pseudolen = datalen + iph->protocol;
202 /* Compute and insert the pseudo-header cheksum. */
203 *check = in_pseudo(iph->saddr, iph->daddr,
205 /* Compute the checksum on TCP/UDP header + payload
206 * (includes the pseudo-header).
208 *check = nm_os_csum_fold(nm_os_csum_raw(data, datalen, 0));
210 static int notsupported = 0;
213 D("inet4 segmentation not supported");
219 nm_os_csum_tcpudp_ipv6(struct nm_ipv6hdr *ip6h, void *data,
220 size_t datalen, uint16_t *check)
223 *check = in6_cksum_pseudo((void*)ip6h, datalen, ip6h->nexthdr, 0);
224 *check = nm_os_csum_fold(nm_os_csum_raw(data, datalen, 0));
226 static int notsupported = 0;
229 D("inet6 segmentation not supported");
234 /* on FreeBSD we send up one packet at a time */
236 nm_os_send_up(struct ifnet *ifp, struct mbuf *m, struct mbuf *prev)
239 NA(ifp)->if_input(ifp, m);
244 nm_os_mbuf_has_offld(struct mbuf *m)
246 return m->m_pkthdr.csum_flags & (CSUM_TCP | CSUM_UDP | CSUM_SCTP |
247 CSUM_TCP_IPV6 | CSUM_UDP_IPV6 |
248 CSUM_SCTP_IPV6 | CSUM_TSO);
252 freebsd_generic_rx_handler(struct ifnet *ifp, struct mbuf *m)
254 struct netmap_generic_adapter *gna =
255 (struct netmap_generic_adapter *)NA(ifp);
256 int stolen = generic_rx_handler(ifp, m);
259 gna->save_if_input(ifp, m);
264 * Intercept the rx routine in the standard device driver.
265 * Second argument is non-zero to intercept, 0 to restore
268 nm_os_catch_rx(struct netmap_generic_adapter *gna, int intercept)
270 struct netmap_adapter *na = &gna->up.up;
271 struct ifnet *ifp = na->ifp;
274 if (gna->save_if_input) {
275 D("cannot intercept again");
276 return EINVAL; /* already set */
278 gna->save_if_input = ifp->if_input;
279 ifp->if_input = freebsd_generic_rx_handler;
281 if (!gna->save_if_input){
283 return EINVAL; /* not saved */
285 ifp->if_input = gna->save_if_input;
286 gna->save_if_input = NULL;
294 * Intercept the packet steering routine in the tx path,
295 * so that we can decide which queue is used for an mbuf.
296 * Second argument is non-zero to intercept, 0 to restore.
297 * On freebsd we just intercept if_transmit.
300 nm_os_catch_tx(struct netmap_generic_adapter *gna, int intercept)
302 struct netmap_adapter *na = &gna->up.up;
303 struct ifnet *ifp = netmap_generic_getifp(gna);
306 na->if_transmit = ifp->if_transmit;
307 ifp->if_transmit = netmap_transmit;
309 ifp->if_transmit = na->if_transmit;
317 * Transmit routine used by generic_netmap_txsync(). Returns 0 on success
318 * and non-zero on error (which may be packet drops or other errors).
319 * addr and len identify the netmap buffer, m is the (preallocated)
320 * mbuf to use for transmissions.
322 * We should add a reference to the mbuf so the m_freem() at the end
323 * of the transmission does not consume resources.
325 * On FreeBSD, and on multiqueue cards, we can force the queue using
326 * if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
327 * i = m->m_pkthdr.flowid % adapter->num_queues;
329 * i = curcpu % adapter->num_queues;
333 nm_os_generic_xmit_frame(struct nm_os_gen_arg *a)
337 struct ifnet *ifp = a->ifp;
338 struct mbuf *m = a->m;
340 #if __FreeBSD_version < 1100000
342 * Old FreeBSD versions. The mbuf has a cluster attached,
343 * we need to copy from the cluster to the netmap buffer.
345 if (MBUF_REFCNT(m) != 1) {
346 D("invalid refcnt %d for %p", MBUF_REFCNT(m), m);
347 panic("in generic_xmit_frame");
349 if (m->m_ext.ext_size < len) {
350 RD(5, "size %d < len %d", m->m_ext.ext_size, len);
351 len = m->m_ext.ext_size;
353 bcopy(a->addr, m->m_data, len);
354 #else /* __FreeBSD_version >= 1100000 */
355 /* New FreeBSD versions. Link the external storage to
356 * the netmap buffer, so that no copy is necessary. */
357 m->m_ext.ext_buf = m->m_data = a->addr;
358 m->m_ext.ext_size = len;
359 #endif /* __FreeBSD_version >= 1100000 */
361 m->m_len = m->m_pkthdr.len = len;
363 /* mbuf refcnt is not contended, no need to use atomic
364 * (a memory barrier is enough). */
365 SET_MBUF_REFCNT(m, 2);
366 M_HASHTYPE_SET(m, M_HASHTYPE_OPAQUE);
367 m->m_pkthdr.flowid = a->ring_nr;
368 m->m_pkthdr.rcvif = ifp; /* used for tx notification */
369 ret = NA(ifp)->if_transmit(ifp, m);
374 #if __FreeBSD_version >= 1100005
375 struct netmap_adapter *
376 netmap_getna(if_t ifp)
378 return (NA((struct ifnet *)ifp));
380 #endif /* __FreeBSD_version >= 1100005 */
383 * The following two functions are empty until we have a generic
384 * way to extract the info from the ifp
387 nm_os_generic_find_num_desc(struct ifnet *ifp, unsigned int *tx, unsigned int *rx)
389 D("called, in tx %d rx %d", *tx, *rx);
395 nm_os_generic_find_num_queues(struct ifnet *ifp, u_int *txq, u_int *rxq)
397 D("called, in txq %d rxq %d", *txq, *rxq);
398 *txq = netmap_generic_rings;
399 *rxq = netmap_generic_rings;
403 nm_os_generic_set_features(struct netmap_generic_adapter *gna)
406 gna->rxsg = 1; /* Supported through m_copydata. */
407 gna->txqdisc = 0; /* Not supported. */
411 nm_os_mitigation_init(struct nm_generic_mit *mit, int idx, struct netmap_adapter *na)
414 mit->mit_pending = 0;
415 mit->mit_ring_idx = idx;
421 nm_os_mitigation_start(struct nm_generic_mit *mit)
428 nm_os_mitigation_restart(struct nm_generic_mit *mit)
435 nm_os_mitigation_active(struct nm_generic_mit *mit)
443 nm_os_mitigation_cleanup(struct nm_generic_mit *mit)
449 nm_vi_dummy(struct ifnet *ifp, u_long cmd, caddr_t addr)
455 nm_vi_start(struct ifnet *ifp)
457 panic("nm_vi_start() must not be called");
461 * Index manager of persistent virtual interfaces.
462 * It is used to decide the lowest byte of the MAC address.
463 * We use the same algorithm with management of bridge port index.
465 #define NM_VI_MAX 255
467 uint8_t index[NM_VI_MAX]; /* XXX just for a reasonable number */
473 nm_os_vi_init_index(void)
476 for (i = 0; i < NM_VI_MAX; i++)
477 nm_vi_indices.index[i] = i;
478 nm_vi_indices.active = 0;
479 mtx_init(&nm_vi_indices.lock, "nm_vi_indices_lock", NULL, MTX_DEF);
482 /* return -1 if no index available */
484 nm_vi_get_index(void)
488 mtx_lock(&nm_vi_indices.lock);
489 ret = nm_vi_indices.active == NM_VI_MAX ? -1 :
490 nm_vi_indices.index[nm_vi_indices.active++];
491 mtx_unlock(&nm_vi_indices.lock);
496 nm_vi_free_index(uint8_t val)
500 mtx_lock(&nm_vi_indices.lock);
501 lim = nm_vi_indices.active;
502 for (i = 0; i < lim; i++) {
503 if (nm_vi_indices.index[i] == val) {
504 /* swap index[lim-1] and j */
505 int tmp = nm_vi_indices.index[lim-1];
506 nm_vi_indices.index[lim-1] = val;
507 nm_vi_indices.index[i] = tmp;
508 nm_vi_indices.active--;
512 if (lim == nm_vi_indices.active)
513 D("funny, index %u didn't found", val);
514 mtx_unlock(&nm_vi_indices.lock);
519 * Implementation of a netmap-capable virtual interface that
520 * registered to the system.
521 * It is based on if_tap.c and ip_fw_log.c in FreeBSD 9.
523 * Note: Linux sets refcount to 0 on allocation of net_device,
524 * then increments it on registration to the system.
525 * FreeBSD sets refcount to 1 on if_alloc(), and does not
526 * increment this refcount on if_attach().
529 nm_os_vi_persist(const char *name, struct ifnet **ret)
533 uint32_t macaddr_mid;
535 int unit = nm_vi_get_index(); /* just to decide MAC address */
540 * We use the same MAC address generation method with tap
541 * except for the highest octet is 00:be instead of 00:bd
543 macaddr_hi = htons(0x00be); /* XXX tap + 1 */
544 macaddr_mid = (uint32_t) ticks;
545 bcopy(&macaddr_hi, eaddr, sizeof(short));
546 bcopy(&macaddr_mid, &eaddr[2], sizeof(uint32_t));
547 eaddr[5] = (uint8_t)unit;
549 ifp = if_alloc(IFT_ETHER);
551 D("if_alloc failed");
554 if_initname(ifp, name, IF_DUNIT_NONE);
556 ifp->if_flags = IFF_UP | IFF_SIMPLEX | IFF_MULTICAST;
557 ifp->if_init = (void *)nm_vi_dummy;
558 ifp->if_ioctl = nm_vi_dummy;
559 ifp->if_start = nm_vi_start;
560 ifp->if_mtu = ETHERMTU;
561 IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
562 ifp->if_capabilities |= IFCAP_LINKSTATE;
563 ifp->if_capenable |= IFCAP_LINKSTATE;
565 ether_ifattach(ifp, eaddr);
570 /* unregister from the system and drop the final refcount */
572 nm_os_vi_detach(struct ifnet *ifp)
574 nm_vi_free_index(((char *)IF_LLADDR(ifp))[5]);
579 /* ======================== PTNETMAP SUPPORT ========================== */
581 #ifdef WITH_PTNETMAP_GUEST
583 #include <sys/rman.h>
584 #include <machine/bus.h> /* bus_dmamap_* */
585 #include <machine/resource.h>
586 #include <dev/pci/pcivar.h>
587 #include <dev/pci/pcireg.h>
589 * ptnetmap memory device (memdev) for freebsd guest,
590 * ssed to expose host netmap memory to the guest through a PCI BAR.
594 * ptnetmap memdev private data structure
596 struct ptnetmap_memdev {
598 struct resource *pci_io;
599 struct resource *pci_mem;
600 struct netmap_mem_d *nm_mem;
603 static int ptn_memdev_probe(device_t);
604 static int ptn_memdev_attach(device_t);
605 static int ptn_memdev_detach(device_t);
606 static int ptn_memdev_shutdown(device_t);
608 static device_method_t ptn_memdev_methods[] = {
609 DEVMETHOD(device_probe, ptn_memdev_probe),
610 DEVMETHOD(device_attach, ptn_memdev_attach),
611 DEVMETHOD(device_detach, ptn_memdev_detach),
612 DEVMETHOD(device_shutdown, ptn_memdev_shutdown),
616 static driver_t ptn_memdev_driver = {
617 PTNETMAP_MEMDEV_NAME,
619 sizeof(struct ptnetmap_memdev),
622 /* We use (SI_ORDER_MIDDLE+1) here, see DEV_MODULE_ORDERED() invocation
624 static devclass_t ptnetmap_devclass;
625 DRIVER_MODULE_ORDERED(ptn_memdev, pci, ptn_memdev_driver, ptnetmap_devclass,
626 NULL, NULL, SI_ORDER_MIDDLE + 1);
629 * Map host netmap memory through PCI-BAR in the guest OS,
630 * returning physical (nm_paddr) and virtual (nm_addr) addresses
631 * of the netmap memory mapped in the guest.
634 nm_os_pt_memdev_iomap(struct ptnetmap_memdev *ptn_dev, vm_paddr_t *nm_paddr,
635 void **nm_addr, uint64_t *mem_size)
639 D("ptn_memdev_driver iomap");
641 rid = PCIR_BAR(PTNETMAP_MEM_PCI_BAR);
642 *mem_size = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMSIZE_HI);
643 *mem_size = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMSIZE_LO) |
646 /* map memory allocator */
647 ptn_dev->pci_mem = bus_alloc_resource(ptn_dev->dev, SYS_RES_MEMORY,
648 &rid, 0, ~0, *mem_size, RF_ACTIVE);
649 if (ptn_dev->pci_mem == NULL) {
655 *nm_paddr = rman_get_start(ptn_dev->pci_mem);
656 *nm_addr = rman_get_virtual(ptn_dev->pci_mem);
658 D("=== BAR %d start %lx len %lx mem_size %lx ===",
659 PTNETMAP_MEM_PCI_BAR,
660 (unsigned long)(*nm_paddr),
661 (unsigned long)rman_get_size(ptn_dev->pci_mem),
662 (unsigned long)*mem_size);
667 nm_os_pt_memdev_ioread(struct ptnetmap_memdev *ptn_dev, unsigned int reg)
669 return bus_read_4(ptn_dev->pci_io, reg);
672 /* Unmap host netmap memory. */
674 nm_os_pt_memdev_iounmap(struct ptnetmap_memdev *ptn_dev)
676 D("ptn_memdev_driver iounmap");
678 if (ptn_dev->pci_mem) {
679 bus_release_resource(ptn_dev->dev, SYS_RES_MEMORY,
680 PCIR_BAR(PTNETMAP_MEM_PCI_BAR), ptn_dev->pci_mem);
681 ptn_dev->pci_mem = NULL;
685 /* Device identification routine, return BUS_PROBE_DEFAULT on success,
686 * positive on failure */
688 ptn_memdev_probe(device_t dev)
692 if (pci_get_vendor(dev) != PTNETMAP_PCI_VENDOR_ID)
694 if (pci_get_device(dev) != PTNETMAP_PCI_DEVICE_ID)
697 snprintf(desc, sizeof(desc), "%s PCI adapter",
698 PTNETMAP_MEMDEV_NAME);
699 device_set_desc_copy(dev, desc);
701 return (BUS_PROBE_DEFAULT);
704 /* Device initialization routine. */
706 ptn_memdev_attach(device_t dev)
708 struct ptnetmap_memdev *ptn_dev;
712 D("ptn_memdev_driver attach");
714 ptn_dev = device_get_softc(dev);
717 pci_enable_busmaster(dev);
719 rid = PCIR_BAR(PTNETMAP_IO_PCI_BAR);
720 ptn_dev->pci_io = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
722 if (ptn_dev->pci_io == NULL) {
723 device_printf(dev, "cannot map I/O space\n");
727 mem_id = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMID);
729 /* create guest allocator */
730 ptn_dev->nm_mem = netmap_mem_pt_guest_attach(ptn_dev, mem_id);
731 if (ptn_dev->nm_mem == NULL) {
732 ptn_memdev_detach(dev);
735 netmap_mem_get(ptn_dev->nm_mem);
737 D("ptn_memdev_driver probe OK - host_mem_id: %d", mem_id);
742 /* Device removal routine. */
744 ptn_memdev_detach(device_t dev)
746 struct ptnetmap_memdev *ptn_dev;
748 D("ptn_memdev_driver detach");
749 ptn_dev = device_get_softc(dev);
751 if (ptn_dev->nm_mem) {
752 netmap_mem_put(ptn_dev->nm_mem);
753 ptn_dev->nm_mem = NULL;
755 if (ptn_dev->pci_mem) {
756 bus_release_resource(dev, SYS_RES_MEMORY,
757 PCIR_BAR(PTNETMAP_MEM_PCI_BAR), ptn_dev->pci_mem);
758 ptn_dev->pci_mem = NULL;
760 if (ptn_dev->pci_io) {
761 bus_release_resource(dev, SYS_RES_IOPORT,
762 PCIR_BAR(PTNETMAP_IO_PCI_BAR), ptn_dev->pci_io);
763 ptn_dev->pci_io = NULL;
770 ptn_memdev_shutdown(device_t dev)
772 D("ptn_memdev_driver shutdown");
773 return bus_generic_shutdown(dev);
776 #endif /* WITH_PTNETMAP_GUEST */
779 * In order to track whether pages are still mapped, we hook into
780 * the standard cdev_pager and intercept the constructor and
784 struct netmap_vm_handle_t {
786 struct netmap_priv_d *priv;
791 netmap_dev_pager_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot,
792 vm_ooffset_t foff, struct ucred *cred, u_short *color)
794 struct netmap_vm_handle_t *vmh = handle;
797 D("handle %p size %jd prot %d foff %jd",
798 handle, (intmax_t)size, prot, (intmax_t)foff);
807 netmap_dev_pager_dtor(void *handle)
809 struct netmap_vm_handle_t *vmh = handle;
810 struct cdev *dev = vmh->dev;
811 struct netmap_priv_d *priv = vmh->priv;
814 D("handle %p", handle);
822 netmap_dev_pager_fault(vm_object_t object, vm_ooffset_t offset,
823 int prot, vm_page_t *mres)
825 struct netmap_vm_handle_t *vmh = object->handle;
826 struct netmap_priv_d *priv = vmh->priv;
827 struct netmap_adapter *na = priv->np_na;
830 vm_memattr_t memattr;
833 ND("object %p offset %jd prot %d mres %p",
834 object, (intmax_t)offset, prot, mres);
835 memattr = object->memattr;
836 pidx = OFF_TO_IDX(offset);
837 paddr = netmap_mem_ofstophys(na->nm_mem, offset);
839 return VM_PAGER_FAIL;
841 if (((*mres)->flags & PG_FICTITIOUS) != 0) {
843 * If the passed in result page is a fake page, update it with
844 * the new physical address.
847 vm_page_updatefake(page, paddr, memattr);
850 * Replace the passed in reqpage page with our own fake page and
851 * free up the all of the original pages.
853 #ifndef VM_OBJECT_WUNLOCK /* FreeBSD < 10.x */
854 #define VM_OBJECT_WUNLOCK VM_OBJECT_UNLOCK
855 #define VM_OBJECT_WLOCK VM_OBJECT_LOCK
856 #endif /* VM_OBJECT_WUNLOCK */
858 VM_OBJECT_WUNLOCK(object);
859 page = vm_page_getfake(paddr, memattr);
860 VM_OBJECT_WLOCK(object);
863 vm_page_unlock(*mres);
865 vm_page_insert(page, object, pidx);
867 page->valid = VM_PAGE_BITS_ALL;
868 return (VM_PAGER_OK);
872 static struct cdev_pager_ops netmap_cdev_pager_ops = {
873 .cdev_pg_ctor = netmap_dev_pager_ctor,
874 .cdev_pg_dtor = netmap_dev_pager_dtor,
875 .cdev_pg_fault = netmap_dev_pager_fault,
880 netmap_mmap_single(struct cdev *cdev, vm_ooffset_t *foff,
881 vm_size_t objsize, vm_object_t *objp, int prot)
884 struct netmap_vm_handle_t *vmh;
885 struct netmap_priv_d *priv;
889 D("cdev %p foff %jd size %jd objp %p prot %d", cdev,
890 (intmax_t )*foff, (intmax_t )objsize, objp, prot);
892 vmh = malloc(sizeof(struct netmap_vm_handle_t), M_DEVBUF,
899 error = devfs_get_cdevpriv((void**)&priv);
902 if (priv->np_nifp == NULL) {
910 obj = cdev_pager_allocate(vmh, OBJT_DEVICE,
911 &netmap_cdev_pager_ops, objsize, prot,
914 D("cdev_pager_allocate failed");
933 * On FreeBSD the close routine is only called on the last close on
934 * the device (/dev/netmap) so we cannot do anything useful.
935 * To track close() on individual file descriptors we pass netmap_dtor() to
936 * devfs_set_cdevpriv() on open(). The FreeBSD kernel will call the destructor
937 * when the last fd pointing to the device is closed.
939 * Note that FreeBSD does not even munmap() on close() so we also have
940 * to track mmap() ourselves, and postpone the call to
941 * netmap_dtor() is called when the process has no open fds and no active
942 * memory maps on /dev/netmap, as in linux.
945 netmap_close(struct cdev *dev, int fflag, int devtype, struct thread *td)
948 D("dev %p fflag 0x%x devtype %d td %p",
949 dev, fflag, devtype, td);
955 netmap_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
957 struct netmap_priv_d *priv;
966 priv = netmap_priv_new();
971 error = devfs_set_cdevpriv(priv, netmap_dtor);
973 netmap_priv_delete(priv);
980 /******************** kthread wrapper ****************/
981 #include <sys/sysproto.h>
988 struct nm_kthread_ctx {
989 struct thread *user_td; /* thread user-space (kthread creator) to send ioctl */
990 struct ptnetmap_cfgentry_bhyve cfg;
992 /* worker function and parameter */
993 nm_kthread_worker_fn_t worker_fn;
994 void *worker_private;
996 struct nm_kthread *nmk;
998 /* integer to manage multiple worker contexts (e.g., RX or TX on ptnetmap) */
1003 struct thread *worker;
1004 struct mtx worker_lock;
1005 uint64_t scheduled; /* pending wake_up request */
1006 struct nm_kthread_ctx worker_ctx;
1007 int run; /* used to stop kthread */
1008 int attach_user; /* kthread attached to user_process */
1013 nm_os_kthread_wakeup_worker(struct nm_kthread *nmk)
1016 * There may be a race between FE and BE,
1017 * which call both this function, and worker kthread,
1018 * that reads nmk->scheduled.
1020 * For us it is not important the counter value,
1021 * but simply that it has changed since the last
1022 * time the kthread saw it.
1024 mtx_lock(&nmk->worker_lock);
1026 if (nmk->worker_ctx.cfg.wchan) {
1027 wakeup((void *)(uintptr_t)nmk->worker_ctx.cfg.wchan);
1029 mtx_unlock(&nmk->worker_lock);
1033 nm_os_kthread_send_irq(struct nm_kthread *nmk)
1035 struct nm_kthread_ctx *ctx = &nmk->worker_ctx;
1038 if (ctx->user_td && ctx->cfg.ioctl_fd > 0) {
1039 err = kern_ioctl(ctx->user_td, ctx->cfg.ioctl_fd, ctx->cfg.ioctl_cmd,
1040 (caddr_t)&ctx->cfg.ioctl_data);
1042 D("kern_ioctl error: %d ioctl parameters: fd %d com %lu data %p",
1043 err, ctx->cfg.ioctl_fd, (unsigned long)ctx->cfg.ioctl_cmd,
1044 &ctx->cfg.ioctl_data);
1050 nm_kthread_worker(void *data)
1052 struct nm_kthread *nmk = data;
1053 struct nm_kthread_ctx *ctx = &nmk->worker_ctx;
1054 uint64_t old_scheduled = nmk->scheduled;
1056 if (nmk->affinity >= 0) {
1057 thread_lock(curthread);
1058 sched_bind(curthread, nmk->affinity);
1059 thread_unlock(curthread);
1064 * check if the parent process dies
1065 * (when kthread is attached to user process)
1069 thread_suspend_check(0);
1070 PROC_UNLOCK(curproc);
1072 kthread_suspend_check();
1076 * if wchan is not defined, we don't have notification
1077 * mechanism and we continually execute worker_fn()
1079 if (!ctx->cfg.wchan) {
1080 ctx->worker_fn(ctx->worker_private); /* worker body */
1082 /* checks if there is a pending notification */
1083 mtx_lock(&nmk->worker_lock);
1084 if (likely(nmk->scheduled != old_scheduled)) {
1085 old_scheduled = nmk->scheduled;
1086 mtx_unlock(&nmk->worker_lock);
1088 ctx->worker_fn(ctx->worker_private); /* worker body */
1091 } else if (nmk->run) {
1092 /* wait on event with one second timeout */
1093 msleep((void *)(uintptr_t)ctx->cfg.wchan,
1094 &nmk->worker_lock, 0, "nmk_ev", hz);
1097 mtx_unlock(&nmk->worker_lock);
1105 nm_os_kthread_set_affinity(struct nm_kthread *nmk, int affinity)
1107 nmk->affinity = affinity;
1111 nm_os_kthread_create(struct nm_kthread_cfg *cfg, unsigned int cfgtype,
1114 struct nm_kthread *nmk = NULL;
1116 if (cfgtype != PTNETMAP_CFGTYPE_BHYVE) {
1117 D("Unsupported cfgtype %u", cfgtype);
1121 nmk = malloc(sizeof(*nmk), M_DEVBUF, M_NOWAIT | M_ZERO);
1125 mtx_init(&nmk->worker_lock, "nm_kthread lock", NULL, MTX_DEF);
1126 nmk->worker_ctx.worker_fn = cfg->worker_fn;
1127 nmk->worker_ctx.worker_private = cfg->worker_private;
1128 nmk->worker_ctx.type = cfg->type;
1131 /* attach kthread to user process (ptnetmap) */
1132 nmk->attach_user = cfg->attach_user;
1134 /* store kick/interrupt configuration */
1136 nmk->worker_ctx.cfg = *((struct ptnetmap_cfgentry_bhyve *)opaque);
1143 nm_os_kthread_start(struct nm_kthread *nmk)
1145 struct proc *p = NULL;
1152 /* check if we want to attach kthread to user process */
1153 if (nmk->attach_user) {
1154 nmk->worker_ctx.user_td = curthread;
1155 p = curthread->td_proc;
1158 /* enable kthread main loop */
1160 /* create kthread */
1161 if((error = kthread_add(nm_kthread_worker, nmk, p,
1162 &nmk->worker, RFNOWAIT /* to be checked */, 0, "nm-kthread-%ld",
1163 nmk->worker_ctx.type))) {
1167 D("nm_kthread started td %p", nmk->worker);
1171 D("nm_kthread start failed err %d", error);
1177 nm_os_kthread_stop(struct nm_kthread *nmk)
1182 /* tell to kthread to exit from main loop */
1185 /* wake up kthread if it sleeps */
1186 kthread_resume(nmk->worker);
1187 nm_os_kthread_wakeup_worker(nmk);
1193 nm_os_kthread_delete(struct nm_kthread *nmk)
1198 nm_os_kthread_stop(nmk);
1201 memset(&nmk->worker_ctx.cfg, 0, sizeof(nmk->worker_ctx.cfg));
1203 free(nmk, M_DEVBUF);
1206 /******************** kqueue support ****************/
1209 * nm_os_selwakeup also needs to issue a KNOTE_UNLOCKED.
1210 * We use a non-zero argument to distinguish the call from the one
1211 * in kevent_scan() which instead also needs to run netmap_poll().
1212 * The knote uses a global mutex for the time being. We might
1213 * try to reuse the one in the si, but it is not allocated
1214 * permanently so it might be a bit tricky.
1216 * The *kqfilter function registers one or another f_event
1217 * depending on read or write mode.
1218 * In the call to f_event() td_fpop is NULL so any child function
1219 * calling devfs_get_cdevpriv() would fail - and we need it in
1220 * netmap_poll(). As a workaround we store priv into kn->kn_hook
1221 * and pass it as first argument to netmap_poll(), which then
1222 * uses the failure to tell that we are called from f_event()
1223 * and do not need the selrecord().
1228 nm_os_selwakeup(struct nm_selinfo *si)
1231 D("on knote %p", &si->si.si_note);
1232 selwakeuppri(&si->si, PI_NET);
1233 /* use a non-zero hint to tell the notification from the
1234 * call done in kqueue_scan() which uses 0
1236 KNOTE_UNLOCKED(&si->si.si_note, 0x100 /* notification */);
1240 nm_os_selrecord(struct thread *td, struct nm_selinfo *si)
1242 selrecord(td, &si->si);
1246 netmap_knrdetach(struct knote *kn)
1248 struct netmap_priv_d *priv = (struct netmap_priv_d *)kn->kn_hook;
1249 struct selinfo *si = &priv->np_si[NR_RX]->si;
1251 D("remove selinfo %p", si);
1252 knlist_remove(&si->si_note, kn, 0);
1256 netmap_knwdetach(struct knote *kn)
1258 struct netmap_priv_d *priv = (struct netmap_priv_d *)kn->kn_hook;
1259 struct selinfo *si = &priv->np_si[NR_TX]->si;
1261 D("remove selinfo %p", si);
1262 knlist_remove(&si->si_note, kn, 0);
1266 * callback from notifies (generated externally) and our
1267 * calls to kevent(). The former we just return 1 (ready)
1268 * since we do not know better.
1269 * In the latter we call netmap_poll and return 0/1 accordingly.
1272 netmap_knrw(struct knote *kn, long hint, int events)
1274 struct netmap_priv_d *priv;
1278 ND(5, "call from notify");
1279 return 1; /* assume we are ready */
1282 /* the notification may come from an external thread,
1283 * in which case we do not want to run the netmap_poll
1284 * This should be filtered above, but check just in case.
1286 if (curthread != priv->np_td) { /* should not happen */
1287 RD(5, "curthread changed %p %p", curthread, priv->np_td);
1290 revents = netmap_poll(priv, events, NULL);
1291 return (events & revents) ? 1 : 0;
1296 netmap_knread(struct knote *kn, long hint)
1298 return netmap_knrw(kn, hint, POLLIN);
1302 netmap_knwrite(struct knote *kn, long hint)
1304 return netmap_knrw(kn, hint, POLLOUT);
1307 static struct filterops netmap_rfiltops = {
1309 .f_detach = netmap_knrdetach,
1310 .f_event = netmap_knread,
1313 static struct filterops netmap_wfiltops = {
1315 .f_detach = netmap_knwdetach,
1316 .f_event = netmap_knwrite,
1321 * This is called when a thread invokes kevent() to record
1322 * a change in the configuration of the kqueue().
1323 * The 'priv' should be the same as in the netmap device.
1326 netmap_kqfilter(struct cdev *dev, struct knote *kn)
1328 struct netmap_priv_d *priv;
1330 struct netmap_adapter *na;
1331 struct nm_selinfo *si;
1332 int ev = kn->kn_filter;
1334 if (ev != EVFILT_READ && ev != EVFILT_WRITE) {
1335 D("bad filter request %d", ev);
1338 error = devfs_get_cdevpriv((void**)&priv);
1340 D("device not yet setup");
1345 D("no netmap adapter for this file descriptor");
1348 /* the si is indicated in the priv */
1349 si = priv->np_si[(ev == EVFILT_WRITE) ? NR_TX : NR_RX];
1351 kn->kn_fop = (ev == EVFILT_WRITE) ?
1352 &netmap_wfiltops : &netmap_rfiltops;
1354 knlist_add(&si->si.si_note, kn, 1);
1356 ND("register %p %s td %p priv %p kn %p np_nifp %p kn_fp/fpop %s",
1357 na, na->ifp->if_xname, curthread, priv, kn,
1359 kn->kn_fp == curthread->td_fpop ? "match" : "MISMATCH");
1364 freebsd_netmap_poll(struct cdev *cdevi __unused, int events, struct thread *td)
1366 struct netmap_priv_d *priv;
1367 if (devfs_get_cdevpriv((void **)&priv)) {
1370 return netmap_poll(priv, events, td);
1374 freebsd_netmap_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data,
1375 int ffla __unused, struct thread *td)
1378 struct netmap_priv_d *priv;
1380 CURVNET_SET(TD_TO_VNET(td));
1381 error = devfs_get_cdevpriv((void **)&priv);
1383 /* XXX ENOENT should be impossible, since the priv
1384 * is now created in the open */
1385 if (error == ENOENT)
1389 error = netmap_ioctl(priv, cmd, data, td);
1396 extern struct cdevsw netmap_cdevsw; /* XXX used in netmap.c, should go elsewhere */
1397 struct cdevsw netmap_cdevsw = {
1398 .d_version = D_VERSION,
1400 .d_open = netmap_open,
1401 .d_mmap_single = netmap_mmap_single,
1402 .d_ioctl = freebsd_netmap_ioctl,
1403 .d_poll = freebsd_netmap_poll,
1404 .d_kqfilter = netmap_kqfilter,
1405 .d_close = netmap_close,
1407 /*--- end of kqueue support ----*/
1410 * Kernel entry point.
1412 * Initialize/finalize the module and return.
1414 * Return 0 on success, errno on failure.
1417 netmap_loader(__unused struct module *module, int event, __unused void *arg)
1423 error = netmap_init();
1428 * if some one is still using netmap,
1429 * then the module can not be unloaded.
1431 if (netmap_use_count) {
1432 D("netmap module can not be unloaded - netmap_use_count: %d",
1448 #ifdef DEV_MODULE_ORDERED
1450 * The netmap module contains three drivers: (i) the netmap character device
1451 * driver; (ii) the ptnetmap memdev PCI device driver, (iii) the ptnet PCI
1452 * device driver. The attach() routines of both (ii) and (iii) need the
1453 * lock of the global allocator, and such lock is initialized in netmap_init(),
1454 * which is part of (i).
1455 * Therefore, we make sure that (i) is loaded before (ii) and (iii), using
1456 * the 'order' parameter of driver declaration macros. For (i), we specify
1457 * SI_ORDER_MIDDLE, while higher orders are used with the DRIVER_MODULE_ORDERED
1458 * macros for (ii) and (iii).
1460 DEV_MODULE_ORDERED(netmap, netmap_loader, NULL, SI_ORDER_MIDDLE);
1461 #else /* !DEV_MODULE_ORDERED */
1462 DEV_MODULE(netmap, netmap_loader, NULL);
1463 #endif /* DEV_MODULE_ORDERED */
1464 MODULE_DEPEND(netmap, pci, 1, 1, 1);
1465 MODULE_VERSION(netmap, 1);
1466 /* reduce conditional code */
1467 // linux API, use for the knlist in FreeBSD
1468 /* use a private mutex for the knlist */