2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (C) 2013-2014 Universita` di Pisa. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 #include "opt_inet6.h"
32 #include <sys/param.h>
33 #include <sys/module.h>
34 #include <sys/errno.h>
36 #include <sys/poll.h> /* POLLIN, POLLOUT */
37 #include <sys/kernel.h> /* types used in module initialization */
38 #include <sys/conf.h> /* DEV_MODULE_ORDERED */
39 #include <sys/endian.h>
40 #include <sys/syscallsubr.h> /* kern_ioctl() */
42 #include <sys/rwlock.h>
44 #include <vm/vm.h> /* vtophys */
45 #include <vm/pmap.h> /* vtophys */
46 #include <vm/vm_param.h>
47 #include <vm/vm_object.h>
48 #include <vm/vm_page.h>
49 #include <vm/vm_pager.h>
53 #include <sys/malloc.h>
54 #include <sys/socket.h> /* sockaddrs */
55 #include <sys/selinfo.h>
56 #include <sys/kthread.h> /* kthread_add() */
57 #include <sys/proc.h> /* PROC_LOCK() */
58 #include <sys/unistd.h> /* RFNOWAIT */
59 #include <sys/sched.h> /* sched_bind() */
60 #include <sys/smp.h> /* mp_maxid */
62 #include <net/if_var.h>
63 #include <net/if_types.h> /* IFT_ETHER */
64 #include <net/ethernet.h> /* ether_ifdetach */
65 #include <net/if_dl.h> /* LLADDR */
66 #include <machine/bus.h> /* bus_dmamap_* */
67 #include <netinet/in.h> /* in6_cksum_pseudo() */
68 #include <machine/in_cksum.h> /* in_pseudo(), in_cksum_hdr() */
70 #include <net/netmap.h>
71 #include <dev/netmap/netmap_kern.h>
72 #include <net/netmap_virt.h>
73 #include <dev/netmap/netmap_mem2.h>
76 /* ======================== FREEBSD-SPECIFIC ROUTINES ================== */
78 void nm_os_selinfo_init(NM_SELINFO_T *si) {
79 struct mtx *m = &si->m;
80 mtx_init(m, "nm_kn_lock", NULL, MTX_DEF);
81 knlist_init_mtx(&si->si.si_note, m);
85 nm_os_selinfo_uninit(NM_SELINFO_T *si)
87 /* XXX kqueue(9) needed; these will mirror knlist_init. */
88 knlist_delete(&si->si.si_note, curthread, 0 /* not locked */ );
89 knlist_destroy(&si->si.si_note);
90 /* now we don't need the mutex anymore */
95 nm_os_malloc(size_t size)
97 return malloc(size, M_DEVBUF, M_NOWAIT | M_ZERO);
101 nm_os_realloc(void *addr, size_t new_size, size_t old_size __unused)
103 return realloc(addr, new_size, M_DEVBUF, M_NOWAIT | M_ZERO);
107 nm_os_free(void *addr)
109 free(addr, M_DEVBUF);
113 nm_os_ifnet_lock(void)
119 nm_os_ifnet_unlock(void)
124 static int netmap_use_count = 0;
127 nm_os_get_module(void)
133 nm_os_put_module(void)
139 netmap_ifnet_arrival_handler(void *arg __unused, struct ifnet *ifp)
141 netmap_undo_zombie(ifp);
145 netmap_ifnet_departure_handler(void *arg __unused, struct ifnet *ifp)
147 netmap_make_zombie(ifp);
150 static eventhandler_tag nm_ifnet_ah_tag;
151 static eventhandler_tag nm_ifnet_dh_tag;
154 nm_os_ifnet_init(void)
157 EVENTHANDLER_REGISTER(ifnet_arrival_event,
158 netmap_ifnet_arrival_handler,
159 NULL, EVENTHANDLER_PRI_ANY);
161 EVENTHANDLER_REGISTER(ifnet_departure_event,
162 netmap_ifnet_departure_handler,
163 NULL, EVENTHANDLER_PRI_ANY);
168 nm_os_ifnet_fini(void)
170 EVENTHANDLER_DEREGISTER(ifnet_arrival_event,
172 EVENTHANDLER_DEREGISTER(ifnet_departure_event,
177 nm_os_ifnet_mtu(struct ifnet *ifp)
179 #if __FreeBSD_version < 1100030
180 return ifp->if_data.ifi_mtu;
181 #else /* __FreeBSD_version >= 1100030 */
187 nm_os_csum_raw(uint8_t *data, size_t len, rawsum_t cur_sum)
189 /* TODO XXX please use the FreeBSD implementation for this. */
190 uint16_t *words = (uint16_t *)data;
194 for (i = 0; i < nw; i++)
195 cur_sum += be16toh(words[i]);
198 cur_sum += (data[len-1] << 8);
203 /* Fold a raw checksum: 'cur_sum' is in host byte order, while the
204 * return value is in network byte order.
207 nm_os_csum_fold(rawsum_t cur_sum)
209 /* TODO XXX please use the FreeBSD implementation for this. */
210 while (cur_sum >> 16)
211 cur_sum = (cur_sum & 0xFFFF) + (cur_sum >> 16);
213 return htobe16((~cur_sum) & 0xFFFF);
216 uint16_t nm_os_csum_ipv4(struct nm_iphdr *iph)
219 return in_cksum_hdr((void *)iph);
221 return nm_os_csum_fold(nm_os_csum_raw((uint8_t*)iph, sizeof(struct nm_iphdr), 0));
226 nm_os_csum_tcpudp_ipv4(struct nm_iphdr *iph, void *data,
227 size_t datalen, uint16_t *check)
230 uint16_t pseudolen = datalen + iph->protocol;
232 /* Compute and insert the pseudo-header cheksum. */
233 *check = in_pseudo(iph->saddr, iph->daddr,
235 /* Compute the checksum on TCP/UDP header + payload
236 * (includes the pseudo-header).
238 *check = nm_os_csum_fold(nm_os_csum_raw(data, datalen, 0));
240 static int notsupported = 0;
243 D("inet4 segmentation not supported");
249 nm_os_csum_tcpudp_ipv6(struct nm_ipv6hdr *ip6h, void *data,
250 size_t datalen, uint16_t *check)
253 *check = in6_cksum_pseudo((void*)ip6h, datalen, ip6h->nexthdr, 0);
254 *check = nm_os_csum_fold(nm_os_csum_raw(data, datalen, 0));
256 static int notsupported = 0;
259 D("inet6 segmentation not supported");
264 /* on FreeBSD we send up one packet at a time */
266 nm_os_send_up(struct ifnet *ifp, struct mbuf *m, struct mbuf *prev)
268 NA(ifp)->if_input(ifp, m);
273 nm_os_mbuf_has_offld(struct mbuf *m)
275 return m->m_pkthdr.csum_flags & (CSUM_TCP | CSUM_UDP | CSUM_SCTP |
276 CSUM_TCP_IPV6 | CSUM_UDP_IPV6 |
277 CSUM_SCTP_IPV6 | CSUM_TSO);
281 freebsd_generic_rx_handler(struct ifnet *ifp, struct mbuf *m)
285 if (!NM_NA_VALID(ifp)) {
286 RD(1, "Warning: got RX packet for invalid emulated adapter");
290 stolen = generic_rx_handler(ifp, m);
292 struct netmap_generic_adapter *gna =
293 (struct netmap_generic_adapter *)NA(ifp);
294 gna->save_if_input(ifp, m);
299 * Intercept the rx routine in the standard device driver.
300 * Second argument is non-zero to intercept, 0 to restore
303 nm_os_catch_rx(struct netmap_generic_adapter *gna, int intercept)
305 struct netmap_adapter *na = &gna->up.up;
306 struct ifnet *ifp = na->ifp;
311 if (gna->save_if_input) {
312 D("cannot intercept again");
313 ret = EINVAL; /* already set */
316 gna->save_if_input = ifp->if_input;
317 ifp->if_input = freebsd_generic_rx_handler;
319 if (!gna->save_if_input){
321 ret = EINVAL; /* not saved */
324 ifp->if_input = gna->save_if_input;
325 gna->save_if_input = NULL;
328 nm_os_ifnet_unlock();
335 * Intercept the packet steering routine in the tx path,
336 * so that we can decide which queue is used for an mbuf.
337 * Second argument is non-zero to intercept, 0 to restore.
338 * On freebsd we just intercept if_transmit.
341 nm_os_catch_tx(struct netmap_generic_adapter *gna, int intercept)
343 struct netmap_adapter *na = &gna->up.up;
344 struct ifnet *ifp = netmap_generic_getifp(gna);
348 na->if_transmit = ifp->if_transmit;
349 ifp->if_transmit = netmap_transmit;
351 ifp->if_transmit = na->if_transmit;
353 nm_os_ifnet_unlock();
360 * Transmit routine used by generic_netmap_txsync(). Returns 0 on success
361 * and non-zero on error (which may be packet drops or other errors).
362 * addr and len identify the netmap buffer, m is the (preallocated)
363 * mbuf to use for transmissions.
365 * We should add a reference to the mbuf so the m_freem() at the end
366 * of the transmission does not consume resources.
368 * On FreeBSD, and on multiqueue cards, we can force the queue using
369 * if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
370 * i = m->m_pkthdr.flowid % adapter->num_queues;
372 * i = curcpu % adapter->num_queues;
376 nm_os_generic_xmit_frame(struct nm_os_gen_arg *a)
380 struct ifnet *ifp = a->ifp;
381 struct mbuf *m = a->m;
383 #if __FreeBSD_version < 1100000
385 * Old FreeBSD versions. The mbuf has a cluster attached,
386 * we need to copy from the cluster to the netmap buffer.
388 if (MBUF_REFCNT(m) != 1) {
389 D("invalid refcnt %d for %p", MBUF_REFCNT(m), m);
390 panic("in generic_xmit_frame");
392 if (m->m_ext.ext_size < len) {
393 RD(5, "size %d < len %d", m->m_ext.ext_size, len);
394 len = m->m_ext.ext_size;
396 bcopy(a->addr, m->m_data, len);
397 #else /* __FreeBSD_version >= 1100000 */
398 /* New FreeBSD versions. Link the external storage to
399 * the netmap buffer, so that no copy is necessary. */
400 m->m_ext.ext_buf = m->m_data = a->addr;
401 m->m_ext.ext_size = len;
402 #endif /* __FreeBSD_version >= 1100000 */
404 m->m_len = m->m_pkthdr.len = len;
406 /* mbuf refcnt is not contended, no need to use atomic
407 * (a memory barrier is enough). */
408 SET_MBUF_REFCNT(m, 2);
409 M_HASHTYPE_SET(m, M_HASHTYPE_OPAQUE);
410 m->m_pkthdr.flowid = a->ring_nr;
411 m->m_pkthdr.rcvif = ifp; /* used for tx notification */
412 ret = NA(ifp)->if_transmit(ifp, m);
417 #if __FreeBSD_version >= 1100005
418 struct netmap_adapter *
419 netmap_getna(if_t ifp)
421 return (NA((struct ifnet *)ifp));
423 #endif /* __FreeBSD_version >= 1100005 */
426 * The following two functions are empty until we have a generic
427 * way to extract the info from the ifp
430 nm_os_generic_find_num_desc(struct ifnet *ifp, unsigned int *tx, unsigned int *rx)
437 nm_os_generic_find_num_queues(struct ifnet *ifp, u_int *txq, u_int *rxq)
439 unsigned num_rings = netmap_generic_rings ? netmap_generic_rings : 1;
446 nm_os_generic_set_features(struct netmap_generic_adapter *gna)
449 gna->rxsg = 1; /* Supported through m_copydata. */
450 gna->txqdisc = 0; /* Not supported. */
454 nm_os_mitigation_init(struct nm_generic_mit *mit, int idx, struct netmap_adapter *na)
457 mit->mit_pending = 0;
458 mit->mit_ring_idx = idx;
464 nm_os_mitigation_start(struct nm_generic_mit *mit)
471 nm_os_mitigation_restart(struct nm_generic_mit *mit)
478 nm_os_mitigation_active(struct nm_generic_mit *mit)
486 nm_os_mitigation_cleanup(struct nm_generic_mit *mit)
492 nm_vi_dummy(struct ifnet *ifp, u_long cmd, caddr_t addr)
498 nm_vi_start(struct ifnet *ifp)
500 panic("nm_vi_start() must not be called");
504 * Index manager of persistent virtual interfaces.
505 * It is used to decide the lowest byte of the MAC address.
506 * We use the same algorithm with management of bridge port index.
508 #define NM_VI_MAX 255
510 uint8_t index[NM_VI_MAX]; /* XXX just for a reasonable number */
516 nm_os_vi_init_index(void)
519 for (i = 0; i < NM_VI_MAX; i++)
520 nm_vi_indices.index[i] = i;
521 nm_vi_indices.active = 0;
522 mtx_init(&nm_vi_indices.lock, "nm_vi_indices_lock", NULL, MTX_DEF);
525 /* return -1 if no index available */
527 nm_vi_get_index(void)
531 mtx_lock(&nm_vi_indices.lock);
532 ret = nm_vi_indices.active == NM_VI_MAX ? -1 :
533 nm_vi_indices.index[nm_vi_indices.active++];
534 mtx_unlock(&nm_vi_indices.lock);
539 nm_vi_free_index(uint8_t val)
543 mtx_lock(&nm_vi_indices.lock);
544 lim = nm_vi_indices.active;
545 for (i = 0; i < lim; i++) {
546 if (nm_vi_indices.index[i] == val) {
547 /* swap index[lim-1] and j */
548 int tmp = nm_vi_indices.index[lim-1];
549 nm_vi_indices.index[lim-1] = val;
550 nm_vi_indices.index[i] = tmp;
551 nm_vi_indices.active--;
555 if (lim == nm_vi_indices.active)
556 D("funny, index %u didn't found", val);
557 mtx_unlock(&nm_vi_indices.lock);
562 * Implementation of a netmap-capable virtual interface that
563 * registered to the system.
564 * It is based on if_tap.c and ip_fw_log.c in FreeBSD 9.
566 * Note: Linux sets refcount to 0 on allocation of net_device,
567 * then increments it on registration to the system.
568 * FreeBSD sets refcount to 1 on if_alloc(), and does not
569 * increment this refcount on if_attach().
572 nm_os_vi_persist(const char *name, struct ifnet **ret)
576 uint32_t macaddr_mid;
578 int unit = nm_vi_get_index(); /* just to decide MAC address */
583 * We use the same MAC address generation method with tap
584 * except for the highest octet is 00:be instead of 00:bd
586 macaddr_hi = htons(0x00be); /* XXX tap + 1 */
587 macaddr_mid = (uint32_t) ticks;
588 bcopy(&macaddr_hi, eaddr, sizeof(short));
589 bcopy(&macaddr_mid, &eaddr[2], sizeof(uint32_t));
590 eaddr[5] = (uint8_t)unit;
592 ifp = if_alloc(IFT_ETHER);
594 D("if_alloc failed");
597 if_initname(ifp, name, IF_DUNIT_NONE);
599 ifp->if_flags = IFF_UP | IFF_SIMPLEX | IFF_MULTICAST;
600 ifp->if_init = (void *)nm_vi_dummy;
601 ifp->if_ioctl = nm_vi_dummy;
602 ifp->if_start = nm_vi_start;
603 ifp->if_mtu = ETHERMTU;
604 IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
605 ifp->if_capabilities |= IFCAP_LINKSTATE;
606 ifp->if_capenable |= IFCAP_LINKSTATE;
608 ether_ifattach(ifp, eaddr);
613 /* unregister from the system and drop the final refcount */
615 nm_os_vi_detach(struct ifnet *ifp)
617 nm_vi_free_index(((char *)IF_LLADDR(ifp))[5]);
623 #include <vm/vm_map.h>
624 #include <vm/vm_kern.h>
625 struct nm_os_extmem {
633 nm_os_extmem_delete(struct nm_os_extmem *e)
635 D("freeing %jx bytes", (uintmax_t)e->size);
636 vm_map_remove(kernel_map, e->kva, e->kva + e->size);
641 nm_os_extmem_nextpage(struct nm_os_extmem *e)
644 if (e->scan < e->kva + e->size) {
645 rv = (char *)e->scan;
646 e->scan += PAGE_SIZE;
652 nm_os_extmem_isequal(struct nm_os_extmem *e1, struct nm_os_extmem *e2)
654 return (e1->obj == e1->obj);
658 nm_os_extmem_nr_pages(struct nm_os_extmem *e)
660 return e->size >> PAGE_SHIFT;
663 struct nm_os_extmem *
664 nm_os_extmem_create(unsigned long p, struct nmreq_pools_info *pi, int *perror)
667 vm_map_entry_t entry;
672 struct nm_os_extmem *e = NULL;
675 e = nm_os_malloc(sizeof(*e));
681 map = &curthread->td_proc->p_vmspace->vm_map;
682 rv = vm_map_lookup(&map, p, VM_PROT_RW, &entry,
683 &obj, &index, &prot, &wired);
684 if (rv != KERN_SUCCESS) {
685 D("address %lx not found", p);
688 /* check that we are given the whole vm_object ? */
689 vm_map_lookup_done(map, entry);
691 // XXX can we really use obj after releasing the map lock?
693 vm_object_reference(obj);
694 /* wire the memory and add the vm_object to the kernel map,
695 * to make sure that it is not fred even if the processes that
696 * are mmap()ing it all exit
698 e->kva = vm_map_min(kernel_map);
699 e->size = obj->size << PAGE_SHIFT;
700 rv = vm_map_find(kernel_map, obj, 0, &e->kva, e->size, 0,
701 VMFS_OPTIMAL_SPACE, VM_PROT_READ | VM_PROT_WRITE,
702 VM_PROT_READ | VM_PROT_WRITE, 0);
703 if (rv != KERN_SUCCESS) {
704 D("vm_map_find(%jx) failed", (uintmax_t)e->size);
707 rv = vm_map_wire(kernel_map, e->kva, e->kva + e->size,
708 VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
709 if (rv != KERN_SUCCESS) {
710 D("vm_map_wire failed");
719 vm_map_remove(kernel_map, e->kva, e->kva + e->size);
722 vm_object_deallocate(e->obj);
730 #endif /* WITH_EXTMEM */
732 /* ======================== PTNETMAP SUPPORT ========================== */
734 #ifdef WITH_PTNETMAP_GUEST
736 #include <sys/rman.h>
737 #include <machine/bus.h> /* bus_dmamap_* */
738 #include <machine/resource.h>
739 #include <dev/pci/pcivar.h>
740 #include <dev/pci/pcireg.h>
742 * ptnetmap memory device (memdev) for freebsd guest,
743 * ssed to expose host netmap memory to the guest through a PCI BAR.
747 * ptnetmap memdev private data structure
749 struct ptnetmap_memdev {
751 struct resource *pci_io;
752 struct resource *pci_mem;
753 struct netmap_mem_d *nm_mem;
756 static int ptn_memdev_probe(device_t);
757 static int ptn_memdev_attach(device_t);
758 static int ptn_memdev_detach(device_t);
759 static int ptn_memdev_shutdown(device_t);
761 static device_method_t ptn_memdev_methods[] = {
762 DEVMETHOD(device_probe, ptn_memdev_probe),
763 DEVMETHOD(device_attach, ptn_memdev_attach),
764 DEVMETHOD(device_detach, ptn_memdev_detach),
765 DEVMETHOD(device_shutdown, ptn_memdev_shutdown),
769 static driver_t ptn_memdev_driver = {
770 PTNETMAP_MEMDEV_NAME,
772 sizeof(struct ptnetmap_memdev),
775 /* We use (SI_ORDER_MIDDLE+1) here, see DEV_MODULE_ORDERED() invocation
777 static devclass_t ptnetmap_devclass;
778 DRIVER_MODULE_ORDERED(ptn_memdev, pci, ptn_memdev_driver, ptnetmap_devclass,
779 NULL, NULL, SI_ORDER_MIDDLE + 1);
782 * Map host netmap memory through PCI-BAR in the guest OS,
783 * returning physical (nm_paddr) and virtual (nm_addr) addresses
784 * of the netmap memory mapped in the guest.
787 nm_os_pt_memdev_iomap(struct ptnetmap_memdev *ptn_dev, vm_paddr_t *nm_paddr,
788 void **nm_addr, uint64_t *mem_size)
792 D("ptn_memdev_driver iomap");
794 rid = PCIR_BAR(PTNETMAP_MEM_PCI_BAR);
795 *mem_size = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMSIZE_HI);
796 *mem_size = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMSIZE_LO) |
799 /* map memory allocator */
800 ptn_dev->pci_mem = bus_alloc_resource(ptn_dev->dev, SYS_RES_MEMORY,
801 &rid, 0, ~0, *mem_size, RF_ACTIVE);
802 if (ptn_dev->pci_mem == NULL) {
808 *nm_paddr = rman_get_start(ptn_dev->pci_mem);
809 *nm_addr = rman_get_virtual(ptn_dev->pci_mem);
811 D("=== BAR %d start %lx len %lx mem_size %lx ===",
812 PTNETMAP_MEM_PCI_BAR,
813 (unsigned long)(*nm_paddr),
814 (unsigned long)rman_get_size(ptn_dev->pci_mem),
815 (unsigned long)*mem_size);
820 nm_os_pt_memdev_ioread(struct ptnetmap_memdev *ptn_dev, unsigned int reg)
822 return bus_read_4(ptn_dev->pci_io, reg);
825 /* Unmap host netmap memory. */
827 nm_os_pt_memdev_iounmap(struct ptnetmap_memdev *ptn_dev)
829 D("ptn_memdev_driver iounmap");
831 if (ptn_dev->pci_mem) {
832 bus_release_resource(ptn_dev->dev, SYS_RES_MEMORY,
833 PCIR_BAR(PTNETMAP_MEM_PCI_BAR), ptn_dev->pci_mem);
834 ptn_dev->pci_mem = NULL;
838 /* Device identification routine, return BUS_PROBE_DEFAULT on success,
839 * positive on failure */
841 ptn_memdev_probe(device_t dev)
845 if (pci_get_vendor(dev) != PTNETMAP_PCI_VENDOR_ID)
847 if (pci_get_device(dev) != PTNETMAP_PCI_DEVICE_ID)
850 snprintf(desc, sizeof(desc), "%s PCI adapter",
851 PTNETMAP_MEMDEV_NAME);
852 device_set_desc_copy(dev, desc);
854 return (BUS_PROBE_DEFAULT);
857 /* Device initialization routine. */
859 ptn_memdev_attach(device_t dev)
861 struct ptnetmap_memdev *ptn_dev;
865 D("ptn_memdev_driver attach");
867 ptn_dev = device_get_softc(dev);
870 pci_enable_busmaster(dev);
872 rid = PCIR_BAR(PTNETMAP_IO_PCI_BAR);
873 ptn_dev->pci_io = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
875 if (ptn_dev->pci_io == NULL) {
876 device_printf(dev, "cannot map I/O space\n");
880 mem_id = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMID);
882 /* create guest allocator */
883 ptn_dev->nm_mem = netmap_mem_pt_guest_attach(ptn_dev, mem_id);
884 if (ptn_dev->nm_mem == NULL) {
885 ptn_memdev_detach(dev);
888 netmap_mem_get(ptn_dev->nm_mem);
890 D("ptn_memdev_driver probe OK - host_mem_id: %d", mem_id);
895 /* Device removal routine. */
897 ptn_memdev_detach(device_t dev)
899 struct ptnetmap_memdev *ptn_dev;
901 D("ptn_memdev_driver detach");
902 ptn_dev = device_get_softc(dev);
904 if (ptn_dev->nm_mem) {
905 netmap_mem_put(ptn_dev->nm_mem);
906 ptn_dev->nm_mem = NULL;
908 if (ptn_dev->pci_mem) {
909 bus_release_resource(dev, SYS_RES_MEMORY,
910 PCIR_BAR(PTNETMAP_MEM_PCI_BAR), ptn_dev->pci_mem);
911 ptn_dev->pci_mem = NULL;
913 if (ptn_dev->pci_io) {
914 bus_release_resource(dev, SYS_RES_IOPORT,
915 PCIR_BAR(PTNETMAP_IO_PCI_BAR), ptn_dev->pci_io);
916 ptn_dev->pci_io = NULL;
923 ptn_memdev_shutdown(device_t dev)
925 D("ptn_memdev_driver shutdown");
926 return bus_generic_shutdown(dev);
929 #endif /* WITH_PTNETMAP_GUEST */
932 * In order to track whether pages are still mapped, we hook into
933 * the standard cdev_pager and intercept the constructor and
937 struct netmap_vm_handle_t {
939 struct netmap_priv_d *priv;
944 netmap_dev_pager_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot,
945 vm_ooffset_t foff, struct ucred *cred, u_short *color)
947 struct netmap_vm_handle_t *vmh = handle;
950 D("handle %p size %jd prot %d foff %jd",
951 handle, (intmax_t)size, prot, (intmax_t)foff);
960 netmap_dev_pager_dtor(void *handle)
962 struct netmap_vm_handle_t *vmh = handle;
963 struct cdev *dev = vmh->dev;
964 struct netmap_priv_d *priv = vmh->priv;
967 D("handle %p", handle);
975 netmap_dev_pager_fault(vm_object_t object, vm_ooffset_t offset,
976 int prot, vm_page_t *mres)
978 struct netmap_vm_handle_t *vmh = object->handle;
979 struct netmap_priv_d *priv = vmh->priv;
980 struct netmap_adapter *na = priv->np_na;
983 vm_memattr_t memattr;
986 ND("object %p offset %jd prot %d mres %p",
987 object, (intmax_t)offset, prot, mres);
988 memattr = object->memattr;
989 pidx = OFF_TO_IDX(offset);
990 paddr = netmap_mem_ofstophys(na->nm_mem, offset);
992 return VM_PAGER_FAIL;
994 if (((*mres)->flags & PG_FICTITIOUS) != 0) {
996 * If the passed in result page is a fake page, update it with
997 * the new physical address.
1000 vm_page_updatefake(page, paddr, memattr);
1003 * Replace the passed in reqpage page with our own fake page and
1004 * free up the all of the original pages.
1006 #ifndef VM_OBJECT_WUNLOCK /* FreeBSD < 10.x */
1007 #define VM_OBJECT_WUNLOCK VM_OBJECT_UNLOCK
1008 #define VM_OBJECT_WLOCK VM_OBJECT_LOCK
1009 #endif /* VM_OBJECT_WUNLOCK */
1011 VM_OBJECT_WUNLOCK(object);
1012 page = vm_page_getfake(paddr, memattr);
1013 VM_OBJECT_WLOCK(object);
1014 vm_page_lock(*mres);
1015 vm_page_free(*mres);
1016 vm_page_unlock(*mres);
1018 vm_page_insert(page, object, pidx);
1020 page->valid = VM_PAGE_BITS_ALL;
1021 return (VM_PAGER_OK);
1025 static struct cdev_pager_ops netmap_cdev_pager_ops = {
1026 .cdev_pg_ctor = netmap_dev_pager_ctor,
1027 .cdev_pg_dtor = netmap_dev_pager_dtor,
1028 .cdev_pg_fault = netmap_dev_pager_fault,
1033 netmap_mmap_single(struct cdev *cdev, vm_ooffset_t *foff,
1034 vm_size_t objsize, vm_object_t *objp, int prot)
1037 struct netmap_vm_handle_t *vmh;
1038 struct netmap_priv_d *priv;
1042 D("cdev %p foff %jd size %jd objp %p prot %d", cdev,
1043 (intmax_t )*foff, (intmax_t )objsize, objp, prot);
1045 vmh = malloc(sizeof(struct netmap_vm_handle_t), M_DEVBUF,
1052 error = devfs_get_cdevpriv((void**)&priv);
1055 if (priv->np_nifp == NULL) {
1063 obj = cdev_pager_allocate(vmh, OBJT_DEVICE,
1064 &netmap_cdev_pager_ops, objsize, prot,
1067 D("cdev_pager_allocate failed");
1081 free(vmh, M_DEVBUF);
1086 * On FreeBSD the close routine is only called on the last close on
1087 * the device (/dev/netmap) so we cannot do anything useful.
1088 * To track close() on individual file descriptors we pass netmap_dtor() to
1089 * devfs_set_cdevpriv() on open(). The FreeBSD kernel will call the destructor
1090 * when the last fd pointing to the device is closed.
1092 * Note that FreeBSD does not even munmap() on close() so we also have
1093 * to track mmap() ourselves, and postpone the call to
1094 * netmap_dtor() is called when the process has no open fds and no active
1095 * memory maps on /dev/netmap, as in linux.
1098 netmap_close(struct cdev *dev, int fflag, int devtype, struct thread *td)
1101 D("dev %p fflag 0x%x devtype %d td %p",
1102 dev, fflag, devtype, td);
1108 netmap_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
1110 struct netmap_priv_d *priv;
1119 priv = netmap_priv_new();
1124 error = devfs_set_cdevpriv(priv, netmap_dtor);
1126 netmap_priv_delete(priv);
1133 /******************** kthread wrapper ****************/
1134 #include <sys/sysproto.h>
1138 return mp_maxid + 1;
1141 struct nm_kctx_ctx {
1142 struct thread *user_td; /* thread user-space (kthread creator) to send ioctl */
1143 struct ptnetmap_cfgentry_bhyve cfg;
1145 /* worker function and parameter */
1146 nm_kctx_worker_fn_t worker_fn;
1147 void *worker_private;
1149 struct nm_kctx *nmk;
1151 /* integer to manage multiple worker contexts (e.g., RX or TX on ptnetmap) */
1156 struct thread *worker;
1157 struct mtx worker_lock;
1158 uint64_t scheduled; /* pending wake_up request */
1159 struct nm_kctx_ctx worker_ctx;
1160 int run; /* used to stop kthread */
1161 int attach_user; /* kthread attached to user_process */
1166 nm_os_kctx_worker_wakeup(struct nm_kctx *nmk)
1169 * There may be a race between FE and BE,
1170 * which call both this function, and worker kthread,
1171 * that reads nmk->scheduled.
1173 * For us it is not important the counter value,
1174 * but simply that it has changed since the last
1175 * time the kthread saw it.
1177 mtx_lock(&nmk->worker_lock);
1179 if (nmk->worker_ctx.cfg.wchan) {
1180 wakeup((void *)(uintptr_t)nmk->worker_ctx.cfg.wchan);
1182 mtx_unlock(&nmk->worker_lock);
1186 nm_os_kctx_send_irq(struct nm_kctx *nmk)
1188 struct nm_kctx_ctx *ctx = &nmk->worker_ctx;
1191 if (ctx->user_td && ctx->cfg.ioctl_fd > 0) {
1192 err = kern_ioctl(ctx->user_td, ctx->cfg.ioctl_fd, ctx->cfg.ioctl_cmd,
1193 (caddr_t)&ctx->cfg.ioctl_data);
1195 D("kern_ioctl error: %d ioctl parameters: fd %d com %lu data %p",
1196 err, ctx->cfg.ioctl_fd, (unsigned long)ctx->cfg.ioctl_cmd,
1197 &ctx->cfg.ioctl_data);
1203 nm_kctx_worker(void *data)
1205 struct nm_kctx *nmk = data;
1206 struct nm_kctx_ctx *ctx = &nmk->worker_ctx;
1207 uint64_t old_scheduled = nmk->scheduled;
1209 if (nmk->affinity >= 0) {
1210 thread_lock(curthread);
1211 sched_bind(curthread, nmk->affinity);
1212 thread_unlock(curthread);
1217 * check if the parent process dies
1218 * (when kthread is attached to user process)
1222 thread_suspend_check(0);
1223 PROC_UNLOCK(curproc);
1225 kthread_suspend_check();
1229 * if wchan is not defined, we don't have notification
1230 * mechanism and we continually execute worker_fn()
1232 if (!ctx->cfg.wchan) {
1233 ctx->worker_fn(ctx->worker_private, 1); /* worker body */
1235 /* checks if there is a pending notification */
1236 mtx_lock(&nmk->worker_lock);
1237 if (likely(nmk->scheduled != old_scheduled)) {
1238 old_scheduled = nmk->scheduled;
1239 mtx_unlock(&nmk->worker_lock);
1241 ctx->worker_fn(ctx->worker_private, 1); /* worker body */
1244 } else if (nmk->run) {
1245 /* wait on event with one second timeout */
1246 msleep((void *)(uintptr_t)ctx->cfg.wchan, &nmk->worker_lock,
1250 mtx_unlock(&nmk->worker_lock);
1258 nm_os_kctx_worker_setaff(struct nm_kctx *nmk, int affinity)
1260 nmk->affinity = affinity;
1264 nm_os_kctx_create(struct nm_kctx_cfg *cfg, void *opaque)
1266 struct nm_kctx *nmk = NULL;
1268 nmk = malloc(sizeof(*nmk), M_DEVBUF, M_NOWAIT | M_ZERO);
1272 mtx_init(&nmk->worker_lock, "nm_kthread lock", NULL, MTX_DEF);
1273 nmk->worker_ctx.worker_fn = cfg->worker_fn;
1274 nmk->worker_ctx.worker_private = cfg->worker_private;
1275 nmk->worker_ctx.type = cfg->type;
1278 /* attach kthread to user process (ptnetmap) */
1279 nmk->attach_user = cfg->attach_user;
1281 /* store kick/interrupt configuration */
1283 nmk->worker_ctx.cfg = *((struct ptnetmap_cfgentry_bhyve *)opaque);
1290 nm_os_kctx_worker_start(struct nm_kctx *nmk)
1292 struct proc *p = NULL;
1299 /* check if we want to attach kthread to user process */
1300 if (nmk->attach_user) {
1301 nmk->worker_ctx.user_td = curthread;
1302 p = curthread->td_proc;
1305 /* enable kthread main loop */
1307 /* create kthread */
1308 if((error = kthread_add(nm_kctx_worker, nmk, p,
1309 &nmk->worker, RFNOWAIT /* to be checked */, 0, "nm-kthread-%ld",
1310 nmk->worker_ctx.type))) {
1314 D("nm_kthread started td %p", nmk->worker);
1318 D("nm_kthread start failed err %d", error);
1324 nm_os_kctx_worker_stop(struct nm_kctx *nmk)
1329 /* tell to kthread to exit from main loop */
1332 /* wake up kthread if it sleeps */
1333 kthread_resume(nmk->worker);
1334 nm_os_kctx_worker_wakeup(nmk);
1340 nm_os_kctx_destroy(struct nm_kctx *nmk)
1345 nm_os_kctx_worker_stop(nmk);
1348 memset(&nmk->worker_ctx.cfg, 0, sizeof(nmk->worker_ctx.cfg));
1350 free(nmk, M_DEVBUF);
1353 /******************** kqueue support ****************/
1356 * nm_os_selwakeup also needs to issue a KNOTE_UNLOCKED.
1357 * We use a non-zero argument to distinguish the call from the one
1358 * in kevent_scan() which instead also needs to run netmap_poll().
1359 * The knote uses a global mutex for the time being. We might
1360 * try to reuse the one in the si, but it is not allocated
1361 * permanently so it might be a bit tricky.
1363 * The *kqfilter function registers one or another f_event
1364 * depending on read or write mode.
1365 * In the call to f_event() td_fpop is NULL so any child function
1366 * calling devfs_get_cdevpriv() would fail - and we need it in
1367 * netmap_poll(). As a workaround we store priv into kn->kn_hook
1368 * and pass it as first argument to netmap_poll(), which then
1369 * uses the failure to tell that we are called from f_event()
1370 * and do not need the selrecord().
1375 nm_os_selwakeup(struct nm_selinfo *si)
1378 D("on knote %p", &si->si.si_note);
1379 selwakeuppri(&si->si, PI_NET);
1380 /* use a non-zero hint to tell the notification from the
1381 * call done in kqueue_scan() which uses 0
1383 KNOTE_UNLOCKED(&si->si.si_note, 0x100 /* notification */);
1387 nm_os_selrecord(struct thread *td, struct nm_selinfo *si)
1389 selrecord(td, &si->si);
1393 netmap_knrdetach(struct knote *kn)
1395 struct netmap_priv_d *priv = (struct netmap_priv_d *)kn->kn_hook;
1396 struct selinfo *si = &priv->np_si[NR_RX]->si;
1398 D("remove selinfo %p", si);
1399 knlist_remove(&si->si_note, kn, 0);
1403 netmap_knwdetach(struct knote *kn)
1405 struct netmap_priv_d *priv = (struct netmap_priv_d *)kn->kn_hook;
1406 struct selinfo *si = &priv->np_si[NR_TX]->si;
1408 D("remove selinfo %p", si);
1409 knlist_remove(&si->si_note, kn, 0);
1413 * callback from notifies (generated externally) and our
1414 * calls to kevent(). The former we just return 1 (ready)
1415 * since we do not know better.
1416 * In the latter we call netmap_poll and return 0/1 accordingly.
1419 netmap_knrw(struct knote *kn, long hint, int events)
1421 struct netmap_priv_d *priv;
1425 ND(5, "call from notify");
1426 return 1; /* assume we are ready */
1429 /* the notification may come from an external thread,
1430 * in which case we do not want to run the netmap_poll
1431 * This should be filtered above, but check just in case.
1433 if (curthread != priv->np_td) { /* should not happen */
1434 RD(5, "curthread changed %p %p", curthread, priv->np_td);
1437 revents = netmap_poll(priv, events, NULL);
1438 return (events & revents) ? 1 : 0;
1443 netmap_knread(struct knote *kn, long hint)
1445 return netmap_knrw(kn, hint, POLLIN);
1449 netmap_knwrite(struct knote *kn, long hint)
1451 return netmap_knrw(kn, hint, POLLOUT);
1454 static struct filterops netmap_rfiltops = {
1456 .f_detach = netmap_knrdetach,
1457 .f_event = netmap_knread,
1460 static struct filterops netmap_wfiltops = {
1462 .f_detach = netmap_knwdetach,
1463 .f_event = netmap_knwrite,
1468 * This is called when a thread invokes kevent() to record
1469 * a change in the configuration of the kqueue().
1470 * The 'priv' should be the same as in the netmap device.
1473 netmap_kqfilter(struct cdev *dev, struct knote *kn)
1475 struct netmap_priv_d *priv;
1477 struct netmap_adapter *na;
1478 struct nm_selinfo *si;
1479 int ev = kn->kn_filter;
1481 if (ev != EVFILT_READ && ev != EVFILT_WRITE) {
1482 D("bad filter request %d", ev);
1485 error = devfs_get_cdevpriv((void**)&priv);
1487 D("device not yet setup");
1492 D("no netmap adapter for this file descriptor");
1495 /* the si is indicated in the priv */
1496 si = priv->np_si[(ev == EVFILT_WRITE) ? NR_TX : NR_RX];
1498 kn->kn_fop = (ev == EVFILT_WRITE) ?
1499 &netmap_wfiltops : &netmap_rfiltops;
1501 knlist_add(&si->si.si_note, kn, 1);
1503 ND("register %p %s td %p priv %p kn %p np_nifp %p kn_fp/fpop %s",
1504 na, na->ifp->if_xname, curthread, priv, kn,
1506 kn->kn_fp == curthread->td_fpop ? "match" : "MISMATCH");
1511 freebsd_netmap_poll(struct cdev *cdevi __unused, int events, struct thread *td)
1513 struct netmap_priv_d *priv;
1514 if (devfs_get_cdevpriv((void **)&priv)) {
1517 return netmap_poll(priv, events, td);
1521 freebsd_netmap_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data,
1522 int ffla __unused, struct thread *td)
1525 struct netmap_priv_d *priv;
1527 CURVNET_SET(TD_TO_VNET(td));
1528 error = devfs_get_cdevpriv((void **)&priv);
1530 /* XXX ENOENT should be impossible, since the priv
1531 * is now created in the open */
1532 if (error == ENOENT)
1536 error = netmap_ioctl(priv, cmd, data, td, /*nr_body_is_user=*/1);
1543 extern struct cdevsw netmap_cdevsw; /* XXX used in netmap.c, should go elsewhere */
1544 struct cdevsw netmap_cdevsw = {
1545 .d_version = D_VERSION,
1547 .d_open = netmap_open,
1548 .d_mmap_single = netmap_mmap_single,
1549 .d_ioctl = freebsd_netmap_ioctl,
1550 .d_poll = freebsd_netmap_poll,
1551 .d_kqfilter = netmap_kqfilter,
1552 .d_close = netmap_close,
1554 /*--- end of kqueue support ----*/
1557 * Kernel entry point.
1559 * Initialize/finalize the module and return.
1561 * Return 0 on success, errno on failure.
1564 netmap_loader(__unused struct module *module, int event, __unused void *arg)
1570 error = netmap_init();
1575 * if some one is still using netmap,
1576 * then the module can not be unloaded.
1578 if (netmap_use_count) {
1579 D("netmap module can not be unloaded - netmap_use_count: %d",
1595 #ifdef DEV_MODULE_ORDERED
1597 * The netmap module contains three drivers: (i) the netmap character device
1598 * driver; (ii) the ptnetmap memdev PCI device driver, (iii) the ptnet PCI
1599 * device driver. The attach() routines of both (ii) and (iii) need the
1600 * lock of the global allocator, and such lock is initialized in netmap_init(),
1601 * which is part of (i).
1602 * Therefore, we make sure that (i) is loaded before (ii) and (iii), using
1603 * the 'order' parameter of driver declaration macros. For (i), we specify
1604 * SI_ORDER_MIDDLE, while higher orders are used with the DRIVER_MODULE_ORDERED
1605 * macros for (ii) and (iii).
1607 DEV_MODULE_ORDERED(netmap, netmap_loader, NULL, SI_ORDER_MIDDLE);
1608 #else /* !DEV_MODULE_ORDERED */
1609 DEV_MODULE(netmap, netmap_loader, NULL);
1610 #endif /* DEV_MODULE_ORDERED */
1611 MODULE_DEPEND(netmap, pci, 1, 1, 1);
1612 MODULE_VERSION(netmap, 1);
1613 /* reduce conditional code */
1614 // linux API, use for the knlist in FreeBSD
1615 /* use a private mutex for the knlist */