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_malloc(size_t size)
95 return malloc(size, M_DEVBUF, M_NOWAIT | M_ZERO);
99 nm_os_realloc(void *addr, size_t new_size, size_t old_size __unused)
101 return realloc(addr, new_size, M_DEVBUF, M_NOWAIT | M_ZERO);
105 nm_os_free(void *addr)
107 free(addr, M_DEVBUF);
111 nm_os_ifnet_lock(void)
117 nm_os_ifnet_unlock(void)
122 static int netmap_use_count = 0;
125 nm_os_get_module(void)
131 nm_os_put_module(void)
137 netmap_ifnet_arrival_handler(void *arg __unused, struct ifnet *ifp)
139 netmap_undo_zombie(ifp);
143 netmap_ifnet_departure_handler(void *arg __unused, struct ifnet *ifp)
145 netmap_make_zombie(ifp);
148 static eventhandler_tag nm_ifnet_ah_tag;
149 static eventhandler_tag nm_ifnet_dh_tag;
152 nm_os_ifnet_init(void)
155 EVENTHANDLER_REGISTER(ifnet_arrival_event,
156 netmap_ifnet_arrival_handler,
157 NULL, EVENTHANDLER_PRI_ANY);
159 EVENTHANDLER_REGISTER(ifnet_departure_event,
160 netmap_ifnet_departure_handler,
161 NULL, EVENTHANDLER_PRI_ANY);
166 nm_os_ifnet_fini(void)
168 EVENTHANDLER_DEREGISTER(ifnet_arrival_event,
170 EVENTHANDLER_DEREGISTER(ifnet_departure_event,
175 nm_os_csum_raw(uint8_t *data, size_t len, rawsum_t cur_sum)
177 /* TODO XXX please use the FreeBSD implementation for this. */
178 uint16_t *words = (uint16_t *)data;
182 for (i = 0; i < nw; i++)
183 cur_sum += be16toh(words[i]);
186 cur_sum += (data[len-1] << 8);
191 /* Fold a raw checksum: 'cur_sum' is in host byte order, while the
192 * return value is in network byte order.
195 nm_os_csum_fold(rawsum_t cur_sum)
197 /* TODO XXX please use the FreeBSD implementation for this. */
198 while (cur_sum >> 16)
199 cur_sum = (cur_sum & 0xFFFF) + (cur_sum >> 16);
201 return htobe16((~cur_sum) & 0xFFFF);
204 uint16_t nm_os_csum_ipv4(struct nm_iphdr *iph)
207 return in_cksum_hdr((void *)iph);
209 return nm_os_csum_fold(nm_os_csum_raw((uint8_t*)iph, sizeof(struct nm_iphdr), 0));
214 nm_os_csum_tcpudp_ipv4(struct nm_iphdr *iph, void *data,
215 size_t datalen, uint16_t *check)
218 uint16_t pseudolen = datalen + iph->protocol;
220 /* Compute and insert the pseudo-header cheksum. */
221 *check = in_pseudo(iph->saddr, iph->daddr,
223 /* Compute the checksum on TCP/UDP header + payload
224 * (includes the pseudo-header).
226 *check = nm_os_csum_fold(nm_os_csum_raw(data, datalen, 0));
228 static int notsupported = 0;
231 D("inet4 segmentation not supported");
237 nm_os_csum_tcpudp_ipv6(struct nm_ipv6hdr *ip6h, void *data,
238 size_t datalen, uint16_t *check)
241 *check = in6_cksum_pseudo((void*)ip6h, datalen, ip6h->nexthdr, 0);
242 *check = nm_os_csum_fold(nm_os_csum_raw(data, datalen, 0));
244 static int notsupported = 0;
247 D("inet6 segmentation not supported");
252 /* on FreeBSD we send up one packet at a time */
254 nm_os_send_up(struct ifnet *ifp, struct mbuf *m, struct mbuf *prev)
256 NA(ifp)->if_input(ifp, m);
261 nm_os_mbuf_has_offld(struct mbuf *m)
263 return m->m_pkthdr.csum_flags & (CSUM_TCP | CSUM_UDP | CSUM_SCTP |
264 CSUM_TCP_IPV6 | CSUM_UDP_IPV6 |
265 CSUM_SCTP_IPV6 | CSUM_TSO);
269 freebsd_generic_rx_handler(struct ifnet *ifp, struct mbuf *m)
273 if (!NM_NA_VALID(ifp)) {
274 RD(1, "Warning: got RX packet for invalid emulated adapter");
278 stolen = generic_rx_handler(ifp, m);
280 struct netmap_generic_adapter *gna =
281 (struct netmap_generic_adapter *)NA(ifp);
282 gna->save_if_input(ifp, m);
287 * Intercept the rx routine in the standard device driver.
288 * Second argument is non-zero to intercept, 0 to restore
291 nm_os_catch_rx(struct netmap_generic_adapter *gna, int intercept)
293 struct netmap_adapter *na = &gna->up.up;
294 struct ifnet *ifp = na->ifp;
297 if (gna->save_if_input) {
298 D("cannot intercept again");
299 return EINVAL; /* already set */
301 gna->save_if_input = ifp->if_input;
302 ifp->if_input = freebsd_generic_rx_handler;
304 if (!gna->save_if_input){
306 return EINVAL; /* not saved */
308 ifp->if_input = gna->save_if_input;
309 gna->save_if_input = NULL;
317 * Intercept the packet steering routine in the tx path,
318 * so that we can decide which queue is used for an mbuf.
319 * Second argument is non-zero to intercept, 0 to restore.
320 * On freebsd we just intercept if_transmit.
323 nm_os_catch_tx(struct netmap_generic_adapter *gna, int intercept)
325 struct netmap_adapter *na = &gna->up.up;
326 struct ifnet *ifp = netmap_generic_getifp(gna);
329 na->if_transmit = ifp->if_transmit;
330 ifp->if_transmit = netmap_transmit;
332 ifp->if_transmit = na->if_transmit;
340 * Transmit routine used by generic_netmap_txsync(). Returns 0 on success
341 * and non-zero on error (which may be packet drops or other errors).
342 * addr and len identify the netmap buffer, m is the (preallocated)
343 * mbuf to use for transmissions.
345 * We should add a reference to the mbuf so the m_freem() at the end
346 * of the transmission does not consume resources.
348 * On FreeBSD, and on multiqueue cards, we can force the queue using
349 * if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
350 * i = m->m_pkthdr.flowid % adapter->num_queues;
352 * i = curcpu % adapter->num_queues;
356 nm_os_generic_xmit_frame(struct nm_os_gen_arg *a)
360 struct ifnet *ifp = a->ifp;
361 struct mbuf *m = a->m;
363 #if __FreeBSD_version < 1100000
365 * Old FreeBSD versions. The mbuf has a cluster attached,
366 * we need to copy from the cluster to the netmap buffer.
368 if (MBUF_REFCNT(m) != 1) {
369 D("invalid refcnt %d for %p", MBUF_REFCNT(m), m);
370 panic("in generic_xmit_frame");
372 if (m->m_ext.ext_size < len) {
373 RD(5, "size %d < len %d", m->m_ext.ext_size, len);
374 len = m->m_ext.ext_size;
376 bcopy(a->addr, m->m_data, len);
377 #else /* __FreeBSD_version >= 1100000 */
378 /* New FreeBSD versions. Link the external storage to
379 * the netmap buffer, so that no copy is necessary. */
380 m->m_ext.ext_buf = m->m_data = a->addr;
381 m->m_ext.ext_size = len;
382 #endif /* __FreeBSD_version >= 1100000 */
384 m->m_len = m->m_pkthdr.len = len;
386 /* mbuf refcnt is not contended, no need to use atomic
387 * (a memory barrier is enough). */
388 SET_MBUF_REFCNT(m, 2);
389 M_HASHTYPE_SET(m, M_HASHTYPE_OPAQUE);
390 m->m_pkthdr.flowid = a->ring_nr;
391 m->m_pkthdr.rcvif = ifp; /* used for tx notification */
392 ret = NA(ifp)->if_transmit(ifp, m);
397 #if __FreeBSD_version >= 1100005
398 struct netmap_adapter *
399 netmap_getna(if_t ifp)
401 return (NA((struct ifnet *)ifp));
403 #endif /* __FreeBSD_version >= 1100005 */
406 * The following two functions are empty until we have a generic
407 * way to extract the info from the ifp
410 nm_os_generic_find_num_desc(struct ifnet *ifp, unsigned int *tx, unsigned int *rx)
417 nm_os_generic_find_num_queues(struct ifnet *ifp, u_int *txq, u_int *rxq)
419 unsigned num_rings = netmap_generic_rings ? netmap_generic_rings : 1;
426 nm_os_generic_set_features(struct netmap_generic_adapter *gna)
429 gna->rxsg = 1; /* Supported through m_copydata. */
430 gna->txqdisc = 0; /* Not supported. */
434 nm_os_mitigation_init(struct nm_generic_mit *mit, int idx, struct netmap_adapter *na)
437 mit->mit_pending = 0;
438 mit->mit_ring_idx = idx;
444 nm_os_mitigation_start(struct nm_generic_mit *mit)
451 nm_os_mitigation_restart(struct nm_generic_mit *mit)
458 nm_os_mitigation_active(struct nm_generic_mit *mit)
466 nm_os_mitigation_cleanup(struct nm_generic_mit *mit)
472 nm_vi_dummy(struct ifnet *ifp, u_long cmd, caddr_t addr)
478 nm_vi_start(struct ifnet *ifp)
480 panic("nm_vi_start() must not be called");
484 * Index manager of persistent virtual interfaces.
485 * It is used to decide the lowest byte of the MAC address.
486 * We use the same algorithm with management of bridge port index.
488 #define NM_VI_MAX 255
490 uint8_t index[NM_VI_MAX]; /* XXX just for a reasonable number */
496 nm_os_vi_init_index(void)
499 for (i = 0; i < NM_VI_MAX; i++)
500 nm_vi_indices.index[i] = i;
501 nm_vi_indices.active = 0;
502 mtx_init(&nm_vi_indices.lock, "nm_vi_indices_lock", NULL, MTX_DEF);
505 /* return -1 if no index available */
507 nm_vi_get_index(void)
511 mtx_lock(&nm_vi_indices.lock);
512 ret = nm_vi_indices.active == NM_VI_MAX ? -1 :
513 nm_vi_indices.index[nm_vi_indices.active++];
514 mtx_unlock(&nm_vi_indices.lock);
519 nm_vi_free_index(uint8_t val)
523 mtx_lock(&nm_vi_indices.lock);
524 lim = nm_vi_indices.active;
525 for (i = 0; i < lim; i++) {
526 if (nm_vi_indices.index[i] == val) {
527 /* swap index[lim-1] and j */
528 int tmp = nm_vi_indices.index[lim-1];
529 nm_vi_indices.index[lim-1] = val;
530 nm_vi_indices.index[i] = tmp;
531 nm_vi_indices.active--;
535 if (lim == nm_vi_indices.active)
536 D("funny, index %u didn't found", val);
537 mtx_unlock(&nm_vi_indices.lock);
542 * Implementation of a netmap-capable virtual interface that
543 * registered to the system.
544 * It is based on if_tap.c and ip_fw_log.c in FreeBSD 9.
546 * Note: Linux sets refcount to 0 on allocation of net_device,
547 * then increments it on registration to the system.
548 * FreeBSD sets refcount to 1 on if_alloc(), and does not
549 * increment this refcount on if_attach().
552 nm_os_vi_persist(const char *name, struct ifnet **ret)
556 uint32_t macaddr_mid;
558 int unit = nm_vi_get_index(); /* just to decide MAC address */
563 * We use the same MAC address generation method with tap
564 * except for the highest octet is 00:be instead of 00:bd
566 macaddr_hi = htons(0x00be); /* XXX tap + 1 */
567 macaddr_mid = (uint32_t) ticks;
568 bcopy(&macaddr_hi, eaddr, sizeof(short));
569 bcopy(&macaddr_mid, &eaddr[2], sizeof(uint32_t));
570 eaddr[5] = (uint8_t)unit;
572 ifp = if_alloc(IFT_ETHER);
574 D("if_alloc failed");
577 if_initname(ifp, name, IF_DUNIT_NONE);
579 ifp->if_flags = IFF_UP | IFF_SIMPLEX | IFF_MULTICAST;
580 ifp->if_init = (void *)nm_vi_dummy;
581 ifp->if_ioctl = nm_vi_dummy;
582 ifp->if_start = nm_vi_start;
583 ifp->if_mtu = ETHERMTU;
584 IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
585 ifp->if_capabilities |= IFCAP_LINKSTATE;
586 ifp->if_capenable |= IFCAP_LINKSTATE;
588 ether_ifattach(ifp, eaddr);
593 /* unregister from the system and drop the final refcount */
595 nm_os_vi_detach(struct ifnet *ifp)
597 nm_vi_free_index(((char *)IF_LLADDR(ifp))[5]);
602 /* ======================== PTNETMAP SUPPORT ========================== */
604 #ifdef WITH_PTNETMAP_GUEST
606 #include <sys/rman.h>
607 #include <machine/bus.h> /* bus_dmamap_* */
608 #include <machine/resource.h>
609 #include <dev/pci/pcivar.h>
610 #include <dev/pci/pcireg.h>
612 * ptnetmap memory device (memdev) for freebsd guest,
613 * ssed to expose host netmap memory to the guest through a PCI BAR.
617 * ptnetmap memdev private data structure
619 struct ptnetmap_memdev {
621 struct resource *pci_io;
622 struct resource *pci_mem;
623 struct netmap_mem_d *nm_mem;
626 static int ptn_memdev_probe(device_t);
627 static int ptn_memdev_attach(device_t);
628 static int ptn_memdev_detach(device_t);
629 static int ptn_memdev_shutdown(device_t);
631 static device_method_t ptn_memdev_methods[] = {
632 DEVMETHOD(device_probe, ptn_memdev_probe),
633 DEVMETHOD(device_attach, ptn_memdev_attach),
634 DEVMETHOD(device_detach, ptn_memdev_detach),
635 DEVMETHOD(device_shutdown, ptn_memdev_shutdown),
639 static driver_t ptn_memdev_driver = {
640 PTNETMAP_MEMDEV_NAME,
642 sizeof(struct ptnetmap_memdev),
645 /* We use (SI_ORDER_MIDDLE+1) here, see DEV_MODULE_ORDERED() invocation
647 static devclass_t ptnetmap_devclass;
648 DRIVER_MODULE_ORDERED(ptn_memdev, pci, ptn_memdev_driver, ptnetmap_devclass,
649 NULL, NULL, SI_ORDER_MIDDLE + 1);
652 * Map host netmap memory through PCI-BAR in the guest OS,
653 * returning physical (nm_paddr) and virtual (nm_addr) addresses
654 * of the netmap memory mapped in the guest.
657 nm_os_pt_memdev_iomap(struct ptnetmap_memdev *ptn_dev, vm_paddr_t *nm_paddr,
658 void **nm_addr, uint64_t *mem_size)
662 D("ptn_memdev_driver iomap");
664 rid = PCIR_BAR(PTNETMAP_MEM_PCI_BAR);
665 *mem_size = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMSIZE_HI);
666 *mem_size = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMSIZE_LO) |
669 /* map memory allocator */
670 ptn_dev->pci_mem = bus_alloc_resource(ptn_dev->dev, SYS_RES_MEMORY,
671 &rid, 0, ~0, *mem_size, RF_ACTIVE);
672 if (ptn_dev->pci_mem == NULL) {
678 *nm_paddr = rman_get_start(ptn_dev->pci_mem);
679 *nm_addr = rman_get_virtual(ptn_dev->pci_mem);
681 D("=== BAR %d start %lx len %lx mem_size %lx ===",
682 PTNETMAP_MEM_PCI_BAR,
683 (unsigned long)(*nm_paddr),
684 (unsigned long)rman_get_size(ptn_dev->pci_mem),
685 (unsigned long)*mem_size);
690 nm_os_pt_memdev_ioread(struct ptnetmap_memdev *ptn_dev, unsigned int reg)
692 return bus_read_4(ptn_dev->pci_io, reg);
695 /* Unmap host netmap memory. */
697 nm_os_pt_memdev_iounmap(struct ptnetmap_memdev *ptn_dev)
699 D("ptn_memdev_driver iounmap");
701 if (ptn_dev->pci_mem) {
702 bus_release_resource(ptn_dev->dev, SYS_RES_MEMORY,
703 PCIR_BAR(PTNETMAP_MEM_PCI_BAR), ptn_dev->pci_mem);
704 ptn_dev->pci_mem = NULL;
708 /* Device identification routine, return BUS_PROBE_DEFAULT on success,
709 * positive on failure */
711 ptn_memdev_probe(device_t dev)
715 if (pci_get_vendor(dev) != PTNETMAP_PCI_VENDOR_ID)
717 if (pci_get_device(dev) != PTNETMAP_PCI_DEVICE_ID)
720 snprintf(desc, sizeof(desc), "%s PCI adapter",
721 PTNETMAP_MEMDEV_NAME);
722 device_set_desc_copy(dev, desc);
724 return (BUS_PROBE_DEFAULT);
727 /* Device initialization routine. */
729 ptn_memdev_attach(device_t dev)
731 struct ptnetmap_memdev *ptn_dev;
735 D("ptn_memdev_driver attach");
737 ptn_dev = device_get_softc(dev);
740 pci_enable_busmaster(dev);
742 rid = PCIR_BAR(PTNETMAP_IO_PCI_BAR);
743 ptn_dev->pci_io = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
745 if (ptn_dev->pci_io == NULL) {
746 device_printf(dev, "cannot map I/O space\n");
750 mem_id = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMID);
752 /* create guest allocator */
753 ptn_dev->nm_mem = netmap_mem_pt_guest_attach(ptn_dev, mem_id);
754 if (ptn_dev->nm_mem == NULL) {
755 ptn_memdev_detach(dev);
758 netmap_mem_get(ptn_dev->nm_mem);
760 D("ptn_memdev_driver probe OK - host_mem_id: %d", mem_id);
765 /* Device removal routine. */
767 ptn_memdev_detach(device_t dev)
769 struct ptnetmap_memdev *ptn_dev;
771 D("ptn_memdev_driver detach");
772 ptn_dev = device_get_softc(dev);
774 if (ptn_dev->nm_mem) {
775 netmap_mem_put(ptn_dev->nm_mem);
776 ptn_dev->nm_mem = NULL;
778 if (ptn_dev->pci_mem) {
779 bus_release_resource(dev, SYS_RES_MEMORY,
780 PCIR_BAR(PTNETMAP_MEM_PCI_BAR), ptn_dev->pci_mem);
781 ptn_dev->pci_mem = NULL;
783 if (ptn_dev->pci_io) {
784 bus_release_resource(dev, SYS_RES_IOPORT,
785 PCIR_BAR(PTNETMAP_IO_PCI_BAR), ptn_dev->pci_io);
786 ptn_dev->pci_io = NULL;
793 ptn_memdev_shutdown(device_t dev)
795 D("ptn_memdev_driver shutdown");
796 return bus_generic_shutdown(dev);
799 #endif /* WITH_PTNETMAP_GUEST */
802 * In order to track whether pages are still mapped, we hook into
803 * the standard cdev_pager and intercept the constructor and
807 struct netmap_vm_handle_t {
809 struct netmap_priv_d *priv;
814 netmap_dev_pager_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot,
815 vm_ooffset_t foff, struct ucred *cred, u_short *color)
817 struct netmap_vm_handle_t *vmh = handle;
820 D("handle %p size %jd prot %d foff %jd",
821 handle, (intmax_t)size, prot, (intmax_t)foff);
830 netmap_dev_pager_dtor(void *handle)
832 struct netmap_vm_handle_t *vmh = handle;
833 struct cdev *dev = vmh->dev;
834 struct netmap_priv_d *priv = vmh->priv;
837 D("handle %p", handle);
845 netmap_dev_pager_fault(vm_object_t object, vm_ooffset_t offset,
846 int prot, vm_page_t *mres)
848 struct netmap_vm_handle_t *vmh = object->handle;
849 struct netmap_priv_d *priv = vmh->priv;
850 struct netmap_adapter *na = priv->np_na;
853 vm_memattr_t memattr;
856 ND("object %p offset %jd prot %d mres %p",
857 object, (intmax_t)offset, prot, mres);
858 memattr = object->memattr;
859 pidx = OFF_TO_IDX(offset);
860 paddr = netmap_mem_ofstophys(na->nm_mem, offset);
862 return VM_PAGER_FAIL;
864 if (((*mres)->flags & PG_FICTITIOUS) != 0) {
866 * If the passed in result page is a fake page, update it with
867 * the new physical address.
870 vm_page_updatefake(page, paddr, memattr);
873 * Replace the passed in reqpage page with our own fake page and
874 * free up the all of the original pages.
876 #ifndef VM_OBJECT_WUNLOCK /* FreeBSD < 10.x */
877 #define VM_OBJECT_WUNLOCK VM_OBJECT_UNLOCK
878 #define VM_OBJECT_WLOCK VM_OBJECT_LOCK
879 #endif /* VM_OBJECT_WUNLOCK */
881 VM_OBJECT_WUNLOCK(object);
882 page = vm_page_getfake(paddr, memattr);
883 VM_OBJECT_WLOCK(object);
886 vm_page_unlock(*mres);
888 vm_page_insert(page, object, pidx);
890 page->valid = VM_PAGE_BITS_ALL;
891 return (VM_PAGER_OK);
895 static struct cdev_pager_ops netmap_cdev_pager_ops = {
896 .cdev_pg_ctor = netmap_dev_pager_ctor,
897 .cdev_pg_dtor = netmap_dev_pager_dtor,
898 .cdev_pg_fault = netmap_dev_pager_fault,
903 netmap_mmap_single(struct cdev *cdev, vm_ooffset_t *foff,
904 vm_size_t objsize, vm_object_t *objp, int prot)
907 struct netmap_vm_handle_t *vmh;
908 struct netmap_priv_d *priv;
912 D("cdev %p foff %jd size %jd objp %p prot %d", cdev,
913 (intmax_t )*foff, (intmax_t )objsize, objp, prot);
915 vmh = malloc(sizeof(struct netmap_vm_handle_t), M_DEVBUF,
922 error = devfs_get_cdevpriv((void**)&priv);
925 if (priv->np_nifp == NULL) {
933 obj = cdev_pager_allocate(vmh, OBJT_DEVICE,
934 &netmap_cdev_pager_ops, objsize, prot,
937 D("cdev_pager_allocate failed");
956 * On FreeBSD the close routine is only called on the last close on
957 * the device (/dev/netmap) so we cannot do anything useful.
958 * To track close() on individual file descriptors we pass netmap_dtor() to
959 * devfs_set_cdevpriv() on open(). The FreeBSD kernel will call the destructor
960 * when the last fd pointing to the device is closed.
962 * Note that FreeBSD does not even munmap() on close() so we also have
963 * to track mmap() ourselves, and postpone the call to
964 * netmap_dtor() is called when the process has no open fds and no active
965 * memory maps on /dev/netmap, as in linux.
968 netmap_close(struct cdev *dev, int fflag, int devtype, struct thread *td)
971 D("dev %p fflag 0x%x devtype %d td %p",
972 dev, fflag, devtype, td);
978 netmap_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
980 struct netmap_priv_d *priv;
989 priv = netmap_priv_new();
994 error = devfs_set_cdevpriv(priv, netmap_dtor);
996 netmap_priv_delete(priv);
1003 /******************** kthread wrapper ****************/
1004 #include <sys/sysproto.h>
1008 return mp_maxid + 1;
1011 struct nm_kctx_ctx {
1012 struct thread *user_td; /* thread user-space (kthread creator) to send ioctl */
1013 struct ptnetmap_cfgentry_bhyve cfg;
1015 /* worker function and parameter */
1016 nm_kctx_worker_fn_t worker_fn;
1017 void *worker_private;
1019 struct nm_kctx *nmk;
1021 /* integer to manage multiple worker contexts (e.g., RX or TX on ptnetmap) */
1026 struct thread *worker;
1027 struct mtx worker_lock;
1028 uint64_t scheduled; /* pending wake_up request */
1029 struct nm_kctx_ctx worker_ctx;
1030 int run; /* used to stop kthread */
1031 int attach_user; /* kthread attached to user_process */
1036 nm_os_kctx_worker_wakeup(struct nm_kctx *nmk)
1039 * There may be a race between FE and BE,
1040 * which call both this function, and worker kthread,
1041 * that reads nmk->scheduled.
1043 * For us it is not important the counter value,
1044 * but simply that it has changed since the last
1045 * time the kthread saw it.
1047 mtx_lock(&nmk->worker_lock);
1049 if (nmk->worker_ctx.cfg.wchan) {
1050 wakeup((void *)(uintptr_t)nmk->worker_ctx.cfg.wchan);
1052 mtx_unlock(&nmk->worker_lock);
1056 nm_os_kctx_send_irq(struct nm_kctx *nmk)
1058 struct nm_kctx_ctx *ctx = &nmk->worker_ctx;
1061 if (ctx->user_td && ctx->cfg.ioctl_fd > 0) {
1062 err = kern_ioctl(ctx->user_td, ctx->cfg.ioctl_fd, ctx->cfg.ioctl_cmd,
1063 (caddr_t)&ctx->cfg.ioctl_data);
1065 D("kern_ioctl error: %d ioctl parameters: fd %d com %lu data %p",
1066 err, ctx->cfg.ioctl_fd, (unsigned long)ctx->cfg.ioctl_cmd,
1067 &ctx->cfg.ioctl_data);
1073 nm_kctx_worker(void *data)
1075 struct nm_kctx *nmk = data;
1076 struct nm_kctx_ctx *ctx = &nmk->worker_ctx;
1077 uint64_t old_scheduled = nmk->scheduled;
1079 if (nmk->affinity >= 0) {
1080 thread_lock(curthread);
1081 sched_bind(curthread, nmk->affinity);
1082 thread_unlock(curthread);
1087 * check if the parent process dies
1088 * (when kthread is attached to user process)
1092 thread_suspend_check(0);
1093 PROC_UNLOCK(curproc);
1095 kthread_suspend_check();
1099 * if wchan is not defined, we don't have notification
1100 * mechanism and we continually execute worker_fn()
1102 if (!ctx->cfg.wchan) {
1103 ctx->worker_fn(ctx->worker_private, 1); /* worker body */
1105 /* checks if there is a pending notification */
1106 mtx_lock(&nmk->worker_lock);
1107 if (likely(nmk->scheduled != old_scheduled)) {
1108 old_scheduled = nmk->scheduled;
1109 mtx_unlock(&nmk->worker_lock);
1111 ctx->worker_fn(ctx->worker_private, 1); /* worker body */
1114 } else if (nmk->run) {
1115 /* wait on event with one second timeout */
1116 msleep((void *)(uintptr_t)ctx->cfg.wchan, &nmk->worker_lock,
1120 mtx_unlock(&nmk->worker_lock);
1128 nm_os_kctx_worker_setaff(struct nm_kctx *nmk, int affinity)
1130 nmk->affinity = affinity;
1134 nm_os_kctx_create(struct nm_kctx_cfg *cfg, unsigned int cfgtype,
1137 struct nm_kctx *nmk = NULL;
1139 if (cfgtype != PTNETMAP_CFGTYPE_BHYVE) {
1140 D("Unsupported cfgtype %u", cfgtype);
1144 nmk = malloc(sizeof(*nmk), M_DEVBUF, M_NOWAIT | M_ZERO);
1148 mtx_init(&nmk->worker_lock, "nm_kthread lock", NULL, MTX_DEF);
1149 nmk->worker_ctx.worker_fn = cfg->worker_fn;
1150 nmk->worker_ctx.worker_private = cfg->worker_private;
1151 nmk->worker_ctx.type = cfg->type;
1154 /* attach kthread to user process (ptnetmap) */
1155 nmk->attach_user = cfg->attach_user;
1157 /* store kick/interrupt configuration */
1159 nmk->worker_ctx.cfg = *((struct ptnetmap_cfgentry_bhyve *)opaque);
1166 nm_os_kctx_worker_start(struct nm_kctx *nmk)
1168 struct proc *p = NULL;
1175 /* check if we want to attach kthread to user process */
1176 if (nmk->attach_user) {
1177 nmk->worker_ctx.user_td = curthread;
1178 p = curthread->td_proc;
1181 /* enable kthread main loop */
1183 /* create kthread */
1184 if((error = kthread_add(nm_kctx_worker, nmk, p,
1185 &nmk->worker, RFNOWAIT /* to be checked */, 0, "nm-kthread-%ld",
1186 nmk->worker_ctx.type))) {
1190 D("nm_kthread started td %p", nmk->worker);
1194 D("nm_kthread start failed err %d", error);
1200 nm_os_kctx_worker_stop(struct nm_kctx *nmk)
1205 /* tell to kthread to exit from main loop */
1208 /* wake up kthread if it sleeps */
1209 kthread_resume(nmk->worker);
1210 nm_os_kctx_worker_wakeup(nmk);
1216 nm_os_kctx_destroy(struct nm_kctx *nmk)
1221 nm_os_kctx_worker_stop(nmk);
1224 memset(&nmk->worker_ctx.cfg, 0, sizeof(nmk->worker_ctx.cfg));
1226 free(nmk, M_DEVBUF);
1229 /******************** kqueue support ****************/
1232 * nm_os_selwakeup also needs to issue a KNOTE_UNLOCKED.
1233 * We use a non-zero argument to distinguish the call from the one
1234 * in kevent_scan() which instead also needs to run netmap_poll().
1235 * The knote uses a global mutex for the time being. We might
1236 * try to reuse the one in the si, but it is not allocated
1237 * permanently so it might be a bit tricky.
1239 * The *kqfilter function registers one or another f_event
1240 * depending on read or write mode.
1241 * In the call to f_event() td_fpop is NULL so any child function
1242 * calling devfs_get_cdevpriv() would fail - and we need it in
1243 * netmap_poll(). As a workaround we store priv into kn->kn_hook
1244 * and pass it as first argument to netmap_poll(), which then
1245 * uses the failure to tell that we are called from f_event()
1246 * and do not need the selrecord().
1251 nm_os_selwakeup(struct nm_selinfo *si)
1254 D("on knote %p", &si->si.si_note);
1255 selwakeuppri(&si->si, PI_NET);
1256 /* use a non-zero hint to tell the notification from the
1257 * call done in kqueue_scan() which uses 0
1259 KNOTE_UNLOCKED(&si->si.si_note, 0x100 /* notification */);
1263 nm_os_selrecord(struct thread *td, struct nm_selinfo *si)
1265 selrecord(td, &si->si);
1269 netmap_knrdetach(struct knote *kn)
1271 struct netmap_priv_d *priv = (struct netmap_priv_d *)kn->kn_hook;
1272 struct selinfo *si = &priv->np_si[NR_RX]->si;
1274 D("remove selinfo %p", si);
1275 knlist_remove(&si->si_note, kn, 0);
1279 netmap_knwdetach(struct knote *kn)
1281 struct netmap_priv_d *priv = (struct netmap_priv_d *)kn->kn_hook;
1282 struct selinfo *si = &priv->np_si[NR_TX]->si;
1284 D("remove selinfo %p", si);
1285 knlist_remove(&si->si_note, kn, 0);
1289 * callback from notifies (generated externally) and our
1290 * calls to kevent(). The former we just return 1 (ready)
1291 * since we do not know better.
1292 * In the latter we call netmap_poll and return 0/1 accordingly.
1295 netmap_knrw(struct knote *kn, long hint, int events)
1297 struct netmap_priv_d *priv;
1301 ND(5, "call from notify");
1302 return 1; /* assume we are ready */
1305 /* the notification may come from an external thread,
1306 * in which case we do not want to run the netmap_poll
1307 * This should be filtered above, but check just in case.
1309 if (curthread != priv->np_td) { /* should not happen */
1310 RD(5, "curthread changed %p %p", curthread, priv->np_td);
1313 revents = netmap_poll(priv, events, NULL);
1314 return (events & revents) ? 1 : 0;
1319 netmap_knread(struct knote *kn, long hint)
1321 return netmap_knrw(kn, hint, POLLIN);
1325 netmap_knwrite(struct knote *kn, long hint)
1327 return netmap_knrw(kn, hint, POLLOUT);
1330 static struct filterops netmap_rfiltops = {
1332 .f_detach = netmap_knrdetach,
1333 .f_event = netmap_knread,
1336 static struct filterops netmap_wfiltops = {
1338 .f_detach = netmap_knwdetach,
1339 .f_event = netmap_knwrite,
1344 * This is called when a thread invokes kevent() to record
1345 * a change in the configuration of the kqueue().
1346 * The 'priv' should be the same as in the netmap device.
1349 netmap_kqfilter(struct cdev *dev, struct knote *kn)
1351 struct netmap_priv_d *priv;
1353 struct netmap_adapter *na;
1354 struct nm_selinfo *si;
1355 int ev = kn->kn_filter;
1357 if (ev != EVFILT_READ && ev != EVFILT_WRITE) {
1358 D("bad filter request %d", ev);
1361 error = devfs_get_cdevpriv((void**)&priv);
1363 D("device not yet setup");
1368 D("no netmap adapter for this file descriptor");
1371 /* the si is indicated in the priv */
1372 si = priv->np_si[(ev == EVFILT_WRITE) ? NR_TX : NR_RX];
1374 kn->kn_fop = (ev == EVFILT_WRITE) ?
1375 &netmap_wfiltops : &netmap_rfiltops;
1377 knlist_add(&si->si.si_note, kn, 1);
1379 ND("register %p %s td %p priv %p kn %p np_nifp %p kn_fp/fpop %s",
1380 na, na->ifp->if_xname, curthread, priv, kn,
1382 kn->kn_fp == curthread->td_fpop ? "match" : "MISMATCH");
1387 freebsd_netmap_poll(struct cdev *cdevi __unused, int events, struct thread *td)
1389 struct netmap_priv_d *priv;
1390 if (devfs_get_cdevpriv((void **)&priv)) {
1393 return netmap_poll(priv, events, td);
1397 freebsd_netmap_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data,
1398 int ffla __unused, struct thread *td)
1401 struct netmap_priv_d *priv;
1403 CURVNET_SET(TD_TO_VNET(td));
1404 error = devfs_get_cdevpriv((void **)&priv);
1406 /* XXX ENOENT should be impossible, since the priv
1407 * is now created in the open */
1408 if (error == ENOENT)
1412 error = netmap_ioctl(priv, cmd, data, td);
1419 extern struct cdevsw netmap_cdevsw; /* XXX used in netmap.c, should go elsewhere */
1420 struct cdevsw netmap_cdevsw = {
1421 .d_version = D_VERSION,
1423 .d_open = netmap_open,
1424 .d_mmap_single = netmap_mmap_single,
1425 .d_ioctl = freebsd_netmap_ioctl,
1426 .d_poll = freebsd_netmap_poll,
1427 .d_kqfilter = netmap_kqfilter,
1428 .d_close = netmap_close,
1430 /*--- end of kqueue support ----*/
1433 * Kernel entry point.
1435 * Initialize/finalize the module and return.
1437 * Return 0 on success, errno on failure.
1440 netmap_loader(__unused struct module *module, int event, __unused void *arg)
1446 error = netmap_init();
1451 * if some one is still using netmap,
1452 * then the module can not be unloaded.
1454 if (netmap_use_count) {
1455 D("netmap module can not be unloaded - netmap_use_count: %d",
1471 #ifdef DEV_MODULE_ORDERED
1473 * The netmap module contains three drivers: (i) the netmap character device
1474 * driver; (ii) the ptnetmap memdev PCI device driver, (iii) the ptnet PCI
1475 * device driver. The attach() routines of both (ii) and (iii) need the
1476 * lock of the global allocator, and such lock is initialized in netmap_init(),
1477 * which is part of (i).
1478 * Therefore, we make sure that (i) is loaded before (ii) and (iii), using
1479 * the 'order' parameter of driver declaration macros. For (i), we specify
1480 * SI_ORDER_MIDDLE, while higher orders are used with the DRIVER_MODULE_ORDERED
1481 * macros for (ii) and (iii).
1483 DEV_MODULE_ORDERED(netmap, netmap_loader, NULL, SI_ORDER_MIDDLE);
1484 #else /* !DEV_MODULE_ORDERED */
1485 DEV_MODULE(netmap, netmap_loader, NULL);
1486 #endif /* DEV_MODULE_ORDERED */
1487 MODULE_DEPEND(netmap, pci, 1, 1, 1);
1488 MODULE_VERSION(netmap, 1);
1489 /* reduce conditional code */
1490 // linux API, use for the knlist in FreeBSD
1491 /* use a private mutex for the knlist */