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 */
61 #include <sys/taskqueue.h> /* taskqueue_enqueue(), taskqueue_create(), ... */
63 #include <net/if_var.h>
64 #include <net/if_types.h> /* IFT_ETHER */
65 #include <net/ethernet.h> /* ether_ifdetach */
66 #include <net/if_dl.h> /* LLADDR */
67 #include <machine/bus.h> /* bus_dmamap_* */
68 #include <netinet/in.h> /* in6_cksum_pseudo() */
69 #include <machine/in_cksum.h> /* in_pseudo(), in_cksum_hdr() */
71 #include <net/netmap.h>
72 #include <dev/netmap/netmap_kern.h>
73 #include <net/netmap_virt.h>
74 #include <dev/netmap/netmap_mem2.h>
77 /* ======================== FREEBSD-SPECIFIC ROUTINES ================== */
80 nm_kqueue_notify(void *opaque, int pending)
82 struct nm_selinfo *si = opaque;
84 /* We use a non-zero hint to distinguish this notification call
85 * from the call done in kqueue_scan(), which uses hint=0.
87 KNOTE_UNLOCKED(&si->si.si_note, /*hint=*/0x100);
90 int nm_os_selinfo_init(NM_SELINFO_T *si, const char *name) {
93 TASK_INIT(&si->ntfytask, 0, nm_kqueue_notify, si);
94 si->ntfytq = taskqueue_create(name, M_NOWAIT,
95 taskqueue_thread_enqueue, &si->ntfytq);
96 if (si->ntfytq == NULL)
98 err = taskqueue_start_threads(&si->ntfytq, 1, PI_NET, "tq %s", name);
100 taskqueue_free(si->ntfytq);
105 snprintf(si->mtxname, sizeof(si->mtxname), "nmkl%s", name);
106 mtx_init(&si->m, si->mtxname, NULL, MTX_DEF);
107 knlist_init_mtx(&si->si.si_note, &si->m);
113 nm_os_selinfo_uninit(NM_SELINFO_T *si)
115 if (si->ntfytq == NULL) {
116 return; /* si was not initialized */
118 taskqueue_drain(si->ntfytq, &si->ntfytask);
119 taskqueue_free(si->ntfytq);
121 knlist_delete(&si->si.si_note, curthread, /*islocked=*/0);
122 knlist_destroy(&si->si.si_note);
123 /* now we don't need the mutex anymore */
128 nm_os_malloc(size_t size)
130 return malloc(size, M_DEVBUF, M_NOWAIT | M_ZERO);
134 nm_os_realloc(void *addr, size_t new_size, size_t old_size __unused)
136 return realloc(addr, new_size, M_DEVBUF, M_NOWAIT | M_ZERO);
140 nm_os_free(void *addr)
142 free(addr, M_DEVBUF);
146 nm_os_ifnet_lock(void)
152 nm_os_ifnet_unlock(void)
157 static int netmap_use_count = 0;
160 nm_os_get_module(void)
166 nm_os_put_module(void)
172 netmap_ifnet_arrival_handler(void *arg __unused, struct ifnet *ifp)
174 netmap_undo_zombie(ifp);
178 netmap_ifnet_departure_handler(void *arg __unused, struct ifnet *ifp)
180 netmap_make_zombie(ifp);
183 static eventhandler_tag nm_ifnet_ah_tag;
184 static eventhandler_tag nm_ifnet_dh_tag;
187 nm_os_ifnet_init(void)
190 EVENTHANDLER_REGISTER(ifnet_arrival_event,
191 netmap_ifnet_arrival_handler,
192 NULL, EVENTHANDLER_PRI_ANY);
194 EVENTHANDLER_REGISTER(ifnet_departure_event,
195 netmap_ifnet_departure_handler,
196 NULL, EVENTHANDLER_PRI_ANY);
201 nm_os_ifnet_fini(void)
203 EVENTHANDLER_DEREGISTER(ifnet_arrival_event,
205 EVENTHANDLER_DEREGISTER(ifnet_departure_event,
210 nm_os_ifnet_mtu(struct ifnet *ifp)
212 #if __FreeBSD_version < 1100030
213 return ifp->if_data.ifi_mtu;
214 #else /* __FreeBSD_version >= 1100030 */
220 nm_os_csum_raw(uint8_t *data, size_t len, rawsum_t cur_sum)
222 /* TODO XXX please use the FreeBSD implementation for this. */
223 uint16_t *words = (uint16_t *)data;
227 for (i = 0; i < nw; i++)
228 cur_sum += be16toh(words[i]);
231 cur_sum += (data[len-1] << 8);
236 /* Fold a raw checksum: 'cur_sum' is in host byte order, while the
237 * return value is in network byte order.
240 nm_os_csum_fold(rawsum_t cur_sum)
242 /* TODO XXX please use the FreeBSD implementation for this. */
243 while (cur_sum >> 16)
244 cur_sum = (cur_sum & 0xFFFF) + (cur_sum >> 16);
246 return htobe16((~cur_sum) & 0xFFFF);
249 uint16_t nm_os_csum_ipv4(struct nm_iphdr *iph)
252 return in_cksum_hdr((void *)iph);
254 return nm_os_csum_fold(nm_os_csum_raw((uint8_t*)iph, sizeof(struct nm_iphdr), 0));
259 nm_os_csum_tcpudp_ipv4(struct nm_iphdr *iph, void *data,
260 size_t datalen, uint16_t *check)
263 uint16_t pseudolen = datalen + iph->protocol;
265 /* Compute and insert the pseudo-header cheksum. */
266 *check = in_pseudo(iph->saddr, iph->daddr,
268 /* Compute the checksum on TCP/UDP header + payload
269 * (includes the pseudo-header).
271 *check = nm_os_csum_fold(nm_os_csum_raw(data, datalen, 0));
273 static int notsupported = 0;
276 nm_prerr("inet4 segmentation not supported");
282 nm_os_csum_tcpudp_ipv6(struct nm_ipv6hdr *ip6h, void *data,
283 size_t datalen, uint16_t *check)
286 *check = in6_cksum_pseudo((void*)ip6h, datalen, ip6h->nexthdr, 0);
287 *check = nm_os_csum_fold(nm_os_csum_raw(data, datalen, 0));
289 static int notsupported = 0;
292 nm_prerr("inet6 segmentation not supported");
297 /* on FreeBSD we send up one packet at a time */
299 nm_os_send_up(struct ifnet *ifp, struct mbuf *m, struct mbuf *prev)
301 NA(ifp)->if_input(ifp, m);
306 nm_os_mbuf_has_csum_offld(struct mbuf *m)
308 return m->m_pkthdr.csum_flags & (CSUM_TCP | CSUM_UDP | CSUM_SCTP |
309 CSUM_TCP_IPV6 | CSUM_UDP_IPV6 |
314 nm_os_mbuf_has_seg_offld(struct mbuf *m)
316 return m->m_pkthdr.csum_flags & CSUM_TSO;
320 freebsd_generic_rx_handler(struct ifnet *ifp, struct mbuf *m)
324 if (unlikely(!NM_NA_VALID(ifp))) {
325 nm_prlim(1, "Warning: RX packet intercepted, but no"
326 " emulated adapter");
330 stolen = generic_rx_handler(ifp, m);
332 struct netmap_generic_adapter *gna =
333 (struct netmap_generic_adapter *)NA(ifp);
334 gna->save_if_input(ifp, m);
339 * Intercept the rx routine in the standard device driver.
340 * Second argument is non-zero to intercept, 0 to restore
343 nm_os_catch_rx(struct netmap_generic_adapter *gna, int intercept)
345 struct netmap_adapter *na = &gna->up.up;
346 struct ifnet *ifp = na->ifp;
351 if (gna->save_if_input) {
352 nm_prerr("RX on %s already intercepted", na->name);
353 ret = EBUSY; /* already set */
356 gna->save_if_input = ifp->if_input;
357 ifp->if_input = freebsd_generic_rx_handler;
359 if (!gna->save_if_input) {
360 nm_prerr("Failed to undo RX intercept on %s",
362 ret = EINVAL; /* not saved */
365 ifp->if_input = gna->save_if_input;
366 gna->save_if_input = NULL;
369 nm_os_ifnet_unlock();
376 * Intercept the packet steering routine in the tx path,
377 * so that we can decide which queue is used for an mbuf.
378 * Second argument is non-zero to intercept, 0 to restore.
379 * On freebsd we just intercept if_transmit.
382 nm_os_catch_tx(struct netmap_generic_adapter *gna, int intercept)
384 struct netmap_adapter *na = &gna->up.up;
385 struct ifnet *ifp = netmap_generic_getifp(gna);
389 na->if_transmit = ifp->if_transmit;
390 ifp->if_transmit = netmap_transmit;
392 ifp->if_transmit = na->if_transmit;
394 nm_os_ifnet_unlock();
401 * Transmit routine used by generic_netmap_txsync(). Returns 0 on success
402 * and non-zero on error (which may be packet drops or other errors).
403 * addr and len identify the netmap buffer, m is the (preallocated)
404 * mbuf to use for transmissions.
406 * We should add a reference to the mbuf so the m_freem() at the end
407 * of the transmission does not consume resources.
409 * On FreeBSD, and on multiqueue cards, we can force the queue using
410 * if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
411 * i = m->m_pkthdr.flowid % adapter->num_queues;
413 * i = curcpu % adapter->num_queues;
417 nm_os_generic_xmit_frame(struct nm_os_gen_arg *a)
421 struct ifnet *ifp = a->ifp;
422 struct mbuf *m = a->m;
424 #if __FreeBSD_version < 1100000
426 * Old FreeBSD versions. The mbuf has a cluster attached,
427 * we need to copy from the cluster to the netmap buffer.
429 if (MBUF_REFCNT(m) != 1) {
430 nm_prerr("invalid refcnt %d for %p", MBUF_REFCNT(m), m);
431 panic("in generic_xmit_frame");
433 if (m->m_ext.ext_size < len) {
434 nm_prlim(2, "size %d < len %d", m->m_ext.ext_size, len);
435 len = m->m_ext.ext_size;
437 bcopy(a->addr, m->m_data, len);
438 #else /* __FreeBSD_version >= 1100000 */
439 /* New FreeBSD versions. Link the external storage to
440 * the netmap buffer, so that no copy is necessary. */
441 m->m_ext.ext_buf = m->m_data = a->addr;
442 m->m_ext.ext_size = len;
443 #endif /* __FreeBSD_version >= 1100000 */
445 m->m_len = m->m_pkthdr.len = len;
447 /* mbuf refcnt is not contended, no need to use atomic
448 * (a memory barrier is enough). */
449 SET_MBUF_REFCNT(m, 2);
450 M_HASHTYPE_SET(m, M_HASHTYPE_OPAQUE);
451 m->m_pkthdr.flowid = a->ring_nr;
452 m->m_pkthdr.rcvif = ifp; /* used for tx notification */
453 ret = NA(ifp)->if_transmit(ifp, m);
458 #if __FreeBSD_version >= 1100005
459 struct netmap_adapter *
460 netmap_getna(if_t ifp)
462 return (NA((struct ifnet *)ifp));
464 #endif /* __FreeBSD_version >= 1100005 */
467 * The following two functions are empty until we have a generic
468 * way to extract the info from the ifp
471 nm_os_generic_find_num_desc(struct ifnet *ifp, unsigned int *tx, unsigned int *rx)
478 nm_os_generic_find_num_queues(struct ifnet *ifp, u_int *txq, u_int *rxq)
480 unsigned num_rings = netmap_generic_rings ? netmap_generic_rings : 1;
487 nm_os_generic_set_features(struct netmap_generic_adapter *gna)
490 gna->rxsg = 1; /* Supported through m_copydata. */
491 gna->txqdisc = 0; /* Not supported. */
495 nm_os_mitigation_init(struct nm_generic_mit *mit, int idx, struct netmap_adapter *na)
497 mit->mit_pending = 0;
498 mit->mit_ring_idx = idx;
504 nm_os_mitigation_start(struct nm_generic_mit *mit)
510 nm_os_mitigation_restart(struct nm_generic_mit *mit)
516 nm_os_mitigation_active(struct nm_generic_mit *mit)
524 nm_os_mitigation_cleanup(struct nm_generic_mit *mit)
529 nm_vi_dummy(struct ifnet *ifp, u_long cmd, caddr_t addr)
536 nm_vi_start(struct ifnet *ifp)
538 panic("nm_vi_start() must not be called");
542 * Index manager of persistent virtual interfaces.
543 * It is used to decide the lowest byte of the MAC address.
544 * We use the same algorithm with management of bridge port index.
546 #define NM_VI_MAX 255
548 uint8_t index[NM_VI_MAX]; /* XXX just for a reasonable number */
554 nm_os_vi_init_index(void)
557 for (i = 0; i < NM_VI_MAX; i++)
558 nm_vi_indices.index[i] = i;
559 nm_vi_indices.active = 0;
560 mtx_init(&nm_vi_indices.lock, "nm_vi_indices_lock", NULL, MTX_DEF);
563 /* return -1 if no index available */
565 nm_vi_get_index(void)
569 mtx_lock(&nm_vi_indices.lock);
570 ret = nm_vi_indices.active == NM_VI_MAX ? -1 :
571 nm_vi_indices.index[nm_vi_indices.active++];
572 mtx_unlock(&nm_vi_indices.lock);
577 nm_vi_free_index(uint8_t val)
581 mtx_lock(&nm_vi_indices.lock);
582 lim = nm_vi_indices.active;
583 for (i = 0; i < lim; i++) {
584 if (nm_vi_indices.index[i] == val) {
585 /* swap index[lim-1] and j */
586 int tmp = nm_vi_indices.index[lim-1];
587 nm_vi_indices.index[lim-1] = val;
588 nm_vi_indices.index[i] = tmp;
589 nm_vi_indices.active--;
593 if (lim == nm_vi_indices.active)
594 nm_prerr("Index %u not found", val);
595 mtx_unlock(&nm_vi_indices.lock);
600 * Implementation of a netmap-capable virtual interface that
601 * registered to the system.
602 * It is based on if_tap.c and ip_fw_log.c in FreeBSD 9.
604 * Note: Linux sets refcount to 0 on allocation of net_device,
605 * then increments it on registration to the system.
606 * FreeBSD sets refcount to 1 on if_alloc(), and does not
607 * increment this refcount on if_attach().
610 nm_os_vi_persist(const char *name, struct ifnet **ret)
614 uint32_t macaddr_mid;
616 int unit = nm_vi_get_index(); /* just to decide MAC address */
621 * We use the same MAC address generation method with tap
622 * except for the highest octet is 00:be instead of 00:bd
624 macaddr_hi = htons(0x00be); /* XXX tap + 1 */
625 macaddr_mid = (uint32_t) ticks;
626 bcopy(&macaddr_hi, eaddr, sizeof(short));
627 bcopy(&macaddr_mid, &eaddr[2], sizeof(uint32_t));
628 eaddr[5] = (uint8_t)unit;
630 ifp = if_alloc(IFT_ETHER);
632 nm_prerr("if_alloc failed");
635 if_initname(ifp, name, IF_DUNIT_NONE);
637 ifp->if_flags = IFF_UP | IFF_SIMPLEX | IFF_MULTICAST;
638 ifp->if_init = (void *)nm_vi_dummy;
639 ifp->if_ioctl = nm_vi_dummy;
640 ifp->if_start = nm_vi_start;
641 ifp->if_mtu = ETHERMTU;
642 IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
643 ifp->if_capabilities |= IFCAP_LINKSTATE;
644 ifp->if_capenable |= IFCAP_LINKSTATE;
646 ether_ifattach(ifp, eaddr);
651 /* unregister from the system and drop the final refcount */
653 nm_os_vi_detach(struct ifnet *ifp)
655 nm_vi_free_index(((char *)IF_LLADDR(ifp))[5]);
661 #include <vm/vm_map.h>
662 #include <vm/vm_kern.h>
663 struct nm_os_extmem {
671 nm_os_extmem_delete(struct nm_os_extmem *e)
673 nm_prinf("freeing %zx bytes", (size_t)e->size);
674 vm_map_remove(kernel_map, e->kva, e->kva + e->size);
679 nm_os_extmem_nextpage(struct nm_os_extmem *e)
682 if (e->scan < e->kva + e->size) {
683 rv = (char *)e->scan;
684 e->scan += PAGE_SIZE;
690 nm_os_extmem_isequal(struct nm_os_extmem *e1, struct nm_os_extmem *e2)
692 return (e1->obj == e2->obj);
696 nm_os_extmem_nr_pages(struct nm_os_extmem *e)
698 return e->size >> PAGE_SHIFT;
701 struct nm_os_extmem *
702 nm_os_extmem_create(unsigned long p, struct nmreq_pools_info *pi, int *perror)
705 vm_map_entry_t entry;
710 struct nm_os_extmem *e = NULL;
713 e = nm_os_malloc(sizeof(*e));
719 map = &curthread->td_proc->p_vmspace->vm_map;
720 rv = vm_map_lookup(&map, p, VM_PROT_RW, &entry,
721 &obj, &index, &prot, &wired);
722 if (rv != KERN_SUCCESS) {
723 nm_prerr("address %lx not found", p);
726 /* check that we are given the whole vm_object ? */
727 vm_map_lookup_done(map, entry);
729 // XXX can we really use obj after releasing the map lock?
731 vm_object_reference(obj);
732 /* wire the memory and add the vm_object to the kernel map,
733 * to make sure that it is not fred even if the processes that
734 * are mmap()ing it all exit
736 e->kva = vm_map_min(kernel_map);
737 e->size = obj->size << PAGE_SHIFT;
738 rv = vm_map_find(kernel_map, obj, 0, &e->kva, e->size, 0,
739 VMFS_OPTIMAL_SPACE, VM_PROT_READ | VM_PROT_WRITE,
740 VM_PROT_READ | VM_PROT_WRITE, 0);
741 if (rv != KERN_SUCCESS) {
742 nm_prerr("vm_map_find(%zx) failed", (size_t)e->size);
745 rv = vm_map_wire(kernel_map, e->kva, e->kva + e->size,
746 VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
747 if (rv != KERN_SUCCESS) {
748 nm_prerr("vm_map_wire failed");
757 vm_map_remove(kernel_map, e->kva, e->kva + e->size);
760 vm_object_deallocate(e->obj);
768 #endif /* WITH_EXTMEM */
770 /* ================== PTNETMAP GUEST SUPPORT ==================== */
774 #include <sys/rman.h>
775 #include <machine/bus.h> /* bus_dmamap_* */
776 #include <machine/resource.h>
777 #include <dev/pci/pcivar.h>
778 #include <dev/pci/pcireg.h>
780 * ptnetmap memory device (memdev) for freebsd guest,
781 * ssed to expose host netmap memory to the guest through a PCI BAR.
785 * ptnetmap memdev private data structure
787 struct ptnetmap_memdev {
789 struct resource *pci_io;
790 struct resource *pci_mem;
791 struct netmap_mem_d *nm_mem;
794 static int ptn_memdev_probe(device_t);
795 static int ptn_memdev_attach(device_t);
796 static int ptn_memdev_detach(device_t);
797 static int ptn_memdev_shutdown(device_t);
799 static device_method_t ptn_memdev_methods[] = {
800 DEVMETHOD(device_probe, ptn_memdev_probe),
801 DEVMETHOD(device_attach, ptn_memdev_attach),
802 DEVMETHOD(device_detach, ptn_memdev_detach),
803 DEVMETHOD(device_shutdown, ptn_memdev_shutdown),
807 static driver_t ptn_memdev_driver = {
808 PTNETMAP_MEMDEV_NAME,
810 sizeof(struct ptnetmap_memdev),
813 /* We use (SI_ORDER_MIDDLE+1) here, see DEV_MODULE_ORDERED() invocation
815 static devclass_t ptnetmap_devclass;
816 DRIVER_MODULE_ORDERED(ptn_memdev, pci, ptn_memdev_driver, ptnetmap_devclass,
817 NULL, NULL, SI_ORDER_MIDDLE + 1);
820 * Map host netmap memory through PCI-BAR in the guest OS,
821 * returning physical (nm_paddr) and virtual (nm_addr) addresses
822 * of the netmap memory mapped in the guest.
825 nm_os_pt_memdev_iomap(struct ptnetmap_memdev *ptn_dev, vm_paddr_t *nm_paddr,
826 void **nm_addr, uint64_t *mem_size)
830 nm_prinf("ptn_memdev_driver iomap");
832 rid = PCIR_BAR(PTNETMAP_MEM_PCI_BAR);
833 *mem_size = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMSIZE_HI);
834 *mem_size = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMSIZE_LO) |
837 /* map memory allocator */
838 ptn_dev->pci_mem = bus_alloc_resource(ptn_dev->dev, SYS_RES_MEMORY,
839 &rid, 0, ~0, *mem_size, RF_ACTIVE);
840 if (ptn_dev->pci_mem == NULL) {
846 *nm_paddr = rman_get_start(ptn_dev->pci_mem);
847 *nm_addr = rman_get_virtual(ptn_dev->pci_mem);
849 nm_prinf("=== BAR %d start %lx len %lx mem_size %lx ===",
850 PTNETMAP_MEM_PCI_BAR,
851 (unsigned long)(*nm_paddr),
852 (unsigned long)rman_get_size(ptn_dev->pci_mem),
853 (unsigned long)*mem_size);
858 nm_os_pt_memdev_ioread(struct ptnetmap_memdev *ptn_dev, unsigned int reg)
860 return bus_read_4(ptn_dev->pci_io, reg);
863 /* Unmap host netmap memory. */
865 nm_os_pt_memdev_iounmap(struct ptnetmap_memdev *ptn_dev)
867 nm_prinf("ptn_memdev_driver iounmap");
869 if (ptn_dev->pci_mem) {
870 bus_release_resource(ptn_dev->dev, SYS_RES_MEMORY,
871 PCIR_BAR(PTNETMAP_MEM_PCI_BAR), ptn_dev->pci_mem);
872 ptn_dev->pci_mem = NULL;
876 /* Device identification routine, return BUS_PROBE_DEFAULT on success,
877 * positive on failure */
879 ptn_memdev_probe(device_t dev)
883 if (pci_get_vendor(dev) != PTNETMAP_PCI_VENDOR_ID)
885 if (pci_get_device(dev) != PTNETMAP_PCI_DEVICE_ID)
888 snprintf(desc, sizeof(desc), "%s PCI adapter",
889 PTNETMAP_MEMDEV_NAME);
890 device_set_desc_copy(dev, desc);
892 return (BUS_PROBE_DEFAULT);
895 /* Device initialization routine. */
897 ptn_memdev_attach(device_t dev)
899 struct ptnetmap_memdev *ptn_dev;
903 ptn_dev = device_get_softc(dev);
906 pci_enable_busmaster(dev);
908 rid = PCIR_BAR(PTNETMAP_IO_PCI_BAR);
909 ptn_dev->pci_io = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
911 if (ptn_dev->pci_io == NULL) {
912 device_printf(dev, "cannot map I/O space\n");
916 mem_id = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMID);
918 /* create guest allocator */
919 ptn_dev->nm_mem = netmap_mem_pt_guest_attach(ptn_dev, mem_id);
920 if (ptn_dev->nm_mem == NULL) {
921 ptn_memdev_detach(dev);
924 netmap_mem_get(ptn_dev->nm_mem);
926 nm_prinf("ptnetmap memdev attached, host memid: %u", mem_id);
931 /* Device removal routine. */
933 ptn_memdev_detach(device_t dev)
935 struct ptnetmap_memdev *ptn_dev;
937 ptn_dev = device_get_softc(dev);
939 if (ptn_dev->nm_mem) {
940 nm_prinf("ptnetmap memdev detached, host memid %u",
941 netmap_mem_get_id(ptn_dev->nm_mem));
942 netmap_mem_put(ptn_dev->nm_mem);
943 ptn_dev->nm_mem = NULL;
945 if (ptn_dev->pci_mem) {
946 bus_release_resource(dev, SYS_RES_MEMORY,
947 PCIR_BAR(PTNETMAP_MEM_PCI_BAR), ptn_dev->pci_mem);
948 ptn_dev->pci_mem = NULL;
950 if (ptn_dev->pci_io) {
951 bus_release_resource(dev, SYS_RES_IOPORT,
952 PCIR_BAR(PTNETMAP_IO_PCI_BAR), ptn_dev->pci_io);
953 ptn_dev->pci_io = NULL;
960 ptn_memdev_shutdown(device_t dev)
962 return bus_generic_shutdown(dev);
965 #endif /* WITH_PTNETMAP */
968 * In order to track whether pages are still mapped, we hook into
969 * the standard cdev_pager and intercept the constructor and
973 struct netmap_vm_handle_t {
975 struct netmap_priv_d *priv;
980 netmap_dev_pager_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot,
981 vm_ooffset_t foff, struct ucred *cred, u_short *color)
983 struct netmap_vm_handle_t *vmh = handle;
986 nm_prinf("handle %p size %jd prot %d foff %jd",
987 handle, (intmax_t)size, prot, (intmax_t)foff);
996 netmap_dev_pager_dtor(void *handle)
998 struct netmap_vm_handle_t *vmh = handle;
999 struct cdev *dev = vmh->dev;
1000 struct netmap_priv_d *priv = vmh->priv;
1003 nm_prinf("handle %p", handle);
1005 free(vmh, M_DEVBUF);
1011 netmap_dev_pager_fault(vm_object_t object, vm_ooffset_t offset,
1012 int prot, vm_page_t *mres)
1014 struct netmap_vm_handle_t *vmh = object->handle;
1015 struct netmap_priv_d *priv = vmh->priv;
1016 struct netmap_adapter *na = priv->np_na;
1019 vm_memattr_t memattr;
1022 nm_prdis("object %p offset %jd prot %d mres %p",
1023 object, (intmax_t)offset, prot, mres);
1024 memattr = object->memattr;
1025 pidx = OFF_TO_IDX(offset);
1026 paddr = netmap_mem_ofstophys(na->nm_mem, offset);
1028 return VM_PAGER_FAIL;
1030 if (((*mres)->flags & PG_FICTITIOUS) != 0) {
1032 * If the passed in result page is a fake page, update it with
1033 * the new physical address.
1036 vm_page_updatefake(page, paddr, memattr);
1039 * Replace the passed in reqpage page with our own fake page and
1040 * free up the all of the original pages.
1042 #ifndef VM_OBJECT_WUNLOCK /* FreeBSD < 10.x */
1043 #define VM_OBJECT_WUNLOCK VM_OBJECT_UNLOCK
1044 #define VM_OBJECT_WLOCK VM_OBJECT_LOCK
1045 #endif /* VM_OBJECT_WUNLOCK */
1047 VM_OBJECT_WUNLOCK(object);
1048 page = vm_page_getfake(paddr, memattr);
1049 VM_OBJECT_WLOCK(object);
1050 vm_page_lock(*mres);
1051 vm_page_free(*mres);
1052 vm_page_unlock(*mres);
1054 vm_page_insert(page, object, pidx);
1056 page->valid = VM_PAGE_BITS_ALL;
1057 return (VM_PAGER_OK);
1061 static struct cdev_pager_ops netmap_cdev_pager_ops = {
1062 .cdev_pg_ctor = netmap_dev_pager_ctor,
1063 .cdev_pg_dtor = netmap_dev_pager_dtor,
1064 .cdev_pg_fault = netmap_dev_pager_fault,
1069 netmap_mmap_single(struct cdev *cdev, vm_ooffset_t *foff,
1070 vm_size_t objsize, vm_object_t *objp, int prot)
1073 struct netmap_vm_handle_t *vmh;
1074 struct netmap_priv_d *priv;
1078 nm_prinf("cdev %p foff %jd size %jd objp %p prot %d", cdev,
1079 (intmax_t )*foff, (intmax_t )objsize, objp, prot);
1081 vmh = malloc(sizeof(struct netmap_vm_handle_t), M_DEVBUF,
1088 error = devfs_get_cdevpriv((void**)&priv);
1091 if (priv->np_nifp == NULL) {
1099 obj = cdev_pager_allocate(vmh, OBJT_DEVICE,
1100 &netmap_cdev_pager_ops, objsize, prot,
1103 nm_prerr("cdev_pager_allocate failed");
1117 free(vmh, M_DEVBUF);
1122 * On FreeBSD the close routine is only called on the last close on
1123 * the device (/dev/netmap) so we cannot do anything useful.
1124 * To track close() on individual file descriptors we pass netmap_dtor() to
1125 * devfs_set_cdevpriv() on open(). The FreeBSD kernel will call the destructor
1126 * when the last fd pointing to the device is closed.
1128 * Note that FreeBSD does not even munmap() on close() so we also have
1129 * to track mmap() ourselves, and postpone the call to
1130 * netmap_dtor() is called when the process has no open fds and no active
1131 * memory maps on /dev/netmap, as in linux.
1134 netmap_close(struct cdev *dev, int fflag, int devtype, struct thread *td)
1137 nm_prinf("dev %p fflag 0x%x devtype %d td %p",
1138 dev, fflag, devtype, td);
1144 netmap_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
1146 struct netmap_priv_d *priv;
1155 priv = netmap_priv_new();
1160 error = devfs_set_cdevpriv(priv, netmap_dtor);
1162 netmap_priv_delete(priv);
1169 /******************** kthread wrapper ****************/
1170 #include <sys/sysproto.h>
1174 return mp_maxid + 1;
1177 struct nm_kctx_ctx {
1178 /* Userspace thread (kthread creator). */
1179 struct thread *user_td;
1181 /* worker function and parameter */
1182 nm_kctx_worker_fn_t worker_fn;
1183 void *worker_private;
1185 struct nm_kctx *nmk;
1187 /* integer to manage multiple worker contexts (e.g., RX or TX on ptnetmap) */
1192 struct thread *worker;
1193 struct mtx worker_lock;
1194 struct nm_kctx_ctx worker_ctx;
1195 int run; /* used to stop kthread */
1196 int attach_user; /* kthread attached to user_process */
1201 nm_kctx_worker(void *data)
1203 struct nm_kctx *nmk = data;
1204 struct nm_kctx_ctx *ctx = &nmk->worker_ctx;
1206 if (nmk->affinity >= 0) {
1207 thread_lock(curthread);
1208 sched_bind(curthread, nmk->affinity);
1209 thread_unlock(curthread);
1214 * check if the parent process dies
1215 * (when kthread is attached to user process)
1219 thread_suspend_check(0);
1220 PROC_UNLOCK(curproc);
1222 kthread_suspend_check();
1225 /* Continuously execute worker process. */
1226 ctx->worker_fn(ctx->worker_private); /* worker body */
1233 nm_os_kctx_worker_setaff(struct nm_kctx *nmk, int affinity)
1235 nmk->affinity = affinity;
1239 nm_os_kctx_create(struct nm_kctx_cfg *cfg, void *opaque)
1241 struct nm_kctx *nmk = NULL;
1243 nmk = malloc(sizeof(*nmk), M_DEVBUF, M_NOWAIT | M_ZERO);
1247 mtx_init(&nmk->worker_lock, "nm_kthread lock", NULL, MTX_DEF);
1248 nmk->worker_ctx.worker_fn = cfg->worker_fn;
1249 nmk->worker_ctx.worker_private = cfg->worker_private;
1250 nmk->worker_ctx.type = cfg->type;
1253 /* attach kthread to user process (ptnetmap) */
1254 nmk->attach_user = cfg->attach_user;
1260 nm_os_kctx_worker_start(struct nm_kctx *nmk)
1262 struct proc *p = NULL;
1265 /* Temporarily disable this function as it is currently broken
1266 * and causes kernel crashes. The failure can be triggered by
1267 * the "vale_polling_enable_disable" test in ctrl-api-test.c. */
1273 /* check if we want to attach kthread to user process */
1274 if (nmk->attach_user) {
1275 nmk->worker_ctx.user_td = curthread;
1276 p = curthread->td_proc;
1279 /* enable kthread main loop */
1281 /* create kthread */
1282 if((error = kthread_add(nm_kctx_worker, nmk, p,
1283 &nmk->worker, RFNOWAIT /* to be checked */, 0, "nm-kthread-%ld",
1284 nmk->worker_ctx.type))) {
1288 nm_prinf("nm_kthread started td %p", nmk->worker);
1292 nm_prerr("nm_kthread start failed err %d", error);
1298 nm_os_kctx_worker_stop(struct nm_kctx *nmk)
1303 /* tell to kthread to exit from main loop */
1306 /* wake up kthread if it sleeps */
1307 kthread_resume(nmk->worker);
1313 nm_os_kctx_destroy(struct nm_kctx *nmk)
1319 nm_os_kctx_worker_stop(nmk);
1321 free(nmk, M_DEVBUF);
1324 /******************** kqueue support ****************/
1327 * In addition to calling selwakeuppri(), nm_os_selwakeup() also
1328 * needs to call knote() to wake up kqueue listeners.
1329 * This operation is deferred to a taskqueue in order to avoid possible
1330 * lock order reversals; these may happen because knote() grabs a
1331 * private lock associated to the 'si' (see struct selinfo,
1332 * struct nm_selinfo, and nm_os_selinfo_init), and nm_os_selwakeup()
1333 * can be called while holding the lock associated to a different
1335 * When calling knote() we use a non-zero 'hint' argument to inform
1336 * the netmap_knrw() function that it is being called from
1337 * 'nm_os_selwakeup'; this is necessary because when netmap_knrw() is
1338 * called by the kevent subsystem (i.e. kevent_scan()) we also need to
1339 * call netmap_poll().
1341 * The netmap_kqfilter() function registers one or another f_event
1342 * depending on read or write mode. A pointer to the struct
1343 * 'netmap_priv_d' is stored into kn->kn_hook, so that it can later
1344 * be passed to netmap_poll(). We pass NULL as a third argument to
1345 * netmap_poll(), so that the latter only runs the txsync/rxsync
1346 * (if necessary), and skips the nm_os_selrecord() calls.
1351 nm_os_selwakeup(struct nm_selinfo *si)
1354 nm_prinf("on knote %p", &si->si.si_note);
1355 selwakeuppri(&si->si, PI_NET);
1356 taskqueue_enqueue(si->ntfytq, &si->ntfytask);
1360 nm_os_selrecord(struct thread *td, struct nm_selinfo *si)
1362 selrecord(td, &si->si);
1366 netmap_knrdetach(struct knote *kn)
1368 struct netmap_priv_d *priv = (struct netmap_priv_d *)kn->kn_hook;
1369 struct selinfo *si = &priv->np_si[NR_RX]->si;
1371 nm_prinf("remove selinfo %p", si);
1372 knlist_remove(&si->si_note, kn, /*islocked=*/0);
1376 netmap_knwdetach(struct knote *kn)
1378 struct netmap_priv_d *priv = (struct netmap_priv_d *)kn->kn_hook;
1379 struct selinfo *si = &priv->np_si[NR_TX]->si;
1381 nm_prinf("remove selinfo %p", si);
1382 knlist_remove(&si->si_note, kn, /*islocked=*/0);
1386 * Callback triggered by netmap notifications (see netmap_notify()),
1387 * and by the application calling kevent(). In the former case we
1388 * just return 1 (events ready), since we are not able to do better.
1389 * In the latter case we use netmap_poll() to see which events are
1393 netmap_knrw(struct knote *kn, long hint, int events)
1395 struct netmap_priv_d *priv;
1399 /* Called from netmap_notify(), typically from a
1400 * thread different from the one issuing kevent().
1401 * Assume we are ready. */
1405 /* Called from kevent(). */
1407 revents = netmap_poll(priv, events, /*thread=*/NULL);
1409 return (events & revents) ? 1 : 0;
1413 netmap_knread(struct knote *kn, long hint)
1415 return netmap_knrw(kn, hint, POLLIN);
1419 netmap_knwrite(struct knote *kn, long hint)
1421 return netmap_knrw(kn, hint, POLLOUT);
1424 static struct filterops netmap_rfiltops = {
1426 .f_detach = netmap_knrdetach,
1427 .f_event = netmap_knread,
1430 static struct filterops netmap_wfiltops = {
1432 .f_detach = netmap_knwdetach,
1433 .f_event = netmap_knwrite,
1438 * This is called when a thread invokes kevent() to record
1439 * a change in the configuration of the kqueue().
1440 * The 'priv' is the one associated to the open netmap device.
1443 netmap_kqfilter(struct cdev *dev, struct knote *kn)
1445 struct netmap_priv_d *priv;
1447 struct netmap_adapter *na;
1448 struct nm_selinfo *si;
1449 int ev = kn->kn_filter;
1451 if (ev != EVFILT_READ && ev != EVFILT_WRITE) {
1452 nm_prerr("bad filter request %d", ev);
1455 error = devfs_get_cdevpriv((void**)&priv);
1457 nm_prerr("device not yet setup");
1462 nm_prerr("no netmap adapter for this file descriptor");
1465 /* the si is indicated in the priv */
1466 si = priv->np_si[(ev == EVFILT_WRITE) ? NR_TX : NR_RX];
1467 kn->kn_fop = (ev == EVFILT_WRITE) ?
1468 &netmap_wfiltops : &netmap_rfiltops;
1470 knlist_add(&si->si.si_note, kn, /*islocked=*/0);
1476 freebsd_netmap_poll(struct cdev *cdevi __unused, int events, struct thread *td)
1478 struct netmap_priv_d *priv;
1479 if (devfs_get_cdevpriv((void **)&priv)) {
1482 return netmap_poll(priv, events, td);
1486 freebsd_netmap_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data,
1487 int ffla __unused, struct thread *td)
1490 struct netmap_priv_d *priv;
1492 CURVNET_SET(TD_TO_VNET(td));
1493 error = devfs_get_cdevpriv((void **)&priv);
1495 /* XXX ENOENT should be impossible, since the priv
1496 * is now created in the open */
1497 if (error == ENOENT)
1501 error = netmap_ioctl(priv, cmd, data, td, /*nr_body_is_user=*/1);
1509 nm_os_onattach(struct ifnet *ifp)
1511 ifp->if_capabilities |= IFCAP_NETMAP;
1515 nm_os_onenter(struct ifnet *ifp)
1517 struct netmap_adapter *na = NA(ifp);
1519 na->if_transmit = ifp->if_transmit;
1520 ifp->if_transmit = netmap_transmit;
1521 ifp->if_capenable |= IFCAP_NETMAP;
1525 nm_os_onexit(struct ifnet *ifp)
1527 struct netmap_adapter *na = NA(ifp);
1529 ifp->if_transmit = na->if_transmit;
1530 ifp->if_capenable &= ~IFCAP_NETMAP;
1533 extern struct cdevsw netmap_cdevsw; /* XXX used in netmap.c, should go elsewhere */
1534 struct cdevsw netmap_cdevsw = {
1535 .d_version = D_VERSION,
1537 .d_open = netmap_open,
1538 .d_mmap_single = netmap_mmap_single,
1539 .d_ioctl = freebsd_netmap_ioctl,
1540 .d_poll = freebsd_netmap_poll,
1541 .d_kqfilter = netmap_kqfilter,
1542 .d_close = netmap_close,
1544 /*--- end of kqueue support ----*/
1547 * Kernel entry point.
1549 * Initialize/finalize the module and return.
1551 * Return 0 on success, errno on failure.
1554 netmap_loader(__unused struct module *module, int event, __unused void *arg)
1560 error = netmap_init();
1565 * if some one is still using netmap,
1566 * then the module can not be unloaded.
1568 if (netmap_use_count) {
1569 nm_prerr("netmap module can not be unloaded - netmap_use_count: %d",
1585 #ifdef DEV_MODULE_ORDERED
1587 * The netmap module contains three drivers: (i) the netmap character device
1588 * driver; (ii) the ptnetmap memdev PCI device driver, (iii) the ptnet PCI
1589 * device driver. The attach() routines of both (ii) and (iii) need the
1590 * lock of the global allocator, and such lock is initialized in netmap_init(),
1591 * which is part of (i).
1592 * Therefore, we make sure that (i) is loaded before (ii) and (iii), using
1593 * the 'order' parameter of driver declaration macros. For (i), we specify
1594 * SI_ORDER_MIDDLE, while higher orders are used with the DRIVER_MODULE_ORDERED
1595 * macros for (ii) and (iii).
1597 DEV_MODULE_ORDERED(netmap, netmap_loader, NULL, SI_ORDER_MIDDLE);
1598 #else /* !DEV_MODULE_ORDERED */
1599 DEV_MODULE(netmap, netmap_loader, NULL);
1600 #endif /* DEV_MODULE_ORDERED */
1601 MODULE_DEPEND(netmap, pci, 1, 1, 1);
1602 MODULE_VERSION(netmap, 1);
1603 /* reduce conditional code */
1604 // linux API, use for the knlist in FreeBSD
1605 /* use a private mutex for the knlist */