Hyunsun Moon | 6ff622e | 2020-03-11 17:14:48 -0700 | [diff] [blame] | 1 | # vim: syntax=py |
| 2 | # -*- mode: python -*- |
| 3 | # SPDX-License-Identifier: Apache-2.0 |
Hyunsun Moon | 6ff622e | 2020-03-11 17:14:48 -0700 | [diff] [blame] | 4 | # Copyright(c) 2019 Intel Corporation |
| 5 | |
| 6 | # for errnos |
| 7 | import errno |
| 8 | from conf.utils import * |
| 9 | |
| 10 | |
| 11 | # ==================================================== |
| 12 | # Parameters |
| 13 | # ==================================================== |
| 14 | |
| 15 | |
| 16 | conf_file = get_env('CONF_FILE', 'conf/spgwu.json') |
| 17 | conf = get_json_conf(conf_file, False) |
| 18 | |
| 19 | # Maximum number of flows to manage ip frags for re-assembly |
| 20 | max_ip_defrag_flows = None |
| 21 | try: |
| 22 | max_ip_defrag_flows = int(conf["max_ip_defrag_flows"]) |
| 23 | except ValueError: |
| 24 | print('Invalid value for max_ip_defrag_flows. Not installing IPDefrag module.') |
| 25 | except KeyError: |
| 26 | print('max_ip_defrag_flows value not set. Not installing IPDefrag module.') |
| 27 | |
| 28 | # ==================================================== |
| 29 | # Port Helpers |
| 30 | # ==================================================== |
| 31 | |
| 32 | |
| 33 | MAX_GATES = 8192 |
| 34 | dpdk_ports = {} |
| 35 | |
| 36 | |
| 37 | def scan_dpdk_ports(): |
| 38 | idx = 0 |
| 39 | while True: |
| 40 | try: |
| 41 | intf = PMDPort(name="Port {}".format(idx), port_id=idx) |
| 42 | if intf: |
| 43 | # Need to declare mac so that we don't lose key during destroy_port |
| 44 | mac = intf.mac_addr |
| 45 | dpdk_ports[mac] = idx |
| 46 | bess.destroy_port(intf.name) |
| 47 | except bess.Error as e: |
| 48 | if e.code == errno.ENODEV: |
| 49 | break |
| 50 | else: |
| 51 | raise |
| 52 | idx += 1 |
Hyunsun Moon | 531f42a | 2020-03-25 20:11:02 -0700 | [diff] [blame] | 53 | # RTE_MAX_ETHPORTS is 32 and we need 2 for vdevs |
| 54 | if idx == 30: |
| 55 | break |
Hyunsun Moon | 6ff622e | 2020-03-11 17:14:48 -0700 | [diff] [blame] | 56 | return True if dpdk_ports else False |
| 57 | |
| 58 | |
| 59 | class Port: |
| 60 | def __init__(self, name): |
| 61 | self.name = name |
| 62 | self.wid = None |
| 63 | self.fpi = None |
| 64 | self.fpo = None |
| 65 | self.bpf = None |
| 66 | self.bpfgate = 0 |
| 67 | self.routes_table = None |
| 68 | |
| 69 | def bpf_gate(self): |
| 70 | if self.bpfgate < MAX_GATES - 2: |
| 71 | self.bpfgate += 1 |
| 72 | return self.bpfgate |
| 73 | else: |
| 74 | raise Exception('Port {}: Out of BPF gates to allocate'.format(self.name)) |
| 75 | |
| 76 | def detect_mode(self): |
| 77 | # default case |
| 78 | mode = "unselected" |
| 79 | |
| 80 | try: |
| 81 | peer_by_interface(self.name) |
| 82 | mode = "dpdk" |
| 83 | except: |
| 84 | mode = "linux" |
| 85 | return mode |
| 86 | |
| 87 | def init_fastpath(self, **kwargs): |
| 88 | # Initialize PMDPort and RX/TX modules |
| 89 | name = self.name |
| 90 | fast = PMDPort(name="{}Fast".format(name), **kwargs) |
| 91 | self.fpi = __bess_module__("{}FastPI".format(name), 'PortInc', port=fast.name) |
| 92 | self.fpo = __bess_module__("{}FastPO".format(name), 'PortOut', port=fast.name) |
| 93 | |
| 94 | # Initialize BPF to classify incoming traffic to go to kernel and/or pipeline |
| 95 | self.bpf = __bess_module__("{}FastBPF".format(name), 'BPF') |
| 96 | self.bpf.clear() |
| 97 | |
Hyunsun Moon | 531f42a | 2020-03-25 20:11:02 -0700 | [diff] [blame] | 98 | # Reassemble IP4 fragments (if needed) |
| 99 | defrag = __bess_module__("{}IP4Defrag".format(name), 'IPDefrag', num_flows=max_ip_defrag_flows, numa=0) |
Hyunsun Moon | 6ff622e | 2020-03-11 17:14:48 -0700 | [diff] [blame] | 100 | # Default drop when no matches |
Hyunsun Moon | 531f42a | 2020-03-25 20:11:02 -0700 | [diff] [blame] | 101 | self.fpi -> defrag:1 -> self.bpf:0 -> Sink() |
| 102 | defrag:0 -> Sink() |
Hyunsun Moon | 6ff622e | 2020-03-11 17:14:48 -0700 | [diff] [blame] | 103 | |
| 104 | # Initialize route module |
| 105 | self.rtr = __bess_module__("{}Routes".format(name), 'IPLookup') |
| 106 | |
| 107 | # Default route goes to Sink |
| 108 | self.rtr.add(prefix='0.0.0.0', prefix_len=0, gate=MAX_GATES-1) |
| 109 | self.rtr:(MAX_GATES-1) -> Sink() |
| 110 | |
| 111 | # Attach fastpath to worker's root TC |
| 112 | self.fpi.attach_task(wid=self.wid) |
| 113 | |
| 114 | def setup_port(self, idx, workers): |
| 115 | # Pick the worker handling this port |
| 116 | self.wid = idx % workers |
| 117 | |
| 118 | name = self.name |
| 119 | wid = self.wid |
| 120 | print('Setting up port {} on worker {}'.format(name,wid)) |
| 121 | |
| 122 | # Detect the mode of this interface - DPDK/AF_XDP/AF_PACKET |
| 123 | mode = self.detect_mode() |
| 124 | |
| 125 | if mode == 'linux': |
| 126 | try: |
| 127 | # Initialize kernel fastpath. |
| 128 | # AF_XDP requires that num_rx_qs == num_tx_qs |
| 129 | kwargs = {"vdev" : "net_af_xdp{},iface={},start_queue=0,queue_count={}" |
| 130 | .format(idx, name, workers), "num_out_q": workers, "num_inc_q": workers} |
| 131 | self.init_fastpath(**kwargs) |
| 132 | except: |
| 133 | print('Failed to create AF_XDP socket for {}. Creating AF_PACKET socket instead.'.format(name)) |
| 134 | kwargs = {"vdev" : "net_af_packet{},iface={},qpairs={}".format(idx, name, workers), "num_out_q": workers} |
| 135 | self.init_fastpath(**kwargs) |
| 136 | |
| 137 | elif mode == 'dpdk': |
| 138 | # if port list is empty, scan for dpdk_ports first |
| 139 | if not dpdk_ports and scan_dpdk_ports() == False: |
| 140 | print('Registered dpdk ports do not exist.') |
| 141 | sys.exit() |
| 142 | # Initialize DPDK fastpath |
| 143 | fidx = dpdk_ports.get(mac_by_interface(name)) |
| 144 | if fidx is None: |
| 145 | raise Exception('Registered port for {} not detected!'.format(name)) |
| 146 | kwargs = {"port_id" : fidx, "num_out_q": workers} |
| 147 | self.init_fastpath( **kwargs) |
| 148 | |
| 149 | # Initialize kernel slowpath port and RX/TX modules |
| 150 | try: |
| 151 | peer = peer_by_interface(name) |
| 152 | vdev = "net_af_packet{},iface={}".format(idx, peer) |
| 153 | slow = PMDPort(name="{}Slow".format(name), vdev=vdev) |
| 154 | spi = __bess_module__("{}SlowPI".format(name), 'PortInc', port=slow.name) |
| 155 | spo = __bess_module__("{}SlowPO".format(name), 'PortOut', port=slow.name) |
| 156 | qspo = __bess_module__("{}QSlowPO".format(name), 'Queue') |
| 157 | |
| 158 | # host_ip_filter: tcpdump -i foo 'dst host 198.19.0.1 or 198.18.0.1' -d |
| 159 | # Should always be set to lowest priority |
| 160 | HostGate = MAX_GATES - 1 |
| 161 | ips = ips_by_interface(name) |
| 162 | host_ip_filter = {"priority": -HostGate, "filter": "dst host " |
| 163 | + " or ".join(str(x) for x in ips), "gate": HostGate} |
| 164 | |
| 165 | self.bpf.add(filters=[host_ip_filter]) |
| 166 | |
| 167 | # Direct control traffic from DPDK to kernel |
| 168 | self.bpf:HostGate -> qspo -> spo |
| 169 | |
| 170 | # Direct control traffic from kernel to DPDK |
| 171 | spi -> self.fpo |
| 172 | |
Hyunsun Moon | 531f42a | 2020-03-25 20:11:02 -0700 | [diff] [blame] | 173 | # Direct fast path traffic to Frag module |
| 174 | merge = __bess_module__("{}Merge".format(name), 'Merge') |
| 175 | frag = __bess_module__("{}IP4Frag".format(name), 'IPFrag') |
| 176 | merge -> frag:1 -> self.fpo |
| 177 | frag:0 -> Sink() |
| 178 | |
Hyunsun Moon | 6ff622e | 2020-03-11 17:14:48 -0700 | [diff] [blame] | 179 | tc = 'slow{}'.format(wid) |
| 180 | try: |
| 181 | bess.add_tc(tc, policy='round_robin', wid=wid) |
| 182 | except Exception as e: |
| 183 | if e.errmsg == "Name '{}' already exists".format(tc): |
| 184 | pass |
| 185 | else: |
| 186 | raise e |
| 187 | # Limit scheduling slow path RX/TX to 1000 times/second each |
| 188 | for mod in spi, qspo: |
| 189 | bess.add_tc(mod.name, |
| 190 | parent=tc, |
| 191 | policy='rate_limit', |
| 192 | resource='count', |
| 193 | limit={'count': 1000}) |
| 194 | mod.attach_task(mod.name) |
| 195 | except Exception as e: |
| 196 | print('Mirror veth interface: {} misconfigured: {}'.format(name, e)) |
| 197 | else: |
| 198 | raise Exception('Invalid mode selected.') |
| 199 | |
| 200 | |
| 201 | # ==================================================== |
| 202 | # Validate |
| 203 | # ==================================================== |
| 204 | |
| 205 | |
| 206 | # CIDRs |
| 207 | enb_cidr = conf["enb_cidr"] |
| 208 | ue_cidr = conf["ue_cidr"] |
| 209 | |
| 210 | cidrs = [enb_cidr, ue_cidr] |
| 211 | for cidr in cidrs: |
| 212 | if validate_cidr(cidr) is False: |
| 213 | exit(1, 'Invalid {}'.format(cidr)) |
| 214 | |
| 215 | # ==================================================== |
| 216 | # Core Setup |
| 217 | # ==================================================== |
| 218 | |
| 219 | |
| 220 | # Initialize workers |
| 221 | workers = 1 |
| 222 | try: |
| 223 | workers = int(conf["workers"]) |
| 224 | except ValueError: |
| 225 | print('Invalid workers value! Re-setting # of workers to 1.') |
| 226 | |
| 227 | cores = get_process_affinity() |
| 228 | for wid in xrange(workers): |
| 229 | bess.add_worker(wid=wid, core=int(cores[wid % len(cores)])) |
| 230 | |
| 231 | # ==================================================== |
| 232 | # Port Setup |
| 233 | # ==================================================== |
| 234 | |
| 235 | |
| 236 | interfaces = ["s1u", "sgi"] |
| 237 | ports = {} |
| 238 | for idx, interface in enumerate(interfaces): |
| 239 | port = Port(conf[interface]["ifname"]) |
| 240 | if port.name in ports: |
| 241 | continue |
| 242 | port.setup_port(idx, workers) |
| 243 | ports[port.name] = port |
| 244 | |
| 245 | s1u_ifname = conf["s1u"]["ifname"] |
| 246 | sgi_ifname = conf["sgi"]["ifname"] |
| 247 | |
| 248 | # ==================================================== |
| 249 | # Downlink Pipeline |
| 250 | # ==================================================== |
| 251 | |
| 252 | s1uRoutes = ports[s1u_ifname].rtr |
| 253 | |
| 254 | # Maximum number of sessions to manage |
| 255 | try: |
| 256 | max_sessions = int(conf["max_sessions"]) |
| 257 | except ValueError: |
| 258 | print('Invalid max_sessions value!') |
| 259 | |
| 260 | # Setting filter to detect UE subnet |
| 261 | sgiFastBPF = ports[sgi_ifname].bpf |
| 262 | UEGate = ports[sgi_ifname].bpf_gate() |
| 263 | ue_filter = {"priority": -UEGate, |
| 264 | "filter": "ip dst net {}".format(ue_cidr), "gate": UEGate} |
| 265 | sgiFastBPF.add(filters=[ue_filter]) |
| 266 | |
| 267 | sgiFastBPF:UEGate \ |
| 268 | -> EtherTrim::GenericDecap(bytes=14) \ |
| 269 | -> GTPUEncap::GtpuEncap(s1u_sgw_ip=ip2long(ips_by_interface(s1u_ifname)[0]), num_subscribers=max_sessions):1 \ |
| 270 | -> S1UEtherAdd::GenericEncap(fields=[ |
| 271 | {'size': 6, 'value': {'value_int': 0x0}}, |
| 272 | {'size': 6, 'value': {'value_int': mac2hex(mac_by_interface(s1u_ifname))}}, |
| 273 | {'size': 2, 'value': {'value_int': 0x0800}}]) \ |
| 274 | -> OuterUDPCsum::L4Checksum() \ |
| 275 | -> OuterIPCsum::IPChecksum() \ |
| 276 | -> s1uRoutes |
| 277 | |
| 278 | # Drop unknown packets |
| 279 | GTPUEncap:0 -> Sink() |
| 280 | |
Hyunsun Moon | 6ff622e | 2020-03-11 17:14:48 -0700 | [diff] [blame] | 281 | # ==================================================== |
| 282 | # Uplink Pipeline |
| 283 | # ==================================================== |
| 284 | |
| 285 | |
| 286 | # Setting filter to detect gtpu traffic |
| 287 | # src net 11.1.1.0 mask 255.255.255.0 # check eNB subnet |
| 288 | # and dst host 11.1.1.1 # check S/PGWU IP |
| 289 | # and udp dst port 2152 # check GTPU port |
| 290 | # and (udp[28:4] & 0xffffff00) = 0x10000000 # check UE subnet |
| 291 | s1uFastBPF = ports[s1u_ifname].bpf |
| 292 | check_enb_subnet = "src net {} ".format(enb_cidr) |
| 293 | check_spgwu_ip = " and dst host " + \ |
| 294 | " or ".join(str(x) for x in ips_by_interface(s1u_ifname)) |
| 295 | check_gtpu_port = " and udp dst port 2152" |
| 296 | check_ue_subnet = " and (udp[28:4] & 0x{}) = 0x{}".format( |
| 297 | cidr2mask(ue_cidr), ip2hex(cidr2block(ue_cidr)[0])) |
| 298 | check_gtpu_msg_echo = " and udp[9] = 0x1" |
| 299 | |
| 300 | GTPUEchoGate = ports[s1u_ifname].bpf_gate() |
| 301 | uplink_echo_filter = {"priority": -GTPUEchoGate, "filter": check_enb_subnet + |
| 302 | check_spgwu_ip + check_gtpu_port + |
| 303 | check_gtpu_msg_echo, "gate": GTPUEchoGate} |
| 304 | s1uFastBPF.add(filters=[uplink_echo_filter]) |
| 305 | |
| 306 | GTPUGate = ports[s1u_ifname].bpf_gate() |
| 307 | uplink_filter = {"priority": -GTPUGate, "filter": check_enb_subnet + |
| 308 | check_spgwu_ip + check_gtpu_port, "gate": GTPUGate} |
| 309 | s1uFastBPF.add(filters=[uplink_filter]) |
| 310 | |
| 311 | sgiRoutes = ports[sgi_ifname].rtr |
| 312 | |
Hyunsun Moon | 531f42a | 2020-03-25 20:11:02 -0700 | [diff] [blame] | 313 | s1uFastBPF:GTPUGate \ |
| 314 | -> EtherDecapTrim::GenericDecap(bytes=14) -> GTPUDecap::GtpuDecap(ename="GTPUEncap"):1 \ |
Hyunsun Moon | 6ff622e | 2020-03-11 17:14:48 -0700 | [diff] [blame] | 315 | -> SGIEtherAdd::GenericEncap(fields=[ |
| 316 | {'size': 6, 'value': {'value_int': 0x0}}, |
| 317 | {'size': 6, 'value': {'value_int': mac2hex(mac_by_interface(sgi_ifname))}}, |
| 318 | {'size': 2, 'value': {'value_int': 0x0800}}]) \ |
| 319 | -> sgiRoutes |
| 320 | |
| 321 | s1uFastBPF:GTPUEchoGate \ |
| 322 | -> GTPUEcho::GtpuEcho(s1u_sgw_ip=ip2long(ips_by_interface(s1u_ifname)[0])):1 \ |
| 323 | -> EthSwap::MACSwap() \ |
| 324 | -> 1:OuterUDPCsum |
| 325 | |
| 326 | # Drop unknown packets |
| 327 | GTPUEcho:0 -> Sink() |
| 328 | GTPUDecap:0 -> Sink() |
| 329 | |
Hyunsun Moon | 6ff622e | 2020-03-11 17:14:48 -0700 | [diff] [blame] | 330 | # ==================================================== |
| 331 | # SIM_TEST |
| 332 | # ==================================================== |
| 333 | |
| 334 | import time |
| 335 | |
| 336 | def sim_start_test(): |
| 337 | start_teid = 0xf0000000 |
| 338 | start_ue_ip = 0x10000001 |
| 339 | start_enb_ip = 0x0b010181 |
| 340 | NG4T_MAX_UE_RAN = 500000 |
| 341 | NG4T_MAX_ENB_RAN = 80 |
| 342 | |
| 343 | for i in range(max_sessions): |
| 344 | |
| 345 | # NG4T-based formula to calculate enodeB IP address against a given UE IP address |
| 346 | # il_trafficgen also uses the same scheme |
| 347 | # See SimuCPEnbv4Teid(...) in ngic code for more details |
| 348 | ue_of_ran = i % NG4T_MAX_UE_RAN |
| 349 | ran = i / NG4T_MAX_UE_RAN |
| 350 | enb_of_ran = ue_of_ran % NG4T_MAX_ENB_RAN |
| 351 | enb_idx = ran * NG4T_MAX_ENB_RAN + enb_of_ran |
| 352 | |
| 353 | GTPUEncap.add(teid=start_teid+i, eteid=i+1, ueaddr=start_ue_ip+i, enodeb_ip=start_enb_ip+enb_idx) |
| 354 | |
| 355 | def sim_end_test(): |
| 356 | start_ue_ip = 0x10000001 |
| 357 | |
| 358 | for i in range(max_sessions): |
| 359 | GTPUEncap.remove(ueaddr=start_ue_ip+i) |
| 360 | |
| 361 | GTPUEncap.show_records() |
| 362 | |
| 363 | ### Uncomment the following lines to test with il_trafficgen ### |
| 364 | # Start the test |
| 365 | #sim_start_test() |
| 366 | # Wait for 30 seconds before deleting the session info entries (optional) |
| 367 | #time.sleep(30) |
| 368 | #sim_end_test() |
| 369 | |
| 370 | # Finally send SIGHUP to route_control daemon on reload |
| 371 | # TODO: behavior is unspecified if route_control.py pid is not found |
| 372 | route_control_pid = getpythonpid('route_control.py') |
| 373 | if route_control_pid: |
| 374 | os.kill(route_control_pid, signal.SIGHUP) |