blob: 76e546da77d15dc32622cddb13c288436fe280a1 [file] [log] [blame]
Hyunsun Moon6ff622e2020-03-11 17:14:48 -07001# vim: syntax=py
2# -*- mode: python -*-
3# SPDX-License-Identifier: Apache-2.0
Hyunsun Moon6ff622e2020-03-11 17:14:48 -07004# Copyright(c) 2019 Intel Corporation
5
6# for errnos
7import errno
8from conf.utils import *
9
10
11# ====================================================
12# Parameters
13# ====================================================
14
15
16conf_file = get_env('CONF_FILE', 'conf/spgwu.json')
17conf = get_json_conf(conf_file, False)
18
19# Maximum number of flows to manage ip frags for re-assembly
20max_ip_defrag_flows = None
21try:
22 max_ip_defrag_flows = int(conf["max_ip_defrag_flows"])
23except ValueError:
24 print('Invalid value for max_ip_defrag_flows. Not installing IPDefrag module.')
25except KeyError:
26 print('max_ip_defrag_flows value not set. Not installing IPDefrag module.')
27
28# ====================================================
29# Port Helpers
30# ====================================================
31
32
33MAX_GATES = 8192
34dpdk_ports = {}
35
36
37def 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 Moon531f42a2020-03-25 20:11:02 -070053 # RTE_MAX_ETHPORTS is 32 and we need 2 for vdevs
54 if idx == 30:
55 break
Hyunsun Moon6ff622e2020-03-11 17:14:48 -070056 return True if dpdk_ports else False
57
58
59class 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 Moon531f42a2020-03-25 20:11:02 -070098 # Reassemble IP4 fragments (if needed)
99 defrag = __bess_module__("{}IP4Defrag".format(name), 'IPDefrag', num_flows=max_ip_defrag_flows, numa=0)
Hyunsun Moon6ff622e2020-03-11 17:14:48 -0700100 # Default drop when no matches
Hyunsun Moon531f42a2020-03-25 20:11:02 -0700101 self.fpi -> defrag:1 -> self.bpf:0 -> Sink()
102 defrag:0 -> Sink()
Hyunsun Moon6ff622e2020-03-11 17:14:48 -0700103
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 Moon531f42a2020-03-25 20:11:02 -0700173 # 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 Moon6ff622e2020-03-11 17:14:48 -0700179 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
207enb_cidr = conf["enb_cidr"]
208ue_cidr = conf["ue_cidr"]
209
210cidrs = [enb_cidr, ue_cidr]
211for 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
221workers = 1
222try:
223 workers = int(conf["workers"])
224except ValueError:
225 print('Invalid workers value! Re-setting # of workers to 1.')
226
227cores = get_process_affinity()
228for wid in xrange(workers):
229 bess.add_worker(wid=wid, core=int(cores[wid % len(cores)]))
230
231# ====================================================
232# Port Setup
233# ====================================================
234
235
236interfaces = ["s1u", "sgi"]
237ports = {}
238for 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
245s1u_ifname = conf["s1u"]["ifname"]
246sgi_ifname = conf["sgi"]["ifname"]
247
248# ====================================================
249# Downlink Pipeline
250# ====================================================
251
252s1uRoutes = ports[s1u_ifname].rtr
253
254# Maximum number of sessions to manage
255try:
256 max_sessions = int(conf["max_sessions"])
257except ValueError:
258 print('Invalid max_sessions value!')
259
260# Setting filter to detect UE subnet
261sgiFastBPF = ports[sgi_ifname].bpf
262UEGate = ports[sgi_ifname].bpf_gate()
263ue_filter = {"priority": -UEGate,
264 "filter": "ip dst net {}".format(ue_cidr), "gate": UEGate}
265sgiFastBPF.add(filters=[ue_filter])
266
267sgiFastBPF: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
279GTPUEncap:0 -> Sink()
280
Hyunsun Moon6ff622e2020-03-11 17:14:48 -0700281# ====================================================
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
291s1uFastBPF = ports[s1u_ifname].bpf
292check_enb_subnet = "src net {} ".format(enb_cidr)
293check_spgwu_ip = " and dst host " + \
294 " or ".join(str(x) for x in ips_by_interface(s1u_ifname))
295check_gtpu_port = " and udp dst port 2152"
296check_ue_subnet = " and (udp[28:4] & 0x{}) = 0x{}".format(
297 cidr2mask(ue_cidr), ip2hex(cidr2block(ue_cidr)[0]))
298check_gtpu_msg_echo = " and udp[9] = 0x1"
299
300GTPUEchoGate = ports[s1u_ifname].bpf_gate()
301uplink_echo_filter = {"priority": -GTPUEchoGate, "filter": check_enb_subnet +
302 check_spgwu_ip + check_gtpu_port +
303 check_gtpu_msg_echo, "gate": GTPUEchoGate}
304s1uFastBPF.add(filters=[uplink_echo_filter])
305
306GTPUGate = ports[s1u_ifname].bpf_gate()
307uplink_filter = {"priority": -GTPUGate, "filter": check_enb_subnet +
308 check_spgwu_ip + check_gtpu_port, "gate": GTPUGate}
309s1uFastBPF.add(filters=[uplink_filter])
310
311sgiRoutes = ports[sgi_ifname].rtr
312
Hyunsun Moon531f42a2020-03-25 20:11:02 -0700313s1uFastBPF:GTPUGate \
314 -> EtherDecapTrim::GenericDecap(bytes=14) -> GTPUDecap::GtpuDecap(ename="GTPUEncap"):1 \
Hyunsun Moon6ff622e2020-03-11 17:14:48 -0700315 -> 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
321s1uFastBPF: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
327GTPUEcho:0 -> Sink()
328GTPUDecap:0 -> Sink()
329
Hyunsun Moon6ff622e2020-03-11 17:14:48 -0700330# ====================================================
331# SIM_TEST
332# ====================================================
333
334import time
335
336def 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
355def 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
372route_control_pid = getpythonpid('route_control.py')
373if route_control_pid:
374 os.kill(route_control_pid, signal.SIGHUP)