Beispiel #1
0
    def setup_1pf_2vf_1vm_env(self, driver='default'):

        self.used_dut_port = self.dut_ports[0]
        self.dut.generate_sriov_vfs_by_port(self.used_dut_port, 2, driver=driver)
        self.sriov_vfs_port = self.dut.ports_info[self.used_dut_port]['vfs_port']

        try:

            for port in self.sriov_vfs_port:
                port.bind_driver(self.vf_driver)

            time.sleep(1)

            vf0_prop = {'opt_host': self.sriov_vfs_port[0].pci}
            vf1_prop = {'opt_host': self.sriov_vfs_port[1].pci}

            if driver == 'igb_uio':
                # start testpmd without the two VFs on the host
                self.host_testpmd = PmdOutput(self.dut)
                eal_param = '-b %(vf0)s -b %(vf1)s' % {'vf0': self.sriov_vfs_port[0].pci,
                                                       'vf1': self.sriov_vfs_port[1].pci}
                self.host_testpmd.start_testpmd("1S/2C/2T", eal_param=eal_param)

            # set up VM0 ENV
            self.vm0 = QEMUKvm(self.dut, 'vm0', 'vf_port_start_stop')
            self.vm0.set_vm_device(driver=self.vf_assign_method, **vf0_prop)
            self.vm0.set_vm_device(driver=self.vf_assign_method, **vf1_prop)
            self.vm_dut_0 = self.vm0.start()
            if self.vm_dut_0 is None:
                raise Exception("Set up VM0 ENV failed!")

            self.setup_1pf_2vf_1vm_env_flag = 1
        except Exception as e:
            self.destroy_1pf_2vf_1vm_env()
            raise Exception(e)
Beispiel #2
0
    def set_up_all(self):
        """
        Run at the start of each test suite.
        New rx tx offload API Prerequisites
        """
        self.verify(
            self.nic in [
                "fortville_eagle", "fortville_spirit",
                "fortville_spirit_single", "niantic"
            ], "NIC Unsupported: " + str(self.nic))
        # Based on h/w type, choose how many ports to use
        self.dut_ports = self.dut.get_ports(self.nic)
        # Verify that enough ports are available
        self.verify(len(self.dut_ports) >= 2, "Insufficient ports")

        localPort0 = self.tester.get_local_port(self.dut_ports[0])
        localPort1 = self.tester.get_local_port(self.dut_ports[1])
        self.tester_itf0 = self.tester.get_interface(localPort0)
        self.tester_itf1 = self.tester.get_interface(localPort1)

        self.tester_mac0 = self.tester.get_mac(localPort0)
        self.pf_interface = self.dut.ports_info[self.dut_ports[0]]['intf']
        self.pf_mac = self.dut.get_mac_address(0)
        self.pf_pci = self.dut.ports_info[self.dut_ports[0]]['pci']
        self.pmdout = PmdOutput(self.dut)
        self.cores = "1S/4C/1T"
        self.jumbo_pkt1 = r'sendp([Ether(dst="%s")/IP(dst="192.168.0.1",src="192.168.0.2", len=8981)/Raw(load="P"*8961)], iface="%s")' % (
            self.pf_mac, self.tester_itf0)
        self.jumbo_pkt2 = r'sendp([Ether(dst="%s")/IP(dst="192.168.0.1",src="192.168.0.3", len=8981)/Raw(load="P"*8961)], iface="%s")' % (
            self.pf_mac, self.tester_itf0)
        self.vlan_pkt1 = r'sendp([Ether(dst="%s")/Dot1Q(vlan=1)/IP(src="192.168.0.1",dst="192.168.0.3")/UDP(sport=33, dport=34)/Raw("x"*20)], iface="%s")' % (
            self.pf_mac, self.tester_itf0)
        self.vlan_pkt2 = r'sendp([Ether(dst="%s")/Dot1Q(vlan=1)/IP(src="192.168.0.2",dst="192.168.0.3")/UDP(sport=33, dport=34)/Raw("x"*20)], iface="%s")' % (
            self.pf_mac, self.tester_itf0)
Beispiel #3
0
 def setup_vm_env(self, driver='igb_uio'):
     """
     Create testing environment with VF generated from 1PF
     """
     if self.env_done is False:
         self.bind_nic_driver(self.dut_ports[:1], driver="igb_uio")
         self.used_dut_port = self.dut_ports[0]
         tester_port = self.tester.get_local_port(self.used_dut_port)
         self.tester_intf = self.tester.get_interface(tester_port)
         self.dut.generate_sriov_vfs_by_port(self.used_dut_port,
                                             1,
                                             driver=driver)
         self.sriov_vfs_port = self.dut.ports_info[
             self.used_dut_port]['vfs_port']
         for port in self.sriov_vfs_port:
             port.bind_driver('pci-stub')
         time.sleep(1)
         self.dut_testpmd = PmdOutput(self.dut)
         time.sleep(1)
         vf0_prop = {'opt_host': self.sriov_vfs_port[0].pci}
         # set up VM0 ENV
         self.vm0 = QEMUKvm(self.dut, 'vm0', 'ddp_gtp')
         self.vm0.set_vm_device(driver='pci-assign', **vf0_prop)
         try:
             self.vm0_dut = self.vm0.start()
             if self.vm0_dut is None:
                 raise Exception("Set up VM0 ENV failed!")
         except Exception as e:
             self.destroy_vm_env()
             raise Exception(e)
         self.vm0_dut_ports = self.vm0_dut.get_ports('any')
         self.vm0_testpmd = PmdOutput(self.vm0_dut)
         self.env_done = True
Beispiel #4
0
    def test_kernel_2pf_2vf_1vm_iplink_macfilter(self):

        self.setup_2pf_2vf_1vm_env(driver='')

        self.vm0_dut_ports = self.vm_dut_0.get_ports('any')
        self.vm0_testpmd = PmdOutput(self.vm_dut_0)
        self.vm0_testpmd.start_testpmd(VM_CORES_MASK)
        # Get VF's MAC
        pmd_vf0_mac = self.vm0_testpmd.get_port_mac(0)
        vf0_wrongmac = "00:11:22:33:48:55"
        self.vm0_testpmd.execute_cmd('set promisc all off')
        self.vm0_testpmd.execute_cmd('set fwd mac')
        self.vm0_testpmd.execute_cmd('start')
              
        time.sleep(2)

        tgen_ports = []
        tx_port = self.tester.get_local_port(self.dut_ports[0])
        rx_port = self.tester.get_local_port(self.dut_ports[1])
        tgen_ports.append((tx_port, rx_port))
        dst_mac = self.pf0_vf0_mac
        src_mac = self.tester.get_mac(tx_port)
        pkt_param=[("ether", {'dst': dst_mac, 'src': src_mac})]
        
        print "\nfirst send packets to the kernel PF set MAC, expected result is RX packets=TX packets\n"
        result1 = self.tester.check_random_pkts(tgen_ports, pktnum=100, allow_miss=False, params=pkt_param)
	print "\nshow port stats in testpmd for double check: \n", self.vm0_testpmd.execute_cmd('show port stats all')   
        self.verify(result1 != False, "VF0 failed to forward packets to VF1")
        
        print "\nSecondly, negative test, send packets to a wrong MAC, expected result is RX packets=0\n"
        dst_mac = vf0_wrongmac
        pkt_param=[("ether", {'dst': dst_mac, 'src': src_mac})]
        result2 = self.tester.check_random_pkts(tgen_ports, pktnum=100, allow_miss=False, params=pkt_param)
        print "\nshow port stats in testpmd for double check: \n", self.vm0_testpmd.execute_cmd('show port stats all')
        self.verify(result2 != True, "VF0 failed to forward packets to VF1")
Beispiel #5
0
    def set_up_all(self):
        """
        Prerequisite steps for each test suit.
        """
        self.dut_ports = self.dut.get_ports()
        self.verify(len(self.dut_ports) >= 1, "Insufficient ports")
        self.rx_port = self.dut_ports[0]
        self.tx_port = self.dut_ports[0]

        cores = self.dut.get_core_list("1S/2C/1T")
        self.coremask = utils.create_mask(cores)

        self.port_mask = utils.create_mask([self.rx_port, self.tx_port])

        if self.kdriver == "fm10k":
            netobj = self.dut.ports_info[self.tx_port]['port']
            netobj.enable_jumbo(framesize=ETHER_JUMBO_FRAME_MTU)
            netobj = self.dut.ports_info[self.rx_port]['port']
            netobj.enable_jumbo(framesize=ETHER_JUMBO_FRAME_MTU)

        self.tester.send_expect(
            "ifconfig %s mtu %s" %
            (self.tester.get_interface(self.tester.get_local_port(
                self.rx_port)), ETHER_JUMBO_FRAME_MTU + 200), "# ")
        #        self.tester.send_expect("ifconfig %s mtu %s" % (self.tester.get_interface(self.tester.get_local_port(self.tx_port)), ETHER_JUMBO_FRAME_MTU + 200), "# ")

        self.pmdout = PmdOutput(self.dut)
Beispiel #6
0
    def set_up_all(self):
        """
        Run at the start of each test suite.
        Whitelist Prerequistites:
            Two Ports
            testpmd can normally started
        """

        self.frames_to_send = 1

        # Based on h/w type, choose how many ports to use
        self.dutPorts = self.dut.get_ports()

        # Verify that enough ports are available
        self.verify(len(self.dutPorts) >= 1, "Insufficient ports")

        portMask = dts.create_mask(self.dutPorts[:2])

        self.pmdout = PmdOutput(self.dut)
        self.pmdout.start_testpmd("1S/2C/1T", "--portmask=%s" % portMask)
        self.dut.send_expect("set verbose 1", "testpmd> ")

        # get dest address from self.target port
        out = self.dut.send_expect("show port info %d" % self.dutPorts[0],
                                   "testpmd> ")

        self.dest = self.dut.get_mac_address(self.dutPorts[0])
        mac_scanner = r"MAC address: (([\dA-F]{2}:){5}[\dA-F]{2})"

        ret = dts.regexp(out, mac_scanner)
        self.verify(ret is not None, "MAC address not found")
        self.verify(cmp(ret.lower(), self.dest) == 0, "MAC address wrong")

        self.max_mac_addr = dts.regexp(
            out, "Maximum number of MAC addresses: ([0-9]+)")
Beispiel #7
0
    def set_up_all(self):
        """
        Run at the start of each test suite.

        Vlan Prerequistites
        """
        global dutRxPortId
        global dutTxPortId

        # Based on h/w type, choose how many ports to use
        ports = self.dut.get_ports(self.nic)
        self.verify(len(ports) >= 2, "Insufficient ports")
        self.ports_socket = self.dut.get_numa_id(ports[0])

        cores = self.dut.get_core_list('1S/2C/2T')
        coreMask = utils.create_mask(cores)

        ports = self.dut.get_ports(self.nic)
        valports = [_ for _ in ports if self.tester.get_local_port(_) != -1]

        portMask = utils.create_mask(valports[:2])

        dutRxPortId = valports[0]
        dutTxPortId = valports[1]

        self.pmdout = PmdOutput(self.dut)
        self.pmdout.start_testpmd("Default", "--portmask=%s" % portMask, socket=self.ports_socket)

        if self.nic in ["fortville_eagle", "fortville_spirit", "fortville_spirit_single", "fortville_25g", "fortpark_TLV"]:
            self.dut.send_expect("vlan set filter on all", "testpmd> ")
            self.dut.send_expect("set promisc all off", "testpmd> ")

        out = self.dut.send_expect("set fwd mac", "testpmd> ")
        self.verify('Set mac packet forwarding mode' in out, "set fwd mac error")
        out = self.dut.send_expect("start", "testpmd> ", 120)
Beispiel #8
0
    def set_up_all(self):
        """
        Run at the start of each test suite.
        Scatter Prerequistites
        """
        dutPorts = self.dut.get_ports(self.nic)
        # Verify that enough ports are available
        self.verify(len(dutPorts) >= 1, "Insufficient ports")
        self.port = dutPorts[0]
        tester_port = self.tester.get_local_port(self.port)
        self.intf = self.tester.get_interface(tester_port)

        self.pmdout = PmdOutput(self.dut)
        if self.nic in ["magnolia_park", "niantic", "sageville", "fortpark", "fortville_eagle",
                        "fortville_spirit", "fortville_spirit_single",
                        "redrockcanyou", "atwood", "boulderrapid",
                        "ironpond", "twinpond", "springfountain", "fortpark_TLV"]:
            self.mbsize = 2048
        else:
            self.mbsize = 1024

        if self.kdriver == "fm10k":
            self.dut.ports_info[self.port]['port'].enable_jumbo(framesize=9000)

        self.tester.send_expect("ifconfig %s mtu 9000" % self.intf, "#")
Beispiel #9
0
    def set_up_all(self):
        """
        Run at the start of each test suite.
        Queue region Prerequisites
        """
        self.verify(
            self.nic in [
                "fortville_eagle", "fortville_spirit",
                "fortville_spirit_single", "fortpark_TLV"
            ], "NIC Unsupported: " + str(self.nic))

        # Based on h/w type, choose how many ports to use
        self.dut_ports = self.dut.get_ports(self.nic)
        # Verify that enough ports are available
        self.verify(len(self.dut_ports) >= 1, "Insufficient ports")

        localPort = self.tester.get_local_port(self.dut_ports[0])
        self.tester_intf = self.tester.get_interface(localPort)
        self.tester_mac = self.tester.get_mac(localPort)
        self.pf_interface = self.dut.ports_info[self.dut_ports[0]]['intf']
        self.pf_mac = self.dut.get_mac_address(0)
        self.pf_pci = self.dut.ports_info[self.dut_ports[0]]['pci']
        self.pmdout = PmdOutput(self.dut)
        self.cores = "1S/4C/1T"
        self.pmdout.start_testpmd("%s" % self.cores, "--rxq=16 --txq=16")
        self.dut.send_expect("port config all rss all", "testpmd> ", 120)
        self.dut.send_expect("set fwd rxonly", "testpmd> ", 120)
        self.dut.send_expect("set verbose 1", "testpmd> ", 120)
        self.dut.send_expect("start", "testpmd> ", 120)
        time.sleep(2)
Beispiel #10
0
    def test_pvid_vf_tx(self):
        """
        Add port based vlan on vf device and check vlan tx work
        """
        random_vlan = random.randint(1, MAX_VLAN)

        self.dut.send_expect(
            "ip link set %s vf 0 vlan %d" % (self.host_intf0, random_vlan),
            "# ")
        out = self.dut.send_expect("ip link show %s" % self.host_intf0, "# ")
        self.verify("vlan %d" % random_vlan in out,
                    "Failed to add pvid on VF0")

        self.vm0_dut_ports = self.vm_dut_0.get_ports('any')

        self.vm0_testpmd = PmdOutput(self.vm_dut_0)
        self.vm0_testpmd.start_testpmd(VM_CORES_MASK)
        self.vm0_testpmd.execute_cmd('set fwd mac')
        self.vm0_testpmd.execute_cmd('start')

        pkt = Packet(pkt_type='UDP')
        pkt.config_layer('ether', {'dst': self.vf1_mac})
        inst = self.tester.tcpdump_sniff_packets(self.tester_intf0, timeout=5)
        pkt.send_pkt(tx_port=self.tester_intf1)
        pkts = self.tester.load_tcpdump_sniff_packets(inst)

        self.verify(len(pkts), "Not receive expected packet")
        self.vm0_testpmd.quit()

        # disable pvid
        self.dut.send_expect("ip link set %s vf 0 vlan 0" % (self.host_intf0),
                             "# ")
Beispiel #11
0
    def packet_rx_tx(self, driver='default'):

        if driver == 'igb_uio':
            self.setup_2pf_2vf_1vm_env(driver='igb_uio')
        else:
            self.setup_2pf_2vf_1vm_env(driver='')

        self.vm0_dut_ports = self.vm_dut_0.get_ports('any')
        port_id_0 = 0
        self.vm0_testpmd = PmdOutput(self.vm_dut_0)
        out = self.vm0_testpmd.start_testpmd(VM_CORES_MASK)
        pmd_vf0_mac = self.vm0_testpmd.get_port_mac(port_id_0)
        self.vm0_testpmd.execute_cmd('set fwd mac')
        self.vm0_testpmd.execute_cmd('start')

        time.sleep(2)

        tgen_ports = []
        tx_port = self.tester.get_local_port(self.dut_ports[0])
        rx_port = self.tester.get_local_port(self.dut_ports[1])
        tgen_ports.append((tx_port, rx_port))

        dst_mac = pmd_vf0_mac
        src_mac = self.tester.get_mac(tx_port)

        pkt_param = [("ether", {'dst': dst_mac, 'src': src_mac})]

        result = self.tester.check_random_pkts(tgen_ports,
                                               allow_miss=False,
                                               params=pkt_param)
        print self.vm0_testpmd.execute_cmd('show port stats all')
        self.verify(result != False, "VF0 failed to forward packets to VF1")
Beispiel #12
0
    def test_2vf_d2d_pktgen_stream(self):
        self.vm0_ports = self.vm0_dut.get_ports('any')
        self.vm0_pmd = PmdOutput(self.vm0_dut)
        self.vm0_pmd.start_testpmd('all')
        self.vm0_pmd.execute_cmd('set fwd rxonly')
        self.vm0_pmd.execute_cmd("set promisc all off")
        self.vm0_pmd.execute_cmd('start')

        self.vm1_ports = self.vm1_dut.get_ports('any')
        self.prepare_pktgen(self.vm1_dut)

        dst = {}
        dst['server'] = self.vm0_dut
        dst['ether'] = self.vm0_dut.ports_info[self.vm0_ports[0]]['mac']
        src = {}
        src['server'] = self.vm1_dut
        src['ether'] = self.vm1_dut.ports_info[self.vm1_ports[0]]['mac']
        load = {}
        load['content'] = "'X'*46"
        self.generate_pcap_pkt(dst, src, load)
        self.vm0_pmd.execute_cmd('clear port stats all')
        self.send_stream_pktgen(self.vm1_dut)
        recv_num = self.vm0_pmd.get_pmd_stats(0)['RX-packets']
        time.sleep(1)
        self.stop_stream_pktgen(self.vm1_dut)
        self.vm0_pmd.execute_cmd('stop')
        self.vm0_pmd.execute_cmd('quit', '# ')

        self.verify(recv_num is SEND_PACKET,
                    'Rx port recv error: %d' % recv_num)
Beispiel #13
0
    def test_vf_vlan_tx(self):
        self.verify(self.kdriver not in ["ixgbe"],
                    "NIC Unsupported: " + str(self.nic))
        random_vlan = random.randint(1, MAX_VLAN)
        tx_vlans = [1, random_vlan, MAX_VLAN]
        # start testpmd in VM
        self.vm0_dut_ports = self.vm_dut_0.get_ports('any')

        self.vm0_testpmd = PmdOutput(self.vm_dut_0)
        self.vm0_testpmd.start_testpmd(VM_CORES_MASK)
        self.vm0_testpmd.execute_cmd('set verbose 1')

        for tx_vlan in tx_vlans:
            # for fortville ,
            # if you want insert tx_vlan,
            # please enable rx_vlan at the same time
            if self.kdriver == "i40e":
                self.vm0_testpmd.execute_cmd('rx_vlan add %d 0' % tx_vlan)
            self.vm0_testpmd.execute_cmd('stop')
            self.vm0_testpmd.execute_cmd('port stop all')
            self.vm0_testpmd.execute_cmd('tx_vlan set 0 %d' % tx_vlan)
            self.vm0_testpmd.execute_cmd('port start all')
            self.tx_and_check(tx_vlan=tx_vlan)

        self.vm0_testpmd.quit()
Beispiel #14
0
    def set_up_all(self):
        """
        Run at the start of each test suite.


        IEEE1588 Prerequisites
        """

        dutPorts = self.dut.get_ports()
        self.verify(len(dutPorts) > 0, "No ports found for " + self.nic)

        # Change the config file to support IEEE1588 and recompile the package.
        if "bsdapp" in self.target:
            self.dut.send_expect(
                "sed -i -e 's/IEEE1588=n$/IEEE1588=y/' config/common_bsdapp",
                "# ", 30)
        else:
            self.dut.send_expect(
                "sed -i -e 's/IEEE1588=n$/IEEE1588=y/' config/common_linuxapp",
                "# ", 30)
        self.dut.skip_setup = False
        self.dut.build_install_dpdk(self.target)

        self.pmdout = PmdOutput(self.dut)
        self.pmdout.start_testpmd("all")
Beispiel #15
0
    def test_2vf_k2d_scapy_stream(self):
        self.vm0_ports = self.vm0_dut.get_ports('any')
        self.vm0_pmd = PmdOutput(self.vm0_dut)
        self.vm0_pmd.start_testpmd('all')

        self.vm1_ports = self.vm1_dut.get_ports('any')
        self.vm1_dut.restore_interfaces()
        vf1_intf = self.vm1_dut.ports_info[self.vm1_ports[0]]['intf']

        dst_mac = self.vm0_dut.ports_info[self.vm0_ports[0]]['mac']
        src_mac = self.vm1_dut.ports_info[self.vm1_ports[0]]['mac']
        pkt_content = 'Ether(dst="%s", src="%s")/IP()/Raw(load="X"*46)' % \
                      (dst_mac, src_mac)
        self.vm1_dut.send_expect('scapy', '>>> ', 10)

        self.vm0_pmd.execute_cmd('set promisc all off')
        self.vm0_pmd.execute_cmd('set fwd rxonly')
        self.vm0_pmd.execute_cmd('set verbose 1')
        self.vm0_pmd.execute_cmd('start')

        self.vm1_dut.send_expect('sendp([%s], iface="%s", count=%d)' %
                                 (pkt_content, vf1_intf, SEND_PACKET), '>>> ', 30)

        out = self.vm0_dut.get_session_output(timeout=60)
        rx_packets = re.findall("src=%s - dst=%s" % (src_mac, dst_mac), out)
        recv_num = len(rx_packets)

        self.vm1_dut.send_expect('quit()', '# ', 10)
        self.vm1_dut.bind_interfaces_linux(self.drivername)
        self.vm0_pmd.execute_cmd('stop')
        self.vm0_pmd.execute_cmd('quit', '# ')

        self.verify(recv_num is SEND_PACKET,
                    'Rx port recv error: %d' % recv_num)
Beispiel #16
0
    def test_vf_vlan_strip(self):
        random_vlan = random.randint(1, MAX_VLAN - 1)
        rx_vlans = [1, random_vlan, MAX_VLAN]
        # start testpmd in VM
        self.vm0_dut_ports = self.vm_dut_0.get_ports('any')

        self.vm0_testpmd = PmdOutput(self.vm_dut_0)
        if self.kdriver == "i40e":
            self.vm0_testpmd.start_testpmd(VM_CORES_MASK, '')
        else:
            self.vm0_testpmd.start_testpmd(VM_CORES_MASK)
        self.vm0_testpmd.execute_cmd('set fwd rxonly')
        self.vm0_testpmd.execute_cmd('set verbose 1')
        self.vm0_testpmd.execute_cmd('start')

        for rx_vlan in rx_vlans:
            self.vm0_testpmd.execute_cmd('vlan set strip on 0')
            self.vm0_testpmd.execute_cmd('rx_vlan add %d 0' % rx_vlan)
            time.sleep(1)
            out = self.send_and_getout(vlan=rx_vlan, pkt_type="VLAN_UDP")
            # enable strip, vlan will be in mbuf
            vlan_hex = hex(rx_vlan)
            self.verify("VLAN tci=%s" %
                        vlan_hex in out, "Failed to strip vlan packet!!!")
            self.verify("PKT_RX_VLAN_STRIPPED" in out, "Failed to strip vlan packet!")

            self.vm0_testpmd.execute_cmd('vlan set strip off 0')

            out = self.send_and_getout(vlan=rx_vlan, pkt_type="VLAN_UDP")
            self.verify(
                "received 1 packets" in out, "Not received vlan packet as expected!!!")
            self.verify(
                "PKT_RX_VLAN_STRIPPED" not in out, "Failed to disable strip vlan!!!")

        self.vm0_testpmd.quit()
Beispiel #17
0
    def set_up_all(self):
        """
        Run at the start of each test suite.
        Move RSS to rte_flow Prerequisites
        """
        # Based on h/w type, choose how many ports to use
        self.dut_ports = self.dut.get_ports(self.nic)
        # Verify that enough ports are available
        self.verify(len(self.dut_ports) >= 1, "Insufficient ports")

        localPort = self.tester.get_local_port(self.dut_ports[0])
        self.tester_itf = self.tester.get_interface(localPort)
        self.tester_mac = self.tester.get_mac(localPort)
        self.pf_interface = self.dut.ports_info[self.dut_ports[0]]['intf']
        self.pf_mac = self.dut.get_mac_address(0)
        self.pf_pci = self.dut.ports_info[self.dut_ports[0]]['pci']
        self.pmdout = PmdOutput(self.dut)
        self.cores = "1S/2C/1T"
        self.pkt1 = "Ether(dst='%s')/IP(src='10.0.0.1',dst='192.168.0.2')/SCTP(dport=80, sport=80)/('X'*48)" % self.pf_mac
        self.pkt2 = "Ether(dst='%s')/IP(src='10.0.0.1',dst='192.168.0.2')/UDP(dport=50, sport=50)/('X'*48)" % self.pf_mac
        self.pkt3 = "Ether(dst='%s')/IP(src='10.0.0.1',dst='192.168.0.3')/TCP(dport=50, sport=50)/('X'*48)" % self.pf_mac
        self.pkt4 = "Ether(dst='%s')/IP(src='10.0.0.1',dst='192.168.0.2')/('X'*48)" % self.pf_mac
        self.pkt5 = "Ether(dst='%s')/IPv6(src='2001::1',dst='2001::2',nh=132)/SCTP(dport=80, sport=80)/('X'*48)" % self.pf_mac
        self.pkt6 = "Ether(dst='%s')/IPv6(src='2001::1',dst='2001::2')/UDP(dport=50, sport=50)/('X'*48)" % self.pf_mac
        self.pkt7 = "Ether(dst='%s')/IPv6(src='2001::2',dst='2001::3')/TCP(dport=50, sport=50)/('X'*48)" % self.pf_mac
        self.pkt8 = "Ether(dst='%s')/IPv6(src='2001::2',dst='2001::3')/('X'*48)" % self.pf_mac
        self.prio_pkt1 = "Ether(dst='%s')/Dot1Q(prio=1)/IP(src='10.0.0.1',dst='192.168.0.2')/TCP(dport=80, sport=80)/('X'*48)" % self.pf_mac
        self.prio_pkt2 = "Ether(dst='%s')/Dot1Q(prio=2)/IP(src='10.0.0.1',dst='192.168.0.2')/TCP(dport=80, sport=80)/('X'*48)" % self.pf_mac
        self.prio_pkt3 = "Ether(dst='%s')/Dot1Q(prio=3)/IP(src='10.0.0.1',dst='192.168.0.2')/TCP(dport=80, sport=80)/('X'*48)" % self.pf_mac
Beispiel #18
0
    def set_up_all(self):
        """
        Run at the start of each test suite.


        Vlan Prerequistites
        """

        # Based on h/w type, choose how many ports to use
        ports = self.dut.get_ports()

        # Verify that enough ports are available
        self.verify(len(ports) >= 2, "Insufficient ports")

        global valports
        valports = [_ for _ in ports if self.tester.get_local_port(_) != -1]

        portMask = dts.create_mask(valports[:2])

        self.pmdout = PmdOutput(self.dut)
        self.pmdout.start_testpmd("all", "--portmask=%s" % portMask)

        self.dut.send_expect("set verbose 1", "testpmd> ")
        out = self.dut.send_expect("set fwd mac", "testpmd> ")
        self.dut.send_expect("vlan set strip off %s" % valports[0],
                             "testpmd> ")
        self.verify('Set mac packet forwarding mode' in out,
                    "set fwd rxonly error")
Beispiel #19
0
    def setup_vm_env(self):
        """
        Start One VM with one virtio device
        """
        self.dut_testpmd = PmdOutput(self.dut)
        self.dut_testpmd.start_testpmd(
            "Default", "--rxq=4 --txq=4 --port-topology=chained")
        self.dut_testpmd.execute_cmd("start")

        vf0_prop_1 = {'opt_host': self.sriov_vfs_port_0[0].pci}
        vf0_prop_2 = {'opt_host': self.sriov_vfs_port_1[0].pci}
        self.vm0 = QEMUKvm(self.dut, 'vm0', 'vf_interrupt_pmd')
        self.vm0.set_vm_device(driver='pci-assign', **vf0_prop_1)
        self.vm0.set_vm_device(driver='pci-assign', **vf0_prop_2)
        try:
            self.vm0_dut = self.vm0.start()
            if self.vm0_dut is None:
                raise Exception("Set up VM ENV failed")
            else:
                self.verify(self.vm0_dut.ports_info[0]['intf'] != 'N/A',
                            "Not interface")
        except Exception as e:
            self.destroy_vm_env()
            self.logger.error("Failure for %s" % str(e))

        self.vm0_vf0_mac = self.vm0_dut.get_mac_address(0)
        self.vm0_vf1_mac = self.vm0_dut.get_mac_address(1)
        self.vm0_dut.send_expect("systemctl stop NetworkManager", "# ", 60)
Beispiel #20
0
    def test_2vf_k2d_scapy_stream(self):
        self.vm0_ports = self.vm0_dut.get_ports('any')
        self.vm0_pmd = PmdOutput(self.vm0_dut)
        self.vm0_pmd.start_testpmd('all')
        self.vm0_pmd.execute_cmd('set fwd rxonly')
        self.vm0_pmd.execute_cmd('start')
        # disable promisc to filter misc packets from tester.
        self.vm0_pmd.execute_cmd('set promisc all off')
        self.vm0_pmd.execute_cmd('clear port stats all')

        self.vm1_ports = self.vm1_dut.get_ports('any')
        self.vm1_dut.restore_interfaces()
        vf1_intf = self.vm1_dut.ports_info[self.vm1_ports[0]]['intf']

        dst_mac = self.vm0_dut.ports_info[self.vm0_ports[0]]['mac']
        src_mac = self.vm1_dut.ports_info[self.vm1_ports[0]]['mac']
        pkt_content = 'Ether(dst="%s", src="%s")/IP()/Raw(load="X"*46)' % \
                      (dst_mac, src_mac)
        self.vm1_dut.send_expect('scapy', '>>> ', 10)
        self.vm1_dut.send_expect(
            'sendp([%s], iface="%s", count=%d)' %
            (pkt_content, vf1_intf, SEND_PACKET), '>>> ', 30)
        self.vm1_dut.send_expect('quit()', '# ', 10)
        self.vm1_dut.bind_interfaces_linux(self.drivername)
        recv_num = self.vm0_pmd.get_pmd_stats(0)['RX-packets']
        self.vm0_pmd.execute_cmd('stop')
        self.vm0_pmd.execute_cmd('quit', '# ')

        self.verify(recv_num is SEND_PACKET,
                    'Rx port recv error: %d' % recv_num)
Beispiel #21
0
    def setup_3vf_2vm_env(self, driver='default'):

        self.used_dut_port = self.dut_ports[0]
        self.dut.generate_sriov_vfs_by_port(self.used_dut_port,
                                            3,
                                            driver=driver)
        self.sriov_vfs_port = self.dut.ports_info[
            self.used_dut_port]['vfs_port']

        try:

            for port in self.sriov_vfs_port:
                print port.pci
                port.bind_driver(self.vf_driver)

            time.sleep(1)
            vf0_prop = {'opt_host': self.sriov_vfs_port[0].pci}
            vf1_prop = {'opt_host': self.sriov_vfs_port[1].pci}
            vf2_prop = {'opt_host': self.sriov_vfs_port[2].pci}

            for port_id in self.dut_ports:
                if port_id == self.used_dut_port:
                    continue
                port = self.dut.ports_info[port_id]['port']
                port.bind_driver()

            if driver == 'igb_uio':
                self.host_testpmd = PmdOutput(self.dut)
                eal_param = '-b %(vf0)s -b %(vf1)s -b %(vf2)s' % {
                    'vf0': self.sriov_vfs_port[0].pci,
                    'vf1': self.sriov_vfs_port[1].pci,
                    'vf2': self.sriov_vfs_port[2].pci
                }
                if (self.nic in ["niantic", "sageville", "sagepond"]):
                    self.host_testpmd.start_testpmd("1S/9C/1T",
                                                    "--txq=4 --rxq=4 ",
                                                    eal_param=eal_param)
                else:
                    self.host_testpmd.start_testpmd("1S/2C/2T",
                                                    eal_param=eal_param)

            # set up VM0 ENV
            self.vm0 = VM(self.dut, 'vm0', 'vf_packet_rxtx')
            self.vm0.set_vm_device(driver=self.vf_assign_method, **vf0_prop)
            self.vm0.set_vm_device(driver=self.vf_assign_method, **vf1_prop)
            self.vm_dut_0 = self.vm0.start()
            if self.vm_dut_0 is None:
                raise Exception("Set up VM0 ENV failed!")
            # set up VM1 ENV
            self.vm1 = VM(self.dut, 'vm1', 'vf_packet_rxtx')
            self.vm1.set_vm_device(driver=self.vf_assign_method, **vf2_prop)
            self.vm_dut_1 = self.vm1.start()
            if self.vm_dut_1 is None:
                raise Exception("Set up VM1 ENV failed!")

            self.setup_3vf_2vm_env_flag = 1
        except Exception as e:
            self.destroy_3vf_2vm_env()
            raise Exception(e)
Beispiel #22
0
 def get_stats(self, portid):
     """
     Get packets number from port statistic.
     @param: stop -- stop forward before get stats
     """
     output = PmdOutput(self.dut)
     stats = output.get_pmd_stats(portid)
     return stats
 def set_up(self):
     """
     Run before each test case.
     """
     self.pmdout = PmdOutput(self.dut)
     self.pmdout.start_testpmd("Default", "--portmask=%s" % self.portmask)
     if self.kdriver == "i40e":
         self.dut.send_expect("set promisc all off", "testpmd> ")
Beispiel #24
0
    def set_up_all(self):
        """
        Run at the start of each test suite.
        """
        ports = self.dut.get_ports()
        self.verify(len(ports) >= 2, "Not enough ports available")

        self.pmdout = PmdOutput(self.dut)
Beispiel #25
0
 def set_up(self):
     """
     Run before each test case.
     """
     self.dut_testpmd = PmdOutput(self.dut)
     self.dut_testpmd.start_testpmd(
         "Default", "--port-topology=chained --txq=%s --rxq=%s" %
         (self.PF_QUEUE, self.PF_QUEUE))
     self.load_profile()
Beispiel #26
0
 def set_up_all(self):
     self.dut_ports = self.dut.get_ports(self.nic)
     self.verify(len(self.dut_ports) > 1, "Insufficient ports")
     self.vm0 = None
     self.setup_2pf_2vf_1vm_env_flag = 0
     self.setup_2pf_2vf_1vm_env(driver='')
     self.vm0_dut_ports = self.vm_dut_0.get_ports('any')
     self.portMask = utils.create_mask([self.vm0_dut_ports[0]])
     self.vm0_testpmd = PmdOutput(self.vm_dut_0)
Beispiel #27
0
    def test_vf_reset(self):

        self.setup_3vf_2vm_env(driver='')

        self.vm0_dut_ports = self.vm_dut_0.get_ports('any')
        self.vm1_dut_ports = self.vm_dut_1.get_ports('any')

        port_id_0 = 0
        port_id_1 = 1

        self.vm0_testpmd = PmdOutput(self.vm_dut_0)
        self.vm0_testpmd.start_testpmd(VM_CORES_MASK)
        self.vm0_testpmd.execute_cmd('show port info all')
        pmd0_vf0_mac = self.vm0_testpmd.get_port_mac(port_id_0)
        self.vm0_testpmd.execute_cmd('set fwd mac')
        self.vm0_testpmd.execute_cmd('start')

        time.sleep(2)

        self.vm1_testpmd = PmdOutput(self.vm_dut_1)
        self.vm1_testpmd.start_testpmd(VM_CORES_MASK)
        self.vm1_testpmd.execute_cmd('show port info all')

        tx_port = self.tester.get_local_port(self.dut_ports[0])
        rx_port = tx_port

        dst_mac = pmd0_vf0_mac
        self.tester.sendpkt_bg(tx_port, dst_mac)

        #vf port stop/start can trigger reset action
        for num in range(1000):
            self.vm1_testpmd.execute_cmd('port stop all')
            time.sleep(0.1)
            self.vm1_testpmd.execute_cmd('port start all')
            time.sleep(0.1)

        self.tester.stop_sendpkt_bg()

        pmd0_vf0_stats = self.vm0_testpmd.get_pmd_stats(port_id_0)
        pmd0_vf1_stats = self.vm0_testpmd.get_pmd_stats(port_id_1)

        vf0_rx_cnt = pmd0_vf0_stats['RX-packets']
        self.verify(vf0_rx_cnt != 0, "no packet was received by vm0_VF0")

        vf0_rx_err = pmd0_vf0_stats['RX-errors']
        self.verify(vf0_rx_err == 0, "vm0_VF0 rx-errors")

        vf1_tx_cnt = pmd0_vf1_stats['TX-packets']
        self.verify(vf1_tx_cnt != 0, "no packet was transmitted by vm0_VF1")

        vf1_tx_err = pmd0_vf1_stats['TX-errors']
        self.verify(vf1_tx_err == 0, "vm0_VF0 tx-errors")

        self.verify(
            vf0_rx_cnt == vf1_tx_cnt,
            "vm0_VF0 failed to forward packets to vm0_VF1 when reset vm1_VF0 frequently"
        )
Beispiel #28
0
    def test_add_pvid_vf(self):
        random_vlan = random.randint(1, MAX_VLAN)

        self.dut.send_expect(
            "ip link set %s vf 0 vlan %d" % (self.host_intf0, random_vlan),
            "# ")
        out = self.dut.send_expect("ip link show %s" % self.host_intf0, "# ")
        self.verify("vlan %d" % random_vlan in out,
                    "Failed to add pvid on VF0")

        # start testpmd in VM
        self.vm0_dut_ports = self.vm_dut_0.get_ports('any')

        self.vm0_testpmd = PmdOutput(self.vm_dut_0)
        self.vm0_testpmd.start_testpmd(VM_CORES_MASK)
        self.vm0_testpmd.execute_cmd('set fwd rxonly')
        self.vm0_testpmd.execute_cmd('set verbose 1')
        self.vm0_testpmd.execute_cmd('start')

        out = self.send_and_getout(vlan=random_vlan, pkt_type="VLAN_UDP")
        self.verify("received" in out, "Failed to received vlan packet!!!")

        # send packet without vlan
        out = self.send_and_getout(pkt_type="UDP")
        self.verify("received" not in out, "Received packet without vlan!!!")

        # send packet with vlan not matched
        wrong_vlan = (random_vlan + 1) % 4096
        out = self.send_and_getout(vlan=wrong_vlan, pkt_type="VLAN_UDP")
        self.verify("received" not in out,
                    "Received pacekt with wrong vlan!!!")

        # remove vlan
        self.dut.send_expect("ip link set %s vf 0 vlan 0" % self.host_intf0,
                             "# ")

        # send packet with vlan
        out = self.send_and_getout(vlan=random_vlan, pkt_type="VLAN_UDP")
        if self.kdriver == "i40e":
            self.verify("received" in out, "Failed to received vlan packet!!!")
        else:
            self.verify("received" not in out,
                        "Received vlan packet without pvid!!!")

        # send packet with vlan 0
        out = self.send_and_getout(vlan=0, pkt_type="VLAN_UDP")
        self.verify("received" in out, "Not recevied packet with vlan 0!!!")

        # send packet without vlan
        out = self.send_and_getout(vlan=0, pkt_type="UDP")
        self.verify("received" in out, "Not received packet without vlan!!!")

        self.vm0_testpmd.quit()

        # disable pvid
        self.dut.send_expect("ip link set %s vf 0 vlan 0" % (self.host_intf0),
                             "# ")
Beispiel #29
0
 def set_up(self):
     """
     Run before each test case.
     """
     self.dut_testpmd = PmdOutput(self.dut)
     self.dut_testpmd.start_testpmd("Default", "--port-topology=chained")
     self.dut_testpmd.execute_cmd('set fwd rxonly')
     self.dut_testpmd.execute_cmd('set verbose 1')
     self.dut_testpmd.execute_cmd('start')
Beispiel #30
0
    def send_packet_and_verify(self):
        self.vm0_dut_ports = self.vm_dut_0.get_ports('any')
        self.vm0_testpmd = PmdOutput(self.vm_dut_0)
        self.vm0_testpmd.start_testpmd(VM_CORES_MASK)

        # Get VF0 port MAC address
        pmd_vf0_mac = self.vm0_testpmd.get_port_mac(0)
        self.vm0_testpmd.execute_cmd('set promisc all off')
        ret = self.vm0_testpmd.execute_cmd('mac_addr add 0 %s' %
                                           self.vf0_setmac)
        # check the operation is supported or not.
        print ret

        self.vm0_testpmd.execute_cmd('set fwd mac')
        self.vm0_testpmd.execute_cmd('start')

        time.sleep(2)

        tgen_ports = []
        tx_port = self.tester.get_local_port(self.dut_ports[0])
        rx_port = self.tester.get_local_port(self.dut_ports[1])
        tgen_ports.append((tx_port, rx_port))
        src_mac = self.tester.get_mac(tx_port)
        dst_mac = pmd_vf0_mac
        pkt_param = [("ether", {'dst': dst_mac, 'src': src_mac})]

        print "\nfirst send packets to the random generated VF MAC, expected result is RX packets=TX packets\n"
        result1 = self.tester.check_random_pkts(tgen_ports,
                                                pktnum=100,
                                                allow_miss=False,
                                                params=pkt_param)
        print "\nshow port stats in testpmd for double check: \n", self.vm0_testpmd.execute_cmd(
            'show port stats all')
        self.verify(result1 != False, "VF0 failed to forward packets to VF1")

        print "\nsecondly, send packets to the new added MAC, expected result is RX packets=TX packets\n"
        dst_mac = self.vf0_setmac
        pkt_param = [("ether", {'dst': dst_mac, 'src': src_mac})]
        result2 = self.tester.check_random_pkts(tgen_ports,
                                                pktnum=100,
                                                allow_miss=False,
                                                params=pkt_param)
        print "\nshow port stats in testpmd for double check: \n", self.vm0_testpmd.execute_cmd(
            'show port stats all')
        self.verify(result2 != False, "VF0 failed to forward packets to VF1")

        print "\nThirdly, negative test, send packets to a wrong MAC, expected result is RX packets=0\n"
        dst_mac = self.vf0_wrongmac
        pkt_param = [("ether", {'dst': dst_mac, 'src': src_mac})]
        result3 = self.tester.check_random_pkts(tgen_ports,
                                                pktnum=100,
                                                allow_miss=False,
                                                params=pkt_param)
        print "\nshow port stats in testpmd for double check: \n", self.vm0_testpmd.execute_cmd(
            'show port stats all')
        self.verify(result3 != True, "VF0 failed to forward packets to VF1")
    def set_up_all(self):
        """
        Run at the start of each test suite.


        Vlan Prerequistites
        """

        # Based on h/w type, choose how many ports to use
        ports = self.dut.get_ports()

        # Verify that enough ports are available
        self.verify(len(ports) >= 2, "Insufficient ports")

        global valports
        valports = [_ for _ in ports if self.tester.get_local_port(_) != -1]

        portMask = dts.create_mask(valports[:2])

        self.pmdout = PmdOutput(self.dut)
        self.pmdout.start_testpmd("all", "--portmask=%s" % portMask)

        self.dut.send_expect("set verbose 1", "testpmd> ")
        out = self.dut.send_expect("set fwd mac", "testpmd> ")
        self.dut.send_expect("vlan set strip off %s" % valports[0], "testpmd> ")
        self.verify('Set mac packet forwarding mode' in out, "set fwd rxonly error")
    def set_up_all(self):
        """
        Run at the start of each test suite.
        Whitelist Prerequistites:
            Two Ports
            testpmd can normally started
        """

        self.frames_to_send = 1

        # Based on h/w type, choose how many ports to use
        self.dutPorts = self.dut.get_ports()

        # Verify that enough ports are available
        self.verify(len(self.dutPorts) >= 1, "Insufficient ports")

        portMask = dts.create_mask(self.dutPorts[:2])

        self.pmdout = PmdOutput(self.dut)
        self.pmdout.start_testpmd("1S/2C/1T", "--portmask=%s" % portMask)
        self.dut.send_expect("set verbose 1", "testpmd> ")

        # get dest address from self.target port
        out = self.dut.send_expect("show port info %d" % self.dutPorts[0], "testpmd> ")

        self.dest = self.dut.get_mac_address(self.dutPorts[0])
        mac_scanner = r"MAC address: (([\dA-F]{2}:){5}[\dA-F]{2})"

        ret = dts.regexp(out, mac_scanner)
        self.verify(ret is not None, "MAC address not found")
        self.verify(cmp(ret.lower(), self.dest) == 0, "MAC address wrong")

        self.max_mac_addr = dts.regexp(out, "Maximum number of MAC addresses: ([0-9]+)")
    def set_up_all(self):
        """
        Run at the start of each test suite.

        PMD prerequisites.
        """
        self.frame_sizes = [64, 65, 128, 256, 512, 1024, 1280, 1518]

        self.rxfreet_values = [0, 8, 16, 32, 64, 128]

        self.test_cycles = [{'cores': '1S/1C/1T', 'Mpps': {}, 'pct': {}},
                            {'cores': '1S/1C/2T', 'Mpps': {}, 'pct': {}},
                            {'cores': '1S/2C/1T', 'Mpps': {}, 'pct': {}},
                            {'cores': '1S/2C/2T', 'Mpps': {}, 'pct': {}},
                            {'cores': '1S/4C/2T', 'Mpps': {}, 'pct': {}}
                            ]

        self.table_header = ['Frame Size']
        for test_cycle in self.test_cycles:
            self.table_header.append("%s Mpps" % test_cycle['cores'])
            self.table_header.append("% linerate")

        self.blacklist = ""

        # Based on h/w type, choose how many ports to use
        self.dut_ports = self.dut.get_ports()

        self.headers_size = HEADER_SIZE['eth'] + HEADER_SIZE[
            'ip'] + HEADER_SIZE['udp']

        self.ports_socket = self.dut.get_numa_id(self.dut_ports[0])

        self.plotting = Plotting(self.dut.crb['name'], self.target, self.nic)

        self.pmdout = PmdOutput(self.dut)
    def set_up_all(self):
        """
        Run at the start of each test suite.
        """
        ports = self.dut.get_ports()
        self.verify(len(ports) >= 2, "Not enough ports available")

        self.pmdout = PmdOutput(self.dut)
    def set_up_all(self):
        """
        Run at the start of each test suite.
        Blacklist Prerequisites.
        Requirements:
            Two Ports
        """
        self.ports = self.dut.get_ports()
        self.verify(len(self.ports) >= 2, "Insufficient ports for testing")
        [arch, machine, self.env, toolchain] = self.target.split('-')

        if self.env == 'bsdapp':
            self.regexp_blacklisted_port = "EAL: PCI device 0000:%02x:%s on NUMA socket [-0-9]+[^\n]*\nEAL:   probe driver[^\n]*\nEAL:   Device is blacklisted, not initializing"
        else:
            self.regexp_blacklisted_port = "EAL: PCI device 0000:%s on NUMA socket [-0-9]+[^\n]*\nEAL:   probe driver[^\n]*\nEAL:   Device is blacklisted, not initializing"
        self.pmdout = PmdOutput(self.dut)
    def set_up_all(self):
        """
        Prerequisite steps for each test suit.
        """

        self.dut_ports = self.dut.get_ports()
        self.verify(len(self.dut_ports) >= 2, "Insufficient ports")
        self.rx_port = self.dut_ports[0]
        self.tx_port = self.dut_ports[1]

        cores = self.dut.get_core_list('1S/2C/2T')
        self.coremask = dts.create_mask(cores)

        self.port_mask = dts.create_mask([self.rx_port, self.tx_port])

        self.tester.send_expect("ifconfig %s mtu %s" % (self.tester.get_interface(self.tester.get_local_port(self.rx_port)), ETHER_JUMBO_FRAME_MTU + 200), "# ")
        self.tester.send_expect("ifconfig %s mtu %s" % (self.tester.get_interface(self.tester.get_local_port(self.tx_port)), ETHER_JUMBO_FRAME_MTU + 200), "# ")

        self.pmdout = PmdOutput(self.dut)
    def set_up_all(self):
        """
        Run at the start of each test suite.


        IEEE1588 Prerequisites
        """

        dutPorts = self.dut.get_ports()
        self.verify(len(dutPorts) > 0, "No ports found for " + self.nic)

        # Change the config file to support IEEE1588 and recompile the package.
        if "bsdapp" in self.target:
            self.dut.send_expect("sed -i -e 's/IEEE1588=n$/IEEE1588=y/' config/common_bsdapp", "# ", 30)
        else:
            self.dut.send_expect("sed -i -e 's/IEEE1588=n$/IEEE1588=y/' config/common_linuxapp", "# ", 30)
        self.dut.skip_setup = False
        self.dut.build_install_dpdk(self.target)

        self.pmdout = PmdOutput(self.dut)
        self.pmdout.start_testpmd("all")
class TestIeee1588(TestCase):

    def set_up_all(self):
        """
        Run at the start of each test suite.


        IEEE1588 Prerequisites
        """

        dutPorts = self.dut.get_ports()
        self.verify(len(dutPorts) > 0, "No ports found for " + self.nic)

        # Change the config file to support IEEE1588 and recompile the package.
        if "bsdapp" in self.target:
            self.dut.send_expect("sed -i -e 's/IEEE1588=n$/IEEE1588=y/' config/common_bsdapp", "# ", 30)
        else:
            self.dut.send_expect("sed -i -e 's/IEEE1588=n$/IEEE1588=y/' config/common_linuxapp", "# ", 30)
        self.dut.skip_setup = False
        self.dut.build_install_dpdk(self.target)

        self.pmdout = PmdOutput(self.dut)
        self.pmdout.start_testpmd("all")

    def set_up(self):
        """
        Run before each test case.
        """
        pass

    def test_ieee1588_enable(self):
        """
        IEEE1588 Enable test case.
        """

        self.dut.send_expect("set fwd ieee1588", "testpmd> ")
        self.dut.send_expect("start", ">", 5)  # Waiting for 'testpmd> ' Fails due to log messages, "Received non PTP packet", in the output
        time.sleep(1)  # Allow the output from the "start" command to finish before looking for a regexp in expect

        # use the first port on that self.nic
        dutPorts = self.dut.get_ports()
        port = self.tester.get_local_port(dutPorts[0])
        itf = self.tester.get_interface(port)

        self.tester.scapy_background()
        self.tester.scapy_append('p = sniff(iface="%s", count=2)' % itf)
        self.tester.scapy_append('RESULT = p[1].summary()')

        # this is the output of sniff
        # [<Ether  dst=01:1b:19:00:00:00 src=00:00:00:00:00:00 type=0x88f7 |<Raw  load='\x00\x02' |>>]

        self.tester.scapy_foreground()
        self.tester.scapy_append('nutmac="01:1b:19:00:00:00"')
        self.tester.scapy_append('sendp([Ether(dst=nutmac,type=0x88f7)/"\\x00\\x02"], iface="%s")' % itf)
        self.tester.scapy_append('time.sleep(1)')

        self.tester.scapy_execute()
        out = self.tester.scapy_get_result()
        self.verify("0x88f7" in out, "Ether type is not PTP")
        # self.verify("\\x00\\x02" in out, "Payload wrong in PTP")

        time.sleep(1)
        out = self.dut.send_expect("stop", "testpmd> ")

        text = dts.regexp(out, "(.*) by hardware")
        self.verify("IEEE1588 PTP V2 SYNC" in text, "Not filtered " + text)

        rx_time = dts.regexp(out, "RX timestamp value (0x[0-9a-fA-F]+)")
        tx_time = dts.regexp(out, "TX timestamp value (0x[0-9a-fA-F]+)")

        self.verify(rx_time is not None, "RX timestamp error ")
        self.verify(tx_time is not None, "TX timestamp error ")
        self.verify(int(tx_time, 16) > int(rx_time, 16), "Timestamp mismatch")

    def test_ieee1588_disable(self):
        """
        IEEE1588 Disable test case.
        """

        self.dut.send_expect("stop", "testpmd> ")
        time.sleep(3)

        # use the first port on that self.nic
        dutPorts = self.dut.get_ports()
        port = self.tester.get_local_port(dutPorts[0])
        itf = self.tester.get_interface(port)

        self.tester.scapy_background()
        self.tester.scapy_append('p = sniff(iface="%s", count=2, timeout=1)' % itf)
        self.tester.scapy_append('RESULT = p[1].summary()')

        self.tester.scapy_foreground()
        self.tester.scapy_append('nutmac="01:1b:19:00:00:00"')
        self.tester.scapy_append('sendp([Ether(dst=nutmac,type=0x88f7)/"\\x00\\x02"], iface="%s")' % itf)

        self.tester.scapy_execute()
        time.sleep(2)

        out = self.tester.scapy_get_result()
        self.verify("Ether" not in out, "Ether type is not PTP")

    def tear_down(self):
        """
        Run after each test case.
        """
        pass

    def tear_down_all(self):
        """
        Run after each test suite.
        """
        self.dut.send_expect("quit", "# ", 30)

        # Restore the config file and recompile the package.
        if "bsdapp" in self.target:
            self.dut.send_expect("sed -i -e 's/IEEE1588=y$/IEEE1588=n/' config/common_bsdapp", "# ", 30)
        else:
            self.dut.send_expect("sed -i -e 's/IEEE1588=y$/IEEE1588=n/' config/common_linuxapp", "# ", 30)
        self.dut.build_install_dpdk(self.target)
class TestFdir(TestCase):

    def set_up_all(self):
        """
        Run at the start of each test suite.
        """
        ports = self.dut.get_ports()
        self.verify(len(ports) >= 2, "Not enough ports available")

        self.pmdout = PmdOutput(self.dut)

    def set_up(self):
        """
        Run before each test case.
        """
        pass

    def send_and_verify(self, condition, packet):
        """
        Send packages and verify behavior.
        """
        self.tester.scapy_foreground()
        self.tester.scapy_append('sys.path.append("./")')
        self.tester.scapy_append('from sctp import *')
        self.tester.scapy_append(packet)
        self.dut.send_expect("start", "testpmd>")
        self.tester.scapy_execute()
        time.sleep(.5)
        out = self.dut.send_expect("stop", "testpmd>")
        if condition:
            self.verify("PKT_RX_FDIR" in out, "FDIR hash not displayed when required")
        else:
            self.verify("PKT_RX_FDIR" not in out, "FDIR hash displayed when not required")

    def test_fdir_space(self):
        """
        Setting memory reserved for FDir filters.
        """

        dutPorts = self.dut.get_ports()

        self.pmdout.start_testpmd("all", "--rxq=2 --txq=2 --disable-rss --pkt-filter-mode=perfect --pkt-filter-size=64K")
        out = self.dut.send_expect("show port fdir %s" % dutPorts[0], "testpmd>")
        self.dut.send_expect("quit", "# ", 30)
        self.verify("free:     2048" in out, "Free space doesn't match the expected value")

        self.pmdout.start_testpmd("all", "--rxq=2 --txq=2 --disable-rss --pkt-filter-mode=perfect --pkt-filter-size=128K")
        out = self.dut.send_expect("show port fdir %s" % dutPorts[0], "testpmd>")
        self.dut.send_expect("quit", "# ", 30)
        self.verify("free:     4096" in out, "Free space doesn't match the expected value")

        self.pmdout.start_testpmd("all", "--rxq=2 --txq=2 --disable-rss --pkt-filter-mode=perfect --pkt-filter-size=256K")
        out = self.dut.send_expect("show port fdir %s" % dutPorts[0], "testpmd>")
        self.dut.send_expect("quit", "# ", 30)
        self.verify("free:     8192" in out, "Free space doesn't match the expected value")

    def test_fdir_signatures(self):
        """
        FDir signature matching mode.
        There are three different reporting modes, that can be set in testpmd using the ``--pkt-filter-report-hash`` command line
        argument:
            --pkt-filter-report-hash=none
            --pkt-filter-report-hash=match
            --pkt-filter-report-hash=always
        The test for each mode is following the steps below.
          - Start the ``testpmd`` application by using paramter of each mode.
          - Send the ``p_udp`` packet with Scapy on the traffic generator and check that FDir information is printed
        """

        dutPorts = self.dut.get_ports()
        localPort = self.tester.get_local_port(dutPorts[0])
        itf = self.tester.get_interface(localPort)

        self.dut.kill_all()
        self.pmdout.start_testpmd("all", "--portmask=%s --rxq=2 --txq=2 --disable-rss --pkt-filter-mode=perfect --pkt-filter-report-hash=none" % dts.create_mask([dutPorts[0]]))
        self.dut.send_expect("set verbose 1", "testpmd>")
        self.dut.send_expect("set fwd rxonly", "testpmd>")
        self.dut.send_expect("set nbcore 3", "testpmd>")

        self.send_and_verify(False, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/UDP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.dut.send_expect("add_perfect_filter %s udp src 192.168.0.1 1024 dst 192.168.0.2 1024 flexbytes 0x800 vlan 0 queue 1 soft 0x14" % dutPorts[0], "testpmd>")
        self.send_and_verify(False, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/UDP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.dut.send_expect("quit", "# ", 30)

        self.pmdout.start_testpmd("all", "--portmask=%s --rxq=2 --txq=2 --disable-rss --pkt-filter-mode=perfect --pkt-filter-report-hash=match" % dts.create_mask([dutPorts[0]]))
        self.dut.send_expect("set verbose 1", "testpmd>")
        self.dut.send_expect("set fwd rxonly", "testpmd>")
        self.dut.send_expect("set nbcore 3", "testpmd>")

        self.send_and_verify(False, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/UDP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.dut.send_expect("add_perfect_filter %s udp src 192.168.0.1 1024 dst 192.168.0.2 1024 flexbytes 0x800 vlan 0 queue 1 soft 0x14" % dutPorts[0], "testpmd>")
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/UDP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.dut.send_expect("upd_perfect_filter %s udp src 192.168.1.1 0 dst 192.168.1.2 0 flexbytes 0x800 vlan 0 queue 1 soft 0x14" % dutPorts[0], "testpmd>")

        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/UDP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.1.1", dst="192.168.1.2")/UDP(sport=0,dport=0)], iface="%s")' % (itf, itf))

        self.dut.send_expect("rm_perfect_filter %s udp src 192.168.1.1 0 dst 192.168.1.2 0 flexbytes 0x800 vlan 0 soft 0x14" % dutPorts[0], "testpmd>")

        self.send_and_verify(False, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.1.1", dst="192.168.1.2")/UDP(sport=0,dport=0)], iface="%s")' % (itf, itf))

        self.dut.send_expect("quit", "# ", 30)

        self.pmdout.start_testpmd("all", "--portmask=%s --rxq=2 --txq=2 --disable-rss --pkt-filter-mode=perfect --pkt-filter-report-hash=always" % dts.create_mask([dutPorts[0]]))
        self.dut.send_expect("set verbose 1", "testpmd>")
        self.dut.send_expect("set fwd rxonly", "testpmd>")
        self.dut.send_expect("set nbcore 3", "testpmd>")

        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/UDP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.dut.send_expect("add_perfect_filter %s udp src 192.168.0.1 1024 dst 192.168.0.2 1024 flexbytes 0x800 vlan 0 queue 1 soft 0x14" % dutPorts[0], "testpmd>")
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/UDP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.dut.send_expect("quit", "# ", 30)

    def test_fdir_matching(self):
        """
        FDir matching mode
        This test adds signature filters to the hardware, and then checks
        whether sent packets match those filters.
        The test for each mode is following the steps below.
          - Start the ``testpmd`` application
          - Add filter with upd, tcp sctp, IP4 or IP6
          - Send the packet and validate the filter function.
        """

        dutPorts = self.dut.get_ports()
        localPort = self.tester.get_local_port(dutPorts[0])
        itf = self.tester.get_interface(localPort)

        self.dut.kill_all()
        self.pmdout.start_testpmd("all", "--portmask=%s --rxq=2 --txq=2 --disable-rss --pkt-filter-mode=signature --pkt-filter-report-hash=match" % dts.create_mask([dutPorts[0]]))
        self.dut.send_expect("set verbose 1", "testpmd>")
        self.dut.send_expect("set fwd rxonly", "testpmd>")
        self.dut.send_expect("set nbcore 3", "testpmd>")

        self.send_and_verify(False, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/UDP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.dut.send_expect("add_signature_filter %s udp src 192.168.0.1 1024 dst 192.168.0.2 1024 flexbytes 0x800 vlan 0 queue 1" % dutPorts[0], "testpmd>")
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/UDP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.send_and_verify(False, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/TCP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.dut.send_expect("upd_signature_filter %s udp src 192.168.1.1 0 dst 192.168.1.2 0 flexbytes 0x800 vlan 0 queue 1" % dutPorts[0], "testpmd>")

        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/UDP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.1.1", dst="192.168.1.2")/UDP(sport=0,dport=0)], iface="%s")' % (itf, itf))

        self.dut.send_expect("rm_signature_filter %s udp src 192.168.1.1 0 dst 192.168.1.2 0 flexbytes 0x800 vlan 0" % dutPorts[0], "testpmd>")

        self.send_and_verify(False, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.1.1", dst="192.168.1.2")/UDP(sport=0,dport=0)], iface="%s")' % (itf, itf))

        self.dut.send_expect("add_signature_filter %s tcp src 192.168.0.1 1024 dst 192.168.0.2 1024 flexbytes 0x800 vlan 0 queue 1" % dutPorts[0], "testpmd>")
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/TCP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.send_and_verify(False, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/SCTP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.dut.send_expect("add_signature_filter %s sctp src 192.168.0.1 0 dst 192.168.0.2 0 flexbytes 0x800 vlan 0 queue 1" % dutPorts[0], "testpmd>")
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/SCTP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.send_and_verify(False, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")], iface="%s")' % (itf, itf))

        self.dut.send_expect("add_signature_filter %s ip src 192.168.0.1 0 dst 192.168.0.2 0 flexbytes 0x800 vlan 0 queue 1" % dutPorts[0], "testpmd>")
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")], iface="%s")' % (itf, itf))

        self.send_and_verify(False, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IPv6(src="2001:0db8:85a3:0000:0000:8a2e:0370:7000", dst="2001:0db8:85a3:0000:0000:8a2e:0370:7338")/UDP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.dut.send_expect("add_signature_filter %s udp src 2001:0db8:85a3:0000:0000:8a2e:0370:7000 1024 dst 2001:0db8:85a3:0000:0000:8a2e:0370:7338 1024 flexbytes 0x86dd vlan 0 queue 1" % dutPorts[0], "testpmd>")
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IPv6(src="2001:0db8:85a3:0000:0000:8a2e:0370:7000", dst="2001:0db8:85a3:0000:0000:8a2e:0370:7338")/UDP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.dut.send_expect("quit", "# ", 30)

    def test_fdir_perfect_matching(self):
        """
        FDir perfect matching mode.
        This test adds perfect-match filters to the hardware, and then checks whether sent packets match those filters.
        The test for each mode is following the steps below.
          - Start the ``testpmd`` application with perfect match;
          - Add filter with upd, tcp sctp, IP4;
          - Send the packet and validate the perfect filter function.
        """

        dutPorts = self.dut.get_ports()
        localPort = self.tester.get_local_port(dutPorts[0])
        itf = self.tester.get_interface(localPort)

        self.dut.kill_all()
        self.pmdout.start_testpmd("all", "--portmask=%s --rxq=2 --txq=2 --disable-rss --pkt-filter-mode=perfect --pkt-filter-report-hash=match" % dts.create_mask([dutPorts[0]]))
        self.dut.send_expect("set verbose 1", "testpmd>")
        self.dut.send_expect("set fwd rxonly", "testpmd>")
        self.dut.send_expect("set nbcore 3", "testpmd>")

        self.dut.send_expect("add_perfect_filter %s udp src 192.168.0.1 1024 dst 192.168.0.2 1024 flexbytes 0x800 vlan 0 queue 1 soft 0x14" % dutPorts[0], "testpmd>")
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/UDP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.dut.send_expect("add_perfect_filter %s tcp src 192.168.0.1 1024 dst 192.168.0.2 1024 flexbytes 0x800 vlan 0 queue 1 soft 0x15" % dutPorts[0], "testpmd>")
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/TCP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.dut.send_expect("add_perfect_filter %s sctp src 192.168.0.1 0 dst 192.168.0.2 0 flexbytes 0x800 vlan 0 queue 1 soft 0x16" % dutPorts[0], "testpmd>")
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/SCTP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.dut.send_expect("add_perfect_filter %s ip src 192.168.0.1 0 dst 192.168.0.2 0 flexbytes 0x800 vlan 0 queue 1 soft 0x17" % dutPorts[0], "testpmd>")
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")], iface="%s")' % (itf, itf))

        self.dut.send_expect("quit", "# ", 30)

    def test_fdir_filter_masks(self):
        """
        FDir filter masks.
        This tests the functionality of the setting FDir masks to to affect which
        fields, or parts of fields are used in the matching process.
        """

        dutPorts = self.dut.get_ports()
        localPort = self.tester.get_local_port(dutPorts[0])
        itf = self.tester.get_interface(localPort)

        self.dut.kill_all()
        self.pmdout.start_testpmd("all", "--portmask=%s --rxq=2 --txq=2 --disable-rss --pkt-filter-mode=perfect --pkt-filter-size=64K --pkt-filter-report-hash=match" % dts.create_mask([dutPorts[0]]))
        self.dut.send_expect("set verbose 1", "testpmd>")
        self.dut.send_expect("set fwd rxonly", "testpmd>")
        self.dut.send_expect("set nbcore 3", "testpmd>")

        self.dut.send_expect("set_masks_filter %s only_ip_flow 0 src_mask 0xffffff00 0xffff dst_mask 0xffffff00 0xffff flexbytes 1 vlan_id 1 vlan_prio 1" % dutPorts[0], "testpmd>")
        self.dut.send_expect("add_perfect_filter %s udp src 192.168.0.0 1024 dst 192.168.0.0 1024 flexbytes 0x800 vlan 0 queue 1 soft 0x17" % dutPorts[0], "testpmd>")
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/UDP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.15", dst="192.168.0.15")/UDP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.send_and_verify(False, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.1.1")/UDP(sport=1024,dport=1024)], iface="%s")' % (itf, itf))

        self.dut.send_expect("set_masks_filter %s only_ip_flow 0 src_mask 0xffffffff 0xff00 dst_mask 0xffffffff 0xff00 flexbytes 1 vlan_id 1 vlan_prio 1" % dutPorts[0], "testpmd>")
        self.dut.send_expect("add_perfect_filter %s udp src 10.11.12.1 0x4400 dst 10.11.12.2 0x4500 flexbytes 0x800 vlan 0 queue 1 soft 0x4" % dutPorts[0], "testpmd>")
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="10.11.12.1", dst="10.11.12.2")/UDP(sport=0x4400,dport=0x4500)], iface="%s")' % (itf, itf))

        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="10.11.12.1", dst="10.11.12.2")/UDP(sport=0x4411,dport=0x4517)], iface="%s")' % (itf, itf))

        self.send_and_verify(False, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="10.11.12.1", dst="10.11.12.2")/UDP(sport=0x4500,dport=0x5500)], iface="%s")' % (itf, itf))

        self.dut.send_expect("set_masks_filter %s only_ip_flow 1 src_mask 0xffffffff 0x0 dst_mask 0xffffffff 0x0 flexbytes 1 vlan_id 1 vlan_prio 1" % dutPorts[0], "testpmd>")
        self.dut.send_expect("add_perfect_filter %s ip src 192.168.0.1 0 dst 192.168.0.2 0 flexbytes 0x800 vlan 0 queue 1 soft 0x42" % dutPorts[0], "testpmd>")
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/UDP(sport=1024, dport=1024)], iface="%s")' % (itf, itf))

        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/TCP(sport=1024, dport=1024)], iface="%s")' % (itf, itf))

        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/SCTP(sport=1024, dport=1024)], iface="%s")' % (itf, itf))

        self.dut.send_expect("quit", "# ", 30)

    def test_fdir_flexbytes_filtering(self):
        """
        FDir flexbytes filtering
        The FDir feature supports setting up filters that can match on any two byte field
        within the first 64 bytes of a packet. Which byte offset to use is set by passing
        command line arguments to ``testpmd``. In this test a value of ``18`` corresponds
        to the bytes at offset 36 and 37, as the offset is in 2-byte units
        """

        dutPorts = self.dut.get_ports()
        localPort = self.tester.get_local_port(dutPorts[0])
        itf = self.tester.get_interface(localPort)

        self.dut.kill_all()
        self.pmdout.start_testpmd("all", "--portmask=%s --rxq=2 --txq=2 --disable-rss --pkt-filter-mode=perfect --pkt-filter-size=64K --pkt-filter-report-hash=match --pkt-filter-flexbytes-offset=18" % dts.create_mask([dutPorts[0]]))
        self.dut.send_expect("set verbose 1", "testpmd>")
        self.dut.send_expect("set fwd rxonly", "testpmd>")
        self.dut.send_expect("set nbcore 3", "testpmd>")

        self.dut.send_expect("add_perfect_filter %s ip src 192.168.0.1 0 dst 192.168.0.2 0 flexbytes 0x1 vlan 0 queue 1 soft 0x1" % dutPorts[0], "testpmd>")
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/GRE(proto=0x1)/IP()/UDP()], iface="%s")' % (itf, itf))

        self.dut.send_expect("add_perfect_filter %s ip src 192.168.0.1 0 dst 192.168.0.2 0 flexbytes 0xff vlan 0 queue 1 soft 0xff" % dutPorts[0], "testpmd>")
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/GRE(proto=0xff)/IP()/UDP()], iface="%s")' % (itf, itf))

        self.dut.send_expect("set_masks_filter %s only_ip_flow 0 src_mask 0xffffffff 0xffff dst_mask 0xffffffff 0xffff flexbytes 0 vlan_id 1 vlan_prio 1" % dutPorts[0], "testpmd>")
        self.dut.send_expect("add_perfect_filter %s ip src 192.168.0.1 0 dst 192.168.0.2 0 flexbytes 0x0 vlan 0 queue 1 soft 0x42" % dutPorts[0], "testpmd>")
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/GRE(proto=0x1)/IP()/UDP()], iface="%s")' % (itf, itf))

        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/IP(src="192.168.0.1", dst="192.168.0.2")/GRE(proto=0xFF)/IP()/UDP()], iface="%s")' % (itf, itf))

        self.dut.send_expect("quit", "# ", 30)

    def test_fdir_vlanfiltering(self):
        """
        FDir VLAN field filtering
        """

        dutPorts = self.dut.get_ports()
        localPort = self.tester.get_local_port(dutPorts[0])
        itf = self.tester.get_interface(localPort)

        self.dut.kill_all()
        self.pmdout.start_testpmd("all", "--portmask=%s --nb-cores=2 --rxq=2 --txq=2 --disable-rss --pkt-filter-mode=perfect" % dts.create_mask([dutPorts[0]]))
        self.dut.send_expect("set verbose 1", "testpmd>")
        self.dut.send_expect("set fwd rxonly", "testpmd>")
        # "rx_vlan add all" has been removed from testpmd
        self.dut.send_expect("rx_vlan add 0xFFF %s" % dutPorts[0], "testpmd>")
        self.dut.send_expect("rx_vlan add 0x001 %s" % dutPorts[0], "testpmd>")
        self.dut.send_expect("rx_vlan add 0x017 %s" % dutPorts[0], "testpmd>")

        self.send_and_verify(False, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/Dot1Q(vlan=0x0FFF)/IP(src="192.168.0.1", dst="192.168.0.2")/UDP(sport=1024, dport=1024)], iface="%s")' % (itf, itf))

        self.dut.send_expect("add_perfect_filter %s udp src 192.168.0.1 1024 dst 192.168.0.2 1024 flexbytes 0x8100 vlan 0xfff queue 1 soft 0x47" % dutPorts[0], "testpmd>")
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/Dot1Q(vlan=0x0FFF)/IP(src="192.168.0.1", dst="192.168.0.2")/UDP(sport=1024, dport=1024)], iface="%s")' % (itf, itf))

        self.dut.send_expect("set_masks_filter %s only_ip_flow 0 src_mask 0xffffffff 0xffff  dst_mask 0xffffffff 0xffff flexbytes 1 vlan_id 0 vlan_prio 0" % dutPorts[0], "testpmd>")
        self.dut.send_expect("add_perfect_filter %s udp src 192.168.0.1 1024 dst 192.168.0.2 1024 flexbytes 0x8100 vlan 0 queue 1 soft 0x47" % dutPorts[0], "testpmd>")
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/Dot1Q(vlan=0x001)/IP(src="192.168.0.1", dst="192.168.0.2")/UDP(sport=1024, dport=1024)], iface="%s")' % (itf, itf))
        self.send_and_verify(True, 'sendp([Ether(src=get_if_hwaddr("%s"), dst="00:1B:21:8E:B2:30")/Dot1Q(vlan=0x0017)/IP(src="192.168.0.1", dst="192.168.0.2")/UDP(sport=1024, dport=1024)], iface="%s")' % (itf, itf))

        self.dut.send_expect("quit", "# ", 30)

    def tear_down(self):
        """
        Run after each test case.
        """
        pass

    def tear_down_all(self):
        """
        Run after each test suite.
        """
        pass
class TestWhitelist(TestCase):

    def set_up_all(self):
        """
        Run at the start of each test suite.
        Whitelist Prerequistites:
            Two Ports
            testpmd can normally started
        """

        self.frames_to_send = 1

        # Based on h/w type, choose how many ports to use
        self.dutPorts = self.dut.get_ports()

        # Verify that enough ports are available
        self.verify(len(self.dutPorts) >= 1, "Insufficient ports")

        portMask = dts.create_mask(self.dutPorts[:2])

        self.pmdout = PmdOutput(self.dut)
        self.pmdout.start_testpmd("1S/2C/1T", "--portmask=%s" % portMask)
        self.dut.send_expect("set verbose 1", "testpmd> ")

        # get dest address from self.target port
        out = self.dut.send_expect("show port info %d" % self.dutPorts[0], "testpmd> ")

        self.dest = self.dut.get_mac_address(self.dutPorts[0])
        mac_scanner = r"MAC address: (([\dA-F]{2}:){5}[\dA-F]{2})"

        ret = dts.regexp(out, mac_scanner)
        self.verify(ret is not None, "MAC address not found")
        self.verify(cmp(ret.lower(), self.dest) == 0, "MAC address wrong")

        self.max_mac_addr = dts.regexp(out, "Maximum number of MAC addresses: ([0-9]+)")

    def set_up(self):
        """
        Run before each test case.
        Nothing to do.
        """
        pass

    def whitelist_send_packet(self, portid, destMac="00:11:22:33:44:55"):
        """
        Send 1 packet to portid.
        """

        itf = self.tester.get_interface(self.tester.get_local_port(portid))

        self.tester.scapy_foreground()
        self.tester.scapy_append('sendp([Ether(dst="%s", src="52:00:00:00:00:00")], iface="%s", count=%d)' % (destMac,
                                                                                                              itf,
                                                                                                              self.frames_to_send))
        self.tester.scapy_execute()

        time.sleep(5)

    def test_whitelist_add_remove_mac_address(self):
        """
        Add mac address and check packet can received
        Remove mac address and check packet can't received
        """
        # initialise first port without promiscuous mode
        fake_mac_addr = "01:01:01:00:00:00"
        portid = self.dutPorts[0]
        self.dut.send_expect("set promisc %d off" % portid, "testpmd> ")

        out = self.dut.send_expect("show port stats %d" % portid, "testpmd> ")
        pre_rxpkt = dts.regexp(out, "RX-packets: ([0-9]+)")

        # send one packet with the portid MAC address
        self.whitelist_send_packet(portid, self.dest)
        out = self.dut.send_expect("show port stats %d" % portid, "testpmd> ")
        cur_rxpkt = dts.regexp(out, "RX-packets: ([0-9]+)")
        # check the packet increase
        self.verify(int(cur_rxpkt) == int(pre_rxpkt) + self.frames_to_send,
                    "Packet has not been received on default address")
        # send one packet to a different MAC address
        # new_mac = self.dut.get_mac_address(portid)
        self.whitelist_send_packet(portid, fake_mac_addr)

        pre_rxpkt = cur_rxpkt
        out = self.dut.send_expect("show port stats %d" % portid, "testpmd> ")
        cur_rxpkt = dts.regexp(out, "RX-packets: ([0-9]+)")

        # check the packet DO NOT increase
        self.verify(int(cur_rxpkt) == int(pre_rxpkt),
                    "Packet has been received on a new MAC address that has not been added yet")
        # add the different MAC address
        out = self.dut.send_expect("mac_addr add %d" % portid + " %s" % fake_mac_addr, "testpmd>")

        # send again one packet to a different MAC address
        self.whitelist_send_packet(portid, fake_mac_addr)

        pre_rxpkt = cur_rxpkt
        out = self.dut.send_expect("show port stats %d" % portid, "testpmd> ")
        cur_rxpkt = dts.regexp(out, "RX-packets: ([0-9]+)")

        # check the packet increase
        self.verify(int(cur_rxpkt) == int(pre_rxpkt) + self.frames_to_send,
                    "Packet has not been received on a new MAC address that has been added to the port")

        # remove the fake MAC address
        out = self.dut.send_expect("mac_addr remove %d" % portid + " %s" % fake_mac_addr, "testpmd>")

        # send again one packet to a different MAC address
        self.whitelist_send_packet(portid, fake_mac_addr)

        pre_rxpkt = cur_rxpkt
        out = self.dut.send_expect("show port stats %d" % portid, "testpmd> ")
        cur_rxpkt = dts.regexp(out, "RX-packets: ([0-9]+)")

        # check the packet increase
        self.verify(int(cur_rxpkt) == int(pre_rxpkt),
                    "Packet has been received on a new MAC address that has been removed from the port")
        self.dut.send_expect("stop", "testpmd> ")

    def test_whitelist_invalid_addresses(self):
        """
        Invalid operation:
            Add NULL MAC should not be added
            Remove using MAC will be failed
            Add Same MAC twice will be failed
            Add more than MAX number will be failed
        """

        portid = self.dutPorts[0]
        fake_mac_addr = "00:00:00:00:00:00"

        # add an address with all zeroes to the port (-EINVAL)
        out = self.dut.send_expect("mac_addr add %d" % portid + " %s" % fake_mac_addr, "testpmd>")
        self.verify("Invalid argument" in out, "Added a NULL MAC address")

        # remove the default MAC address (-EADDRINUSE)
        out = self.dut.send_expect("mac_addr remove %d" % portid + " %s" % self.dest, "testpmd>")
        self.verify("Address already in use" in out, "default address removed")

        # add same address 2 times
        fake_mac_addr = "00:00:00:00:00:01"
        out = self.dut.send_expect("mac_addr add %d" % portid + " %s" % fake_mac_addr, "testpmd>")
        out = self.dut.send_expect("mac_addr add %d" % portid + " %s" % fake_mac_addr, "testpmd>")
        self.verify("error" not in out, "added 2 times the same address with an error")

        # add 1 address more that max number
        i = 0
        base_addr = "01:00:00:00:00:"
        while i <= int(self.max_mac_addr):
            new_addr = base_addr + "%0.2X" % i
            out = self.dut.send_expect("mac_addr add %d" % portid + " %s" % new_addr, "testpmd>")
            i = i + 1

        self.verify("No space left on device" in out, "added 1 address more than max MAC addresses")

    def tear_down(self):
        """
        Run after each test case.
        Nothing to do.
        """
        pass

    def tear_down_all(self):
        """
        Run after each test suite.
        """
        self.dut.send_expect("quit", "# ", 10)
class TestPmd(TestCase):

    def plot_results(self, number_ports):

        cores_configs = []
        percent_values = []

        # Append the percentage results for the all the cores configs
        for test_cycle in self.test_cycles:
            cores_configs.append(test_cycle['cores'])
            config_results = []
            for frame_size in self.frame_sizes:
                config_results.append(test_cycle['pct'][frame_size])

            percent_values.append(config_results)

        image_path = self.plotting.create_bars_plot(
            'test_perf_pmd_%sports' % number_ports,
            'PMD, %d ports' % number_ports,
            self.frame_sizes,
            percent_values,
            ylabel='% linerate',
            legend=cores_configs)

        dts.results_plot_print(image_path)

    def set_up_all(self):
        """
        Run at the start of each test suite.

        PMD prerequisites.
        """
        self.frame_sizes = [64, 65, 128, 256, 512, 1024, 1280, 1518]

        self.rxfreet_values = [0, 8, 16, 32, 64, 128]

        self.test_cycles = [{'cores': '1S/1C/1T', 'Mpps': {}, 'pct': {}},
                            {'cores': '1S/1C/2T', 'Mpps': {}, 'pct': {}},
                            {'cores': '1S/2C/1T', 'Mpps': {}, 'pct': {}},
                            {'cores': '1S/2C/2T', 'Mpps': {}, 'pct': {}},
                            {'cores': '1S/4C/2T', 'Mpps': {}, 'pct': {}}
                            ]

        self.table_header = ['Frame Size']
        for test_cycle in self.test_cycles:
            self.table_header.append("%s Mpps" % test_cycle['cores'])
            self.table_header.append("% linerate")

        self.blacklist = ""

        # Based on h/w type, choose how many ports to use
        self.dut_ports = self.dut.get_ports()

        self.headers_size = HEADER_SIZE['eth'] + HEADER_SIZE[
            'ip'] + HEADER_SIZE['udp']

        self.ports_socket = self.dut.get_numa_id(self.dut_ports[0])

        self.plotting = Plotting(self.dut.crb['name'], self.target, self.nic)

        self.pmdout = PmdOutput(self.dut)

    def set_up(self):
        """
        Run before each test case.
        """
        pass

    def test_perf_pmd_performance_4ports(self):
        """
        PMD Performance Benchmarking with 4 ports.
        """
        all_cores_mask = dts.create_mask(self.dut.get_core_list("all"))

        # prepare traffic generator input
        self.verify(len(self.dut_ports) >= 4,
                    "Insufficient ports for 4 ports performance")
        tgen_input = []

        tgen_input.append((self.tester.get_local_port(self.dut_ports[0]),
                           self.tester.get_local_port(self.dut_ports[1]),
                           "test.pcap"))
        tgen_input.append((self.tester.get_local_port(self.dut_ports[2]),
                           self.tester.get_local_port(self.dut_ports[3]),
                           "test.pcap"))
        tgen_input.append((self.tester.get_local_port(self.dut_ports[1]),
                           self.tester.get_local_port(self.dut_ports[0]),
                           "test.pcap"))
        tgen_input.append((self.tester.get_local_port(self.dut_ports[3]),
                           self.tester.get_local_port(self.dut_ports[2]),
                           "test.pcap"))

        # run testpmd for each core config
        for test_cycle in self.test_cycles:
            core_config = test_cycle['cores']

            core_list = self.dut.get_core_list(core_config,
                                               socket=self.ports_socket)

            if len(core_list) > 4:
                queues = len(core_list) / 4
            else:
                queues = 1

            core_mask = dts.create_mask(core_list)
            port_mask = dts.create_mask(self.dut.get_ports())

            self.pmdout.start_testpmd("all", "--coremask=%s --rxq=%d --txq=%d --portmask=%s" % (core_mask, queues, queues, port_mask))

            info = "Executing PMD (mac fwd) using %s\n" % test_cycle['cores']
            dts.report(info, annex=True)
            self.logger.info(info)

            dts.report(commandLine + "\n\n", frame=True, annex=True)

            # self.dut.send_expect("set fwd mac", "testpmd> ", 100)
            self.dut.send_expect("start", "testpmd> ")

            for frame_size in self.frame_sizes:
                wirespeed = self.wirespeed(self.nic, frame_size, 4)

                # create pcap file
                self.logger.info("Running with frame size %d " % frame_size)
                payload_size = frame_size - self.headers_size
                self.tester.scapy_append(
                    'wrpcap("test.pcap", [Ether(src="52:00:00:00:00:00")/IP()/UDP()/("X"*%d)])' % payload_size)
                self.tester.scapy_execute()

                # run traffic generator
                _, pps = self.tester.traffic_generator_throughput(tgen_input)

                pps /= 1000000.0
                test_cycle['Mpps'][frame_size] = pps
                test_cycle['pct'][frame_size] = pps * 100 / wirespeed

            self.dut.send_expect("stop", "testpmd> ")
            self.dut.send_expect("quit", "# ", 30)
            sleep(5)

        for n in range(len(self.test_cycles)):
            for frame_size in self.frame_sizes:
                self.verify(self.test_cycles[n]['Mpps'][
                            frame_size] is not 0, "No traffic detected")

        # Print results
        dts.results_table_add_header(self.table_header)

        for frame_size in self.frame_sizes:
            table_row = [frame_size]

            for test_cycle in self.test_cycles:
                table_row.append(test_cycle['Mpps'][frame_size])
                table_row.append(test_cycle['pct'][frame_size])

            dts.results_table_add_row(table_row)

        self.plot_results(number_ports=4)
        dts.results_table_print()

    def test_perf_pmd_performance_2ports(self):
        """
        PMD Performance Benchmarking with 2 ports.
        """

        all_cores_mask = dts.create_mask(self.dut.get_core_list("all"))

        # prepare traffic generator input
        tgen_input = []
        tgen_input.append((self.tester.get_local_port(self.dut_ports[0]),
                           self.tester.get_local_port(self.dut_ports[1]),
                           "test.pcap"))
        tgen_input.append((self.tester.get_local_port(self.dut_ports[1]),
                           self.tester.get_local_port(self.dut_ports[0]),
                           "test.pcap"))

        # run testpmd for each core config
        for test_cycle in self.test_cycles:
            core_config = test_cycle['cores']

            core_list = self.dut.get_core_list(core_config,
                                               socket=self.ports_socket)

            if len(core_list) > 2:
                queues = len(core_list) / 2
            else:
                queues = 1

            core_mask = dts.create_mask(core_list)
            port_mask = dts.create_mask([self.dut_ports[0], self.dut_ports[1]])

            self.pmdout.start_testpmd("all", "--coremask=%s --rxq=%d --txq=%d --portmask=%s" % (core_mask, queues, queues, port_mask))
            command_line = self.pmdout.get_pmd_cmd()

            info = "Executing PMD using %s\n" % test_cycle['cores']
            self.logger.info(info)
            dts.report(info, annex=True)
            dts.report(command_line + "\n\n", frame=True, annex=True)

            self.dut.send_expect("start", "testpmd> ")
            for frame_size in self.frame_sizes:
                wirespeed = self.wirespeed(self.nic, frame_size, 2)

                # create pcap file
                self.logger.info("Running with frame size %d " % frame_size)
                payload_size = frame_size - self.headers_size
                self.tester.scapy_append(
                    'wrpcap("test.pcap", [Ether(src="52:00:00:00:00:00")/IP()/UDP()/("X"*%d)])' % payload_size)
                self.tester.scapy_execute()

                # run traffic generator
                _, pps = self.tester.traffic_generator_throughput(tgen_input)

                pps /= 1000000.0
                test_cycle['Mpps'][frame_size] = pps
                test_cycle['pct'][frame_size] = pps * 100 / wirespeed

            self.dut.send_expect("stop", "testpmd> ")
            self.dut.send_expect("quit", "# ", 30)
            sleep(5)

        for n in range(len(self.test_cycles)):
            for frame_size in self.frame_sizes:
                self.verify(self.test_cycles[n]['Mpps'][
                            frame_size] > 0, "No traffic detected")

        # Print results
        dts.results_table_add_header(self.table_header)
        for frame_size in self.frame_sizes:
            table_row = [frame_size]
            for test_cycle in self.test_cycles:
                table_row.append(test_cycle['Mpps'][frame_size])
                table_row.append(test_cycle['pct'][frame_size])

            dts.results_table_add_row(table_row)

        self.plot_results(number_ports=2)
        dts.results_table_print()

    def test_checksum_checking(self):
        """
        Packet forwarding checking test
        """

        self.dut.kill_all()

        all_cores_mask = dts.create_mask(self.dut.get_core_list("all"))
        core_mask = dts.create_mask(self.dut.get_core_list('1S/1C/1T',
                                                           socket=self.ports_socket))
        port_mask = dts.create_mask([self.dut_ports[0], self.dut_ports[1]])

        for rxfreet_value in self.rxfreet_values:

            self.pmdout.start_testpmd("all", "--coremask=%s --portmask=%s --nb-cores=2 --enable-rx-cksum --disable-hw-vlan --disable-rss --crc-strip --rxd=1024 --txd=1024 --rxfreet=%d" % (core_mask, port_mask, rxfreet_value))
            self.dut.send_expect("set fwd csum", "testpmd> ")
            self.dut.send_expect("start", "testpmd> ")

            self.send_packet(self.frame_sizes[0], checksum_test=True)

            l4csum_error = self.stop_and_get_l4csum_errors()

            # Check the l4 checksum errors reported for Rx port
            self.verify(1 == int(l4csum_error[1]),
                        "Wrong l4 checksum error count using rxfreet=%d (expected 1, reported %s)" %
                        (rxfreet_value, l4csum_error[1]))

            self.dut.send_expect("quit", "# ", 30)
            sleep(5)

    def test_packet_checking(self):
        """
        Packet forwarding checking test
        """

        self.dut.kill_all()

        all_cores_mask = dts.create_mask(self.dut.get_core_list("all"))
        core_mask = dts.create_mask(self.dut.get_core_list('1S/1C/1T',
                                                           socket=self.ports_socket))
        port_mask = dts.create_mask([self.dut_ports[0], self.dut_ports[1]])

        self.pmdout.start_testpmd("all", "--coremask=%s --portmask=%s" % (core_mask, port_mask))
        self.dut.send_expect("start", "testpmd> ")
        for size in self.frame_sizes:
            self.send_packet(size)

        self.dut.send_expect("stop", "testpmd> ")
        self.dut.send_expect("quit", "# ", 30)
        sleep(5)

    def stop_and_get_l4csum_errors(self):
        """
        Stop forwarding and get Bad-l4csum number from stop statistic
        """

        out = self.dut.send_expect("stop", "testpmd> ")
        result_scanner = r"Bad-l4csum: ([0-9]+) \s*"
        scanner = re.compile(result_scanner, re.DOTALL)
        m = scanner.findall(out)

        return m

    def get_stats(self, portid):
        """
        Get packets number from port statistic
        """

        stats = self.pmdout.get_pmd_stats(portid)
        return stats

    def send_packet(self, frame_size, checksum_test=False):
        """
        Send 1 packet to portid
        """

        port0_stats = self.get_stats(self.dut_ports[0])
        gp0tx_pkts, gp0tx_bytes = [port0_stats['TX-packets'], port0_stats['TX-bytes']]
        port1_stats = self.get_stats(self.dut_ports[1])
        gp1rx_pkts, gp1rx_err, gp1rx_bytes = [port1_stats['RX-packets'], port1_stats['RX-errors'], port1_stats['RX-bytes']]

        interface = self.tester.get_interface(
            self.tester.get_local_port(self.dut_ports[1]))
        mac = self.dut.get_mac_address(self.dut_ports[1])

        load_size = frame_size - HEADER_SIZE['eth']
        padding = frame_size - HEADER_SIZE['eth'] - HEADER_SIZE['ip'] - \
            HEADER_SIZE['udp']

        checksum = ''
        if checksum_test:
            checksum = 'chksum=0x0'

        self.tester.scapy_foreground()
        self.tester.scapy_append('nutmac="%s"' % mac)
        self.tester.scapy_append('sendp([Ether(dst=nutmac, src="52:00:00:00:00:00")/IP(len=%s)/UDP(%s)/Raw(load="\x50"*%s)], iface="%s")' % (
            load_size, checksum, padding, interface))

        out = self.tester.scapy_execute()
        time.sleep(.5)

        port0_stats = self.get_stats(self.dut_ports[0])
        p0tx_pkts, p0tx_bytes = [port0_stats['TX-packets'], port0_stats['TX-bytes']]
        port1_stats = self.get_stats(self.dut_ports[1])
        p1rx_pkts, p1rx_err, p1rx_bytes = [port1_stats['RX-packets'], port1_stats['RX-errors'], port1_stats['RX-bytes']]

        p0tx_pkts -= gp0tx_pkts
        p0tx_bytes -= gp0tx_bytes
        p1rx_pkts -= gp1rx_pkts
        p1rx_bytes -= gp1rx_bytes
        p1rx_err -= gp1rx_err

        time.sleep(5)

        self.verify(p0tx_pkts == p1rx_pkts,
                    "packet pass assert error, %d RX packets, %d TX packets" % (p1rx_pkts, p0tx_pkts))

        if checksum_test:
            self.verify(p1rx_bytes == frame_size - 4,
                        "packet pass assert error, expected %d RX bytes, actual %d" % (frame_size - 4, p1rx_bytes))
        else:
            self.verify(p1rx_bytes == frame_size,
                        "packet pass assert error, expected %d RX bytes, actual %d" % (frame_size, p1rx_bytes))

        self.verify(p0tx_bytes == frame_size,
                    "packet pass assert error, expected %d TX bytes, actual %d" % (frame_size, p0tx_bytes))

        return out

    def tear_down(self):
        """
        Run after each test case.
        """
        pass

    def tear_down_all(self):
        """
        Run after each test suite.
        """
        self.dut.kill_all()
class TestVlan(TestCase):

    def set_up_all(self):
        """
        Run at the start of each test suite.


        Vlan Prerequistites
        """

        # Based on h/w type, choose how many ports to use
        ports = self.dut.get_ports()

        # Verify that enough ports are available
        self.verify(len(ports) >= 2, "Insufficient ports")

        global valports
        valports = [_ for _ in ports if self.tester.get_local_port(_) != -1]

        portMask = dts.create_mask(valports[:2])

        self.pmdout = PmdOutput(self.dut)
        self.pmdout.start_testpmd("all", "--portmask=%s" % portMask)

        self.dut.send_expect("set verbose 1", "testpmd> ")
        out = self.dut.send_expect("set fwd mac", "testpmd> ")
        self.dut.send_expect("vlan set strip off %s" % valports[0], "testpmd> ")
        self.verify('Set mac packet forwarding mode' in out, "set fwd rxonly error")

    def vlan_send_packet(self, vid, num=1):
        """
        Send $num of packet to portid
        """

        port = self.tester.get_local_port(valports[0])
        txItf = self.tester.get_interface(port)

        port = self.tester.get_local_port(valports[1])
        rxItf = self.tester.get_interface(port)

        mac = self.dut.get_mac_address(valports[0])

        # FIXME  send a burst with only num packet
        self.tester.scapy_background()
        self.tester.scapy_append('p=sniff(iface="%s",count=1,timeout=5)' % rxItf)
        self.tester.scapy_append('RESULT=str(p)')

        self.tester.scapy_foreground()
        self.tester.scapy_append('sendp([Ether(dst="%s")/Dot1Q(vlan=%s)/IP(len=46)], iface="%s")' % (mac, vid, txItf))

        self.tester.scapy_execute()

    def set_up(self):
        """
        Run before each test case.
        """
        pass

    def test_vlan_enable_receipt(self):
        """
        Enable receipt of VLAN packets
        """
        self.dut.send_expect("set promisc all off", "testpmd> ")
        self.dut.send_expect("rx_vlan add 1 %s" % valports[0], "testpmd> ")
        self.dut.send_expect("start", "testpmd> ", 120)

        self.vlan_send_packet(1)
        out = self.tester.scapy_get_result()
        self.verify("vlan=1L" in out, "Wrong vlan:" + out)

        self.dut.send_expect("stop", "testpmd> ")

    def test_vlan_disable_receipt(self):
        """
        Disable receipt of VLAN packets
        """

        self.dut.send_expect("rx_vlan rm 1 %s" % valports[0], "testpmd> ")
        self.dut.send_expect("start", "testpmd> ", 120)

        self.vlan_send_packet(1)

        out = self.tester.scapy_get_result()
        self.verify("vlan=1L" not in out, "Wrong vlan:" + out)

        out = self.dut.send_expect("stop", "testpmd> ")

    def test_vlan_strip_config_on(self):
        """
        Set vlan strip on
        """
        self.dut.send_expect("vlan set strip on %s" % valports[0], "testpmd> ", 20)
        self.dut.send_expect("set promisc all off", "testpmd> ", 20)
        out = self.dut.send_expect("vlan set strip on %s" % valports[0], "testpmd> ", 20)
        self.verify("strip on" in out, "Wrong strip:" + out)

        self.dut.send_expect("start", "testpmd> ", 120)
        self.vlan_send_packet(1)
        out = self.tester.scapy_get_result()
        self.verify("vlan=1L" not in out, "Wrong vlan:" + out)
        out = self.dut.send_expect("quit", "#", 120)

    def test_vlan_strip_config_off(self):
        """
        Set vlan strip off
        """

        self.dut.send_expect("vlan set strip off %s" % valports[0], "testpmd> ", 20)
        out = self.dut.send_expect("show port info %s" % valports[0], "testpmd> ", 20)
        self.verify("strip off" in out, "Wrong strip:" + out)
        self.dut.send_expect("set nbport 2", "testpmd> ")
        self.dut.send_expect("start", "testpmd> ", 120)
        self.vlan_send_packet(1)
        out = self.tester.scapy_get_result()
        self.verify("vlan=1L" in out, "Wrong strip vlan:" + out)
        out = self.dut.send_expect("stop", "testpmd> ", 120)

    def FAILING_test_vlan_enable_vlan_insertion(self):
        """
        Enable VLAN header insertion in transmitted packets
        """

        port = self.tester.get_local_port(valports[0])
        intf = self.tester.get_interface(port)

        self.dut.send_expect("set nbport 2", "testpmd> ")
        self.dut.send_expect("tx_vlan set 1 %s" % valports[0], "testpmd> ")

        self.dut.send_expect("set promisc all on", "testpmd> ")
        if self.nic == 'hartwell':
            self.dut.send_expect("vlan set strip on %s" % valports[0], "testpmd> ")

        self.tester.scapy_background()
        self.tester.scapy_append('p = sniff(iface="%s", count=1, timeout=5)' % intf)
        self.tester.scapy_append('RESULT=str(p)')
        self.tester.scapy_foreground()

        self.tester.scapy_execute()
        time.sleep(2)
        self.dut.send_expect("start tx_first", "testpmd> ")
        time.sleep(2)

        out = self.tester.scapy_get_result()
        self.verify("vlan=1L" in out, "Wrong vlan: " + out)
        self.dut.send_expect("quit", "# ", 30)

    def tear_down(self):
        """
        Run after each test case.
        """
        pass

    def tear_down_all(self):
        """
        Run after each test suite.
        """
        pass
class TestJumboframes(TestCase):

    def jumboframes_get_stat(self, portid, rx_tx):
        """
        Get packets number from port statistic
        """
        stats = self.pmdout.get_pmd_stats(portid)
        if rx_tx == "rx":
            return [stats['RX-packets'], stats['RX-errors'], stats['RX-bytes']]
        elif rx_tx == "tx":
            return [stats['TX-packets'], stats['TX-errors'], stats['TX-bytes']]
        else:
            return None

    def jumboframes_send_packet(self, pktsize, received=True):
        """
        Send 1 packet to portid
        """
        gp0tx_pkts, _, gp0tx_bytes = [int(_) for _ in self.jumboframes_get_stat(self.rx_port, "tx")]
        gp1rx_pkts, gp1rx_err, gp1rx_bytes = [int(_) for _ in self.jumboframes_get_stat(self.tx_port, "rx")]

        itf = self.tester.get_interface(self.tester.get_local_port(self.tx_port))
        mac = self.dut.get_mac_address(self.tx_port)

        # The packet total size include ethernet header, ip header, and payload.
        # ethernet header length is 18 bytes, ip standard header length is 20 bytes.
        pktlen = pktsize - ETHER_HEADER_LEN
        padding = pktlen - IP_HEADER_LEN

        self.tester.scapy_foreground()
        self.tester.scapy_append('nutmac="%s"' % mac)
        self.tester.scapy_append('sendp([Ether(dst=nutmac, src="52:00:00:00:00:00")/IP(len=%s)/Raw(load="\x50"*%s)], iface="%s")' % (pktlen, padding, itf))

        out = self.tester.scapy_execute()
        sleep(5)

        p0tx_pkts, _, p0tx_bytes = [int(_) for _ in self.jumboframes_get_stat(self.rx_port, "tx")]
        # p0tx_pkts, p0tx_err, p0tx_bytes
        p1rx_pkts, p1rx_err, p1rx_bytes = [int(_) for _ in self.jumboframes_get_stat(self.tx_port, "rx")]

        p0tx_pkts -= gp0tx_pkts
        p0tx_bytes -= gp0tx_bytes
        p1rx_pkts -= gp1rx_pkts
        p1rx_bytes -= gp1rx_bytes
        p1rx_err -= gp1rx_err

        if received:
            self.verify(p0tx_pkts == p1rx_pkts and p0tx_bytes == pktsize and p1rx_bytes == pktsize,
                        "packet pass assert error")

        else:
            self.verify(p0tx_pkts == p1rx_pkts and (p1rx_err == 1 or p1rx_pkts == 0),
                        "packet drop assert error")

        return out

    #
    #
    #
    # Test cases.
    #
    def set_up_all(self):
        """
        Prerequisite steps for each test suit.
        """

        self.dut_ports = self.dut.get_ports()
        self.verify(len(self.dut_ports) >= 2, "Insufficient ports")
        self.rx_port = self.dut_ports[0]
        self.tx_port = self.dut_ports[1]

        cores = self.dut.get_core_list('1S/2C/2T')
        self.coremask = dts.create_mask(cores)

        self.port_mask = dts.create_mask([self.rx_port, self.tx_port])

        self.tester.send_expect("ifconfig %s mtu %s" % (self.tester.get_interface(self.tester.get_local_port(self.rx_port)), ETHER_JUMBO_FRAME_MTU + 200), "# ")
        self.tester.send_expect("ifconfig %s mtu %s" % (self.tester.get_interface(self.tester.get_local_port(self.tx_port)), ETHER_JUMBO_FRAME_MTU + 200), "# ")

        self.pmdout = PmdOutput(self.dut)

    def set_up(self):
        """
        This is to clear up environment before the case run.
        """
        self.dut.kill_all()

    def test_jumboframes_normal_nojumbo(self):
        """
        This case aims to test transmitting normal size packet without jumbo
        frame on testpmd app.
        """

        self.dut.kill_all()

        self.pmdout.start_testpmd("all", "--max-pkt-len=%d" % (ETHER_STANDARD_MTU))
        self.dut.send_expect("start", "testpmd> ")

        self.jumboframes_send_packet(ETHER_STANDARD_MTU - 1)
        self.jumboframes_send_packet(ETHER_STANDARD_MTU)

        self.dut.send_expect("stop", "testpmd> ")
        self.dut.send_expect("quit", "# ", 30)

    def test_jumboframes_jumbo_nojumbo(self):
        """
        This case aims to test transmitting jumbo frame packet on testpmd without
        jumbo frame support.
        """

        self.dut.kill_all()

        self.pmdout.start_testpmd("all", "--max-pkt-len=%d" % (ETHER_STANDARD_MTU))
        self.dut.send_expect("start", "testpmd> ")

        self.jumboframes_send_packet(ETHER_STANDARD_MTU + 1, False)

        self.dut.send_expect("stop", "testpmd> ")
        self.dut.send_expect("quit", "# ", 30)

    def test_jumboframes_normal_jumbo(self):
        """
        When jumbo frame supported, this case is to verify that the normal size
        packet forwrding should be support correct.
        """

        self.dut.kill_all()

        self.pmdout.start_testpmd("all", "--max-pkt-len=%s" % (ETHER_JUMBO_FRAME_MTU))
        self.dut.send_expect("start", "testpmd> ")

        self.jumboframes_send_packet(1517)
        self.jumboframes_send_packet(1518)

        self.dut.send_expect("stop", "testpmd> ")
        self.dut.send_expect("quit", "# ", 30)

    def test_jumboframes_jumbo_jumbo(self):
        """
        When jumbo frame supported, this case is to verify that jumbo frame
        packet can be forwarded correct.
        """

        self.dut.kill_all()

        self.pmdout.start_testpmd("all", "--max-pkt-len=%s" % (ETHER_JUMBO_FRAME_MTU))
        self.dut.send_expect("start", "testpmd> ")

        self.jumboframes_send_packet(ETHER_STANDARD_MTU + 1)
        self.jumboframes_send_packet(ETHER_JUMBO_FRAME_MTU - 1)
        self.jumboframes_send_packet(ETHER_JUMBO_FRAME_MTU)

        self.dut.send_expect("stop", "testpmd> ")
        self.dut.send_expect("quit", "# ", 30)

    def test_jumboframes_bigger_jumbo(self):
        """
        When the jubmo frame MTU set as 9000, this case is to verify that the
        packet which the length bigger than MTU can not be forwarded.
        """

        self.dut.kill_all()

        self.pmdout.start_testpmd("1S/2C/1T", "--max-pkt-len=%s" % (ETHER_JUMBO_FRAME_MTU))
        self.dut.send_expect("start", "testpmd> ")

        self.jumboframes_send_packet(ETHER_JUMBO_FRAME_MTU + 1, False)

        self.dut.send_expect("quit", "# ", 30)

    def tear_down(self):
        """
        Run after each test case.
        """
        pass

    def tear_down_all(self):
        """
        When the case of this test suite finished, the enviroment should
        clear up.
        """
        self.tester.send_expect("ifconfig %s mtu %s" % (self.tester.get_interface(self.tester.get_local_port(self.rx_port)), ETHER_STANDARD_MTU), "# ")
        self.tester.send_expect("ifconfig %s mtu %s" % (self.tester.get_interface(self.tester.get_local_port(self.tx_port)), ETHER_STANDARD_MTU), "# ")
class TestBlackList(TestCase):
    def set_up_all(self):
        """
        Run at the start of each test suite.
        Blacklist Prerequisites.
        Requirements:
            Two Ports
        """
        self.ports = self.dut.get_ports()
        self.verify(len(self.ports) >= 2, "Insufficient ports for testing")
        [arch, machine, self.env, toolchain] = self.target.split('-')

        if self.env == 'bsdapp':
            self.regexp_blacklisted_port = "EAL: PCI device 0000:%02x:%s on NUMA socket [-0-9]+[^\n]*\nEAL:   probe driver[^\n]*\nEAL:   Device is blacklisted, not initializing"
        else:
            self.regexp_blacklisted_port = "EAL: PCI device 0000:%s on NUMA socket [-0-9]+[^\n]*\nEAL:   probe driver[^\n]*\nEAL:   Device is blacklisted, not initializing"
        self.pmdout = PmdOutput(self.dut)

    def set_up(self):
        """
        Run before each test case.
        Nothing to do.
        """
        pass

    def check_blacklisted_ports(self, output, ports, blacklisted=False):
        """
        Check if any of the ports in `ports` have been blacklisted, if so, raise
        exception.
        If `blacklisted` is True, then raise an exception if any of the ports
        in `ports` have not been blacklisted.
        """
        for port in ports:
            # Look for the PCI ID of each card followed by
            # "Device is blacklisted, not initializing" but avoid to consume more
            # than one device.
            if self.env == 'bsdapp':
                pci = self.dut.ports_info[port]['pci']
                regexp_blacklisted_port = self.regexp_blacklisted_port % (int(pci.split(':')[0], 16), pci.split(':')[1])
            else:
                regexp_blacklisted_port = self.regexp_blacklisted_port % self.dut.ports_info[port]['pci']
            matching_ports = dts.regexp(output, regexp_blacklisted_port, True)
            if blacklisted:
                self.verify(len(matching_ports) == 1,
                            "Blacklisted port is being initialized")
            else:
                self.verify(len(matching_ports) == 0,
                            "Not blacklisted port is being blacklisted")

    def test_bl_noblacklisted(self):
        """
        Run testpmd with no blacklisted device.
        """
        out = self.pmdout.start_testpmd("Default")
        rexp = r"Link"
        match_status = dts.regexp(out, rexp, True)

        self.check_blacklisted_ports(out, self.ports)

    def test_bl_oneportblacklisted(self):
        """
        Run testpmd with one port blacklisted.
        """
        self.dut.kill_all()
        out = self.pmdout.start_testpmd("Default", eal_param="-b 0000:%s -- -i" % self.dut.ports_info[0]['pci'])
        self.check_blacklisted_ports(out, self.ports[1:])

    def test_bl_allbutoneportblacklisted(self):
        """
        Run testpmd with all but one port blacklisted.
        """
        self.dut.kill_all()
        ports_to_blacklist = self.ports[:-1]
        cmdline = ""
        for port in ports_to_blacklist:
            cmdline += " -b 0000:%s" % self.dut.ports_info[port]['pci']
        out = self.pmdout.start_testpmd("Default", eal_param=cmdline)
        blacklisted_ports = self.check_blacklisted_ports(out,
                                              ports_to_blacklist, True)

    def tear_down(self):
        """
        Run after each test case.
        Quit testpmd.
        """
        self.dut.send_expect("quit", "# ", 10)
    def tear_down_all(self):
        """
        Run after each test suite.
        Nothing to do.
        """
        pass